From d19a82c6bdcd41ad6f8c1dc9302f14803d106d13 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:17:39 +0000 Subject: [PATCH 001/361] h3: the image decoder reads safetensors and pictures through core, as main does image_decoder.zig pulls in geometry.zig, which on main reads core.safetensors, and image_decoder_test.zig runs in test-h3-geometry, whose module imports core alone, so the decoder's files read st from core.safetensors. The tool also writes PNGs with MOSS-Image's writer, whose test reads core/picture/png.zig by path, and a file may sit in one module of a build only. So the tool's core is h3_decoder_core.zig, one module holding safetensors, core's pictures and that writer, in place of picture_writer.zig; it resamples through core.picture. --- zig/src/h3_decoder_core.zig | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 zig/src/h3_decoder_core.zig diff --git a/zig/src/h3_decoder_core.zig b/zig/src/h3_decoder_core.zig new file mode 100644 index 00000000000..56907e2ea67 --- /dev/null +++ b/zig/src/h3_decoder_core.zig @@ -0,0 +1,4 @@ +//! tf-h3-image-decoder's `core`: safetensors, pictures and MOSS-Image's PNG writer, so each file is in one module. +pub const safetensors = @import("core/safetensors.zig"); +pub const picture = @import("core/picture/picture.zig"); +pub const png = @import("families/moss_image/png.zig"); From 1754680ba0380bee58542085ce9d6a6a6ef1cbc9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:59:30 +0000 Subject: [PATCH 002/361] changelog: #2781 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57ef96ae11b..0e018cd4d4d 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 +- MiniMax-H3-Image on Metal: `tf-h3-image-prompt` writes a whole text-to-image case from a size and a seed (the canvas, the size and the seed's starting rows), so text to image runs end to end with TensorFold's own tools, and `tf-h3-image ... free` exits 0 when there is no reference to gate against (#2781). + - Flash Next on Metal: `TF_FN_GX_SHARED=1` (opt-in) routes eligible shared rounds through the existing bit-preserving grouped expert kernels; off keeps per-pair launches (#4834). - Metal: the two pairs of u32 copy kernels build from one source, with the kernels unchanged (#4740). Thanks @jschmied. From c8ecc1fac722796a116d4711e513c5d658585366 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:59:30 +0000 Subject: [PATCH 003/361] changelog: #2781 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e018cd4d4d..b77d1a701af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - MiniMax-H3-Image on Metal: `tf-h3-image-prompt` writes a whole text-to-image case from a size and a seed (the canvas, the size and the seed's starting rows), so text to image runs end to end with TensorFold's own tools, and `tf-h3-image ... free` exits 0 when there is no reference to gate against (#2781). + + - Flash Next on Metal: `TF_FN_GX_SHARED=1` (opt-in) routes eligible shared rounds through the existing bit-preserving grouped expert kernels; off keeps per-pair launches (#4834). - Metal: the two pairs of u32 copy kernels build from one source, with the kernels unchanged (#4740). Thanks @jschmied. From 8500725ededb2d6ec2f22e25b5d0504cbbb1b430 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:12:21 +0000 Subject: [PATCH 004/361] h3: tf-h3-image on main: core for safetensors and its fixture, Model.load's io, and H3's Metal tools in h3_metal.zig Main moved H3's safetensors import into the core module (h3_core in metal_targets.zig, core in h3_host.zig). This series came from before that move: tf-h3-image imported safetensors and checkpoint_fixture modules of their own. It now imports core and reads both from it, since a file may sit in one module of a build only and core holds both. Main's h3.Model.load also takes the process's io now, so tf-h3-image passes init.io as tf-h3-dit does. Main's metal_targets.zig is at the 600-line cap, so tf-h3-image's target, and main's tf-h3-dit beside it, move to h3_metal.zig with the H3 modules they share (and the kernel sources they take); metal_targets.zig calls it in one line (589 lines). The steps and their modules are otherwise unchanged. --- zig/build/h3_host.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index 5f27f5b582a..c5cd3409142 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -21,7 +21,7 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = .Debug }) } } }); const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) }); const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core } } }) }); - const compile = b.step("compile-h3-host", "Compile the actual H3 tools without compiling or executing shaders"); + const compile = b.step("compile-h3-host", "Compile the actual H3 tools (tf-h3-dit, tf-h3-image) without compiling or executing shaders"); compile.dependOn(&tool.step); compile.dependOn(&picture_tool.step); const modulation = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/modulation.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } } }); From d1f42f5a14081206c5e1be594ee2ea02b93d5b1e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:35:48 +0000 Subject: [PATCH 005/361] kernel contract: MiniMax-H3-Image's runner, records and launch resolver (suites to come) --- build.zig | 1 + zig/build/h3_image_contract.zig | 28 ++++++++ zig/build/kernel_contract.zig | 4 ++ zig/src/core/contract.zig | 2 + zig/src/core/contract/h3_image_records.zig | 11 ++++ zig/src/core/contract/registry_joins.zig | 1 + zig/tests/contract/h3_image_main.zig | 66 +++++++++++++++++++ zig/tests/contract/metal_h3_image_common.zig | 42 ++++++++++++ zig/tests/contract/metal_h3_image_decoder.zig | 24 +++++++ zig/tests/contract/metal_h3_image_encoder.zig | 24 +++++++ zig/tests/contract/metal_h3_image_prompt.zig | 24 +++++++ zig/tests/contract/metal_limits.zig | 3 + zig/tests/contract/metal_main.zig | 6 ++ 13 files changed, 236 insertions(+) create mode 100644 zig/build/h3_image_contract.zig create mode 100644 zig/src/core/contract/h3_image_records.zig create mode 100644 zig/tests/contract/h3_image_main.zig create mode 100644 zig/tests/contract/metal_h3_image_common.zig create mode 100644 zig/tests/contract/metal_h3_image_decoder.zig create mode 100644 zig/tests/contract/metal_h3_image_encoder.zig create mode 100644 zig/tests/contract/metal_h3_image_prompt.zig diff --git a/build.zig b/build.zig index 982b12e53fd..841e2c3fc54 100644 --- a/build.zig +++ b/build.zig @@ -122,6 +122,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/h3_host.zig").tests(b, target, test_step); @import("zig/build/h3_image_prompt.zig").tests(b, target, test_step); @import("zig/build/h3_image_decoder.zig").compileHost(b, target); + @import("zig/build/h3_image_contract.zig").steps(b, target, optimize); @import("zig/build/ling_host.zig").tests(b, target, test_step); @import("zig/build/inkling2_host.zig").tests(b, target, test_step); @import("zig/build/gpt_oss_host.zig").tests(b, test_step); diff --git a/zig/build/h3_image_contract.zig b/zig/build/h3_image_contract.zig new file mode 100644 index 00000000000..d0fff4f2b52 --- /dev/null +++ b/zig/build/h3_image_contract.zig @@ -0,0 +1,28 @@ +//! MiniMax-H3-Image's kernels under the contract: tf-h3-image-contract compiles them at load, as its tools do. +const std = @import("std"); + +/// The edit encoder's, prompt path's and image decoder's kernel sources (each module embeds one .metal file). +pub fn sources(b: *std.Build) [3]std.Build.Module.Import { + return .{ + .{ .name = "h3_image_encoder_kernels", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_encoder.zig") }) }, + .{ .name = "h3_prompt_kernels", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/prompt_kernels.zig") }) }, + .{ .name = "h3_image_decoder_kernels", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_decoder.zig") }) }, + }; +} + +/// macOS: `tf-h3-image-contract` (gates 1-4, controls, this GPU's limits) and `h3-image-contract`, which runs it. +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) void { + if (target.result.os.tag != .macos) return; + const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize, .link_libc = true }); + metal.linkFramework("Metal", .{}); + metal.linkFramework("Foundation", .{}); + metal.linkFramework("IOSurface", .{}); + metal.linkSystemLibrary("objc", .{}); + const root = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/h3_image_main.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "contract", .module = @import("kernel_contract.zig").module(b, target, optimize) } } }); + for (sources(b)) |s| root.addImport(s.name, s.module); + const exe = b.addExecutable(.{ .name = "tf-h3-image-contract", .root_module = root }); + b.step("tf-h3-image-contract", "Build MiniMax-H3-Image's kernel contract runner from runtime sources only").dependOn(&b.addInstallArtifact(exe, .{}).step); + const run = b.addRunArtifact(exe); + run.has_side_effects = true; + b.step("h3-image-contract", "MiniMax-H3-Image's Metal kernels through the contract's gates on this GPU, each control red").dependOn(&run.step); +} diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 89212400781..f763661d93d 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -154,6 +154,7 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil const inkling2_metal = engine.import_table.get("inkling2_metal").?; const inkling2_glue_plan = engine.import_table.get("inkling2_glue_plan").?; const inkling2_loop_plan = engine.import_table.get("inkling2_loop_plan").?; + const image = @import("h3_image_contract.zig").sources(b); const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), .target = target, @@ -165,6 +166,9 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .{ .name = "kernel_sources", .module = sources }, .{ .name = "contract", .module = module(b, target, optimize) }, .{ .name = "h3_kernels", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }) }, + .{ .name = "h3_image_encoder_kernels", .module = image[0].module }, + .{ .name = "h3_prompt_kernels", .module = image[1].module }, + .{ .name = "h3_image_decoder_kernels", .module = image[2].module }, .{ .name = "ling_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }) }, .{ .name = "ling_route", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/route.zig") }) }, .{ .name = "masked_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/masked_value_sources.zig"), .imports = &.{.{ .name = "kernel_sources", .module = sources }} }) }, diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 726f0d1e4a6..d4528b8ed4b 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -19,6 +19,7 @@ pub const inkling2_runtime_metal_records = @import("contract/inkling2_runtime_me pub const lane_q8 = @import("contract/lane_q8_records.zig"); pub const q27_prompt = @import("contract/qwen27_prompt_records.zig"); pub const registry = @import("contract/registry.zig"); +pub const h3_image_records = @import("contract/h3_image_records.zig"); pub const cubin = @import("contract/cubin.zig"); pub const hsaco = @import("contract/hsaco.zig"); pub const hip_records = @import("contract/hip_records.zig"); @@ -30,6 +31,7 @@ pub const zebin = @import("contract/zebin.zig"); pub const zeinfo = @import("contract/zeinfo.zig"); test { _ = vulkan_records; + _ = h3_image_records; } test { _ = xpu_records; diff --git a/zig/src/core/contract/h3_image_records.zig b/zig/src/core/contract/h3_image_records.zig new file mode 100644 index 00000000000..02c522b501a --- /dev/null +++ b/zig/src/core/contract/h3_image_records.zig @@ -0,0 +1,11 @@ +//! MiniMax-H3-Image's launches: its edit encoder's, prompt path's and image decoder's kernels, each source-reserved. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const encoder = [_]M{}; +pub const prompt = [_]M{}; +pub const decoder = [_]M{}; +pub const records = encoder ++ prompt ++ decoder; + +test "the MiniMax-H3-Image launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 8458d50d3bb..7cd96798c8e 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -97,6 +97,7 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("moss_image_records.zig").records ++ @import("idol_dino_records.zig").records ++ @import("idol_records.zig").records ++ + @import("h3_image_records.zig").records ++ @import("dsv41_metal_records.zig").records ++ @import("minimax_records.zig").records ++ @import("ling_route_records.zig").records ++ diff --git a/zig/tests/contract/h3_image_main.zig b/zig/tests/contract/h3_image_main.zig new file mode 100644 index 00000000000..9a57843f529 --- /dev/null +++ b/zig/tests/contract/h3_image_main.zig @@ -0,0 +1,66 @@ +//! tf-h3-image-contract: MiniMax-H3-Image's Metal kernels through gates 1-4, their controls, then gate 5 on this GPU. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const common = @import("metal_h3_image_common.zig"); +const g = contract.gates; +const records = contract.h3_image_records.records; +const usage = "usage: tf-h3-image-contract [--only TEXT] [--seed N] [--no-limits]"; + +/// Each launch compiled as its launcher compiles it: the pipeline's thread limit and threadgroup bytes. +fn limitsHere(a: std.mem.Allocator, device: mtl.Device, only: ?[]const u8) !usize { + var n: usize = 0; + for (records) |d| { + if (!common.keep(only, d.name)) continue; + const part: common.Part = if (std.mem.indexOf(u8, d.name, " encoder ") != null) .encoder else if (std.mem.indexOf(u8, d.name, " prompt ") != null) .prompt else .decoder; + const lib = try common.library(device, part, common.source(part)); + defer lib.deinit(); + const p = try mtl.Pipeline.init(device, lib, d.name[std.mem.lastIndexOfScalar(u8, d.name, ' ').? + 1 ..], false); + defer p.deinit(); + const most = p.maxThreads(); + const tg = mtl.objc.msg(usize, p.id, "staticThreadgroupMemoryLength", .{}); + const bad = most < d.threads or tg > d.tg_memory or (d.reserved != 0 and most > d.reserved); + if (bad) n += 1; + std.debug.print("{s} limits here {s}: {d} threads launched, the pipeline takes {d} (reserved {d}); {d} threadgroup bytes (declared {d})\n", .{ if (bad) "FAIL" else "PASS", d.name, d.threads, most, d.reserved, tg, d.tg_memory }); + } + return n + try contract.registry.checkMetal(a, &records, false); +} + +pub fn main(init: std.process.Init) !u8 { + const a = std.heap.page_allocator; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + var only: ?[]const u8 = null; + var seed: u64 = 0x6b63; + var limits = true; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--no-limits")) limits = false else if (i + 1 < args.len and std.mem.eql(u8, args[i], "--only")) { + i += 1; + only = args[i]; + } else if (i + 1 < args.len and std.mem.eql(u8, args[i], "--seed")) { + i += 1; + seed = try std.fmt.parseInt(u64, args[i], 0); + } else { + std.debug.print("{s}\n", .{usage}); + return 2; + } + } + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + std.debug.print("H3_IMAGE_DEVICE {s} tensor_units={any}\n", .{ device.name(), device.tensorUnits() }); + var kernels: std.ArrayList(g.Kernel) = .empty; + defer kernels.deinit(a); + const encoder = try @import("metal_h3_image_encoder.zig").Suite.create(a, device, queue, &kernels, only); + defer encoder.destroy(); + const prompt = try @import("metal_h3_image_prompt.zig").Suite.create(a, device, queue, &kernels, only); + defer prompt.destroy(); + const decoder = try @import("metal_h3_image_decoder.zig").Suite.create(a, device, queue, &kernels, only); + defer decoder.destroy(); + var t: g.Tally = .{}; + try g.runAll(a, kernels.items, seed, &t); + const lim = if (limits) try limitsHere(a, device, only) else 0; + std.debug.print("H3_IMAGE_SUMMARY {d} kernels: {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed; {d} limit problems\n", .{ t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed, lim }); + return if (t.problems() + lim == 0) 0 else 1; +} diff --git a/zig/tests/contract/metal_h3_image_common.zig b/zig/tests/contract/metal_h3_image_common.zig new file mode 100644 index 00000000000..4ea14aadd86 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_common.zig @@ -0,0 +1,42 @@ +//! MiniMax-H3-Image's kernel tests' shared parts: the three sources compiled as their launchers compile them, controls. +const std = @import("std"); +const mtl = @import("metal"); + +pub const Part = enum { encoder, prompt, decoder }; + +/// The .metal source a part's launcher compiles at load. +pub fn source(part: Part) []const u8 { + return switch (part) { + .encoder => @import("h3_image_encoder_kernels").source, + .prompt => @import("h3_prompt_kernels").source, + .decoder => @import("h3_image_decoder_kernels").source, + }; +} + +/// MLX's options, and for the edit encoder precise fp32 functions (image_encoder.zig's Kernels.init). +pub fn options(part: Part) mtl.CompileOptions { + var o = mtl.CompileOptions.mlx(); + if (part == .encoder) o.math_functions = .precise; + return o; +} + +pub fn library(device: mtl.Device, part: Part, text: []const u8) !mtl.Library { + return mtl.Library.fromSource(device, text, options(part)); +} + +/// The record and spec name of a part's kernel: "minimax image ". +pub fn name(comptime part: Part, comptime function: []const u8) []const u8 { + return "minimax image " ++ @tagName(part) ++ " " ++ function; +} + +/// A part's source with `old` replaced by `new`, exactly once: a planted control's edit (refused when `old` moved). +pub fn edited(a: std.mem.Allocator, part: Part, old: []const u8, new: []const u8) ![]u8 { + const text = source(part); + const at = std.mem.indexOf(u8, text, old) orelse return error.ControlEditMissing; + if (std.mem.indexOfPos(u8, text, at + 1, old) != null) return error.ControlEditAmbiguous; + return std.mem.concat(a, u8, &.{ text[0..at], new, text[at + old.len ..] }); +} + +pub fn keep(only: ?[]const u8, label: []const u8) bool { + return if (only) |needle| std.mem.indexOf(u8, label, needle) != null else true; +} diff --git a/zig/tests/contract/metal_h3_image_decoder.zig b/zig/tests/contract/metal_h3_image_decoder.zig new file mode 100644 index 00000000000..e7a8b24beb0 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_decoder.zig @@ -0,0 +1,24 @@ +//! MiniMax-H3-Image's decoder kernels (image_decoder.metal) under the contract: each against its own formula in float64. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const common = @import("metal_h3_image_common.zig"); +const g = contract.gates; + +pub const Suite = struct { + a: std.mem.Allocator, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + _ = device; + _ = queue; + _ = kernels; + _ = only; + const s = try a.create(Suite); + s.* = .{ .a = a }; + return s; + } + + pub fn destroy(s: *Suite) void { + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_h3_image_encoder.zig b/zig/tests/contract/metal_h3_image_encoder.zig new file mode 100644 index 00000000000..7638859bc1b --- /dev/null +++ b/zig/tests/contract/metal_h3_image_encoder.zig @@ -0,0 +1,24 @@ +//! MiniMax-H3-Image's encoder kernels (h3_image_encoder.metal) under the contract: each against its own formula in float64. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const common = @import("metal_h3_image_common.zig"); +const g = contract.gates; + +pub const Suite = struct { + a: std.mem.Allocator, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + _ = device; + _ = queue; + _ = kernels; + _ = only; + const s = try a.create(Suite); + s.* = .{ .a = a }; + return s; + } + + pub fn destroy(s: *Suite) void { + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_h3_image_prompt.zig b/zig/tests/contract/metal_h3_image_prompt.zig new file mode 100644 index 00000000000..2e5f4504ca9 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_prompt.zig @@ -0,0 +1,24 @@ +//! MiniMax-H3-Image's prompt kernels (h3_prompt.metal) under the contract: each against its own formula in float64. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const common = @import("metal_h3_image_common.zig"); +const g = contract.gates; + +pub const Suite = struct { + a: std.mem.Allocator, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + _ = device; + _ = queue; + _ = kernels; + _ = only; + const s = try a.create(Suite); + s.* = .{ .a = a }; + return s; + } + + pub fn destroy(s: *Suite) void { + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 9aded632e4b..c1c9451b274 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -304,6 +304,9 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp if (!assemble) return undefined; text = if (std.mem.eql(u8, fun, "tf_sattn_nax")) sources.flashnext_attn else sources.flashnext_qmm6; frags = true; + } else if (std.mem.startsWith(u8, d.name, "minimax image ")) { + if (!assemble) return undefined; + text = if (has(d.name, " encoder ")) @import("h3_image_encoder_kernels").source else if (has(d.name, " prompt ")) @import("h3_prompt_kernels").source else @import("h3_image_decoder_kernels").source; } else if (std.mem.startsWith(u8, d.name, "h3 ")) { if (!assemble) return undefined; text = @import("h3_kernels").source; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index a6491bafae1..23dcfc498ae 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -566,6 +566,12 @@ pub fn main(init: std.process.Init) !u8 { defer moss_image.destroy(); const moss_image_decoder = try @import("metal_moss_image_decoder.zig").Suite.create(a, device, queue, &kernels, o.only); defer moss_image_decoder.destroy(); + const h3_image_encoder = try @import("metal_h3_image_encoder.zig").Suite.create(a, device, queue, &kernels, o.only); + defer h3_image_encoder.destroy(); + const h3_image_prompt = try @import("metal_h3_image_prompt.zig").Suite.create(a, device, queue, &kernels, o.only); + defer h3_image_prompt.destroy(); + const h3_image_decoder = try @import("metal_h3_image_decoder.zig").Suite.create(a, device, queue, &kernels, o.only); + defer h3_image_decoder.destroy(); var dsv41_suites = try @import("metal_dsv41_main.zig").Suites.create(a, device, queue, &kernels, o.only); defer dsv41_suites.destroy(); const idol = try @import("metal_idol.zig").Suite.create(a, device, queue, &kernels, o.only); From 51e92ee4bf5e23d27a07219ac6cb1bdeeb973a4e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:10:55 +0000 Subject: [PATCH 006/361] kernel contract: MiniMax-H3-Image's edit encoder kernels, eight registrations and nine planted controls --- zig/src/core/contract/h3_image_records.zig | 7 +- zig/tests/contract/metal_h3_image_encoder.zig | 118 ++++- .../contract/metal_h3_image_encoder_conv.zig | 290 ++++++++++++ .../contract/metal_h3_image_encoder_norms.zig | 435 ++++++++++++++++++ .../contract/metal_h3_image_encoder_ref.zig | 132 ++++++ 5 files changed, 975 insertions(+), 7 deletions(-) create mode 100644 zig/tests/contract/metal_h3_image_encoder_conv.zig create mode 100644 zig/tests/contract/metal_h3_image_encoder_norms.zig create mode 100644 zig/tests/contract/metal_h3_image_encoder_ref.zig diff --git a/zig/src/core/contract/h3_image_records.zig b/zig/src/core/contract/h3_image_records.zig index 02c522b501a..9ec93eb6886 100644 --- a/zig/src/core/contract/h3_image_records.zig +++ b/zig/src/core/contract/h3_image_records.zig @@ -1,7 +1,12 @@ //! MiniMax-H3-Image's launches: its edit encoder's, prompt path's and image decoder's kernels, each source-reserved. const std = @import("std"); const M = @import("limits.zig").MetalLaunch; -pub const encoder = [_]M{}; +pub const encoder = [_]M{ + .{ .name = "minimax image encoder hie_conv", .threads = 256, .tg_memory = 16384, .reserved = 256 }, + .{ .name = "minimax image encoder hie_group_part", .threads = 1024, .tg_memory = 0, .reserved = 1024 }, + .{ .name = "minimax image encoder hie_group_finish", .threads = 1024, .tg_memory = 0, .reserved = 1024 }, + .{ .name = "minimax image encoder hie_norm_silu", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; pub const prompt = [_]M{}; pub const decoder = [_]M{}; pub const records = encoder ++ prompt ++ decoder; diff --git a/zig/tests/contract/metal_h3_image_encoder.zig b/zig/tests/contract/metal_h3_image_encoder.zig index 7638859bc1b..e1326979604 100644 --- a/zig/tests/contract/metal_h3_image_encoder.zig +++ b/zig/tests/contract/metal_h3_image_encoder.zig @@ -1,24 +1,130 @@ -//! MiniMax-H3-Image's encoder kernels (h3_image_encoder.metal) under the contract: each against its own formula in float64. +//! MiniMax-H3-Image's edit encoder kernels (h3_image_encoder.metal) under the contract, each against float64. const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); const common = @import("metal_h3_image_common.zig"); +const rig_ = @import("rig.zig"); +const cv = @import("metal_h3_image_encoder_conv.zig"); +const nm = @import("metal_h3_image_encoder_norms.zig"); const g = contract.gates; +/// The test an entry runs: a convolution form, a GroupNorm pass, or the norm's map. +const Test = enum { conv, part, part_centered, finish, norm }; + +/// One registration: its name, its kernel function, its test and (a convolution) its form. +const Entry = struct { name: []const u8, function: []const u8, test_: Test, form: usize = 0 }; + +fn conv(comptime form: usize) Entry { + return .{ .name = common.name(.encoder, "hie_conv") ++ " " ++ cv.forms[form].label, .function = "hie_conv", .test_ = .conv, .form = form }; +} + +const entries = [_]Entry{ + conv(0), + conv(1), + conv(2), + conv(3), + .{ .name = common.name(.encoder, "hie_group_part"), .function = "hie_group_part", .test_ = .part }, + .{ .name = common.name(.encoder, "hie_group_part") ++ " centered", .function = "hie_group_part", .test_ = .part_centered }, + .{ .name = common.name(.encoder, "hie_group_finish"), .function = "hie_group_finish", .test_ = .finish }, + .{ .name = common.name(.encoder, "hie_norm_silu"), .function = "hie_norm_silu", .test_ = .norm }, +}; + +/// A planted control: the entry it breaks, the gate that must catch it, and its one edit to the source. +const Control = struct { entry: usize, gate: g.Gate, what: []const u8, old: []const u8, new: []const u8 }; + +const controls = [_]Control{ + .{ .entry = 0, .gate = .shapes, .what = "drops its last input channel", .old = "(live && c < s.cin) ? src[c] : 0.0f", .new = "(live && c + 1 < s.cin) ? src[c] : 0.0f" }, + .{ .entry = 0, .gate = .sums, .what = "rounds its sums to half after each 8-deep step", .old = "simdgroup_multiply_accumulate(acc[i][j], am[i], bm[j], acc[i][j]);", .new = "{ simdgroup_multiply_accumulate(acc[i][j], am[i], bm[j], acc[i][j]); thread auto& q = acc[i][j].thread_elements(); for (uint z = 0; z < sizeof(q) / sizeof(float); z++) q[z] = float(half(q[z])); }" }, + .{ .entry = 4, .gate = .sums, .what = "sums in half", .old = "sum += g.centered != 0 ? v * v : v;", .new = "sum = float(half(sum) + half(g.centered != 0 ? v * v : v));" }, + .{ .entry = 5, .gate = .shapes, .what = "reads the next group's mean", .old = "stats[c / (g.channels / 32)]", .new = "stats[(c / (g.channels / 32) + 1) % 32]" }, + .{ .entry = 6, .gate = .sums, .what = "sums in half", .old = "sum += part[(i / per) * g.channels + sg * per + i % per];", .new = "sum = float(half(sum) + half(part[(i / per) * g.channels + sg * per + i % per]));" }, + .{ .entry = 6, .gate = .shapes, .what = "reads the next group's parts", .old = "sg * per + i % per", .new = "((sg + 1) % 32) * per + i % per" }, + .{ .entry = 7, .gate = .shapes, .what = "SiLU without its sigmoid", .old = "y[at] = v / (1.0f + exp(-v));", .new = "y[at] = v;" }, + .{ .entry = 7, .gate = .shapes, .what = "reads the next group's statistics", .old = "const uint g = i.x / (n.channels / 32);", .new = "const uint g = (i.x / (n.channels / 32) + 1) % 32;" }, + .{ .entry = 7, .gate = .nonfinite, .what = "writes 0 for a NaN", .old = "y[at] = v / (1.0f + exp(-v));", .new = "y[at] = isnan(v) ? 0.0f : v / (1.0f + exp(-v));" }, +}; + pub const Suite = struct { a: std.mem.Allocator, + /// The served source's library, once an entry needs it. + served: ?mtl.Library = null, + libs: std.ArrayList(mtl.Library) = .empty, + pipes: std.ArrayList(mtl.Pipeline) = .empty, + names: std.ArrayList([]u8) = .empty, + convs: std.ArrayList(*cv.Conv) = .empty, + parts: std.ArrayList(*nm.GroupPart) = .empty, + finishes: std.ArrayList(*nm.GroupFinish) = .empty, + norms: std.ArrayList(*nm.NormSilu) = .empty, pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { - _ = device; - _ = queue; - _ = kernels; - _ = only; const s = try a.create(Suite); s.* = .{ .a = a }; + errdefer s.destroy(); + for (entries) |e| try s.add(device, queue, e, null, kernels, only); + for (controls) |x| try s.add(device, queue, entries[x.entry], x, kernels, only); return s; } pub fn destroy(s: *Suite) void { - s.a.destroy(s); + const a = s.a; + inline for (.{ &s.convs, &s.parts, &s.finishes, &s.norms }) |list| { + for (list.items) |t| { + t.deinit(); + a.destroy(t); + } + list.deinit(a); + } + for (s.pipes.items) |p| p.deinit(); + s.pipes.deinit(a); + for (s.libs.items) |l| l.deinit(); + s.libs.deinit(a); + for (s.names.items) |n| a.free(n); + s.names.deinit(a); + a.destroy(s); + } + + /// The served source's library, built once; a control's own copy of the source with its edit. + fn library(s: *Suite, device: mtl.Device, ctl: ?Control) !mtl.Library { + if (ctl == null) if (s.served) |lib| return lib; + const text = if (ctl) |x| try common.edited(s.a, .encoder, x.old, x.new) else try s.a.dupe(u8, common.source(.encoder)); + defer s.a.free(text); + const lib = try common.library(device, .encoder, text); + errdefer lib.deinit(); + try s.libs.append(s.a, lib); + if (ctl == null) s.served = lib; + return lib; + } + + fn make(s: *Suite, comptime T: type, list: *std.ArrayList(*T), value: T) !*T { + const t = try s.a.create(T); + errdefer s.a.destroy(t); + t.* = value; + try list.append(s.a, t); + return t; + } + + /// Entry `e` on the served pipeline, or on a control's (named for what it breaks, red at its gate). + fn add(s: *Suite, device: mtl.Device, queue: mtl.Queue, e: Entry, ctl: ?Control, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + const name = if (ctl) |x| try std.fmt.allocPrint(s.a, "{s} control: {s}", .{ e.name, x.what }) else try s.a.dupe(u8, e.name); + s.names.append(s.a, name) catch |err| { + s.a.free(name); + return err; + }; + if (!common.keep(only, name)) return; + const lib = try s.library(device, ctl); + const pipe = try mtl.Pipeline.init(device, lib, e.function, false); + s.pipes.append(s.a, pipe) catch |err| { + pipe.deinit(); + return err; + }; + const rig: rig_.Rig = .{ .a = s.a, .device = device, .queue = queue }; + const gate: ?g.Gate = if (ctl) |x| x.gate else null; + const k = switch (e.test_) { + .conv => (try s.make(cv.Conv, &s.convs, .{ .a = s.a, .rig = rig, .pipe = pipe, .form = &cv.forms[e.form], .name = name })).kernel(gate), + .part, .part_centered => (try s.make(nm.GroupPart, &s.parts, .{ .a = s.a, .rig = rig, .pipe = pipe, .centered = e.test_ == .part_centered, .name = name })).kernel(gate), + .finish => (try s.make(nm.GroupFinish, &s.finishes, .{ .a = s.a, .rig = rig, .pipe = pipe, .name = name, .ends = .{ .a = s.a } })).kernel(gate), + .norm => (try s.make(nm.NormSilu, &s.norms, .{ .a = s.a, .rig = rig, .pipe = pipe, .name = name, .ends = .{ .a = s.a } })).kernel(gate), + }; + try out.append(s.a, k); } }; diff --git a/zig/tests/contract/metal_h3_image_encoder_conv.zig b/zig/tests/contract/metal_h3_image_encoder_conv.zig new file mode 100644 index 00000000000..abbde5c7d70 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_encoder_conv.zig @@ -0,0 +1,290 @@ +//! hie_conv under the contract: the encoder's convolutions (3x3, 3x3 adding in place, 3x3 down, 1x1) against float64. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("metal_h3_image_encoder_ref.zig"); + +const c = ref.c; +const g = ref.g; +const threads = contract.reference_threads; + +/// A convolution the encoder launches: its kernel side, stride 2 or not, the residual added in place or not. +pub const Form = struct { label: []const u8, side: usize, down: bool = false, add: bool = false, tiles: [3]c.Tile, served: []const c.Shape }; + +/// Rows: the tile's side (square, as the release cuts every tile at 256); n: output channels; k: input channels. +fn sq(side: usize, cout: usize, cin: usize) c.Shape { + return .{ .rows = side, .n = cout, .k = cin }; +} + +/// 8 x 8 output pixels fill the kernel's 64-pixel tile; outputs in 16s around its 64 channels; inputs in steps of 32. +const pixel_tile: c.Tile = .{ .size = 8, .min = 2 }; +const channel_tile: c.Tile = .{ .size = 64, .step = 16, .min = 16 }; +const input_tile: c.Tile = .{ .size = 32 }; + +/// Every layer geometry of the released encoder on its 256-pixel tiles, each form's first the edges' base. +pub const forms = [_]Form{ + // conv_out, conv_in, then each level's conv1 + .{ .label = "3x3", .side = 3, .tiles = .{ pixel_tile, channel_tile, input_tile }, .served = &.{ sq(16, 48, 1024), sq(256, 128, 3), sq(256, 128, 128), sq(128, 256, 128), sq(128, 256, 256), sq(64, 256, 256), sq(32, 512, 256), sq(32, 512, 512), sq(16, 512, 512), sq(16, 1024, 512), sq(16, 1024, 1024) } }, + // each level's conv2, adding into the block's input + .{ .label = "3x3 + residual", .side = 3, .add = true, .tiles = .{ pixel_tile, .{}, .{} }, .served = &.{ sq(256, 128, 128), sq(128, 256, 256), sq(64, 256, 256), sq(32, 512, 512), sq(16, 512, 512), sq(16, 1024, 1024) } }, + // levels 0-3's downsample: two input rows a pixel row, so 16 rows fill the tile + .{ .label = "3x3 down", .side = 3, .down = true, .tiles = .{ .{ .size = 16, .step = 2, .min = 2 }, .{}, .{} }, .served = &.{ sq(256, 128, 128), sq(128, 256, 256), sq(64, 256, 256), sq(32, 512, 512) } }, + // quant_conv, then the shortcuts + .{ .label = "1x1", .side = 1, .tiles = .{ .{ .size = 8 }, channel_tile, input_tile }, .served = &.{ sq(16, 48, 48), sq(128, 256, 128), sq(32, 512, 256), sq(16, 1024, 512) } }, +}; + +/// Each output's taps x cin products in one chain at worst, then its bias and residual. +fn depth9(s: c.Shape) usize { + return 9 * s.k + 2; +} +fn depth1(s: c.Shape) usize { + return s.k + 2; +} + +/// The kernel's HieConv constants. +const HieConv = extern struct { h: u32, w: u32, oh: u32, ow: u32, cin: u32, cout: u32, ldw: u32, k: u32, stride: u32, pad: u32, add: u32 }; + +/// Index i of an axis of n read with reflect padding (-1 reads 1, n reads n - 2). +fn reflect(i: isize, n: usize) usize { + const last: isize = @intCast(n - 1); + return @intCast(if (i < 0) -i else if (i > last) 2 * last - i else i); +} + +pub const Conv = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + form: *const Form, + name: []const u8, + shape: c.Shape = undefined, + /// x [side * side, cin], w [taps, cin, ldw], b [cout], the residual [pixels, cout] y starts from + x: []f32 = &.{}, + w: []f32 = &.{}, + b: []f32 = &.{}, + r: []f32 = &.{}, + ins: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn spec(name: []const u8, f: *const Form) c.Spec { + return .{ .name = name, .accum = .f32, .depth = if (f.side == 3) depth9 else depth1, .out = .f32, .in_place = f.add, .tiles = f.tiles, .served = f.served }; + } + + pub fn kernel(t: *Conv, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name, t.form), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(Conv); + + pub fn deinit(t: *Conv) void { + t.free(); + t.rig.deinit(); + } + + fn free(t: *Conv) void { + inline for (.{ &t.x, &t.w, &t.b, &t.r }) |p| { + t.a.free(p.*); + p.* = &.{}; + } + } + + const Geo = struct { side: usize, out: usize, stride: usize, pad: usize, taps: usize, ldw: usize }; + + /// The launcher's sizes: stride 2 halves the side, a stride-1 3x3 pads by one, weight rows padded to 64. + fn geo(t: *const Conv) Geo { + const s = t.shape.rows; + return .{ + .side = s, + .out = if (t.form.down) s / 2 else s, + .stride = if (t.form.down) 2 else 1, + .pad = if (t.form.side == 3 and !t.form.down) 1 else 0, + .taps = t.form.side * t.form.side, + .ldw = std.mem.alignForward(usize, t.shape.n, 64), + }; + } + + pub fn prepare(t: *Conv, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const least: usize = if (t.form.side == 3) 2 else 1; + if (shape.rows < least or shape.n == 0 or shape.k == 0 or (t.form.down and shape.rows % 2 != 0)) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const e = t.geo(); + t.x = try t.a.alloc(f32, e.side * e.side * shape.k); + t.w = try t.a.alloc(f32, e.taps * shape.k * e.ldw); + t.b = try t.a.alloc(f32, shape.n); + t.r = try t.a.alloc(f32, if (t.form.add) e.out * e.out * shape.n else 0); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // the weights' padded columns stay zero, as packLayers leaves them + @memset(t.w, 0); + if (fill == .stress) t.stress(rng) else { + ref.uniform(rng, t.x, -2, 2); + for (0..e.taps * shape.k) |row| ref.uniform(rng, t.w[row * e.ldw ..][0..shape.n], -0.1, 0.1); + ref.uniform(rng, t.b, -1, 1); + ref.uniform(rng, t.r, -3, 3); + if (fill == .nonfinite) t.plant(); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.b)); + t.out = try t.rig.output(t.count() * 4); + return true; + } + + /// NaN, +Inf and -Inf at three pixels, both infinities at the last one, a +Inf bias and a NaN residual. + fn plant(t: *Conv) void { + const side = t.shape.rows; + const cin = t.shape.k; + const px = side * side; + const at = [_]usize{ 0, 2 * side + 4, 3 * side + 1 }; + for (at, [_]f32{ ref.nan, ref.inf, -ref.inf }, 0..) |p, v, i| if (p < px) { + t.x[p * cin + i % cin] = v; + }; + t.x[(px - 1) * cin] = ref.inf; + t.x[(px - 1) * cin + cin - 1] = -ref.inf; + if (t.shape.n > 1) t.b[t.shape.n - 1] = ref.inf; + if (t.r.len > 0) t.r[t.r.len / 2] = ref.nan; + } + + /// Gate 4: integers, each tap's second half of channels its first (4 nudged by one) under negated weights. + fn stress(t: *Conv, rng: std.Random) void { + const cin = t.shape.k; + const e = t.geo(); + const half = cin / 2; + // terms reach 512 x 2 and number taps x cin at most 9 x 1024: every partial sum stays below 2^24 + for (0..e.side * e.side) |p| { + const x = t.x[p * cin ..][0..cin]; + @memset(x, 0); + for (0..half) |i| { + x[i] = ref.int(rng, 100, 511); + x[half + i] = x[i] + @as(f32, if (i < 4) 1 else 0); + } + } + for (0..e.taps) |tap| for (0..half) |i| for (0..t.shape.n) |o| { + const v = ref.int(rng, 1, 2) * @as(f32, if (o % 3 == 1) -1 else 1); + t.w[(tap * cin + i) * e.ldw + o] = v; + t.w[(tap * cin + half + i) * e.ldw + o] = -v; + }; + for (t.b) |*v| v.* = ref.int(rng, -3, 3); + for (t.r) |*v| v.* = ref.int(rng, -3, 3); + } + + /// One launch as image_encoder.zig's `conv` binds and dispatches it (y at r's index when no residual is added). + pub fn run(t: *Conv) !void { + if (t.form.add) @memcpy(t.rig.bytes(t.out, t.r.len * 4), std.mem.sliceAsBytes(t.r)); + const e = t.geo(); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| ref.bind(p.e, r, i); + ref.bind(p.e, t.out, 3); + ref.bind(p.e, t.out, 4); + const s: HieConv = .{ + .h = @intCast(e.side), + .w = @intCast(e.side), + .oh = @intCast(e.out), + .ow = @intCast(e.out), + .cin = @intCast(t.shape.k), + .cout = @intCast(t.shape.n), + .ldw = @intCast(e.ldw), + .k = @intCast(t.form.side), + .stride = @intCast(e.stride), + .pad = @intCast(e.pad), + .add = @intFromBool(t.form.add), + }; + p.e.setValue(s, 5); + p.e.dispatchGroups(mtl.Size.of((e.out * e.out + 63) / 64, e.ldw / 64, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Conv) usize { + const e = t.geo(); + return e.out * e.out * t.shape.n; + } + + /// The input channels tap `tap` of output pixel p reads, through reflect padding. + fn source(t: *const Conv, e: Geo, p: usize, tap: usize) []const f32 { + const oy = p / e.out; + const ox = p % e.out; + const pad: isize = @intCast(e.pad); + const iy = reflect(@as(isize, @intCast(oy * e.stride + tap / t.form.side)) - pad, e.side); + const ix = reflect(@as(isize, @intCast(ox * e.stride + tap % t.form.side)) - pad, e.side); + return t.x[(iy * e.side + ix) * t.shape.k ..][0..t.shape.k]; + } + + /// Output pixel p's every channel in float64: the sums and their terms' magnitude. + fn exact(t: *const Conv, p: usize, want: []f64, mag: []f64, buf: []f64) void { + const e = t.geo(); + const cout = t.shape.n; + const sum = buf[0..cout]; + const abs = buf[cout..][0..cout]; + @memset(sum, 0); + @memset(abs, 0); + for (0..e.taps) |tap| for (t.source(e, p, tap), 0..) |xv, ci| { + const xf: f64 = xv; + for (t.w[(tap * t.shape.k + ci) * e.ldw ..][0..cout], sum, abs) |wv, *s, *m| { + const prod = xf * wv; + s.* += prod; + m.* += @abs(prod); + } + }; + for (0..cout) |o| { + const i = p * cout + o; + const rv: f64 = if (t.form.add) t.r[i] else 0; + want[i] = sum[o] + t.b[o] + rv; + const m = abs[o] + @abs(@as(f64, t.b[o])) + @abs(rv); + mag[i] = if (std.math.isFinite(m)) m else 0; + } + } + + /// Output pixel p's every channel with its products summed in `acc`, in `order` over (tap, input channel). + fn simulated(t: *const Conv, p: usize, acc: c.Accum, order: g.Order, out: []f64, buf: []f64) void { + const e = t.geo(); + const cout = t.shape.n; + for (0..cout) |o| { + var n: usize = 0; + for (0..e.taps) |tap| for (t.source(e, p, tap), 0..) |xv, ci| { + buf[n] = @as(f64, xv) * t.w[(tap * t.shape.k + ci) * e.ldw + o]; + n += 1; + }; + const i = p * cout + o; + const rv: f64 = if (t.form.add) t.r[i] else 0; + out[i] = contract.rows.sumIn(acc, order, buf[0..n]) + t.b[o] + rv; + } + } + + /// A share of the output pixels, computed on a thread of its own. + const Job = struct { + t: *const Conv, + lo: usize, + hi: usize, + acc: ?c.Accum, + order: g.Order, + want: []f64, + mag: []f64, + buf: []f64, + + pub fn run(j: *Job) void { + for (j.lo..j.hi) |p| if (j.acc) |acc| j.t.simulated(p, acc, j.order, j.want, j.buf) else j.t.exact(p, j.want, j.mag, j.buf); + } + }; + + fn each(t: *Conv, acc: ?c.Accum, order: g.Order, want: []f64, mag: []f64) !void { + const e = t.geo(); + const pixels = e.out * e.out; + const n = threads.count(threads.maximum, pixels); + const per = if (acc == null) 2 * t.shape.n else e.taps * t.shape.k; + const buf = try t.a.alloc(f64, n * per); + defer t.a.free(buf); + var jobs: [threads.maximum]Job = undefined; + for (jobs[0..n], 0..) |*j, i| j.* = .{ .t = t, .lo = pixels * i / n, .hi = pixels * (i + 1) / n, .acc = acc, .order = order, .want = want, .mag = mag, .buf = buf[i * per ..][0..per] }; + threads.run(Job, jobs[0..n], .normal); + } + + pub fn reference(t: *Conv, want: []f64, mag: []f64) !void { + return t.each(null, .sequential, want, mag); + } + + pub fn simulate(t: *Conv, acc: c.Accum, order: g.Order, out: []f64) !void { + return t.each(acc, order, out, out); + } +}; diff --git a/zig/tests/contract/metal_h3_image_encoder_norms.zig b/zig/tests/contract/metal_h3_image_encoder_norms.zig new file mode 100644 index 00000000000..5d11dee6d43 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_encoder_norms.zig @@ -0,0 +1,435 @@ +//! hie_group_part, hie_group_finish and hie_norm_silu under the contract: GroupNorm's fp32 steps against float64. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("metal_h3_image_encoder_ref.zig"); + +const c = ref.c; +const g = ref.g; +const Range = ref.Range; +const Ends = ref.Ends; + +/// Rows unused (1); n: channels (32 groups); k: pixels. +fn gs(channels: usize, pixels: usize) c.Shape { + return .{ .rows = 1, .n = channels, .k = pixels }; +} + +/// Every (channels, pixels) the encoder norms at on a 256-pixel tile, level 2's first: the edges' base. +const group_served = [_]c.Shape{ gs(256, 4096), gs(128, 65536), gs(128, 16384), gs(256, 16384), gs(256, 1024), gs(512, 1024), gs(512, 256), gs(1024, 256) }; + +/// Channels around groups of 3 (a size the release never runs), pixels around a part's chunk. +const group_tiles = [3]c.Tile{ .{}, .{ .size = 96, .step = 32, .min = 32 }, .{ .size = ref.chunk } }; + +fn groupShape(s: c.Shape) bool { + return s.n != 0 and s.n % 32 == 0 and s.n <= 1024 and s.k != 0; +} + +// --- hie_group_part: each channel's sum over a chunk of pixels, of the values or of their squared deviations --------- + +pub const GroupPart = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + centered: bool, + name: []const u8, + shape: c.Shape = undefined, + x: []f32 = &.{}, + /// the 32 means, then the 32 reciprocal deviations (unread here) + stats: [64]f32 = undefined, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// A thread's chunk of pixels in turn, each term after its subtraction and square. + fn depth(s: c.Shape) usize { + return @min(s.k, ref.chunk) + 3; + } + + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = depth, .out = .f32, .tiles = group_tiles, .served = &group_served }; + } + + pub fn kernel(t: *GroupPart, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(GroupPart); + + pub fn deinit(t: *GroupPart) void { + t.a.free(t.x); + t.rig.deinit(); + } + + pub fn prepare(t: *GroupPart, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!groupShape(shape)) return false; + t.rig.reset(); + t.a.free(t.x); + t.x = &.{}; + t.shape = shape; + t.x = try t.a.alloc(f32, shape.k * shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + ref.uniform(rng, t.stats[32..], 0.5, 2); + if (fill == .stress) t.stress(rng) else { + ref.uniform(rng, t.x, -3, 3); + ref.uniform(rng, t.stats[0..32], -0.5, 0.5); + if (fill == .nonfinite) t.plant(); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(&t.stats)); + t.out = try t.rig.output(t.count() * 4); + return true; + } + + /// NaN, +Inf and -Inf in three channels, both infinities in one channel's chunk, and group 5's mean NaN. + fn plant(t: *GroupPart) void { + const n = t.shape.n; + const at = [_][2]usize{ .{ 0, 0 }, .{ 1, 1 }, .{ 2, 2 }, .{ 3, 3 }, .{ 5, 3 } }; + for (at, [_]f32{ ref.nan, ref.inf, -ref.inf, ref.inf, -ref.inf }) |p, v| if (p[0] < t.shape.k) { + t.x[p[0] * n + p[1]] = v; + }; + t.stats[5] = ref.nan; + } + + /// Gate 4: integers; plain chunks' second half their first negated (4 nudged by one), centered ones near the mean. + fn stress(t: *GroupPart, rng: std.Random) void { + const n = t.shape.n; + const per = n / 32; + for (t.stats[0..32]) |*m| m.* = ref.int(rng, -4, 4); + // plain: partial sums near 2^18 cancel to 4, a 32-lane order's 4 terms pass fp16's 2,048; centered: 18^2 a term + for (0..ref.chunks(t.shape.k)) |ck| { + const lo = ck * ref.chunk; + const len = @min(ref.chunk, t.shape.k - lo); + const half = len / 2; + for (0..n) |ch| for (0..len) |i| { + const at = (lo + i) * n + ch; + t.x[at] = if (t.centered) + t.stats[ch / per] + ref.int(rng, -18, 18) + else if (i >= 2 * half) + 1 + else if (i < half) + ref.int(rng, 1024, 4095) + else + -t.x[(lo + i - half) * n + ch] + @as(f32, if (i - half < 4) 1 else 0); + }; + } + } + + /// One pass as image_encoder.zig's `normSilu` launches hie_group_part: a group a chunk, a thread a channel. + pub fn run(t: *GroupPart) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + ref.bind(p.e, t.ins[0], 0); + ref.bind(p.e, t.ins[1], 1); + ref.bind(p.e, t.out, 2); + p.e.setValue(ref.group(t.shape.n, t.shape.k, t.centered), 3); + p.e.dispatchGroups(mtl.Size.of(ref.chunks(t.shape.k), 1, 1), mtl.Size.of(t.shape.n, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *GroupPart) usize { + return ref.chunks(t.shape.k) * t.shape.n; + } + + /// Output (chunk ck, channel ch)'s terms in the kernel's order: x - mean, squared when centered. + fn terms(t: *const GroupPart, ck: usize, ch: usize, out: []f64) []f64 { + const n = t.shape.n; + const mean: f64 = if (t.centered) t.stats[ch / (n / 32)] else 0; + const lo = ck * ref.chunk; + const hi = @min(lo + ref.chunk, t.shape.k); + for (lo..hi, out[0 .. hi - lo]) |p, *v| { + const d = @as(f64, t.x[p * n + ch]) - mean; + v.* = if (t.centered) d * d else d; + } + return out[0 .. hi - lo]; + } + + pub fn reference(t: *GroupPart, want: []f64, mag: []f64) !void { + var buf: [ref.chunk]f64 = undefined; + for (0..ref.chunks(t.shape.k)) |ck| for (0..t.shape.n) |ch| { + const s = ref.total(t.terms(ck, ch, &buf)); + want[ck * t.shape.n + ch] = s.sum; + mag[ck * t.shape.n + ch] = s.mag; + }; + } + + pub fn simulate(t: *GroupPart, acc: c.Accum, order: g.Order, out: []f64) !void { + var buf: [ref.chunk]f64 = undefined; + for (0..ref.chunks(t.shape.k)) |ck| for (0..t.shape.n) |ch| { + out[ck * t.shape.n + ch] = contract.rows.sumIn(acc, order, t.terms(ck, ch, &buf)); + }; + } +}; + +// --- hie_group_finish: the 32 means, then the 32 reciprocal deviations, from the parts ------------------------------- + +pub const GroupFinish = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + name: []const u8, + shape: c.Shape = undefined, + fill: g.Fill = .random, + /// parts [chunks, channels] + part: []f32 = &.{}, + ins: [1]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + /// A lane's every 32nd part in turn, then the simdgroup's tree. + fn depth(s: c.Shape) usize { + return (ref.chunks(s.k) * (s.n / 32) + 31) / 32 + 5; + } + + pub fn spec(name: []const u8) c.Spec { + return .{ .name = name, .accum = .f32, .depth = depth, .ops = 2 * ref.div_ulps + ref.sqrt_ulps + 1, .out = .f32, .tiles = group_tiles, .served = &group_served }; + } + + pub fn kernel(t: *GroupFinish, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(GroupFinish); + + pub fn deinit(t: *GroupFinish) void { + t.a.free(t.part); + t.ends.deinit(); + t.rig.deinit(); + } + + /// Where term i of group grp lies in the parts, in the kernel's order: chunk i / per, channel grp * per + i % per. + fn slot(t: *const GroupFinish, grp: usize, i: usize) usize { + const per = t.shape.n / 32; + return (i / per) * t.shape.n + grp * per + i % per; + } + + fn terms(t: *const GroupFinish) usize { + return ref.chunks(t.shape.k) * (t.shape.n / 32); + } + + pub fn prepare(t: *GroupFinish, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (!groupShape(shape)) return false; + t.rig.reset(); + t.a.free(t.part); + t.part = &.{}; + t.shape = shape; + t.fill = fill; + t.part = try t.a.alloc(f32, ref.chunks(shape.k) * shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (fill == .stress) t.stress(rng) else { + ref.uniform(rng, t.part, 0, 5000); + if (fill == .nonfinite) t.plant(); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.part)); + t.out = try t.rig.output(64 * 4); + return true; + } + + /// NaN in group 0's parts, +Inf in group 1's, -Inf in group 2's, both infinities in group 3's. + fn plant(t: *GroupFinish) void { + const last = t.terms() - 1; + for ([_][2]usize{ .{ 0, 0 }, .{ 1, 0 }, .{ 2, 0 }, .{ 3, 0 }, .{ 3, last } }, [_]f32{ ref.nan, ref.inf, -ref.inf, ref.inf, -ref.inf }) |p, v| { + t.part[t.slot(p[0], p[1])] = v; + } + } + + /// Gate 4: integer parts, each group's second half of terms its first negated (4 nudged by one): fp16 overflows. + fn stress(t: *GroupFinish, rng: std.Random) void { + const n = t.terms(); + const half = n / 2; + // 1,024 terms of at most 8,001 keep every partial sum below 2^24 + for (0..32) |grp| for (0..n) |i| { + t.part[t.slot(grp, i)] = if (i >= 2 * half) + 1 + else if (i < half) + ref.int(rng, 4000, 8000) + else + -t.part[t.slot(grp, i - half)] + @as(f32, if (i - half < 4) 1 else 0); + }; + } + + /// Both passes as image_encoder.zig's `normSilu` launches hie_group_finish: the means, then 1 / sqrt(var + eps). + pub fn run(t: *GroupFinish) !void { + const p = t.rig.begin(); + for ([_]bool{ false, true }) |centered| { + p.e.setPipeline(t.pipe); + ref.bind(p.e, t.ins[0], 0); + ref.bind(p.e, t.out, 1); + p.e.setValue(ref.group(t.shape.n, t.shape.k, centered), 2); + p.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(32 * 32, 1, 1)); + } + try t.rig.finish(p); + } + + pub fn count(_: *GroupFinish) usize { + return 64; + } + + /// Group grp's mean and reciprocal deviation from its sum s (range r) over pixels x per values. + fn outputs(t: *GroupFinish, ends: *Ends, grp: usize, s: f64, r: Range, want: []f64, mag: []f64) void { + const n: f64 = @floatFromInt(t.shape.k * (t.shape.n / 32)); + const e: f64 = ref.eps; + const mean = (Range{ .lo = r.lo / n, .hi = r.hi / n }).fp32(ref.div_ulps); + ends.put(want, mag, grp, s / n, mean); + const pos = mean.add(Range.of(e)).fp32(0.5); + const inv = if (pos.lo > 0) pos.sqrt().fp32(ref.sqrt_ulps).recip().fp32(ref.div_ulps) else Range.of(1 / @sqrt(s / n + e)); + ends.put(want, mag, 32 + grp, 1 / @sqrt(s / n + e), inv); + } + + pub fn reference(t: *GroupFinish, want: []f64, mag: []f64) !void { + try t.ends.size(64); + for (0..32) |grp| { + var s: f64 = 0; + var m: f64 = 0; + for (0..t.terms()) |i| { + const v: f64 = t.part[t.slot(grp, i)]; + s += v; + m += @abs(v); + } + // gate 4's integer sums are exact in fp32 whatever the order + const err = if (t.fill == .stress) 0 else c.gamma(@floatFromInt(depth(t.shape)), c.unit(.f32)) * m; + t.outputs(&t.ends, grp, s, .{ .lo = s - err, .hi = s + err }, want, mag); + } + } + pub fn bounds(t: *GroupFinish, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *GroupFinish, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + + pub fn simulate(t: *GroupFinish, acc: c.Accum, order: g.Order, out: []f64) !void { + const buf = try t.a.alloc(f64, t.terms()); + defer t.a.free(buf); + const n: f64 = @floatFromInt(t.shape.k * (t.shape.n / 32)); + const e: f64 = ref.eps; + for (0..32) |grp| { + for (buf, 0..) |*v, i| v.* = t.part[t.slot(grp, i)]; + const s = contract.rows.sumIn(acc, order, buf); + out[grp] = s / n; + out[32 + grp] = 1 / @sqrt(s / n + e); + } + } +}; + +// --- hie_norm_silu: SiLU((x - mean) * rstd * gamma + beta) by the group's statistics --------------------------------- + +/// Rows: pixels; n: channels; every GroupNorm's (pixels, channels) on a 256-pixel tile, level 2's first. +const silu_served = [_]c.Shape{ + .{ .rows = 4096, .n = 256, .k = 1 }, .{ .rows = 65536, .n = 128, .k = 1 }, .{ .rows = 16384, .n = 128, .k = 1 }, + .{ .rows = 16384, .n = 256, .k = 1 }, .{ .rows = 1024, .n = 256, .k = 1 }, .{ .rows = 1024, .n = 512, .k = 1 }, + .{ .rows = 256, .n = 512, .k = 1 }, .{ .rows = 256, .n = 1024, .k = 1 }, +}; + +pub const NormSilu = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + name: []const u8, + shape: c.Shape = undefined, + x: []f32 = &.{}, + stats: [64]f32 = undefined, + gamma: []f32 = &.{}, + beta: []f32 = &.{}, + ins: [4]rig_.Ref = undefined, + out: rig_.Ref = undefined, + ends: Ends, + + /// No sums: four fp32 steps, then exp, an add and a division. + pub fn spec(name: []const u8) c.Spec { + return .{ + .name = name, + .accum = .none, + .depth = ref.noSums, + .ops = 4 + ref.exp_ulps + ref.div_ulps + 1, + .out = .f32, + .tiles = .{ .{ .size = 8 }, .{ .size = 96, .step = 32, .min = 32 }, .{} }, + .served = &silu_served, + }; + } + + pub fn kernel(t: *NormSilu, control: ?g.Gate) g.Kernel { + return .{ .spec = spec(t.name), .ctx = t, .vt = &vt, .control = control }; + } + const vt = g.hooks(NormSilu); + + pub fn deinit(t: *NormSilu) void { + t.free(); + t.ends.deinit(); + t.rig.deinit(); + } + + fn free(t: *NormSilu) void { + inline for (.{ &t.x, &t.gamma, &t.beta }) |p| { + t.a.free(p.*); + p.* = &.{}; + } + } + + pub fn prepare(t: *NormSilu, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 32 != 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.x = try t.a.alloc(f32, shape.rows * shape.n); + t.gamma = try t.a.alloc(f32, shape.n); + t.beta = try t.a.alloc(f32, shape.n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // the normed values stay within +-31, far from fp32 exp's overflow in the SiLU + ref.uniform(rng, t.x, -4, 4); + ref.uniform(rng, t.stats[0..32], -1, 1); + ref.uniform(rng, t.stats[32..], 0.2, 3); + ref.uniform(rng, t.gamma, -2, 2); + ref.uniform(rng, t.beta, -1, 1); + if (fill == .nonfinite) { + for ([_]usize{ 0, 1, 2 }, [_]f32{ ref.nan, ref.inf, -ref.inf }) |p, v| if (p < shape.rows) { + t.x[p * shape.n + p] = v; + }; + t.gamma[5] = ref.nan; + t.beta[6] = ref.inf; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(&t.stats)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.gamma)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.beta)); + t.out = try t.rig.output(t.count() * 4); + return true; + } + + /// One launch as image_encoder.zig's `normSilu` maps the rows: a thread an element, groups of 32 x 8. + pub fn run(t: *NormSilu) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| ref.bind(p.e, r, i); + ref.bind(p.e, t.out, 4); + p.e.setValue(extern struct { pixels: u32, channels: u32 }{ .pixels = @intCast(t.shape.rows), .channels = @intCast(t.shape.n) }, 5); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(32, 8, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *NormSilu) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *NormSilu, want: []f64, mag: []f64) !void { + try t.ends.size(t.count()); + const per = t.shape.n / 32; + for (t.x, 0..) |xv, i| { + const ch = i % t.shape.n; + const x: f64 = xv; + const m: f64 = t.stats[ch / per]; + const r: f64 = t.stats[32 + ch / per]; + const gm: f64 = t.gamma[ch]; + const b: f64 = t.beta[ch]; + const v = (x - m) * r * gm + b; + const vr = Range.of(x - m).fp32(0.5).mul(Range.of(r)).fp32(0.5).mul(Range.of(gm)).fp32(0.5).add(Range.of(b)).fp32(0.5); + t.ends.put(want, mag, i, v / (1 + @exp(-v)), ref.silu(vr)); + } + } + pub fn bounds(t: *NormSilu, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + pub fn intervals(t: *NormSilu, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } +}; diff --git a/zig/tests/contract/metal_h3_image_encoder_ref.zig b/zig/tests/contract/metal_h3_image_encoder_ref.zig new file mode 100644 index 00000000000..01a66d945e4 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_encoder_ref.zig @@ -0,0 +1,132 @@ +//! The edit encoder suite's shared parts: fp32 step ranges and their ends, fills, launch constants and binding. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +pub const c = contract.spec; +pub const g = contract.gates; + +/// Metal's error bounds in ulps with the encoder's options (safe math, precise functions). +pub const div_ulps = 2.5; +pub const sqrt_ulps = 3; +pub const exp_ulps = 4; + +/// GroupNorm's eps as the launcher passes it (picture_vae.zig's group_eps), and the pixels a part sums. +pub const eps: f32 = 1e-6; +pub const chunk = 256; + +pub const nan = std.math.nan(f32); +pub const inf = std.math.inf(f32); + +/// GroupNorm's parts for `pixels` (image_encoder.zig's `chunks`). +pub fn chunks(pixels: usize) usize { + return (pixels + chunk - 1) / chunk; +} + +/// The kernels' HieGroup constants for a pass over `pixels` of `channels`. +pub const HieGroup = extern struct { pixels: u32, channels: u32, chunk: u32, chunks: u32, centered: u32, eps: f32 }; + +pub fn group(channels: usize, pixels: usize, centered: bool) HieGroup { + return .{ .pixels = @intCast(pixels), .channels = @intCast(channels), .chunk = chunk, .chunks = @intCast(chunks(pixels)), .centered = @intFromBool(centered), .eps = eps }; +} + +pub fn bind(e: mtl.ComputeEncoder, r: rig_.Ref, index: usize) void { + e.setBuffer(r.buf, r.off, index); +} + +pub fn uniform(rng: std.Random, out: []f32, lo: f32, hi: f32) void { + for (out) |*v| v.* = lo + rng.float(f32) * (hi - lo); +} + +pub fn int(rng: std.Random, lo: i32, hi: i32) f32 { + return @floatFromInt(rng.intRangeAtMost(i32, lo, hi)); +} + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// Every value an fp32 step may give: each step widens both ends by its ulps. +pub const Range = struct { + lo: f64, + hi: f64, + + pub fn of(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// An fp32 step good to `ulps` units in the last place (a correctly rounded one: 0.5). + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * 0x1p-23; + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [4]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } + /// 1 / a, a positive. + pub fn recip(a: Range) Range { + return .{ .lo = 1 / a.hi, .hi = 1 / a.lo }; + } + /// sqrt(a), a not negative. + pub fn sqrt(a: Range) Range { + return .{ .lo = @sqrt(a.lo), .hi = @sqrt(a.hi) }; + } +}; + +/// v / (1 + exp(-v)) over v's range through the kernel's exp, add and division. +pub fn silu(v: Range) Range { + const e = (Range{ .lo = @exp(-v.hi), .hi = @exp(-v.lo) }).fp32(exp_ulps); + return v.mul(e.add(Range.of(1)).fp32(0.5).recip()).fp32(div_ulps); +} + +/// Each output's float64 value and its range, kept for the bounds and intervals hooks. +pub const Ends = struct { + a: std.mem.Allocator, + lo: []f64 = &.{}, + hi: []f64 = &.{}, + + pub fn deinit(e: *Ends) void { + e.a.free(e.lo); + e.a.free(e.hi); + e.lo = &.{}; + e.hi = &.{}; + } + + pub fn size(e: *Ends, n: usize) !void { + e.deinit(); + e.lo = try e.a.alloc(f64, n); + e.hi = try e.a.alloc(f64, n); + } + + pub fn put(e: *Ends, want: []f64, mag: []f64, i: usize, w: f64, r: Range) void { + want[i] = w; + mag[i] = if (std.math.isFinite(w)) @abs(w) else 0; + e.lo[i] = r.lo; + e.hi[i] = r.hi; + } + + /// The allowance about the float64 value: its range's farther end (a non-finite value is checked by class). + pub fn bounds(e: *const Ends, want: []const f64, allow: []f64) void { + for (allow, want, e.lo, e.hi) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) @max(@abs(w - lo), @abs(hi - w)) else 0; + } + + pub fn intervals(e: *const Ends, low: []f64, high: []f64) void { + @memcpy(low, e.lo); + @memcpy(high, e.hi); + } +}; + +/// A sum and its terms' magnitude, the magnitude 0 where it is not finite (the gate checks those by class). +pub fn total(terms: []const f64) struct { sum: f64, mag: f64 } { + var s: f64 = 0; + var m: f64 = 0; + for (terms) |v| { + s += v; + m += @abs(v); + } + return .{ .sum = s, .mag = if (std.math.isFinite(m)) m else 0 }; +} From 090b8d4592cf6b1a494e16f731efeb99d90891ee Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:16:43 +0000 Subject: [PATCH 007/361] kernel contract: MiniMax-H3-Image's image decoder kernels, nine registrations and ten planted controls; four kernels reserve their group sizes --- zig/kernels/metal/h3/image_decoder.metal | 8 +- zig/src/core/contract/h3_image_records.zig | 11 +- zig/tests/contract/metal_h3_image_decoder.zig | 129 ++++++- .../contract/metal_h3_image_decoder_gemm.zig | 198 +++++++++++ .../contract/metal_h3_image_decoder_heads.zig | 290 +++++++++++++++ .../contract/metal_h3_image_decoder_norms.zig | 195 +++++++++++ .../contract/metal_h3_image_decoder_parts.zig | 331 ++++++++++++++++++ .../contract/metal_h3_image_decoder_rows.zig | 304 ++++++++++++++++ 8 files changed, 1455 insertions(+), 11 deletions(-) create mode 100644 zig/tests/contract/metal_h3_image_decoder_gemm.zig create mode 100644 zig/tests/contract/metal_h3_image_decoder_heads.zig create mode 100644 zig/tests/contract/metal_h3_image_decoder_norms.zig create mode 100644 zig/tests/contract/metal_h3_image_decoder_parts.zig create mode 100644 zig/tests/contract/metal_h3_image_decoder_rows.zig diff --git a/zig/kernels/metal/h3/image_decoder.metal b/zig/kernels/metal/h3/image_decoder.metal index 256d97e0092..178c8dbc601 100644 --- a/zig/kernels/metal/h3/image_decoder.metal +++ b/zig/kernels/metal/h3/image_decoder.metal @@ -23,7 +23,7 @@ struct H3dShape { }; // Each tile's cells rounded to bf16, then post_quant_conv (24 to 24 with bias) to bf16: tok [tiles * h * w, 24]. -[[kernel]] void h3d_post_quant( +[[max_total_threads_per_threadgroup(192)]] [[kernel]] void h3d_post_quant( const device float* lat [[buffer(0)]], const device uint2* org [[buffer(1)]], const device bfloat* pw [[buffer(2)]], const device bfloat* pb [[buffer(3)]], device bfloat* tok [[buffer(4)]], constant H3dShape& p [[buffer(5)]], uint2 at [[thread_position_in_grid]]) { @@ -40,7 +40,7 @@ struct H3dShape { } // A tile's sequence: x_embedder (24 to 1,024 with bias) on its cells to bf16, then the 4 registers and a zero token. -[[kernel]] void h3d_embed( +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void h3d_embed( const device bfloat* tok [[buffer(0)]], const device bfloat* ew [[buffer(1)]], const device bfloat* eb [[buffer(2)]], const device bfloat* reg [[buffer(3)]], device bfloat* x [[buffer(4)]], constant H3dShape& p [[buffer(5)]], uint2 at [[thread_position_in_grid]]) { @@ -194,7 +194,7 @@ inline float h3d_total(float v, threadgroup float* part, uint lane, uint sg) { } // Per row and head: q and k RMS-normed (no weight) to bf16, their first 32 dims turned half-style in bf16; v copied. -[[kernel]] void h3d_heads( +[[max_total_threads_per_threadgroup(32)]] [[kernel]] void h3d_heads( const device bfloat* qkv [[buffer(0)]], const device bfloat* cs [[buffer(1)]], const device bfloat* sn [[buffer(2)]], device bfloat* q [[buffer(3)]], device bfloat* k [[buffer(4)]], device bfloat* v [[buffer(5)]], constant H3dShape& p [[buffer(6)]], uint2 tg [[threadgroup_position_in_grid]], @@ -281,7 +281,7 @@ inline float h3d_total(float v, threadgroup float* part, uint lane, uint sg) { } // act = bf16(bf16(SiLU(gate)) * value), w1's rows read as [gate 4,096 | value 4,096]. Threads [4,096, m]. -[[kernel]] void h3d_swiglu( +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void h3d_swiglu( const device bfloat* wide [[buffer(0)]], device bfloat* act [[buffer(1)]], constant H3dShape& p [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { if (at.x >= 4096 || at.y >= p.m) return; diff --git a/zig/src/core/contract/h3_image_records.zig b/zig/src/core/contract/h3_image_records.zig index 9ec93eb6886..57357b9414b 100644 --- a/zig/src/core/contract/h3_image_records.zig +++ b/zig/src/core/contract/h3_image_records.zig @@ -8,7 +8,16 @@ pub const encoder = [_]M{ .{ .name = "minimax image encoder hie_norm_silu", .threads = 256, .tg_memory = 0, .reserved = 256 }, }; pub const prompt = [_]M{}; -pub const decoder = [_]M{}; +pub const decoder = [_]M{ + .{ .name = "minimax image decoder h3d_post_quant", .threads = 192, .tg_memory = 0, .reserved = 192 }, + .{ .name = "minimax image decoder h3d_embed", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "minimax image decoder h3d_rms_norm", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "minimax image decoder h3d_layer_norm", .threads = 256, .tg_memory = 64, .reserved = 256 }, + .{ .name = "minimax image decoder h3d_gemm", .threads = 128, .tg_memory = 18432, .reserved = 128 }, + .{ .name = "minimax image decoder h3d_heads", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "minimax image decoder h3d_attention", .threads = 256, .tg_memory = 11264, .reserved = 256 }, + .{ .name = "minimax image decoder h3d_swiglu", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; pub const records = encoder ++ prompt ++ decoder; test "the MiniMax-H3-Image launches fit every Apple family" { diff --git a/zig/tests/contract/metal_h3_image_decoder.zig b/zig/tests/contract/metal_h3_image_decoder.zig index e7a8b24beb0..170ed0f63b5 100644 --- a/zig/tests/contract/metal_h3_image_decoder.zig +++ b/zig/tests/contract/metal_h3_image_decoder.zig @@ -1,24 +1,141 @@ -//! MiniMax-H3-Image's decoder kernels (image_decoder.metal) under the contract: each against its own formula in float64. +//! MiniMax-H3-Image's decoder kernels (image_decoder.metal) under the contract: each against its formula in float64. const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); const common = @import("metal_h3_image_common.zig"); +const parts = @import("metal_h3_image_decoder_parts.zig"); +const rows = @import("metal_h3_image_decoder_rows.zig"); +const norms = @import("metal_h3_image_decoder_norms.zig"); +const gemm = @import("metal_h3_image_decoder_gemm.zig"); +const heads = @import("metal_h3_image_decoder_heads.zig"); const g = contract.gates; +/// A registration: one kernel at one form; the gemm's LayerScale form is mode 1 of h3d_gemm. +const Kind = enum { post_quant, embed, rms_norm, layer_norm, gemm, gemm_scale, heads, attention, swiglu }; + +const kinds = [_]Kind{ .post_quant, .embed, .rms_norm, .layer_norm, .gemm, .gemm_scale, .heads, .attention, .swiglu }; + +fn Of(comptime kind: Kind) type { + return switch (kind) { + .post_quant => rows.PostQuant, + .embed => rows.Embed, + .rms_norm => norms.RmsNorm, + .layer_norm => norms.LayerNorm, + .gemm, .gemm_scale => gemm.Gemm, + .heads => heads.Heads, + .attention => heads.Attention, + .swiglu => rows.Swiglu, + }; +} + +fn function(comptime kind: Kind) []const u8 { + return switch (kind) { + .gemm, .gemm_scale => "h3d_gemm", + else => "h3d_" ++ @tagName(kind), + }; +} + +fn label(comptime kind: Kind) []const u8 { + return comptime common.name(.decoder, function(kind)) ++ (if (kind == .gemm_scale) " layer scale" else ""); +} + +fn initial(comptime kind: Kind) Of(kind) { + return switch (kind) { + .gemm => .{ .layer_scale = false }, + .gemm_scale => .{ .layer_scale = true }, + else => .{}, + }; +} + +/// A planted control: the registration it breaks, the gate that must catch it, and its one source edit. +const Control = struct { kind: Kind, gate: g.Gate, what: []const u8, old: []const u8, new: []const u8 }; + +const controls = [_]Control{ + .{ .kind = .post_quant, .gate = .shapes, .what = "drops the latent's bf16 rounding point", .old = "float(bfloat(lat[k * plane + r * p.cols + c]))", .new = "lat[k * plane + r * p.cols + c]" }, + .{ .kind = .embed, .gate = .shapes, .what = "puts the registers after the zero token", .old = "} else if (t < cells + 4) {\n v = reg[(t - cells) * 1024 + at.x];", .new = "} else if (t > cells) {\n v = reg[(t - cells - 1) * 1024 + at.x];" }, + .{ .kind = .rms_norm, .gate = .sums, .what = "sums its simdgroups in half", .old = "v = simd_sum(v);", .new = "v = float(simd_sum(half(v)));" }, + .{ .kind = .layer_norm, .gate = .shapes, .what = "drops its mean", .old = "const float mean = h3d_total(s, sums, lane, sg) / 1024.0f;", .new = "const float mean = 0.0f * h3d_total(s, sums, lane, sg);" }, + .{ .kind = .gemm, .gate = .shapes, .what = "drops its last K step", .old = "for (uint k0 = 0; k0 < p.k; k0 += BK) {", .new = "for (uint k0 = 0; k0 + BK < p.k; k0 += BK) {" }, + .{ .kind = .gemm_scale, .gate = .shapes, .what = "adds LayerScale's product unrounded", .old = "float(bfloat(out * float(s[col])))", .new = "out * float(s[col])" }, + .{ .kind = .heads, .gate = .shapes, .what = "turns the second half of each head", .old = "const float a = float(src[part * 64 + lane]);\n const float z = float(src[part * 64 + 32 + lane]);", .new = "const float a = float(src[part * 64 + 32 + lane]);\n const float z = float(src[part * 64 + lane]);" }, + .{ .kind = .attention, .gate = .shapes, .what = "drops its last key", .old = "for (uint key = 0; key < T; key++) {", .new = "for (uint key = 0; key + 1 < T; key++) {" }, + .{ .kind = .swiglu, .gate = .shapes, .what = "swaps gate and value", .old = "const float g = float(r[at.x]);\n const float silu = float(bfloat(g / (1.0f + precise::exp(-g))));\n act[ulong(at.y) * 4096 + at.x] = bfloat(silu * float(r[4096 + at.x]));", .new = "const float g = float(r[4096 + at.x]);\n const float silu = float(bfloat(g / (1.0f + precise::exp(-g))));\n act[ulong(at.y) * 4096 + at.x] = bfloat(silu * float(r[at.x]));" }, + .{ .kind = .swiglu, .gate = .nonfinite, .what = "takes a NaN gate as zero", .old = "const float g = float(r[at.x]);", .new = "const float g = isnan(float(r[at.x])) ? 0.0f : float(r[at.x]);" }, +}; + pub const Suite = struct { a: std.mem.Allocator, + libs: std.ArrayList(mtl.Library) = .empty, + names: std.ArrayList([]u8) = .empty, + cases: std.ArrayList(Owned) = .empty, + + /// A registration's test, freed with the suite. + const Owned = struct { ptr: *anyopaque, free: *const fn (*anyopaque, std.mem.Allocator) void }; + + fn Free(comptime T: type) type { + return struct { + fn free(p: *anyopaque, a: std.mem.Allocator) void { + const t: *T = @ptrCast(@alignCast(p)); + t.deinit(); + a.destroy(t); + } + }; + } + + /// `kind`'s test on `lib`'s pipeline, named `name`, appended to `out` (a control when `control` names a gate). + fn add(s: *Suite, comptime kind: Kind, device: mtl.Device, queue: mtl.Queue, lib: mtl.Library, name: []const u8, control: ?g.Gate, out: *std.ArrayList(g.Kernel)) !void { + const T = parts.Case(Of(kind)); + const pipe = try mtl.Pipeline.init(device, lib, function(kind), false); + const t = s.a.create(T) catch |err| { + pipe.deinit(); + return err; + }; + t.* = T.init(s.a, device, queue, pipe, name, initial(kind)); + s.cases.append(s.a, .{ .ptr = t, .free = Free(T).free }) catch |err| { + Free(T).free(t, s.a); + return err; + }; + try out.append(s.a, t.kernel(control)); + } pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { - _ = device; - _ = queue; - _ = kernels; - _ = only; const s = try a.create(Suite); s.* = .{ .a = a }; + errdefer s.destroy(); + const lib = try common.library(device, .decoder, common.source(.decoder)); + s.libs.append(a, lib) catch |err| { + lib.deinit(); + return err; + }; + inline for (kinds) |kind| if (common.keep(only, label(kind))) try s.add(kind, device, queue, lib, label(kind), null, kernels); + inline for (controls) |x| { + const name = try std.fmt.allocPrint(a, "{s} control: {s}", .{ label(x.kind), x.what }); + s.names.append(a, name) catch |err| { + a.free(name); + return err; + }; + if (common.keep(only, name)) { + const text = try common.edited(a, .decoder, x.old, x.new); + defer a.free(text); + const edited = try common.library(device, .decoder, text); + s.libs.append(a, edited) catch |err| { + edited.deinit(); + return err; + }; + try s.add(x.kind, device, queue, edited, name, x.gate, kernels); + } + } return s; } pub fn destroy(s: *Suite) void { - s.a.destroy(s); + const a = s.a; + for (s.cases.items) |o| o.free(o.ptr, a); + s.cases.deinit(a); + for (s.libs.items) |l| l.deinit(); + s.libs.deinit(a); + for (s.names.items) |n| a.free(n); + s.names.deinit(a); + a.destroy(s); } }; diff --git a/zig/tests/contract/metal_h3_image_decoder_gemm.zig b/zig/tests/contract/metal_h3_image_decoder_gemm.zig new file mode 100644 index 00000000000..a2a654e84d4 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_decoder_gemm.zig @@ -0,0 +1,198 @@ +//! h3d_gemm under the contract: y = bf16(x w^T + b), and its LayerScale form y += bf16(that s), against float64. +const std = @import("std"); +const mtl = @import("metal"); +const parts = @import("metal_h3_image_decoder_parts.zig"); + +const c = parts.c; +const Range = parts.Range; +const Ends = parts.Ends; +const Sum = parts.Sum; +const bf = parts.bf; +const value = parts.value; +const W = parts.W; +const F = parts.F; + +/// Rows a pass multiplies: one tile of 16 x 16 cells and its 5 tokens after, the batch of 16, one small tile of 65. +const passes = [_]usize{ 261, 16 * 261, 65 }; + +fn served(comptime nk: []const [2]usize) [passes.len * nk.len]c.Shape { + var out: [passes.len * nk.len]c.Shape = undefined; + for (passes, 0..) |r, i| for (nk, 0..) |p, j| { + out[i * nk.len + j] = .{ .rows = r, .n = p[0], .k = p[1] }; + }; + return out; +} + +/// to_qkv (3,072 x 1,024), w1 (8,192 x 1,024) and proj_out (768 x 1,024). +const plain = served(&.{ .{ 3 * W, W }, .{ 2 * F, W }, .{ 768, W } }); +/// to_out (1,024 x 1,024) and w2 (1,024 x 4,096), each added to the stream through its LayerScale. +const scaled = served(&.{ .{ W, W }, .{ W, F } }); + +/// The k-deep chain of the simdgroup products' fp32 sums, then the bias. +fn chain(s: c.Shape) usize { + return s.k + 1; +} + +/// float64 x . w and sum |x_i w_i| over fp32 copies of bf16 values. +fn dot(x: []const f32, w: []const f32) [2]f64 { + var s: @Vector(8, f64) = @splat(0); + var m: @Vector(8, f64) = @splat(0); + var i: usize = 0; + while (i + 8 <= x.len) : (i += 8) { + const a: @Vector(8, f64) = @floatCast(@as(@Vector(8, f32), x[i..][0..8].*)); + const b: @Vector(8, f64) = @floatCast(@as(@Vector(8, f32), w[i..][0..8].*)); + s += a * b; + m += @abs(a * b); + } + var sv = @reduce(.Add, s); + var mv = @reduce(.Add, m); + while (i < x.len) : (i += 1) { + const p = @as(f64, x[i]) * w[i]; + sv += p; + mv += @abs(p); + } + return .{ sv, mv }; +} + +fn widen(a: std.mem.Allocator, b: []const u16) ![]f32 { + const out = try a.alloc(f32, b.len); + for (out, b) |*o, v| o.* = c.fromBf16(v); + return out; +} + +pub const Gemm = struct { + /// The LayerScale form (mode 1): y = bf16(y + bf16(bf16(x w^T + b) s)), in place. + layer_scale: bool, + x: []f32 = &.{}, + w: []f32 = &.{}, + b: []u16 = &.{}, + s: []u16 = &.{}, + y0: []u16 = &.{}, + + /// Rows: rows; n: the projection's outputs (64 a tile); k: its inputs (32 a step). + pub fn spec(name: []const u8, k: Gemm) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = chain, + .mids = if (k.layer_scale) 2 else 0, + .out = .bf16, + .in_place = k.layer_scale, + .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 32, .step = 32, .min = 32 } }, + .served = if (k.layer_scale) &scaled else &plain, + }; + } + + /// Gate 4's rows: integers, k's second half repeating the first, its weights negated plus 1 on 4: every sum is 4. + fn mirror(k: *Gemm, rng: std.Random, xb: []u16, wb: []u16, s: c.Shape) void { + const h = s.k / 2; + for (0..s.rows) |r| for (0..h) |i| { + const v = if (i < 4) 1 else rng.intRangeAtMost(i32, 1, 48); + xb[r * s.k + i] = parts.integer(v); + xb[r * s.k + h + i] = parts.integer(v); + }; + for (0..s.n) |o| for (0..h) |i| { + const v = rng.intRangeAtMost(i32, 0, 48); + wb[o * s.k + i] = parts.integer(v); + wb[o * s.k + h + i] = parts.integer(-v + @as(i32, if (i < 4) 1 else 0)); + }; + @memset(k.b, 0); + @memset(k.s, parts.integer(2)); + parts.integers(rng, k.y0, -8, 8); + } + + pub fn prepare(k: *Gemm, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.n == 0 or s.n % 64 != 0 or s.k == 0 or s.k % 32 != 0) return false; + const al = t.host(); + const xb = try al.alloc(u16, s.rows * s.k); + const wb = try al.alloc(u16, s.n * s.k); + k.b = try al.alloc(u16, s.n); + k.s = try al.alloc(u16, s.n); + k.y0 = try al.alloc(u16, s.rows * s.n); + if (t.fill == .stress) k.mirror(rng, xb, wb, s) else { + parts.uniform(rng, xb, -2, 2); + const a: f32 = @floatCast(@sqrt(3.0 / @as(f64, @floatFromInt(s.k)))); + parts.uniform(rng, wb, -a, a); + parts.uniform(rng, k.b, -0.1, 0.1); + parts.uniform(rng, k.s, 0.1, 0.5); + parts.uniform(rng, k.y0, -2, 2); + } + if (t.fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, s.k / 3 }, .{ 1, s.k / 2 }, .{ 2, s.k - 1 }, .{ 3, 0 }, .{ 3, s.k - 1 } }; + for (at, parts.plants) |p, v| if (p[0] < s.rows) { + xb[p[0] * s.k + p[1]] = v; + }; + // the LayerScale form's old stream value and scale too + if (k.layer_scale and s.rows > 4) k.y0[4 * s.n + 3] = parts.nan16; + if (k.layer_scale) k.s[5] = parts.inf16; + } + k.x = try widen(al, xb); + k.w = try widen(al, wb); + try t.input(xb); + try t.input(wb); + try t.input(k.b); + if (k.layer_scale) try t.input(k.s); + try t.output(s.rows * s.n * 2); + return true; + } + + /// The launcher's gemm: 64 x 64 tiles a group of 128; mode 0 binds the bias again where the scale goes. + pub fn launch(k: *Gemm, t: anytype, e: mtl.ComputeEncoder) void { + const s = t.shape; + const out: usize = if (k.layer_scale) 4 else 3; + // the stream the LayerScale form adds into, fresh before every run + if (k.layer_scale) @memcpy(t.rig.bytes(t.bufs[out], k.y0.len * 2), std.mem.sliceAsBytes(k.y0)); + for (0..3) |i| t.bind(e, i, i); + t.bind(e, if (k.layer_scale) 3 else 2, 3); + t.bind(e, out, 4); + e.setValue(parts.Shape{ .m = @intCast(s.rows), .n = @intCast(s.n), .k = @intCast(s.k), .mode = @intFromBool(k.layer_scale) }, 5); + e.dispatchGroups(mtl.Size.of(s.n / 64, (s.rows + 63) / 64, 1), mtl.Size.of(128, 1, 1)); + } + + pub fn count(_: *Gemm, s: c.Shape) usize { + return s.rows * s.n; + } + + /// Output (r, o) from its sum: the bias and one rounding, then for LayerScale the scale and the old value. + fn finish(k: *const Gemm, s: c.Shape, sum: Sum.Out, r: usize, o: usize, ends: *Ends, want: []f64, mag: []f64) void { + const at = r * s.n + o; + const b = value(k.b[o]); + const v = bf(sum.v + b); + const range = sum.r.add(Range.of(b)).fp32(0.5).bf16(); + if (!k.layer_scale) return ends.put(want, mag, at, v, range); + const sc = value(k.s[o]); + const old = value(k.y0[at]); + const y = range.mul(Range.of(sc)).fp32(0.5).bf16().add(Range.of(old)).fp32(0.5).bf16(); + ends.put(want, mag, at, bf(old + bf(v * sc)), y); + } + + const Job = struct { + k: *const Gemm, + s: c.Shape, + sum: Sum, + ends: *Ends, + want: []f64, + mag: []f64, + + fn rows(j: Job, from: usize, to: usize) void { + const kk = j.s.k; + for (from..to) |r| for (0..j.s.n) |o| { + const d = dot(j.k.x[r * kk ..][0..kk], j.k.w[o * kk ..][0..kk]); + j.k.finish(j.s, .{ .v = d[0], .r = j.sum.spread(d[0], d[1], kk) }, r, o, j.ends, j.want, j.mag); + }; + } + }; + + pub fn outputs(k: *Gemm, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + const s = t.shape; + if (sum.acc == null) return parts.parallel(s.rows, Job{ .k = k, .s = s, .sum = sum, .ends = ends, .want = want, .mag = mag }, Job.rows); + // gate 4's replays: each output's terms in the accumulator and order asked + const terms = try t.a.alloc(f64, s.k); + defer t.a.free(terms); + for (0..s.rows) |r| for (0..s.n) |o| { + for (terms, k.x[r * s.k ..][0..s.k], k.w[o * s.k ..][0..s.k]) |*p, a, b| p.* = @as(f64, a) * b; + k.finish(s, sum.of(terms, s.k), r, o, ends, want, mag); + }; + } +}; diff --git a/zig/tests/contract/metal_h3_image_decoder_heads.zig b/zig/tests/contract/metal_h3_image_decoder_heads.zig new file mode 100644 index 00000000000..e045d950a2b --- /dev/null +++ b/zig/tests/contract/metal_h3_image_decoder_heads.zig @@ -0,0 +1,290 @@ +//! h3d_heads and h3d_attention under the contract: q/k norms and rotary at their bf16 points, attention's range. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const parts = @import("metal_h3_image_decoder_parts.zig"); + +const c = parts.c; +const ar = contract.attention_range; +const Range = parts.Range; +const Ends = parts.Ends; +const Sum = parts.Sum; +const bf = parts.bf; +const value = parts.value; +const W = parts.W; +const D = parts.D; +const H = parts.heads; +/// The rotary dims at the front of each q and k head, as half-style pairs (i, i + 16). +const R = 32; + +/// One tile of 261 tokens, the batch of 16 tiles, one small tile of 65 tokens. +const tiles_served = [_][2]usize{ .{ 1, 261 }, .{ 16, 261 }, .{ 1, 65 } }; + +// --- h3d_heads: per row and head, q and k RMS-normed (no weight) to bf16, the first 32 dims turned; v copied ------ + +pub const Heads = struct { + qkv: []u16 = &.{}, + cs: []u16 = &.{}, + sn: []u16 = &.{}, + + /// A lane's two squares, then the simdgroup's 5-level tree. + fn depth(_: c.Shape) usize { + return 2 + 5; + } + + /// Rows: tiles; n: tokens a tile; k: the head dim each norm sums. Outputs: q, k and v [tiles, 16, tokens, 64]. + pub fn spec(name: []const u8, _: Heads) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = depth, + .ops = 2 * (parts.div_ulps + parts.rsqrt_ulps) + 3, + .mids = 3, + .out = .bf16, + .served = &.{ .{ .rows = tiles_served[0][0], .n = tiles_served[0][1], .k = D }, .{ .rows = tiles_served[1][0], .n = tiles_served[1][1], .k = D }, .{ .rows = tiles_served[2][0], .n = tiles_served[2][1], .k = D } }, + }; + } + + pub fn prepare(k: *Heads, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.n == 0 or s.k != D) return false; + const m = s.rows * s.n; + const al = t.host(); + k.qkv = try al.alloc(u16, m * 3 * W); + k.cs = try al.alloc(u16, s.n * R); + k.sn = try al.alloc(u16, s.n * R); + parts.uniform(rng, k.qkv, -3, 3); + // gate 4: q and k integers whose squares' sums pass fp16's range and stay exact in fp32 + if (t.fill == .stress) for (0..m * H) |i| parts.integers(rng, k.qkv[i * 3 * D ..][0 .. 2 * D], -64, 64); + for (k.cs, k.sn) |*cv, *sv| { + const angle = rng.float(f32) * 2 * std.math.pi; + cv.* = c.toBf16(@cos(angle)); + sv.* = c.toBf16(@sin(angle)); + } + if (t.fill == .nonfinite) { + // NaN in a q's first half, +Inf in a k's second half, -Inf in a v, both infinities in one q + const at = [_][2]usize{ .{ 0, 5 }, .{ 1, 3 * D + D + 40 }, .{ 2, 6 * D + 2 * D + 7 }, .{ 3, 9 * D }, .{ 3, 9 * D + 33 } }; + for (at, parts.plants) |p, b| if (p[0] < m) { + k.qkv[p[0] * 3 * W + p[1]] = b; + }; + } + try t.input(k.qkv); + try t.input(k.cs); + try t.input(k.sn); + for (0..3) |_| try t.output(m * W * 2); + return true; + } + + /// A block's heads: a simdgroup a row and head. + pub fn launch(_: *Heads, t: anytype, e: mtl.ComputeEncoder) void { + const s = t.shape; + for (0..6) |i| t.bind(e, i, i); + e.setValue(parts.Shape{ .tiles = @intCast(s.rows), .tokens = @intCast(s.n), .m = @intCast(s.rows * s.n) }, 6); + e.dispatchGroups(mtl.Size.of(s.rows * s.n, H, 1), mtl.Size.of(32, 1, 1)); + } + + pub fn count(_: *Heads, s: c.Shape) usize { + return 3 * s.rows * s.n * W; + } + + const Job = struct { + k: *const Heads, + s: c.Shape, + sum: Sum, + ends: *Ends, + want: []f64, + mag: []f64, + + /// Rows [from, to): each head's q and k normed and turned, and v. + fn rows(j: Job, from: usize, to: usize) void { + const m = j.s.rows * j.s.n; + for (from..to) |r| for (0..H) |hd| { + const tk = r % j.s.n; + const to_at = ((r / j.s.n * H + hd) * j.s.n + tk) * D; + const src = j.k.qkv[r * 3 * W + hd * 3 * D ..][0 .. 3 * D]; + for (0..2) |part| j.norm(src[part * D ..][0..D], j.k.cs[tk * R ..][0..R], j.k.sn[tk * R ..][0..R], part * m * W + to_at); + for (src[2 * D ..][0..D], 0..) |b, i| j.ends.put(j.want, j.mag, 2 * m * W + to_at + i, value(b), Range.of(value(b))); + }; + } + + fn norm(j: Job, src: []const u16, cs: []const u16, sn: []const u16, at: usize) void { + var x: [D]f64 = undefined; + var terms: [D]f64 = undefined; + for (&x, &terms, src) |*v, *q, b| { + v.* = value(b); + q.* = v.* * v.*; + } + const ss = j.sum.of(&terms, depth(j.s)); + const inv = parts.invNorm(ss.r, D); + const inv64 = 1 / @sqrt(ss.v / D + parts.eps); + var na: [R]f64 = undefined; + var nr: [R]Range = undefined; + for (&na, &nr, x[0..R]) |*v, *vr, xv| { + v.* = bf(xv * inv64); + vr.* = Range.of(xv).mul(inv).fp32(0.5).bf16(); + } + for (0..R) |i| { + // rotate-half: the partner 16 dims away, negated below the half + const p = i ^ 16; + const sign: f64 = if (i < 16) -1 else 1; + const cv = value(cs[i]); + const sv = sign * value(sn[i]); + const y = bf(bf(na[i] * cv) + bf(na[p] * sv)); + const yr = nr[i].mul(Range.of(cv)).fp32(0.5).bf16().add(nr[p].mul(Range.of(sv)).fp32(0.5).bf16()).fp32(0.5).bf16(); + j.ends.put(j.want, j.mag, at + i, y, yr); + const z = x[R + i]; + j.ends.put(j.want, j.mag, at + R + i, bf(z * inv64), Range.of(z).mul(inv).fp32(0.5).bf16()); + } + } + }; + + pub fn outputs(k: *Heads, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + const s = t.shape; + parts.parallel(s.rows * s.n, Job{ .k = k, .s = s, .sum = sum, .ends = ends, .want = want, .mag = mag }, Job.rows); + } +}; + +// --- h3d_attention: softmax(q k^T / 8) v over a tile's tokens, fp32 scores, softmax and sums --------------------- + +/// Keys the kernel holds a query: 9 a lane. +const slots = 9 * 32; + +/// The kernel's fp32 steps: a 64-deep score, precise exp, a lane's 9 keys and a tree, a chain over the keys, division. +fn form(tokens: usize) ar.Form { + return .{ .score = D + 1, .fast_exp = false, .chunk_exp = false, .p_rel = 0, .num = @floatFromInt(tokens + 1), .den = 9 + 5 + 1, .div = 2 * parts.div_ulps, .exp_ulps = .{ parts.exp_ulps, 0 } }; +} + +pub const Attention = struct { + q: []u16 = &.{}, + kk: []u16 = &.{}, + v: []u16 = &.{}, + + /// A score's 64-deep chain, the softmax's exp and total, then the values' chain over every key. + fn depth(s: c.Shape) usize { + return D + s.k + 16; + } + + /// Rows: tiles; n: the 1,024 outputs a query (16 heads of 64); k: tokens a tile, each a query and a key. + pub fn spec(name: []const u8, _: Attention) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = depth, + .ops = 2 * (parts.exp_ulps + parts.div_ulps) + 2, + .out = .bf16, + .tiles = .{ .{}, .{}, .{ .size = 32, .min = parts.suffix + 1 } }, + .served = &.{ .{ .rows = tiles_served[0][0], .n = W, .k = tiles_served[0][1] }, .{ .rows = tiles_served[1][0], .n = W, .k = tiles_served[1][1] }, .{ .rows = tiles_served[2][0], .n = W, .k = tiles_served[2][1] } }, + }; + } + + pub fn prepare(k: *Attention, t: anytype, rng: std.Random) !bool { + const s = t.shape; + const T = s.k; + if (s.rows == 0 or s.n != W or T == 0 or T > slots) return false; + const n = s.rows * H * T * D; + const al = t.host(); + k.q = try al.alloc(u16, n); + k.kk = try al.alloc(u16, n); + k.v = try al.alloc(u16, n); + parts.uniform(rng, k.q, -1, 1); + parts.uniform(rng, k.kk, -1, 1); + parts.uniform(rng, k.v, -2, 2); + if (t.fill == .stress) { + // gate 4: every score 0, so p is 1; each value column's integers reach 2^17 and cancel to 4 + @memset(k.q, 0); + for (0..s.rows * H) |pair| for (0..D) |d| for (0..T) |key| { + k.v[(pair * T + key) * D + d] = parts.integer(even(key, T)); + }; + } + if (t.fill == .nonfinite) { + // (tile, head, token, dim): a NaN query, an infinite key, -Inf and both infinities and a NaN as values + const at = [_][4]usize{ .{ 0, 0, 1, 3 }, .{ 1, 1, 2, 5 }, .{ 2, 2, 4, 7 }, .{ 3, 3, 0, 9 }, .{ 3, 3, 1, 9 }, .{ 4, 4, 5, 11 } }; + const into = [_]*[]u16{ &k.q, &k.kk, &k.v, &k.v, &k.v, &k.v }; + for (at, into, parts.plants ++ [_]u16{parts.nan16}) |p, buf, b| { + buf.*[((@min(p[0], s.rows - 1) * H + p[1]) * T + p[2] % T) * D + p[3]] = b; + } + } + try t.input(k.q); + try t.input(k.kk); + try t.input(k.v); + try t.output(s.rows * T * W * 2); + return true; + } + + /// Gate 4's value `key` of a column: 127 or 2,040, then their negatives plus 1 on 4; integer partials, sum 4. + fn even(key: usize, tokens: usize) i32 { + const half = tokens / 2; + if (key >= 2 * half) return 0; + const at = if (key < half) key else key - half; + const big: i32 = if (at % 2 == 0) 127 else 2040; + return if (key < half) big else @as(i32, if (at < 8 and at % 2 == 0) 1 else 0) - big; + } + + /// A block's attention: groups of 8 queries (256 threads) by 16 heads by tiles. + pub fn launch(_: *Attention, t: anytype, e: mtl.ComputeEncoder) void { + const s = t.shape; + for (0..4) |i| t.bind(e, i, i); + e.setValue(parts.Shape{ .tiles = @intCast(s.rows), .tokens = @intCast(s.k), .m = @intCast(s.rows * s.k) }, 4); + e.dispatchGroups(mtl.Size.of((s.k + 7) / 8, H, s.rows), mtl.Size.of(256, 1, 1)); + } + + pub fn count(_: *Attention, s: c.Shape) usize { + return s.rows * s.k * W; + } + + const Job = struct { + k: *const Attention, + s: c.Shape, + ends: *Ends, + want: []f64, + mag: []f64, + + /// (tile, head) pairs [from, to): each query's outputs within attention_range's float64 range. + fn pairs(j: Job, from: usize, to: usize) void { + const T = j.s.k; + var keys: [slots * D]f64 = undefined; + var vals: [slots * D]f64 = undefined; + var w: [slots]f64 = undefined; + var tau: [slots]f64 = undefined; + var q: [D]f64 = undefined; + var point: [D]f64 = undefined; + var half: [D]f64 = undefined; + for (from..to) |pair| { + const base = pair * T * D; + for (keys[0 .. T * D], vals[0 .. T * D], j.k.kk[base..][0 .. T * D], j.k.v[base..][0 .. T * D]) |*a, *b, x, y| { + a.* = value(x); + b.* = value(y); + } + for (0..T) |qi| { + for (&q, j.k.q[base + qi * D ..][0..D]) |*a, x| a.* = value(x); + ar.head(&q, keys[0 .. T * D], vals[0 .. T * D], T, D, parts.scale, form(T), w[0..T], tau[0..T], &point, &half); + const at = ((pair / H) * T + qi) * W + (pair % H) * D; + for (point, half, 0..) |p, hf, d| { + const e = ar.intervalBf16(p, hf, 0, 0); + j.ends.put(j.want, j.mag, at + d, bf(p), .{ .lo = e[0], .hi = e[1] }); + } + } + } + } + }; + + pub fn outputs(k: *Attention, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + const s = t.shape; + if (t.fill == .stress) return k.equal(s, sum, ends, want, mag); + parts.parallel(s.rows * H, Job{ .k = k, .s = s, .ends = ends, .want = want, .mag = mag }, Job.pairs); + } + + /// Gate 4's equal scores: each output is its value column's sum over the keys' total, by the fast division. + fn equal(k: *const Attention, s: c.Shape, sum: Sum, ends: *Ends, want: []f64, mag: []f64) void { + const T = s.k; + var col: [slots]f64 = undefined; + const ones: [slots]f64 = @splat(1); + const total = sum.of(ones[0..T], T); + for (0..s.rows * H) |pair| for (0..D) |d| { + for (col[0..T], 0..) |*x, key| x.* = value(k.v[(pair * T + key) * D + d]); + const o = sum.of(col[0..T], T).v / total.v; + const range = Range.of(o).fp32(parts.div_ulps).bf16(); + for (0..T) |qi| ends.put(want, mag, ((pair / H) * T + qi) * W + (pair % H) * D + d, bf(o), range); + }; + } +}; diff --git a/zig/tests/contract/metal_h3_image_decoder_norms.zig b/zig/tests/contract/metal_h3_image_decoder_norms.zig new file mode 100644 index 00000000000..4729822e3c3 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_decoder_norms.zig @@ -0,0 +1,195 @@ +//! h3d_rms_norm and h3d_layer_norm under the contract: fp32 statistics, one bf16 rounding, fp32 sums proven in gate 4. +const std = @import("std"); +const mtl = @import("metal"); +const parts = @import("metal_h3_image_decoder_parts.zig"); + +const c = parts.c; +const Range = parts.Range; +const Ends = parts.Ends; +const Sum = parts.Sum; +const bf = parts.bf; +const value = parts.value; +const W = parts.W; +const Wf: f64 = W; + +/// A thread's 4 values in turn, the simdgroup's 5-level tree, then the 8 simdgroups' parts in turn. +fn depth(_: c.Shape) usize { + return 4 + 5 + 8; +} + +/// The variance's chain: each term's subtraction and square, then the same sum. +fn varianceDepth(s: c.Shape) usize { + return depth(s) + 3; +} + +/// Rows of 1,024: one tile of 261 tokens, the batch of 16 tiles, one small tile of 65. +const served = [_]c.Shape{ .{ .rows = 261, .n = W, .k = W }, .{ .rows = 4176, .n = W, .k = W }, .{ .rows = 65, .n = W, .k = W } }; + +/// Gate 1's plants: (row, column) of each of `parts.plants`; the last two in one row. +fn plant(x: []u16, rows: usize) void { + const at = [_][2]usize{ .{ 0, W / 3 }, .{ 1, W / 2 }, .{ 2, W - 1 }, .{ 3, 0 }, .{ 3, W - 1 } }; + for (at, parts.plants) |p, b| if (p[0] < rows) { + x[p[0] * W + p[1]] = b; + }; +} + +/// A norm launch as the launcher makes it: one row a threadgroup of 256. +fn launchRows(t: anytype, e: mtl.ComputeEncoder, buffers: usize) void { + for (0..buffers) |i| t.bind(e, i, i); + e.setValue(parts.Shape{ .m = @intCast(t.shape.rows) }, buffers); + e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); +} + +// --- h3d_rms_norm: y = bf16((x * rsqrt(mean(x^2) + eps)) * g), all in fp32 ------------------------------------------ + +pub const RmsNorm = struct { + x: []u16 = &.{}, + gw: []u16 = &.{}, + + /// Rows: rows; n and k: the row's 1,024 values. + pub fn spec(name: []const u8, _: RmsNorm) c.Spec { + return .{ .name = name, .accum = .f32, .depth = depth, .ops = 2 * (parts.div_ulps + parts.rsqrt_ulps) + 3, .out = .bf16, .served = &served }; + } + + pub fn prepare(k: *RmsNorm, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.n != W or s.k != W) return false; + k.x = try t.host().alloc(u16, s.rows * W); + k.gw = try t.host().alloc(u16, W); + // gate 4: integers, squares to 1,024; a row's sum passes fp16's range and stays exact in fp32 + if (t.fill == .stress) parts.integers(rng, k.x, -32, 32) else parts.uniform(rng, k.x, -3, 3); + if (t.fill == .nonfinite) plant(k.x, s.rows); + parts.uniform(rng, k.gw, 0.5, 1.5); + try t.input(k.x); + try t.input(k.gw); + try t.output(s.rows * W * 2); + return true; + } + + /// A block's norm1 and norm2. + pub fn launch(_: *RmsNorm, t: anytype, e: mtl.ComputeEncoder) void { + launchRows(t, e, 3); + } + + pub fn count(_: *RmsNorm, s: c.Shape) usize { + return s.rows * W; + } + + const Job = struct { + k: *const RmsNorm, + sum: Sum, + ends: *Ends, + want: []f64, + mag: []f64, + + fn rows(j: Job, from: usize, to: usize) void { + var x: [W]f64 = undefined; + var terms: [W]f64 = undefined; + for (from..to) |r| { + for (&x, &terms, j.k.x[r * W ..][0..W]) |*v, *q, b| { + v.* = value(b); + q.* = v.* * v.*; + } + const ss = j.sum.of(&terms, depth(served[0])); + const inv = parts.invNorm(ss.r, Wf); + const inv64 = 1 / @sqrt(ss.v / Wf + parts.eps); + for (x, j.k.gw, 0..) |v, gb, i| { + const gv = value(gb); + const y = Range.of(v).mul(inv).fp32(0.5).mul(Range.of(gv)).fp32(0.5).bf16(); + j.ends.put(j.want, j.mag, r * W + i, bf(v * inv64 * gv), y); + } + } + } + }; + + pub fn outputs(k: *RmsNorm, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + parts.parallel(t.shape.rows, Job{ .k = k, .sum = sum, .ends = ends, .want = want, .mag = mag }, Job.rows); + } +}; + +// --- h3d_layer_norm: norm_out, LayerNorm in fp32 with weight and bias, then bf16 ------------------------------------ + +pub const LayerNorm = struct { + x: []u16 = &.{}, + gw: []u16 = &.{}, + bw: []u16 = &.{}, + + /// Rows: rows; n and k: the row's 1,024 values. + pub fn spec(name: []const u8, _: LayerNorm) c.Spec { + return .{ .name = name, .accum = .f32, .depth = varianceDepth, .ops = 2 * (parts.div_ulps + parts.rsqrt_ulps) + 5, .out = .bf16, .served = &served }; + } + + pub fn prepare(k: *LayerNorm, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.n != W or s.k != W) return false; + k.x = try t.host().alloc(u16, s.rows * W); + k.gw = try t.host().alloc(u16, W); + k.bw = try t.host().alloc(u16, W); + if (t.fill == .stress) { + // gate 4: an integer mean near 100, deviations cancelling in pairs; every step exact in fp32 + for (0..s.rows) |r| { + const mean = rng.intRangeAtMost(i32, 80, 120) * @as(i32, if (rng.boolean()) 1 else -1); + for (0..W / 2) |i| { + const d = rng.intRangeAtMost(i32, -64, 64); + k.x[r * W + i] = parts.integer(mean + d); + k.x[r * W + W / 2 + i] = parts.integer(mean - d); + } + } + } else parts.uniform(rng, k.x, -2, 4); + if (t.fill == .nonfinite) plant(k.x, s.rows); + parts.uniform(rng, k.gw, 0.5, 1.5); + parts.uniform(rng, k.bw, -0.5, 0.5); + try t.input(k.x); + try t.input(k.gw); + try t.input(k.bw); + try t.output(s.rows * W * 2); + return true; + } + + /// The pass's final stage, norm_out. + pub fn launch(_: *LayerNorm, t: anytype, e: mtl.ComputeEncoder) void { + launchRows(t, e, 4); + } + + pub fn count(_: *LayerNorm, s: c.Shape) usize { + return s.rows * W; + } + + const Job = struct { + k: *const LayerNorm, + sum: Sum, + ends: *Ends, + want: []f64, + mag: []f64, + + fn rows(j: Job, from: usize, to: usize) void { + var x: [W]f64 = undefined; + var terms: [W]f64 = undefined; + for (from..to) |r| { + for (&x, j.k.x[r * W ..][0..W]) |*v, b| v.* = value(b); + const total = j.sum.of(&x, depth(served[0])); + const mean = total.v / Wf; + const mr = total.r.div(Wf).fp32(parts.div_ulps); + for (&terms, x) |*q, v| q.* = (v - mean) * (v - mean); + const sq = j.sum.of(&terms, varianceDepth(served[0])); + // the kernel's mean may sit off float64's by `off`: its squares then add W off^2 at most + const off = @max(@abs(mr.lo - mean), @abs(mr.hi - mean)); + var vr = sq.r; + if (std.math.isFinite(off)) vr.hi += Wf * off * off; + const rr = parts.invNorm(vr, Wf); + const rstd = 1 / @sqrt(sq.v / Wf + parts.eps); + for (x, j.k.gw, j.k.bw, 0..) |v, gb, bb, i| { + const gv = value(gb); + const bv = value(bb); + const d = Range.of(v).sub(mr).fp32(0.5); + const y = d.mul(rr).fp32(0.5).mul(Range.of(gv)).fp32(0.5).add(Range.of(bv)).fp32(0.5).bf16(); + j.ends.put(j.want, j.mag, r * W + i, bf((v - mean) * rstd * gv + bv), y); + } + } + } + }; + + pub fn outputs(k: *LayerNorm, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + parts.parallel(t.shape.rows, Job{ .k = k, .sum = sum, .ends = ends, .want = want, .mag = mag }, Job.rows); + } +}; diff --git a/zig/tests/contract/metal_h3_image_decoder_parts.zig b/zig/tests/contract/metal_h3_image_decoder_parts.zig new file mode 100644 index 00000000000..99d2fd2516e --- /dev/null +++ b/zig/tests/contract/metal_h3_image_decoder_parts.zig @@ -0,0 +1,331 @@ +//! The decoder kernels' tests' shared parts: geometry, float64 ranges at bf16 points, fills, threads and the test type. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +pub const c = contract.spec; +pub const g = contract.gates; +const bfr = contract.bf16_round; + +pub const W = 1024; +pub const heads = 16; +pub const D = 64; +pub const F = 4096; +pub const channels = 24; +pub const registers = 4; +/// Tokens after a tile's cells: the registers, then one zero token. +pub const suffix = registers + 1; +/// A tile's most cells a side, and so its most tokens. +pub const most_cells = 16; +pub const most_tokens = most_cells * most_cells + suffix; +/// The norms' epsilon as the kernels hold it (fp32), and the attention scale 1 / sqrt(64). +pub const eps: f64 = @as(f32, 1e-5); +pub const scale: f64 = 0.125; + +// Metal's error bounds with the launcher's options (safe math, fast fp32 functions) and the kernels' `precise::` calls. +pub const div_ulps = 2.5; +pub const rsqrt_ulps = 2; +pub const exp_ulps = 4; + +/// image_decoder.metal's H3dShape. +pub const Shape = extern struct { + tiles: u32 = 0, + h: u32 = 0, + w: u32 = 0, + tokens: u32 = 0, + rows: u32 = 0, + cols: u32 = 0, + m: u32 = 0, + n: u32 = 0, + k: u32 = 0, + mode: u32 = 0, + eps: f32 = 1e-5, + scale: f32 = 0.125, +}; + +/// A value rounded to bf16 in one step, to nearest even (NaN and the infinities kept). +pub fn bf(v: f64) f64 { + return bfr.bf16(v); +} + +pub fn value(b: u16) f64 { + return c.fromBf16(b); +} + +/// A tile of `cells` cells as rows and columns, each 1 to 16 (the widest rows first); null when none holds it. +pub fn geometry(cells: usize) ?[2]usize { + var w: usize = @min(cells, most_cells); + while (w > 0) : (w -= 1) if (cells % w == 0 and cells / w <= most_cells) return .{ cells / w, w }; + return null; +} + +/// Every value a kernel may hold at a step: its fp32 steps widen both ends, its bf16 points round them. +pub const Range = struct { + lo: f64, + hi: f64, + + pub fn of(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + pub fn around(v: f64, e: f64) Range { + return .{ .lo = v - e, .hi = v + e }; + } + /// An fp32 step good to `ulps` units in the last place (a correctly rounded one: 0.5). + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * 0x1p-23; + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + pub fn bf16(a: Range) Range { + return .{ .lo = bf(a.lo), .hi = bf(a.hi) }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn sub(a: Range, b: Range) Range { + return .{ .lo = a.lo - b.hi, .hi = a.hi - b.lo }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [4]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } + pub fn div(a: Range, n: f64) Range { + return .{ .lo = a.lo / n, .hi = a.hi / n }; + } + /// 1 / a, a positive. + pub fn recip(a: Range) Range { + return .{ .lo = 1 / a.hi, .hi = 1 / a.lo }; + } + /// 1 / sqrt(a), a positive. + pub fn rsqrt(a: Range) Range { + return .{ .lo = 1 / @sqrt(a.hi), .hi = 1 / @sqrt(a.lo) }; + } +}; + +/// 1 + exp(-x) through precise::exp and an fp32 add; past fp32's range exp's result is +Inf. +fn denominator(x: f64) Range { + var e = Range.of(@exp(-x)).fp32(exp_ulps); + if (e.hi > std.math.floatMax(f32)) e.hi = std.math.inf(f64); + return e.add(Range.of(1)).fp32(0.5); +} + +/// x / (1 + exp(-x)) through the kernel's precise exp and fast division. +pub fn silu(x: f64) Range { + return Range.of(x).mul(denominator(x).recip()).fp32(div_ulps); +} + +/// rsqrt(ss / n + eps) through the kernel's division, add and precise rsqrt, for a sum of squares in `ss`. +pub fn invNorm(ss: Range, n: f64) Range { + return ss.div(n).fp32(div_ulps).add(Range.of(eps)).fp32(0.5).rsqrt().fp32(rsqrt_ulps); +} + +/// Each output's float64 value at the kernel's rounding points and its range, kept for the bounds and intervals. +pub const Ends = struct { + a: std.mem.Allocator, + lo: []f64 = &.{}, + hi: []f64 = &.{}, + + pub fn deinit(e: *Ends) void { + e.a.free(e.lo); + e.a.free(e.hi); + e.lo = &.{}; + e.hi = &.{}; + } + + pub fn size(e: *Ends, n: usize) !void { + if (e.lo.len == n) return; + e.deinit(); + e.lo = try e.a.alloc(f64, n); + e.hi = try e.a.alloc(f64, n); + } + + pub fn put(e: *Ends, want: []f64, mag: []f64, i: usize, w: f64, r: Range) void { + want[i] = w; + mag[i] = if (std.math.isFinite(w)) @abs(w) else 0; + e.lo[i] = r.lo; + e.hi[i] = r.hi; + } + + /// The allowance about the float64 value: its range's farther end (a non-finite value is checked by class). + pub fn bounds(e: *const Ends, want: []const f64, allow: []f64) void { + for (allow, want, e.lo, e.hi) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) @max(@abs(w - lo), @abs(hi - w)) else 0; + } + + pub fn intervals(e: *const Ends, low: []f64, high: []f64) void { + @memcpy(low, e.lo); + @memcpy(high, e.hi); + } +}; + +/// How a reference takes its sums: float64 with the spread fp32 allows (none when exact), or replayed (gate 4). +pub const Sum = struct { + acc: ?c.Accum = null, + order: g.Order = .sequential, + exact: bool = false, + + pub const Out = struct { v: f64, r: Range }; + + /// The terms' sum and its range: float64's widened by gamma(depth) of their magnitude, or the replay's. + pub fn of(s: Sum, t: []const f64, depth: usize) Out { + if (s.acc) |acc| { + const v = contract.rows.sumIn(acc, s.order, t); + return .{ .v = v, .r = Range.of(v) }; + } + var v: f64 = 0; + var m: f64 = 0; + for (t) |x| { + v += x; + m += @abs(x); + } + return .{ .v = v, .r = s.spread(v, m, depth) }; + } + + pub fn spread(s: Sum, v: f64, m: f64, depth: usize) Range { + if (s.exact or s.acc != null or !std.math.isFinite(m)) return Range.of(v); + return Range.around(v, c.gamma(@floatFromInt(depth), c.unit(.f32)) * m); + } +}; + +pub fn uniform(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +pub fn integer(v: i32) u16 { + return c.toBf16(@floatFromInt(v)); +} + +pub fn integers(rng: std.Random, out: []u16, lo: i32, hi: i32) void { + for (out) |*v| v.* = integer(rng.intRangeAtMost(i32, lo, hi)); +} + +pub const nan16: u16 = 0x7fc0; +pub const inf16: u16 = 0x7f80; +pub const ninf16: u16 = 0xff80; +/// The plants each gate-1 input takes in turn: NaN, +Inf, -Inf, then both infinities in one place. +pub const plants = [_]u16{ nan16, inf16, ninf16, inf16, ninf16 }; + +/// `f(ctx, from, to)` over [0, n) in slices, each on its own thread (reference_threads' most). +pub fn parallel(n: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), usize, usize) void) void { + const Job = struct { + ctx: @TypeOf(ctx), + from: usize, + to: usize, + pub fn run(j: *@This()) void { + f(j.ctx, j.from, j.to); + } + }; + var jobs: [contract.reference_threads.maximum]Job = undefined; + const parts = contract.reference_threads.count(std.Thread.getCpuCount() catch 1, n); + for (jobs[0..parts], 0..) |*j, i| j.* = .{ .ctx = ctx, .from = n * i / parts, .to = n * (i + 1) / parts }; + contract.reference_threads.run(Job, jobs[0..parts], .normal); +} + +/// A decoder kernel's test: rig, pipeline, ranges; `K` gives spec, prepare, launch, count and outputs (or replays). +pub fn Case(comptime K: type) type { + return struct { + const Self = @This(); + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + name: []const u8, + k: K, + shape: c.Shape = undefined, + fill: g.Fill = .random, + /// Host copies of the inputs, dropped at each prepare. + arena: std.heap.ArenaAllocator, + bufs: [8]rig_.Ref = undefined, + nbufs: usize = 0, + ends: Ends, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, pipe: mtl.Pipeline, name: []const u8, k: K) Self { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = pipe, .name = name, .k = k, .arena = std.heap.ArenaAllocator.init(a), .ends = .{ .a = a } }; + } + + pub fn deinit(t: *Self) void { + t.ends.deinit(); + t.rig.deinit(); + t.arena.deinit(); + t.pipe.deinit(); + } + + pub fn kernel(t: *Self, control: ?g.Gate) g.Kernel { + return .{ .spec = K.spec(t.name, t.k), .ctx = t, .vt = &vt, .control = control }; + } + + /// The hooks, with a release that also drops the host copies and ranges once a kernel's gates are done. + const vt = blk: { + var v = g.hooks(Self); + v.release = release; + break :blk v; + }; + + fn release(ctx: *anyopaque) void { + const t: *Self = @ptrCast(@alignCast(ctx)); + t.rig.reset(); + _ = t.arena.reset(.free_all); + t.ends.deinit(); + } + + pub fn host(t: *Self) std.mem.Allocator { + return t.arena.allocator(); + } + + pub fn input(t: *Self, v: anytype) !void { + t.bufs[t.nbufs] = try t.rig.input(std.mem.sliceAsBytes(v)); + t.nbufs += 1; + } + + pub fn output(t: *Self, bytes: usize) !void { + t.bufs[t.nbufs] = try t.rig.output(bytes); + t.nbufs += 1; + } + + /// Buffer `i` at the launch's index `at`. + pub fn bind(t: *Self, e: mtl.ComputeEncoder, i: usize, at: usize) void { + e.setBuffer(t.bufs[i].buf, t.bufs[i].off, at); + } + + pub fn prepare(t: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + t.rig.reset(); + _ = t.arena.reset(.retain_capacity); + t.nbufs = 0; + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + return t.k.prepare(t, prng.random()); + } + + pub fn run(t: *Self) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + t.k.launch(t, p.e); + try t.rig.finish(p); + } + + pub fn count(t: *Self) usize { + return t.k.count(t.shape); + } + + pub fn reference(t: *Self, want: []f64, mag: []f64) !void { + try t.ends.size(want.len); + try t.k.outputs(t, .{ .exact = t.fill == .stress }, &t.ends, want, mag); + } + + pub fn bounds(t: *Self, want: []const f64, _: []const f64, allow: []f64) !void { + t.ends.bounds(want, allow); + } + + pub fn intervals(t: *Self, low: []f64, high: []f64) !void { + t.ends.intervals(low, high); + } + + pub fn simulate(t: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + var scratch: Ends = .{ .a = t.a }; + defer scratch.deinit(); + try scratch.size(out.len); + const mag = try t.a.alloc(f64, out.len); + defer t.a.free(mag); + try t.k.outputs(t, .{ .acc = acc, .order = order }, &scratch, out, mag); + } + }; +} diff --git a/zig/tests/contract/metal_h3_image_decoder_rows.zig b/zig/tests/contract/metal_h3_image_decoder_rows.zig new file mode 100644 index 00000000000..e2e904acb4a --- /dev/null +++ b/zig/tests/contract/metal_h3_image_decoder_rows.zig @@ -0,0 +1,304 @@ +//! h3d_post_quant, h3d_embed and h3d_swiglu under the contract: each output against float64 at its bf16 points. +const std = @import("std"); +const mtl = @import("metal"); +const parts = @import("metal_h3_image_decoder_parts.zig"); + +const c = parts.c; +const Range = parts.Range; +const Ends = parts.Ends; +const Sum = parts.Sum; +const bf = parts.bf; +const value = parts.value; +const C = parts.channels; +const W = parts.W; +const F = parts.F; + +/// Gate 4's weights: channels 12-23 negate 0-11 plus 1 on 4, against inputs repeating 0-11: exact fp32, small sums. +fn mirror(rng: std.Random, w: []u16, outs: usize) void { + for (0..outs) |o| for (0..C / 2) |ch| { + const v = rng.intRangeAtMost(i32, 128, 255); + w[o * C + ch] = parts.integer(v); + w[o * C + C / 2 + ch] = parts.integer(-v + @as(i32, if (ch < 4) 1 else 0)); + }; +} + +/// Gate 4's inputs for one cell: integers in [64, 127], channels 12-23 repeating 0-11. +fn mirrored(rng: std.Random) [C]f32 { + var out: [C]f32 = undefined; + for (0..C / 2) |ch| { + out[ch] = @floatFromInt(rng.intRangeAtMost(i32, 64, 127)); + out[ch + C / 2] = out[ch]; + } + return out; +} + +/// Output `o` of a cell's 24 inputs: the 24-deep fp32 chain, the bias, one rounding to bf16. +fn product(sum: Sum, w: []const u16, bias: u16, in: *const [C]f64, o: usize) Sum.Out { + var terms: [C]f64 = undefined; + for (&terms, in, w[o * C ..][0..C]) |*t, x, wv| t.* = value(wv) * x; + const s = sum.of(&terms, C); + const b = value(bias); + return .{ .v = bf(s.v + b), .r = s.r.add(Range.of(b)).fp32(0.5).bf16() }; +} + +/// The 24-deep chain, then the bias. +fn chain(s: c.Shape) usize { + return s.k + 1; +} + +/// Planted inputs for gate 1: (tile, cell, channel) of each of `parts.plants`; the last two in one cell. +const spots = [_][3]usize{ .{ 0, 0, 3 }, .{ 1, 1, 5 }, .{ 2, 2, 7 }, .{ 3, 3, 0 }, .{ 3, 3, 1 } }; + +// --- h3d_post_quant: a tile's cells of the fp32 latent rounded to bf16, then 24 x 24 with bias to bf16 ----------- + +pub const PostQuant = struct { + lat: []f32 = &.{}, + org: [][2]u32 = &.{}, + pw: []u16 = &.{}, + pb: []u16 = &.{}, + hw: [2]usize = .{ 0, 0 }, + rows: usize = 0, + cols: usize = 0, + + /// Rows: tiles; n: cells a tile (h x w); k: the channels each output sums. One 16 x 16 tile, 16, a 4 x 15 one. + pub fn spec(name: []const u8, _: PostQuant) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = chain, + .out = .bf16, + .tiles = .{ .{}, .{ .size = 8 }, .{} }, + .served = &.{ .{ .rows = 1, .n = 256, .k = C }, .{ .rows = 16, .n = 256, .k = C }, .{ .rows = 1, .n = 60, .k = C } }, + }; + } + + /// Cell `i` of tile `t` in the latent's plane. + fn place(k: *const PostQuant, t: usize, i: usize) usize { + return (k.org[t][0] + i / k.hw[1]) * k.cols + k.org[t][1] + i % k.hw[1]; + } + + pub fn prepare(k: *PostQuant, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.k != C) return false; + k.hw = parts.geometry(s.n) orelse return false; + // a latent wider than the tile, so each tile reads at its own origin + k.rows = k.hw[0] + 3; + k.cols = k.hw[1] + 5; + const plane = k.rows * k.cols; + const al = t.host(); + k.lat = try al.alloc(f32, C * plane); + k.org = try al.alloc([2]u32, s.rows); + k.pw = try al.alloc(u16, C * C); + k.pb = try al.alloc(u16, C); + for (k.org) |*o| o.* = .{ rng.uintAtMost(u32, @intCast(k.rows - k.hw[0])), rng.uintAtMost(u32, @intCast(k.cols - k.hw[1])) }; + if (t.fill == .stress) { + for (0..plane) |i| for (mirrored(rng), 0..) |v, ch| { + k.lat[ch * plane + i] = v; + }; + mirror(rng, k.pw, C); + @memset(k.pb, 0); + } else { + for (k.lat) |*v| v.* = rng.float(f32) * 6 - 3; + parts.uniform(rng, k.pw, -0.35, 0.35); + parts.uniform(rng, k.pb, -0.1, 0.1); + if (t.fill == .nonfinite) for (spots, parts.plants) |at, b| { + k.lat[at[2] * plane + k.place(@min(at[0], s.rows - 1), at[1] % s.n)] = c.fromBf16(b); + }; + } + try t.input(k.lat); + try t.input(k.org); + try t.input(k.pw); + try t.input(k.pb); + try t.output(s.rows * s.n * C * 2); + return true; + } + + /// The launcher's embed stage, its first launch: threads [24, tiles x cells] in groups of 24 x 8. + pub fn launch(k: *PostQuant, t: anytype, e: mtl.ComputeEncoder) void { + const s = t.shape; + for (0..5) |i| t.bind(e, i, i); + e.setValue(parts.Shape{ .tiles = @intCast(s.rows), .h = @intCast(k.hw[0]), .w = @intCast(k.hw[1]), .tokens = @intCast(s.n + parts.suffix), .rows = @intCast(k.rows), .cols = @intCast(k.cols), .m = @intCast(s.rows * (s.n + parts.suffix)) }, 5); + e.dispatchThreads(mtl.Size.of(C, s.rows * s.n, 1), mtl.Size.of(C, 8, 1)); + } + + pub fn count(_: *PostQuant, s: c.Shape) usize { + return s.rows * s.n * C; + } + + pub fn outputs(k: *PostQuant, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + const s = t.shape; + const plane = k.rows * k.cols; + var in: [C]f64 = undefined; + for (0..s.rows) |tl| for (0..s.n) |i| { + const at = k.place(tl, i); + for (&in, 0..) |*v, ch| v.* = bf(k.lat[ch * plane + at]); + for (0..C) |o| { + const y = product(sum, k.pw, k.pb[o], &in, o); + ends.put(want, mag, (tl * s.n + i) * C + o, y.v, y.r); + } + }; + } +}; + +// --- h3d_embed: x_embedder (24 to 1,024 with bias) on a tile's cells to bf16, then the 4 registers and a zero token + +pub const Embed = struct { + tok: []u16 = &.{}, + ew: []u16 = &.{}, + eb: []u16 = &.{}, + reg: []u16 = &.{}, + hw: [2]usize = .{ 0, 0 }, + + /// Rows: tiles; n: tokens a tile (its cells, the registers, the zero token); k: the channels a cell's output sums. + pub fn spec(name: []const u8, _: Embed) c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = chain, + .out = .bf16, + .served = &.{ .{ .rows = 1, .n = 261, .k = C }, .{ .rows = 16, .n = 261, .k = C }, .{ .rows = 1, .n = 65, .k = C } }, + }; + } + + pub fn prepare(k: *Embed, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.k != C or s.n <= parts.suffix) return false; + const cells = s.n - parts.suffix; + k.hw = parts.geometry(cells) orelse return false; + const al = t.host(); + k.tok = try al.alloc(u16, s.rows * cells * C); + k.ew = try al.alloc(u16, W * C); + k.eb = try al.alloc(u16, W); + k.reg = try al.alloc(u16, parts.registers * W); + if (t.fill == .stress) { + for (0..s.rows * cells) |i| for (mirrored(rng), 0..) |v, ch| { + k.tok[i * C + ch] = c.toBf16(v); + }; + mirror(rng, k.ew, W); + @memset(k.eb, 0); + parts.integers(rng, k.reg, -8, 8); + } else { + parts.uniform(rng, k.tok, -2, 2); + parts.uniform(rng, k.ew, -0.35, 0.35); + parts.uniform(rng, k.eb, -0.1, 0.1); + parts.uniform(rng, k.reg, -1.5, 1.5); + if (t.fill == .nonfinite) { + for (spots, parts.plants) |at, b| k.tok[(@min(at[0], s.rows - 1) * cells + at[1] % cells) * C + at[2]] = b; + k.reg[W + 7] = parts.nan16; + k.reg[3 * W + 1000] = parts.inf16; + } + } + try t.input(k.tok); + try t.input(k.ew); + try t.input(k.eb); + try t.input(k.reg); + try t.output(s.rows * s.n * W * 2); + return true; + } + + /// The launcher's embed stage, its second launch: threads [1,024, tiles x tokens] in groups of 256. + pub fn launch(k: *Embed, t: anytype, e: mtl.ComputeEncoder) void { + const s = t.shape; + for (0..5) |i| t.bind(e, i, i); + e.setValue(parts.Shape{ .tiles = @intCast(s.rows), .h = @intCast(k.hw[0]), .w = @intCast(k.hw[1]), .tokens = @intCast(s.n), .m = @intCast(s.rows * s.n) }, 5); + e.dispatchThreads(mtl.Size.of(W, s.rows * s.n, 1), mtl.Size.of(256, 1, 1)); + } + + pub fn count(_: *Embed, s: c.Shape) usize { + return s.rows * s.n * W; + } + + pub fn outputs(k: *Embed, t: anytype, sum: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + const s = t.shape; + const cells = s.n - parts.suffix; + var in: [C]f64 = undefined; + for (0..s.rows) |tl| for (0..s.n) |tk| { + const row = (tl * s.n + tk) * W; + if (tk < cells) { + for (&in, k.tok[(tl * cells + tk) * C ..][0..C]) |*v, b| v.* = value(b); + for (0..W) |j| { + const y = product(sum, k.ew, k.eb[j], &in, j); + ends.put(want, mag, row + j, y.v, y.r); + } + } else for (0..W) |j| { + const v = if (tk < cells + parts.registers) value(k.reg[(tk - cells) * W + j]) else 0; + ends.put(want, mag, row + j, v, Range.of(v)); + } + }; + } +}; + +// --- h3d_swiglu: act = bf16(bf16(SiLU(gate)) * value), each row [gate 4,096 | value 4,096] ------------------------- + +pub const Swiglu = struct { + wide: []u16 = &.{}, + + fn none(_: c.Shape) usize { + return 0; + } + + /// Rows: rows (one tile, the batch of 16, a small tile); n: the 4,096 outputs a row; k: 1, no sums. + pub fn spec(name: []const u8, _: Swiglu) c.Spec { + return .{ + .name = name, + .accum = .none, + .depth = none, + .ops = 2 * (parts.exp_ulps + parts.div_ulps) + 2, + .mids = 1, + .out = .bf16, + .served = &.{ .{ .rows = 261, .n = F, .k = 1 }, .{ .rows = 4176, .n = F, .k = 1 }, .{ .rows = 65, .n = F, .k = 1 } }, + }; + } + + pub fn prepare(k: *Swiglu, t: anytype, rng: std.Random) !bool { + const s = t.shape; + if (s.rows == 0 or s.n != F or s.k != 1) return false; + k.wide = try t.host().alloc(u16, s.rows * 2 * F); + for (0..s.rows) |r| { + parts.uniform(rng, k.wide[r * 2 * F ..][0..F], -6, 6); + parts.uniform(rng, k.wide[r * 2 * F + F ..][0..F], -3, 3); + } + if (t.fill == .nonfinite) { + // NaN, +Inf and -Inf gates, then both infinities as values in one row + const at = [_][2]usize{ .{ 0, 5 }, .{ 1, 9 }, .{ 2, 100 }, .{ 3, F + 7 }, .{ 3, F + 8 } }; + for (at, parts.plants) |p, b| if (p[0] < s.rows) { + k.wide[p[0] * 2 * F + p[1]] = b; + }; + } + try t.input(k.wide); + try t.output(s.rows * F * 2); + return true; + } + + /// A block's FFN: threads [4,096, rows] in groups of 256. + pub fn launch(_: *Swiglu, t: anytype, e: mtl.ComputeEncoder) void { + const s = t.shape; + for (0..2) |i| t.bind(e, i, i); + e.setValue(parts.Shape{ .m = @intCast(s.rows) }, 2); + e.dispatchThreads(mtl.Size.of(F, s.rows, 1), mtl.Size.of(256, 1, 1)); + } + + pub fn count(_: *Swiglu, s: c.Shape) usize { + return s.rows * F; + } + + const Job = struct { + wide: []const u16, + ends: *Ends, + want: []f64, + mag: []f64, + + fn rows(j: Job, from: usize, to: usize) void { + for (from..to) |r| for (0..F) |i| { + const gv = value(j.wide[r * 2 * F + i]); + const vv = value(j.wide[r * 2 * F + F + i]); + const act = parts.silu(gv).bf16().mul(Range.of(vv)).fp32(0.5).bf16(); + j.ends.put(j.want, j.mag, r * F + i, bf(bf(gv / (1 + @exp(-gv))) * vv), act); + }; + } + }; + + pub fn outputs(k: *Swiglu, t: anytype, _: Sum, ends: *Ends, want: []f64, mag: []f64) !void { + parts.parallel(t.shape.rows, Job{ .wide = k.wide, .ends = ends, .want = want, .mag = mag }, Job.rows); + } +}; From 03a186d2f39def16bcc4eff09d62ee763259e5ee Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:23:27 +0000 Subject: [PATCH 008/361] kernel contract: MiniMax-H3-Image's prompt path kernels, fourteen registrations and fourteen planted controls; hp_attention's padded last key is a known finding --- zig/src/core/contract/h3_image_records.zig | 10 +- zig/tests/contract/metal_h3_image_prompt.zig | 150 ++++- .../contract/metal_h3_image_prompt_case.zig | 512 ++++++++++++++++++ .../contract/metal_h3_image_prompt_ref.zig | 265 +++++++++ .../contract/metal_h3_image_prompt_want.zig | 314 +++++++++++ 5 files changed, 1246 insertions(+), 5 deletions(-) create mode 100644 zig/tests/contract/metal_h3_image_prompt_case.zig create mode 100644 zig/tests/contract/metal_h3_image_prompt_ref.zig create mode 100644 zig/tests/contract/metal_h3_image_prompt_want.zig diff --git a/zig/src/core/contract/h3_image_records.zig b/zig/src/core/contract/h3_image_records.zig index 57357b9414b..c8d885c0c03 100644 --- a/zig/src/core/contract/h3_image_records.zig +++ b/zig/src/core/contract/h3_image_records.zig @@ -7,7 +7,15 @@ pub const encoder = [_]M{ .{ .name = "minimax image encoder hie_group_finish", .threads = 1024, .tg_memory = 0, .reserved = 1024 }, .{ .name = "minimax image encoder hie_norm_silu", .threads = 256, .tg_memory = 0, .reserved = 256 }, }; -pub const prompt = [_]M{}; +pub const prompt = [_]M{ + .{ .name = "minimax image prompt hp_gemm", .threads = 128, .tg_memory = 10240, .reserved = 128 }, + .{ .name = "minimax image prompt hp_norm", .threads = 256, .tg_memory = 32, .reserved = 256 }, + .{ .name = "minimax image prompt hp_heads", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "minimax image prompt hp_attention", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "minimax image prompt hp_glu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "minimax image prompt hp_add", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "minimax image prompt hp_scatter_add", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; pub const decoder = [_]M{ .{ .name = "minimax image decoder h3d_post_quant", .threads = 192, .tg_memory = 0, .reserved = 192 }, .{ .name = "minimax image decoder h3d_embed", .threads = 256, .tg_memory = 0, .reserved = 256 }, diff --git a/zig/tests/contract/metal_h3_image_prompt.zig b/zig/tests/contract/metal_h3_image_prompt.zig index 2e5f4504ca9..21830982e44 100644 --- a/zig/tests/contract/metal_h3_image_prompt.zig +++ b/zig/tests/contract/metal_h3_image_prompt.zig @@ -3,22 +3,164 @@ const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); const common = @import("metal_h3_image_common.zig"); +const case = @import("metal_h3_image_prompt_case.zig"); const g = contract.gates; +const c = contract.spec; +const Case = case.Case; +const Form = case.Form; + +/// A short prompt's rows (a 64-row tile and 13 more) and a long presentation's (sixteen tiles and 7 more). +const short = 77; +const long = 1031; + +/// The text model's projections (q, k and v, o, gate and up, down) and the refiner's (qkv, out, fc1, fc2) as N, K. +const projections = [_][2]usize{ .{ 1024, 5120 }, .{ 8192, 5120 }, .{ 5120, 8192 }, .{ 25600, 5120 }, .{ 5120, 25600 }, .{ 21504, 5376 }, .{ 5376, 7168 }, .{ 28672, 5376 }, .{ 5376, 14336 } }; + +const gemm_served = blk: { + var out: []const c.Shape = &.{}; + for (projections) |p| out = out ++ &[_]c.Shape{.{ .rows = short, .n = p[0], .k = p[1] }}; + break :blk out ++ &[_]c.Shape{ .{ .rows = long, .n = 1024, .k = 5120 }, .{ .rows = long, .n = 5376, .k = 7168 } }; +}; + +fn rowsAt(comptime n: usize, comptime k: usize) []const c.Shape { + return &.{ .{ .rows = short, .n = n, .k = k }, .{ .rows = long, .n = n, .k = k } }; +} + +fn headsAt(comptime heads: usize, comptime rows: []const usize) []const c.Shape { + var out: []const c.Shape = &.{}; + for (rows) |t| out = out ++ &[_]c.Shape{.{ .rows = heads, .n = 128, .k = t }}; + return out; +} + +const last_key = "a row whose key count is not a multiple of 4 fills its last block of 4 with its last key at weight " ++ + "0: an infinite value there gives 0 x Inf = NaN where float64 gives the infinity"; + +/// The released checkpoint's launches in prompt.zig (text 5120 wide, 64 over 8 heads; refiner 5376, 56 heads). +const forms = [_]Form{ + .{ .kind = .gemm, .served = gemm_served }, + .{ .kind = .gemm, .label = "bias", .bias = true, .served = rowsAt(5376, 5120) }, + .{ .kind = .norm, .label = "qwen", .mode = .qwen, .eps = 1e-6, .served = rowsAt(5120, 5120) }, + .{ .kind = .norm, .label = "h3", .mode = .h3, .eps = 1e-5, .served = rowsAt(5376, 5376) }, + .{ .kind = .heads, .label = "qwen rotary", .mode = .qwen, .eps = 1e-6, .served = rowsAt(64, 128) }, + .{ .kind = .heads, .label = "h3 fused", .mode = .h3, .eps = 1e-5, .fused = true, .served = rowsAt(56, 128) }, + .{ .kind = .attention, .label = "causal", .causal = true, .served = headsAt(64, &.{ short, long }) }, + .{ .kind = .attention, .label = "fused", .fused = true, .served = headsAt(56, &.{ short, long }) }, + .{ .kind = .attention, .label = "causal last key", .causal = true, .last_key = true, .served = headsAt(64, &.{short}), .known = .{ .gate = .nonfinite, .finding = last_key } }, + .{ .kind = .attention, .label = "fused last key", .fused = true, .last_key = true, .served = headsAt(56, &.{short}), .known = .{ .gate = .nonfinite, .finding = last_key } }, + .{ .kind = .glu, .label = "qwen", .mode = .qwen, .served = rowsAt(25600, 1) }, + .{ .kind = .glu, .label = "h3 fused", .mode = .h3, .fused = true, .served = rowsAt(14336, 1) }, + .{ .kind = .add, .served = rowsAt(5120, 1) ++ rowsAt(5376, 1) }, + .{ .kind = .scatter, .served = &.{ .{ .rows = 1024, .n = 5120, .k = 1 }, .{ .rows = 2560, .n = 5120, .k = 1 } } }, +}; + +/// A planted control: the registration it breaks (its label after the function), the one source edit, and its gate. +const Control = struct { entry: []const u8, gate: g.Gate, what: []const u8, old: []const u8, new: []const u8 }; + +const controls = [_]Control{ + .{ .entry = "hp_gemm", .gate = .shapes, .what = "drops the last K block", .old = "k0 < K; k0 += BK", .new = "k0 + BK < K; k0 += BK" }, + .{ .entry = "hp_gemm bias", .gate = .shapes, .what = "swaps a column pair's biases", .old = "float2(float(bias[c]), float(bias[c + 1]))", .new = "float2(float(bias[c + 1]), float(bias[c]))" }, + .{ .entry = "hp_norm qwen", .gate = .shapes, .what = "rounds as H3's blocks", .old = "return mode == 0 ?", .new = "return mode != 0 ?" }, + .{ .entry = "hp_norm h3", .gate = .shapes, .what = "rounds as the Qwen model", .old = "return mode == 0 ?", .new = "return mode != 0 ?" }, + .{ .entry = "hp_norm qwen", .gate = .sums, .what = "sums its squares in half", .old = "float s = 0.0f;", .new = "half s = 0.0h;" }, + .{ .entry = "hp_heads qwen rotary", .gate = .shapes, .what = "turns the wrong way", .old = "lane < 16 ? -1.0f : 1.0f", .new = "lane < 16 ? 1.0f : -1.0f" }, + .{ .entry = "hp_heads h3 fused", .gate = .shapes, .what = "rounds as the Qwen model", .old = "return mode == 0 ?", .new = "return mode != 0 ?" }, + .{ .entry = "hp_attention causal", .gate = .shapes, .what = "sees the next key", .old = "? row + 1 : p.rows;", .new = "? min(row + 2, p.rows) : p.rows;" }, + .{ .entry = "hp_attention fused", .gate = .shapes, .what = "skips the last key", .old = "? row + 1 : p.rows;", .new = "? row + 1 : p.rows - 1;" }, + .{ .entry = "hp_attention causal", .gate = .nonfinite, .what = "weighs a NaN score 0", .old = "const float e = metal::precise::exp(s[u] - top);", .new = "const float e = isnan(s[u]) ? 0.0f : metal::precise::exp(s[u] - top);" }, + .{ .entry = "hp_glu qwen", .gate = .shapes, .what = "swaps gate and value", .old = "g = float(G[ulong(at.y) * p.g_row + at.x]), v = float(V[ulong(at.y) * p.v_row + at.x])", .new = "g = float(V[ulong(at.y) * p.v_row + at.x]), v = float(G[ulong(at.y) * p.g_row + at.x])" }, + .{ .entry = "hp_glu h3 fused", .gate = .shapes, .what = "rounds as the Qwen model", .old = "const float s = p.mode == 0 ?", .new = "const float s = p.mode != 0 ?" }, + .{ .entry = "hp_add", .gate = .shapes, .what = "skips the last value", .old = "if (i < n)", .new = "if (i + 1 < n)" }, + .{ .entry = "hp_scatter_add", .gate = .shapes, .what = "adds into row i, not idx[i]", .old = "ulong(idx[at.y]) * width", .new = "ulong(at.y) * width" }, +}; + +fn entry(comptime f: Form) []const u8 { + return case.function(f.kind) ++ (if (f.label.len > 0) " " ++ f.label else ""); +} + +fn kChain(s: c.Shape) usize { + return s.k + 2; +} +/// hp_norm: a thread's chain over every 256th value, simd_sum's tree, then the 8 simdgroups' partials in order. +fn normChain(s: c.Shape) usize { + return (s.k + 255) / 256 + 6 + 8; +} +/// hp_heads: a lane's 4 squares, then simd_sum's tree. +fn headChain(_: c.Shape) usize { + return 4 + 6; +} +/// hp_attention: a score's lane dot and tree, then the keys' sequential sum and its rescales. +fn attnChain(s: c.Shape) usize { + return 4 + 6 + s.k + s.k / 4 + 3; +} +fn none(_: c.Shape) usize { + return 0; +} + +pub fn spec(comptime f: Form, name: []const u8) c.Spec { + return switch (f.kind) { + .gemm => .{ .name = name, .accum = .f32, .depth = kChain, .ops = if (f.bias) 1 else 0, .out = .bf16, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 32, .step = 32, .min = 32 } }, .served = f.served }, + .norm => .{ .name = name, .accum = .f32, .depth = normChain, .ops = 8, .mids = if (f.mode == .qwen) 1 else 0, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256 } }, .served = f.served }, + .heads => .{ .name = name, .accum = .f32, .depth = headChain, .ops = 8, .mids = 3, .out = .bf16, .in_place = true, .tiles = .{ .{}, .{ .size = 8 }, .{} }, .served = f.served }, + .attention => .{ .name = name, .accum = .f32, .depth = attnChain, .ops = 8, .out = .bf16, .tiles = .{ .{ .size = 8 }, .{}, .{ .size = 4 } }, .served = f.served, .known = f.known }, + .glu => .{ .name = name, .accum = .none, .depth = none, .ops = 8, .mids = 2, .out = .bf16, .tiles = .{ .{}, .{ .size = 256 }, .{} }, .served = f.served }, + .add, .scatter => .{ .name = name, .accum = .none, .depth = none, .ops = 1, .out = .bf16, .in_place = true, .tiles = .{ .{}, .{ .size = 256 }, .{} }, .served = f.served }, + }; +} pub const Suite = struct { a: std.mem.Allocator, + cases: std.ArrayList(*Case) = .empty, + pipes: std.ArrayList(mtl.Pipeline) = .empty, + + fn add(s: *Suite, device: mtl.Device, queue: mtl.Queue, lib: mtl.Library, comptime f: Form, comptime name: []const u8, gate: ?g.Gate, out: *std.ArrayList(g.Kernel)) !void { + const p = try mtl.Pipeline.init(device, lib, case.function(f.kind), false); + { + errdefer p.deinit(); + try s.pipes.append(s.a, p); + } + const t = try s.a.create(Case); + t.* = Case.init(s.a, device, queue, p, f, spec(f, name), gate); + { + errdefer { + t.deinit(); + s.a.destroy(t); + } + try s.cases.append(s.a, t); + } + try out.append(s.a, t.kernel()); + } pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { - _ = device; - _ = queue; - _ = kernels; - _ = only; const s = try a.create(Suite); s.* = .{ .a = a }; + errdefer s.destroy(); + const lib = try common.library(device, .prompt, common.source(.prompt)); + defer lib.deinit(); + inline for (forms) |f| { + const name = comptime common.name(.prompt, entry(f)); + if (common.keep(only, name)) try s.add(device, queue, lib, f, name, null, kernels); + } + inline for (controls) |x| inline for (forms) |f| if (comptime std.mem.eql(u8, entry(f), x.entry)) { + const name = comptime common.name(.prompt, entry(f)) ++ " control: " ++ x.what; + if (common.keep(only, name)) { + const text = try common.edited(a, .prompt, x.old, x.new); + defer a.free(text); + const edited = try common.library(device, .prompt, text); + defer edited.deinit(); + try s.add(device, queue, edited, f, name, x.gate, kernels); + } + }; return s; } pub fn destroy(s: *Suite) void { + for (s.cases.items) |t| { + t.deinit(); + s.a.destroy(t); + } + s.cases.deinit(s.a); + for (s.pipes.items) |p| p.deinit(); + s.pipes.deinit(s.a); s.a.destroy(s); } }; diff --git a/zig/tests/contract/metal_h3_image_prompt_case.zig b/zig/tests/contract/metal_h3_image_prompt_case.zig new file mode 100644 index 00000000000..b70e019e3dd --- /dev/null +++ b/zig/tests/contract/metal_h3_image_prompt_case.zig @@ -0,0 +1,512 @@ +//! One prompt kernel's contract test: its inputs for each gate's fill, and its launch as prompt_kernels.zig binds it. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const ref = @import("metal_h3_image_prompt_ref.zig"); +const want = @import("metal_h3_image_prompt_want.zig"); + +const c = contract.spec; +const g = contract.gates; +pub const Mode = ref.Mode; + +pub const Kind = enum { gemm, norm, heads, attention, glu, add, scatter }; + +/// A registration: its kernel, its rounding mode and layout, where it is served, and any finding it carries. +pub const Form = struct { + kind: Kind, + /// The name's suffix past the function: the mode, the layout or the planted finding. + label: []const u8 = "", + mode: Mode = .qwen, + eps: f32 = 0, + /// gemm: condition_proj's bias. + bias: bool = false, + /// attention: each row over earlier rows (the text model). + causal: bool = false, + /// heads, attention, glu: the refiner's fused rows (q, k, v of a head together; gate | value). + fused: bool = false, + /// attention: the non-finite plant is an infinite value at a row's last key, alone. + last_key: bool = false, + served: []const c.Shape, + known: ?c.Known = null, +}; + +pub fn function(k: Kind) []const u8 { + return switch (k) { + .gemm => "hp_gemm", + .norm => "hp_norm", + .heads => "hp_heads", + .attention => "hp_attention", + .glu => "hp_glu", + .add => "hp_add", + .scatter => "hp_scatter_add", + }; +} + +/// The text model's key heads for `heads` query heads: 64 over 8, so a group of 8 where it divides, else one. +pub fn kvHeads(f: Form, heads: usize) usize { + if (f.fused) return heads; + return if (heads % 8 == 0) heads / 8 else 1; +} + +pub const nan16: u16 = 0x7fc0; +pub const inf16: u16 = 0x7f80; +pub const ninf16: u16 = 0xff80; + +/// The rig and the host copies of one prepared call; `reset` (the harness's release) frees both. +pub const Bench = struct { + rig: rig_.Rig, + arena: std.heap.ArenaAllocator, + + pub fn outputBytes(b: *Bench) ![]const u8 { + return b.rig.outputBytes(); + } + pub fn inputBytes(b: *Bench) ![]const u8 { + return b.rig.inputBytes(); + } + pub fn intact(b: *Bench) !bool { + return b.rig.intact(); + } + pub fn overlap(b: *Bench) bool { + return b.rig.overlap(); + } + pub fn reset(b: *Bench) void { + b.rig.reset(); + _ = b.arena.reset(.free_all); + } +}; + +const Fresh = struct { ref: rig_.Ref, bytes: []const u8 }; + +pub const Case = struct { + a: std.mem.Allocator, + rig: Bench, + pipe: mtl.Pipeline, + form: Form, + spec: c.Spec, + control: ?g.Gate = null, + shape: c.Shape = undefined, + stress: bool = false, + /// Host bf16 inputs in binding order (gemm x w b; norm x w; heads q k wq wk; attention q k v; glu g v; x y). + in: [4][]u16 = @splat(&.{}), + /// hp_heads' cos and sin [rows, 64]. + tab: [2][]f32 = @splat(&.{}), + idx: []u32 = &.{}, + refs: [8]rig_.Ref = undefined, + /// In-place outputs, their starting bytes copied in before every launch. + fresh: [2]?Fresh = @splat(null), + /// Each output's range ends and allowance from the last reference (null: the spec's own bound). + lo: []f64 = &.{}, + hi: []f64 = &.{}, + allow: ?[]f64 = null, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, pipe: mtl.Pipeline, f: Form, spec: c.Spec, control: ?g.Gate) Case { + return .{ .a = a, .rig = .{ .rig = .{ .a = a, .device = device, .queue = queue }, .arena = std.heap.ArenaAllocator.init(a) }, .pipe = pipe, .form = f, .spec = spec, .control = control }; + } + + pub fn deinit(t: *Case) void { + t.rig.rig.deinit(); + t.rig.arena.deinit(); + } + + pub fn kernel(t: *Case) g.Kernel { + return .{ .spec = t.spec, .ctx = t, .vt = &vt, .control = t.control }; + } + + const vt = g.hooks(Case); + + pub fn alloc(t: *Case, comptime T: type, n: usize) ![]T { + return t.rig.arena.allocator().alloc(T, n); + } + + fn input(t: *Case, at: usize, data: anytype) !void { + t.refs[at] = try t.rig.rig.input(std.mem.sliceAsBytes(data)); + } + + /// An output the kernel reads and writes, holding `data` before every launch. + fn inPlace(t: *Case, at: usize, slot: usize, data: []const u16) !void { + const bytes = std.mem.sliceAsBytes(data); + t.refs[at] = try t.rig.rig.output(bytes.len); + t.fresh[slot] = .{ .ref = t.refs[at], .bytes = bytes }; + } + + fn output(t: *Case, at: usize, len: usize) !void { + t.refs[at] = try t.rig.rig.output(len); + } + + pub fn prepare(t: *Case, s: c.Shape, fill: g.Fill, seed: u64) !bool { + t.rig.reset(); + t.shape = s; + t.stress = fill == .stress; + t.in = @splat(&.{}); + t.tab = @splat(&.{}); + t.idx = &.{}; + t.fresh = @splat(null); + t.lo = &.{}; + t.hi = &.{}; + t.allow = null; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + return switch (t.form.kind) { + .gemm => t.gemm(s, fill, rng), + .norm => t.norm(s, fill, rng), + .heads => t.heads(s, fill, rng), + .attention => t.attention(s, fill, rng), + .glu => t.glu(s, fill, rng), + .add => t.add(s, fill, rng), + .scatter => t.scatter(s, fill, rng), + }; + } + + pub fn run(t: *Case) !void { + for (t.fresh) |f| if (f) |x| @memcpy(t.rig.rig.bytes(x.ref, x.bytes.len), x.bytes); + const p = t.rig.rig.begin(); + t.launch(p.e); + try t.rig.rig.finish(p); + } + + pub fn count(t: *Case) usize { + const s = t.shape; + return switch (t.form.kind) { + .gemm, .glu, .add => s.rows * s.n, + .norm => s.rows * s.k, + .heads => s.rows * (if (t.form.fused) 3 * s.n else s.n + kvHeads(t.form, s.n)) * 128, + .attention => s.k * s.rows * 128, + .scatter => scatterRows(s.rows) * s.n, + }; + } + + pub fn reference(t: *Case, w: []f64, mag: []f64) !void { + return want.reference(t, w, mag); + } + + pub fn bounds(t: *Case, _: []const f64, _: []const f64, allow: []f64) !void { + if (t.allow) |x| @memcpy(allow, x); + } + + pub fn intervals(t: *Case, low: []f64, high: []f64) !void { + if (t.lo.len == low.len) { + @memcpy(low, t.lo); + @memcpy(high, t.hi); + return; + } + @memset(low, -std.math.floatMax(f64)); + @memset(high, std.math.floatMax(f64)); + } + + pub fn simulate(t: *Case, acc: c.Accum, order: g.Order, out: []f64) !void { + return want.simulate(t, .{ .acc = acc, .order = order }, out); + } + + fn gemm(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const M = s.rows; + const N = s.n; + const K = s.k; + if (M == 0 or N == 0 or K == 0 or N % 64 != 0 or K % 32 != 0) return false; + const x = try t.alloc(u16, M * K); + const w = try t.alloc(u16, N * K); + const b = try t.alloc(u16, if (t.form.bias) N else 0); + if (fill == .stress) { + mirror(rng, x, w, M, N, K); + @memset(b, 0); + } else { + uniform(rng, x, -1, 1); + uniform(rng, w, -1, 1); + uniform(rng, b, -0.5, 0.5); + } + if (fill == .nonfinite) { + plant(x, K, M); + w[(N - 1) * K + 5] = nan16; + if (b.len > 7) b[7] = nan16; + } + t.in = .{ x, w, b, &.{} }; + try t.input(0, x); + try t.input(1, w); + if (t.form.bias) try t.input(2, b) else t.refs[2] = t.refs[1]; + try t.output(3, M * N * 2); + return true; + } + + fn norm(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const W = s.k; + if (s.rows == 0 or W == 0) return false; + const x = try t.alloc(u16, s.rows * W); + const w = try t.alloc(u16, W); + if (fill == .stress) ints(rng, x, 32) else uniform(rng, x, -2, 2); + uniform(rng, w, 0.25, 2); + if (fill == .nonfinite) { + plant(x, W, s.rows); + w[W / 5] = nan16; + } + t.in = .{ x, w, &.{}, &.{} }; + try t.input(0, x); + try t.input(1, w); + try t.output(2, x.len * 2); + return true; + } + + fn heads(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const T = s.rows; + const H = s.n; + if (T == 0 or H == 0 or s.k != 128) return false; + const kv = kvHeads(t.form, H); + const q = try t.alloc(u16, T * (if (t.form.fused) 3 * H else H) * 128); + const k = try t.alloc(u16, if (t.form.fused) 0 else T * kv * 128); + const wq = try t.alloc(u16, 128); + const wk = try t.alloc(u16, 128); + for ([_][]u16{ q, k }) |x| if (fill == .stress) ints(rng, x, 64) else uniform(rng, x, -2, 2); + uniform(rng, wq, 0.25, 2); + uniform(rng, wk, 0.25, 2); + const rot = !t.form.fused; + for (&t.tab) |*x| x.* = try t.alloc(f32, if (rot) T * 64 else 0); + for (t.tab[0], t.tab[1]) |*cs, *sn| { + const angle = rng.float(f64) * 2 * std.math.pi; + cs.* = @floatCast(ref.bf(@cos(angle))); + sn.* = @floatCast(ref.bf(@sin(angle))); + } + if (fill == .nonfinite and T >= 5) { + // q: NaN, +Inf, -Inf, then both infinities in one head; k: a NaN; the rest of the q k v row as it was + const qr = if (t.form.fused) 3 * H * 128 else H * 128; + const qh: usize = if (t.form.fused) 384 else 128; + const places = [_][3]usize{ .{ 0, 0, 3 }, .{ 1, 1 % H, 70 }, .{ 2, 0, 127 }, .{ 3, 0, 0 }, .{ 3, 0, 64 } }; + for (places, [_]u16{ nan16, inf16, ninf16, inf16, ninf16 }) |p, v| q[p[0] * qr + p[1] * qh + p[2]] = v; + if (t.form.fused) { + q[4 * qr + 128 + 9] = nan16; + q[4 * qr + 256 + 1] = nan16; + } else { + k[4 * kv * 128 + 9] = nan16; + t.tab[0][(T - 3) * 64 + 10] = std.math.nan(f32); + t.tab[1][(T - 2) * 64 + 20] = std.math.inf(f32); + } + } + t.in = .{ q, k, wq, wk }; + try t.inPlace(0, 0, q); + if (t.form.fused) t.refs[1] = .{ .buf = t.refs[0].buf, .off = t.refs[0].off + 128 * 2 } else try t.inPlace(1, 1, k); + try t.input(2, wq); + try t.input(3, wk); + if (rot) { + try t.input(4, t.tab[0]); + try t.input(5, t.tab[1]); + } else { + t.refs[4] = t.refs[2]; + t.refs[5] = t.refs[2]; + } + return true; + } + + fn attention(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const H = s.rows; + const T = s.k; + if (H == 0 or T == 0 or s.n != 128) return false; + const kv = kvHeads(t.form, H); + const q = try t.alloc(u16, T * (if (t.form.fused) 3 * H else H) * 128); + const k = try t.alloc(u16, if (t.form.fused) 0 else T * kv * 128); + const v = try t.alloc(u16, if (t.form.fused) 0 else T * kv * 128); + t.in = .{ q, k, v, &.{} }; + if (fill == .stress) try want.stressAttention(t, T, kv, rng) else for ([_][]u16{ q, k, v }) |x| uniform(rng, x, -1, 1); + if (fill == .nonfinite) want.plantAttention(t, T, H, kv); + try t.input(0, q); + if (t.form.fused) { + t.refs[1] = .{ .buf = t.refs[0].buf, .off = t.refs[0].off + 128 * 2 }; + t.refs[2] = .{ .buf = t.refs[0].buf, .off = t.refs[0].off + 256 * 2 }; + } else { + try t.input(1, k); + try t.input(2, v); + } + try t.output(3, T * H * 128 * 2); + return true; + } + + fn glu(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const T = s.rows; + const W = s.n; + if (T == 0 or W == 0) return false; + const gt = try t.alloc(u16, T * W * (if (t.form.fused) @as(usize, 2) else 1)); + const v = try t.alloc(u16, if (t.form.fused) 0 else T * W); + const vs = if (t.form.fused) gt else v; + const gr = if (t.form.fused) 2 * W else W; + const vo = if (t.form.fused) W else 0; + for (0..T) |r| { + uniform(rng, gt[r * gr ..][0..W], -8, 8); + uniform(rng, vs[r * gr + vo ..][0..W], -2, 2); + } + if (fill == .nonfinite and T >= 7 and W >= 4) { + for ([_][2]usize{ .{ 0, W / 3 }, .{ 1, W / 2 }, .{ 2, W - 1 }, .{ 3, 0 }, .{ 3, W - 1 } }, [_]u16{ nan16, inf16, ninf16, inf16, ninf16 }) |p, x| gt[p[0] * gr + p[1]] = x; + for ([_][2]usize{ .{ 4, 1 }, .{ 5, 2 }, .{ 6, 3 } }, [_]u16{ nan16, inf16, ninf16 }) |p, x| vs[p[0] * gr + vo + p[1]] = x; + } + t.in = .{ gt, v, &.{}, &.{} }; + try t.input(0, gt); + if (t.form.fused) t.refs[1] = .{ .buf = t.refs[0].buf, .off = t.refs[0].off + W * 2 } else try t.input(1, v); + try t.output(2, T * W * 2); + return true; + } + + fn add(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const n = s.rows * s.n; + if (n == 0) return false; + const x = try t.alloc(u16, n); + const y = try t.alloc(u16, n); + uniform(rng, x, -4, 4); + uniform(rng, y, -4, 4); + if (fill == .nonfinite) { + plant(x, s.n, s.rows); + if (s.rows > 5) { + y[4 * s.n + 1] = nan16; + y[5 * s.n + 2] = inf16; + } + } + t.in = .{ x, y, &.{}, &.{} }; + try t.inPlace(0, 0, x); + try t.input(1, y); + return true; + } + + fn scatter(t: *Case, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const P = s.rows; + const W = s.n; + if (P == 0 or W == 0) return false; + const T = scatterRows(P); + const x = try t.alloc(u16, T * W); + const y = try t.alloc(u16, P * W); + uniform(rng, x, -4, 4); + uniform(rng, y, -4, 4); + // the pads: P rising rows of T, after a label's rows and in runs, as a presentation places them + const rows = try t.alloc(u32, T); + for (rows, 0..) |*r, i| r.* = @intCast(i); + rng.shuffle(u32, rows[3..]); + t.idx = rows[3..][0..P]; + std.mem.sort(u32, t.idx, {}, std.sort.asc(u32)); + if (fill == .nonfinite) { + plant(y, W, P); + if (P > 5) x[@as(usize, t.idx[4]) * W + 1] = nan16; + x[1 * W + 2] = inf16; + } + t.in = .{ x, y, &.{}, &.{} }; + try t.inPlace(0, 0, x); + try t.input(1, y); + try t.input(2, t.idx); + return true; + } + + fn bind(t: *Case, e: mtl.ComputeEncoder, at: usize) void { + e.setBuffer(t.refs[at].buf, t.refs[at].off, at); + } + + fn u(v: usize) u32 { + return @intCast(v); + } + + /// The dispatch of the prompt_kernels.zig function each kind mirrors: same buffers, constants, grid and groups. + fn launch(t: *Case, e: mtl.ComputeEncoder) void { + const s = t.shape; + const f = t.form; + e.setPipeline(t.pipe); + switch (f.kind) { + .gemm => { + // Kernels.gemm + for (0..4) |i| t.bind(e, i); + e.setValue(extern struct { M: u32, N: u32, K: u32, bias: u32 }{ .M = u(s.rows), .N = u(s.n), .K = u(s.k), .bias = @intFromBool(f.bias) }, 4); + e.dispatchGroups(mtl.Size.of(s.n / 64, (s.rows + 63) / 64, 1), mtl.Size.of(128, 1, 1)); + }, + .norm => { + // Kernels.norm + for (0..3) |i| t.bind(e, i); + e.setValue(extern struct { width: u32, mode: u32, eps: f32 }{ .width = u(s.k), .mode = @backingInt(f.mode), .eps = f.eps }, 3); + e.dispatchGroups(mtl.Size.of(s.rows, 1, 1), mtl.Size.of(256, 1, 1)); + }, + .heads => { + // Kernels.heads + const kv = kvHeads(f, s.n); + const row: usize = if (f.fused) 3 * s.n * 128 else s.n * 128; + for (0..6) |i| t.bind(e, i); + e.setValue(extern struct { heads: u32, kv_heads: u32, q_row: u32, k_row: u32, head: u32, mode: u32, rotary: u32, eps: f32 }{ + .heads = u(s.n), + .kv_heads = u(kv), + .q_row = u(row), + .k_row = u(if (f.fused) row else kv * 128), + .head = if (f.fused) 384 else 128, + .mode = @backingInt(f.mode), + .rotary = @intFromBool(!f.fused), + .eps = f.eps, + }, 6); + e.dispatchGroups(mtl.Size.of(s.rows, (s.n + kv + 7) / 8, 1), mtl.Size.of(256, 1, 1)); + }, + .attention => { + // Kernels.attention + const kv = kvHeads(f, s.rows); + const row: usize = if (f.fused) 3 * s.rows * 128 else s.rows * 128; + const kr: usize = if (f.fused) row else kv * 128; + for (0..4) |i| t.bind(e, i); + e.setValue(extern struct { rows: u32, heads: u32, kv_heads: u32, q_row: u32, k_row: u32, v_row: u32, head: u32, causal: u32, scale: f32 }{ + .rows = u(s.k), + .heads = u(s.rows), + .kv_heads = u(kv), + .q_row = u(row), + .k_row = u(kr), + .v_row = u(kr), + .head = if (f.fused) 384 else 128, + .causal = @intFromBool(f.causal), + .scale = want.scale, + }, 4); + e.dispatchGroups(mtl.Size.of(s.k, (s.rows + 7) / 8, 1), mtl.Size.of(256, 1, 1)); + }, + .glu => { + // Kernels.glu + const r: usize = if (f.fused) 2 * s.n else s.n; + for (0..3) |i| t.bind(e, i); + e.setValue(extern struct { width: u32, g_row: u32, v_row: u32, mode: u32 }{ .width = u(s.n), .g_row = u(r), .v_row = u(r), .mode = @backingInt(f.mode) }, 3); + e.dispatchThreads(mtl.Size.of(s.n, s.rows, 1), mtl.Size.of(256, 1, 1)); + }, + .add => { + // Kernels.add + for (0..2) |i| t.bind(e, i); + e.setValue(u(s.rows * s.n), 2); + e.dispatchThreads(mtl.Size.of(s.rows * s.n, 1, 1), mtl.Size.of(256, 1, 1)); + }, + .scatter => { + // Kernels.scatterAdd + for (0..3) |i| t.bind(e, i); + e.setValue(u(s.n), 3); + e.dispatchThreads(mtl.Size.of(s.n, s.rows, 1), mtl.Size.of(256, 1, 1)); + }, + } + } +}; + +/// The presentation rows around `pads` image pads: labels, vision marks and the prompt's own text. +pub fn scatterRows(pads: usize) usize { + return pads + 37; +} + +pub fn uniform(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +/// Integers in [-bound, bound]. +pub fn ints(rng: std.Random, out: []u16, bound: u32) void { + for (out) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 2 * bound + 1))) - @as(f32, @floatFromInt(bound))); +} + +/// NaN, +Inf and -Inf in rows 0 to 2 of [rows, width], and both infinities in row 3. +pub fn plant(x: []u16, width: usize, rows: usize) void { + const at = [_][2]usize{ .{ 0, width / 3 }, .{ 1, width / 2 }, .{ 2, width - 1 }, .{ 3, 0 }, .{ 3, width - 1 } }; + for (at, [_]u16{ nan16, inf16, ninf16, inf16, ninf16 }) |p, v| if (p[0] < rows) { + x[p[0] * width + p[1]] = v; + }; +} + +/// Gate 4's gemm rows: integers to 16, the second half cancelling the first but for 4 ones; every output is 4. +fn mirror(rng: std.Random, x: []u16, w: []u16, M: usize, N: usize, K: usize) void { + // partials pass fp16's range and each 32nd-term chain 2,048, all below 2^24 in any order + const h = K / 2; + for (0..M) |m| for (0..h) |i| { + const v: f32 = if (i < 4) 1 else @floatFromInt(1 + rng.uintLessThan(u32, 16)); + x[m * K + i] = c.toBf16(v); + x[m * K + h + i] = c.toBf16(v); + }; + for (0..N) |n| for (0..h) |i| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 16)); + w[n * K + i] = c.toBf16(v); + w[n * K + h + i] = c.toBf16(if (i < 4) 1 - v else -v); + }; +} diff --git a/zig/tests/contract/metal_h3_image_prompt_ref.zig b/zig/tests/contract/metal_h3_image_prompt_ref.zig new file mode 100644 index 00000000000..b614088213e --- /dev/null +++ b/zig/tests/contract/metal_h3_image_prompt_ref.zig @@ -0,0 +1,265 @@ +//! The prompt kernels in float64: each output at its kernel's bf16 points, the range fp32 allows, gate 4's sums. +const std = @import("std"); +const contract = @import("contract"); + +const c = contract.spec; +const Order = contract.gates.Order; +const sumIn = contract.rows.sumIn; +const ar = contract.attention_range; +const threads = contract.reference_threads; + +/// How a norm or SiLU rounds: as the Qwen text model (mode 0) or as H3's refiner blocks (mode 1). +pub const Mode = enum(u32) { qwen = 0, h3 = 1 }; + +// Metal's error bounds under the launcher's options (safe math, fast functions) and the kernels' `precise::` calls. +pub const div_ulps = 2.5; +pub const rsqrt_ulps = 2; +pub const exp_ulps = 4; + +pub fn bf(v: f64) f64 { + return contract.bf16_round.bf16(v); +} + +pub fn val(h: u16) f64 { + return c.fromBf16(h); +} + +/// Every value a step may hold: its fp32 steps widen both ends, its bf16 points round them. +pub const Range = struct { + lo: f64, + hi: f64, + + pub fn of(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// An fp32 step good to `ulps` units in the last place (a correctly rounded one: 0.5). + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * 0x1p-23; + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + pub fn bf16(a: Range) Range { + return .{ .lo = bf(a.lo), .hi = bf(a.hi) }; + } + pub fn neg(a: Range) Range { + return .{ .lo = -a.hi, .hi = -a.lo }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [4]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } + /// 1 / a, a positive. + pub fn recip(a: Range) Range { + return .{ .lo = 1 / a.hi, .hi = 1 / a.lo }; + } + /// 1 / sqrt(a), a positive. + pub fn rsqrt(a: Range) Range { + return .{ .lo = 1 / @sqrt(a.hi), .hi = 1 / @sqrt(a.lo) }; + } +}; + +/// rsqrt(ss / n + eps) in float64, and its range through fp32 sums `depth` deep (or exact) and the kernel's steps. +pub fn inverse(ss: f64, n: f64, eps: f32, depth: usize, exact: bool) struct { r: f64, range: Range } { + const e = if (exact) 0 else c.gamma(@floatFromInt(depth), c.unit(.f32)) * ss; + const mean = (Range{ .lo = (ss - e) / n, .hi = (ss + e) / n }).fp32(div_ulps); + const eps64: f64 = eps; + return .{ .r = 1 / @sqrt(ss / n + eps64), .range = mean.add(Range.of(eps64)).fp32(0.5).rsqrt().fp32(rsqrt_ulps) }; +} + +/// One normed value as hp_normed rounds it: qwen bf16(w bf16(x r)), h3 bf16(x r w). +pub fn normed(x: f64, r: f64, w: f64, mode: Mode) f64 { + return switch (mode) { + .qwen => bf(w * bf(x * r)), + .h3 => bf(x * r * w), + }; +} + +pub fn normedRange(x: f64, r: Range, w: f64, mode: Mode) Range { + const xr = Range.of(x).mul(r).fp32(0.5); + return switch (mode) { + .qwen => xr.bf16().mul(Range.of(w)).fp32(0.5).bf16(), + .h3 => xr.mul(Range.of(w)).fp32(0.5).bf16(), + }; +} + +/// A channel turned with its signed partner o: bf16(bf16(n cos) + bf16(o sin)), as hp_heads rounds. +pub fn turned(n: f64, o: f64, cs: f64, sn: f64) f64 { + return bf(bf(n * cs) + bf(o * sn)); +} + +pub fn turnedRange(n: Range, o: Range, cs: f64, sn: f64) Range { + const a = n.mul(Range.of(cs)).fp32(0.5).bf16(); + const b = o.mul(Range.of(sn)).fp32(0.5).bf16(); + return a.add(b).fp32(0.5).bf16(); +} + +/// 1 + exp(-g) through the kernel's precise exp and add; past fp32's range its exp is +Inf. +fn denominator(g: f64) Range { + var e = Range.of(@exp(-g)).fp32(exp_ulps); + if (e.hi > std.math.floatMax(f32)) e.hi = std.math.inf(f64); + return e.add(Range.of(1)).fp32(0.5); +} + +/// hp_glu's output: qwen bf16(bf16(g / (1 + e^-g)) v), h3 bf16(bf16(g bf16(1 / (1 + e^-g))) v). +pub fn glu(g: f64, v: f64, mode: Mode) f64 { + const e = 1 + @exp(-g); + const s = switch (mode) { + .qwen => bf(g / e), + .h3 => bf(g * bf(1 / e)), + }; + return bf(s * v); +} + +pub fn gluRange(g: f64, v: f64, mode: Mode) Range { + const e = denominator(g); + const s = switch (mode) { + .qwen => Range.of(g).mul(e.recip()).fp32(div_ulps).bf16(), + .h3 => Range.of(g).mul(e.recip().fp32(div_ulps).bf16()).fp32(0.5).bf16(), + }; + return s.mul(Range.of(v)).fp32(0.5).bf16(); +} + +/// Gate 4's simulated sums: an accumulator and an order, or float64 (`acc` none). +pub const Sum = struct { + acc: c.Accum = .none, + order: Order = .sequential, + + pub fn of(s: Sum, t: []const f64) f64 { + if (s.acc != .none) return sumIn(s.acc, s.order, t); + var x: f64 = 0; + for (t) |v| x += v; + return x; + } +}; + +/// hp_gemm's outputs in float64 (each sum |x w|, plus |b|, its magnitude), or gate 4's sums in `sim`, on 8 threads. +pub const Gemm = struct { + x: []const u16, + w: []const u16, + b: ?[]const u16, + M: usize, + N: usize, + K: usize, + + const Job = struct { + g: *const Gemm, + from: usize, + to: usize, + sim: ?Sum, + out: []f64, + mag: []f64, + row: []f64, + terms: []f64, + + pub fn run(j: *Job) void { + const g = j.g; + var have: usize = std.math.maxInt(usize); + for (j.from..j.to) |i| { + const m = i / g.N; + const n = i % g.N; + if (m != have) { + for (j.row, g.x[m * g.K ..][0..g.K]) |*o, h| o.* = val(h); + have = m; + } + const bias: f64 = if (g.b) |b| val(b[n]) else 0; + const w = g.w[n * g.K ..][0..g.K]; + if (j.sim) |s| { + for (j.terms, j.row, w) |*t, x, h| t.* = x * val(h); + j.out[i] = s.of(j.terms) + bias; + continue; + } + const d = dot(j.row, w); + j.out[i] = d[0] + bias; + j.mag[i] = d[1] + @abs(bias); + } + } + }; + + /// Each output, and its magnitude unless `sim`; `scratch` holds 8 rows and, for `sim`, 8 rows of terms. + pub fn run(g: *const Gemm, a: std.mem.Allocator, sim: ?Sum, out: []f64, mag: []f64) !void { + const total = g.M * g.N; + const n = threads.count(threads.maximum, total); + const scratch = try a.alloc(f64, 2 * n * g.K); + defer a.free(scratch); + var jobs: [threads.maximum]Job = undefined; + for (jobs[0..n], 0..) |*j, t| j.* = .{ + .g = g, + .from = total * t / n, + .to = total * (t + 1) / n, + .sim = sim, + .out = out, + .mag = mag, + .row = scratch[2 * t * g.K ..][0..g.K], + .terms = scratch[(2 * t + 1) * g.K ..][0..g.K], + }; + threads.run(Job, jobs[0..n], .normal); + } +}; + +/// x . w in float64 and sum |x w|, w as bf16 bits. +fn dot(x: []const f64, w: []const u16) [2]f64 { + const V = @Vector(8, f64); + var s: V = @splat(0); + var m: V = @splat(0); + var i: usize = 0; + while (i + 8 <= w.len) : (i += 8) { + const bits: @Vector(8, u32) = w[i..][0..8].*; + const f: @Vector(8, f32) = @bitCast(bits << @splat(16)); + const p = @as(V, x[i..][0..8].*) * @as(V, @floatCast(f)); + s += p; + m += @abs(p); + } + var t = [2]f64{ @reduce(.Add, s), @reduce(.Add, m) }; + while (i < w.len) : (i += 1) { + const p = x[i] * val(w[i]); + t[0] += p; + t[1] += @abs(p); + } + return t; +} + +/// hp_attention's fp32 steps: lane dots, simd_sum, precise exp, `n` keys in order with `raised` rescales, division. +pub fn form(n: usize, raised: usize) ar.Form { + const chain: f64 = @floatFromInt(n + raised + 3); + return .{ + .score = 4 + 6, + .fast_exp = false, + .chunk_exp = true, + .p_rel = 0, + .num = chain, + .den = chain, + .score_round = 1, + .div = 2 * div_ulps, + .exp_ulps = .{ exp_ulps * @as(f64, @floatFromInt(1 + raised)), 0 }, + }; +} + +/// Blocks past the first that may raise the running max; one that does not rescales by exp(0) = 1, changing nothing. +pub fn rises(q: []const f64, k: []const f64, n: usize, scale: f64, s: []f64) usize { + const f = form(n, 0); + const u: f64 = 0x1p-24; + var spread: f64 = 0; + for (0..n) |j| { + var dot_: f64 = 0; + var abs: f64 = 0; + for (q, k[j * 128 ..][0..128]) |x, y| { + dot_ += x * y; + abs += @abs(x * y); + } + s[j] = dot_ * scale; + const t = f.score * u * abs * @abs(scale) + f.score_round * u * @abs(s[j]); + if (std.math.isFinite(t)) spread = @max(spread, t); + } + var top = -std.math.inf(f64); + var count: usize = 0; + var j0: usize = 0; + while (j0 < n) : (j0 += 4) { + var most = -std.math.inf(f64); + for (s[j0..@min(j0 + 4, n)]) |v| most = @max(most, v); + if (j0 > 0 and most + spread >= top - spread) count += 1; + top = @max(top, most); + } + return count; +} diff --git a/zig/tests/contract/metal_h3_image_prompt_want.zig b/zig/tests/contract/metal_h3_image_prompt_want.zig new file mode 100644 index 00000000000..aa6efb71aa8 --- /dev/null +++ b/zig/tests/contract/metal_h3_image_prompt_want.zig @@ -0,0 +1,314 @@ +//! The prompt cases' float64 outputs and ranges, gate 4's simulated sums, and attention's planted inputs. +const std = @import("std"); +const contract = @import("contract"); +const ref = @import("metal_h3_image_prompt_ref.zig"); +const case = @import("metal_h3_image_prompt_case.zig"); + +const c = contract.spec; +const ar = contract.attention_range; +const threads = contract.reference_threads; +const Case = case.Case; +const Range = ref.Range; +const val = ref.val; + +/// hp_attention's score scale as the launcher passes it: fp32 1 / sqrt(128). +pub const scale: f32 = 1.0 / @sqrt(128.0); + +fn sized(t: *Case, n: usize) !void { + t.lo = try t.alloc(f64, n); + t.hi = try t.alloc(f64, n); + t.allow = try t.alloc(f64, n); +} + +/// Output i: the float64 value at the kernel's bf16 points and its range (a non-finite value is checked by class). +fn put(t: *Case, w: []f64, mag: []f64, i: usize, point: f64, r: Range) void { + const finite = std.math.isFinite(point); + w[i] = point; + mag[i] = if (finite) @abs(point) else 0; + t.lo[i] = r.lo; + t.hi[i] = r.hi; + t.allow.?[i] = if (finite) @max(@abs(point - r.lo), @abs(r.hi - point)) else 0; +} + +fn squares(x: []const u16, s: ref.Sum, terms: []f64) f64 { + for (terms, x) |*o, h| o.* = val(h) * val(h); + return s.of(terms); +} + +/// Where a head's values sit: the q heads then the key heads, in their buffers and in the outputs. +const HeadAt = struct { buf: usize, at: usize, out: usize }; + +fn headAt(t: *Case, r: usize, h: usize) HeadAt { + const H = t.shape.n; + const kv = case.kvHeads(t.form, H); + if (t.form.fused) { + const at = r * 3 * H * 128 + (h % H) * 384 + (if (h < H) @as(usize, 0) else 128); + return .{ .buf = 0, .at = at, .out = at }; + } + if (h < H) return .{ .buf = 0, .at = (r * H + h) * 128, .out = (r * H + h) * 128 }; + const at = (r * kv + h - H) * 128; + return .{ .buf = 1, .at = at, .out = t.shape.rows * H * 128 + at }; +} + +pub fn reference(t: *Case, w: []f64, mag: []f64) !void { + const s = t.shape; + const f = t.form; + t.allow = null; + t.lo = &.{}; + t.hi = &.{}; + switch (f.kind) { + .gemm => { + const g: ref.Gemm = .{ .x = t.in[0], .w = t.in[1], .b = if (f.bias) t.in[2] else null, .M = s.rows, .N = s.n, .K = s.k }; + try g.run(t.a, null, w, mag); + }, + .norm => { + try sized(t, w.len); + const W = s.k; + const terms = try t.alloc(f64, W); + for (0..s.rows) |r| { + const x = t.in[0][r * W ..][0..W]; + const inv = ref.inverse(squares(x, .{}, terms), @floatFromInt(W), f.eps, t.spec.depth(s), t.stress); + for (x, t.in[1], 0..) |xh, wh, i| put(t, w, mag, r * W + i, ref.normed(val(xh), inv.r, val(wh), f.mode), ref.normedRange(val(xh), inv.range, val(wh), f.mode)); + } + }, + .heads => try heads(t, null, w, mag), + .attention => try attention(t, w, mag), + .glu => { + try sized(t, w.len); + const W = s.n; + const gr = if (f.fused) 2 * W else W; + const vs = if (f.fused) t.in[0] else t.in[1]; + const vo: usize = if (f.fused) W else 0; + for (0..s.rows) |r| for (0..W) |i| { + const gv = val(t.in[0][r * gr + i]); + const vv = val(vs[r * gr + vo + i]); + put(t, w, mag, r * W + i, ref.glu(gv, vv, f.mode), ref.gluRange(gv, vv, f.mode)); + }; + }, + .add => for (w, mag, t.in[0], t.in[1]) |*o, *m, x, y| { + o.* = val(x) + val(y); + m.* = @abs(val(x)) + @abs(val(y)); + }, + .scatter => { + for (w, mag, t.in[0]) |*o, *m, x| { + o.* = val(x); + m.* = @abs(val(x)); + } + const W = s.n; + for (t.idx, 0..) |row, i| for (0..W) |e| { + const at = @as(usize, row) * W + e; + const y = val(t.in[1][i * W + e]); + w[at] += y; + mag[at] += @abs(y); + }; + }, + } +} + +/// hp_heads in float64 (`sim`: gate 4's sums, points alone): each head normed, then turned when the form ropes. +fn heads(t: *Case, sim: ?ref.Sum, w: []f64, mag: []f64) !void { + const s = t.shape; + const f = t.form; + const H = s.n; + const kv = case.kvHeads(f, H); + if (sim == null) try sized(t, w.len); + var terms: [128]f64 = undefined; + var point: [128]f64 = undefined; + var range: [128]Range = undefined; + for (0..s.rows) |r| { + for (0..H + kv) |h| { + const p = headAt(t, r, h); + const x = t.in[p.buf][p.at..][0..128]; + const wt = t.in[if (h < H) 2 else 3]; + const inv = ref.inverse(squares(x, sim orelse .{}, &terms), 128, f.eps, t.spec.depth(s), t.stress); + for (0..128) |e| { + point[e] = ref.normed(val(x[e]), inv.r, val(wt[e]), f.mode); + if (sim == null) range[e] = ref.normedRange(val(x[e]), inv.range, val(wt[e]), f.mode); + } + for (0..128) |e| { + var o = point[e]; + var or_ = range[e]; + if (!f.fused) { + // rotate-half: channel e pairs with e + 64 negated below the half, e - 64 above + const q = if (e < 64) e + 64 else e - 64; + const sign: f64 = if (e < 64) -1 else 1; + const at = r * 64 + e % 64; + o = ref.turned(point[e], sign * point[q], t.tab[0][at], t.tab[1][at]); + if (sim == null) or_ = ref.turnedRange(range[e], if (e < 64) range[q].neg() else range[q], t.tab[0][at], t.tab[1][at]); + } + if (sim == null) put(t, w, mag, p.out + e, o, or_) else w[p.out + e] = o; + } + } + if (!f.fused) continue; + // the refiner's v heads ride in the same rows, untouched + for (0..H) |h| for (0..128) |e| { + const at = r * 3 * H * 128 + h * 384 + 256 + e; + const v = val(t.in[0][at]); + if (sim == null) put(t, w, mag, at, v, Range.of(v)) else w[at] = v; + }; + } +} + +/// Query `h`'s row `r` and key head `kv`'s rows, in the case's buffers. +fn qAt(t: *Case, r: usize, h: usize) usize { + const H = t.shape.rows; + return if (t.form.fused) r * 3 * H * 128 + h * 384 else (r * H + h) * 128; +} + +fn kvAt(t: *Case, j: usize, kvh: usize, v: bool) struct { buf: usize, at: usize } { + const H = t.shape.rows; + if (t.form.fused) return .{ .buf = 0, .at = j * 3 * H * 128 + kvh * 384 + (if (v) @as(usize, 256) else 128) }; + return .{ .buf = if (v) 2 else 1, .at = (j * case.kvHeads(t.form, H) + kvh) * 128 }; +} + +const AttnJob = struct { + t: *Case, + from: usize, + to: usize, + w: []f64, + mag: []f64, + scratch: []f64, + + pub fn run(j: *AttnJob) void { + const t = j.t; + const H = t.shape.rows; + const T = t.shape.k; + const group = H / case.kvHeads(t.form, H); + const kf = j.scratch[0 .. T * 128]; + const vf = j.scratch[T * 128 .. 2 * T * 128]; + const sc = j.scratch[2 * T * 128 ..][0..T]; + const wt = j.scratch[2 * T * 128 + T ..][0..T]; + const tau = j.scratch[2 * T * 128 + 2 * T ..][0..T]; + var q: [128]f64 = undefined; + var point: [128]f64 = undefined; + var half: [128]f64 = undefined; + var have: usize = std.math.maxInt(usize); + for (j.from..j.to) |h| { + if (h / group != have) { + have = h / group; + for (0..T) |key| for ([_]bool{ false, true }, [_][]f64{ kf, vf }) |isv, dst| { + const p = kvAt(t, key, have, isv); + for (dst[key * 128 ..][0..128], t.in[p.buf][p.at..][0..128]) |*o, x| o.* = val(x); + }; + } + for (0..T) |r| { + for (&q, t.in[0][qAt(t, r, h)..][0..128]) |*o, x| o.* = val(x); + const end = if (t.form.causal) r + 1 else T; + const f = ref.form(end, ref.rises(&q, kf, end, scale, sc)); + ar.head(&q, kf, vf, end, 128, scale, f, wt, tau, &point, &half); + for (0..128) |e| { + const i = (r * H + h) * 128 + e; + j.w[i] = point[e]; + j.mag[i] = if (std.math.isFinite(point[e])) @abs(point[e]) else 0; + t.allow.?[i] = ar.allowBf16(point[e], half[e], 0, 0); + const ends = ar.intervalBf16(point[e], half[e], 0, 0); + t.lo[i] = ends[0]; + t.hi[i] = ends[1]; + } + } + } + } +}; + +/// hp_attention within attention_range's float64 range, heads over 8 threads; gate 4's equal scores exact. +fn attention(t: *Case, w: []f64, mag: []f64) !void { + const H = t.shape.rows; + const T = t.shape.k; + try sized(t, w.len); + if (t.stress) { + t.lo = &.{}; + t.hi = &.{}; + for (0..T) |r| { + const end = if (t.form.causal) r + 1 else T; + var sum: f64 = 0; + for (0..end) |j| sum += val(t.in[kvAt(t, j, 0, true).buf][kvAt(t, j, 0, true).at]); + const o = sum / @as(f64, @floatFromInt(end)); + for (w[r * H * 128 ..][0 .. H * 128], mag[r * H * 128 ..][0 .. H * 128], t.allow.?[r * H * 128 ..][0 .. H * 128]) |*x, *m, *l| { + x.* = o; + m.* = @abs(o); + l.* = c.boundExact(t.spec, o); + } + } + return; + } + const n = threads.count(threads.maximum, H); + const scratch = try t.alloc(f64, n * (2 * T * 128 + 3 * T)); + var jobs: [threads.maximum]AttnJob = undefined; + for (jobs[0..n], 0..) |*j, i| j.* = .{ .t = t, .from = H * i / n, .to = H * (i + 1) / n, .w = w, .mag = mag, .scratch = scratch[i * (2 * T * 128 + 3 * T) ..][0 .. 2 * T * 128 + 3 * T] }; + threads.run(AttnJob, jobs[0..n], .normal); +} + +pub fn simulate(t: *Case, s: ref.Sum, out: []f64) !void { + const sh = t.shape; + const f = t.form; + switch (f.kind) { + .gemm => { + const g: ref.Gemm = .{ .x = t.in[0], .w = t.in[1], .b = if (f.bias) t.in[2] else null, .M = sh.rows, .N = sh.n, .K = sh.k }; + try g.run(t.a, s, out, out); + }, + .norm => { + const W = sh.k; + const terms = try t.alloc(f64, W); + for (0..sh.rows) |r| { + const x = t.in[0][r * W ..][0..W]; + const r_ = ref.inverse(squares(x, s, terms), @floatFromInt(W), f.eps, 0, true).r; + for (x, t.in[1], 0..) |xh, wh, i| out[r * W + i] = ref.normed(val(xh), r_, val(wh), f.mode); + } + }, + .heads => try heads(t, s, out, out), + .attention => { + // equal scores: each row is its keys' values summed, over its keys' count summed the same way + if (!t.stress) return error.AttentionSumsNeedEqualScores; + const H = sh.rows; + const T = sh.k; + const terms = try t.alloc(f64, 2 * T); + for (terms[0..T], 0..) |*v, j| v.* = val(t.in[kvAt(t, j, 0, true).buf][kvAt(t, j, 0, true).at]); + @memset(terms[T..], 1); + for (0..T) |r| { + const end = if (f.causal) r + 1 else T; + @memset(out[r * H * 128 ..][0 .. H * 128], s.of(terms[0..end]) / s.of(terms[T..][0..end])); + } + }, + .glu, .add, .scatter => return error.NoSums, + } +} + +fn setKv(t: *Case, j: usize, kvh: usize, isv: bool, ch: usize, v: u16) void { + const p = kvAt(t, j, kvh, isv); + t.in[p.buf][p.at + ch] = v; +} + +/// Gate 4: q = k = 0, weights 1; values 6,144-8,128 by 64, then negated: prefix sums near 2^22 cancel to 4. +pub fn stressAttention(t: *Case, T: usize, kv: usize, rng: std.Random) !void { + for (t.in[0..3]) |x| @memset(x, 0); + // each 32nd key's chain passes fp16's range; a few keep 127 so 1 - 127 leaves the 4 ones bf16 holds + const half = T / 2; + const vals = try t.alloc(f32, T); + for (vals, 0..) |*v, j| { + const nudge = j >= half and j - half < 8 and (j - half) % 2 == 0; + v.* = if (j < half) + (if (j < 8 and j % 2 == 0) 127 else @floatFromInt(64 * (96 + rng.uintLessThan(u32, 32)))) + else if (j < 2 * half) @as(f32, if (nudge) 1 else 0) - vals[j - half] else 0; + } + for (0..T) |j| for (0..kv) |kvh| { + const p = kvAt(t, j, kvh, true); + @memset(t.in[p.buf][p.at..][0..128], c.toBf16(vals[j])); + }; +} + +/// Gate 1's plants in q, k and v, an infinity only where its rows end on whole blocks; `last_key`: the finding's. +pub fn plantAttention(t: *Case, T: usize, H: usize, kv: usize) void { + if (t.form.last_key) { + // causal: row 1 ends on key 1, two keys; full: every row ends on key T - 1 + setKv(t, if (t.form.causal) 1 else T - 1, 0, true, 2, case.inf16); + return; + } + if (T < 64) return; + t.in[0][qAt(t, 5, 3 % H) + 3] = case.nan16; + setKv(t, 60, kv - 1, false, 7, case.nan16); + setKv(t, 50, (kv + 1) % kv, false, 1, case.inf16); + setKv(t, 30, 0, true, 5, case.nan16); + setKv(t, 31, 1 % kv, true, 6, case.inf16); + setKv(t, 35, 1 % kv, true, 6, case.ninf16); + setKv(t, 39, 2 % kv, true, 8, case.ninf16); +} From a616c8940c9708e69036ae97fcbd3a953a70e8bc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:26:33 +0000 Subject: [PATCH 009/361] h3: the prompt path's attention adds nothing for a padded key, so an infinite last value stays infinite; its contract entries lose their known finding and gain a control --- zig/kernels/metal/h3/h3_prompt.metal | 2 +- zig/tests/contract/metal_h3_image_prompt.zig | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/zig/kernels/metal/h3/h3_prompt.metal b/zig/kernels/metal/h3/h3_prompt.metal index c83ea84b073..38ffdc761ba 100644 --- a/zig/kernels/metal/h3/h3_prompt.metal +++ b/zig/kernels/metal/h3/h3_prompt.metal @@ -174,7 +174,7 @@ struct HpAttn { for (uint u = 0; u < 4; u++) { const float e = metal::precise::exp(s[u] - top); l += e; - acc += e * float4(*(const device bfloat4*)(vp + ulong(at[u]) * p.v_row)); + if (j0 + u < end) acc += e * float4(*(const device bfloat4*)(vp + ulong(at[u]) * p.v_row)); // a pad adds nothing } m = top; } diff --git a/zig/tests/contract/metal_h3_image_prompt.zig b/zig/tests/contract/metal_h3_image_prompt.zig index 21830982e44..285e11f491f 100644 --- a/zig/tests/contract/metal_h3_image_prompt.zig +++ b/zig/tests/contract/metal_h3_image_prompt.zig @@ -32,9 +32,6 @@ fn headsAt(comptime heads: usize, comptime rows: []const usize) []const c.Shape return out; } -const last_key = "a row whose key count is not a multiple of 4 fills its last block of 4 with its last key at weight " ++ - "0: an infinite value there gives 0 x Inf = NaN where float64 gives the infinity"; - /// The released checkpoint's launches in prompt.zig (text 5120 wide, 64 over 8 heads; refiner 5376, 56 heads). const forms = [_]Form{ .{ .kind = .gemm, .served = gemm_served }, @@ -45,8 +42,8 @@ const forms = [_]Form{ .{ .kind = .heads, .label = "h3 fused", .mode = .h3, .eps = 1e-5, .fused = true, .served = rowsAt(56, 128) }, .{ .kind = .attention, .label = "causal", .causal = true, .served = headsAt(64, &.{ short, long }) }, .{ .kind = .attention, .label = "fused", .fused = true, .served = headsAt(56, &.{ short, long }) }, - .{ .kind = .attention, .label = "causal last key", .causal = true, .last_key = true, .served = headsAt(64, &.{short}), .known = .{ .gate = .nonfinite, .finding = last_key } }, - .{ .kind = .attention, .label = "fused last key", .fused = true, .last_key = true, .served = headsAt(56, &.{short}), .known = .{ .gate = .nonfinite, .finding = last_key } }, + .{ .kind = .attention, .label = "causal last key", .causal = true, .last_key = true, .served = headsAt(64, &.{short}) }, + .{ .kind = .attention, .label = "fused last key", .fused = true, .last_key = true, .served = headsAt(56, &.{short}) }, .{ .kind = .glu, .label = "qwen", .mode = .qwen, .served = rowsAt(25600, 1) }, .{ .kind = .glu, .label = "h3 fused", .mode = .h3, .fused = true, .served = rowsAt(14336, 1) }, .{ .kind = .add, .served = rowsAt(5120, 1) ++ rowsAt(5376, 1) }, @@ -66,6 +63,7 @@ const controls = [_]Control{ .{ .entry = "hp_heads h3 fused", .gate = .shapes, .what = "rounds as the Qwen model", .old = "return mode == 0 ?", .new = "return mode != 0 ?" }, .{ .entry = "hp_attention causal", .gate = .shapes, .what = "sees the next key", .old = "? row + 1 : p.rows;", .new = "? min(row + 2, p.rows) : p.rows;" }, .{ .entry = "hp_attention fused", .gate = .shapes, .what = "skips the last key", .old = "? row + 1 : p.rows;", .new = "? row + 1 : p.rows - 1;" }, + .{ .entry = "hp_attention causal last key", .gate = .nonfinite, .what = "adds its padded keys' values at weight 0", .old = "if (j0 + u < end) acc += e", .new = "acc += e" }, .{ .entry = "hp_attention causal", .gate = .nonfinite, .what = "weighs a NaN score 0", .old = "const float e = metal::precise::exp(s[u] - top);", .new = "const float e = isnan(s[u]) ? 0.0f : metal::precise::exp(s[u] - top);" }, .{ .entry = "hp_glu qwen", .gate = .shapes, .what = "swaps gate and value", .old = "g = float(G[ulong(at.y) * p.g_row + at.x]), v = float(V[ulong(at.y) * p.v_row + at.x])", .new = "g = float(V[ulong(at.y) * p.v_row + at.x]), v = float(G[ulong(at.y) * p.g_row + at.x])" }, .{ .entry = "hp_glu h3 fused", .gate = .shapes, .what = "rounds as the Qwen model", .old = "const float s = p.mode == 0 ?", .new = "const float s = p.mode != 0 ?" }, From 643b7c89cee20c65c5f7de5f305ccb1a612af8f5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:26:58 +0000 Subject: [PATCH 010/361] docs: MiniMax-H3-Image's kernels in the kernel contract's coverage and its recipe --- docs/kernel-contract.md | 16 ++++++++++++++++ docs/recipes/minimax-h3-image-metal.md | 13 ++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 4841b24f5be..c4d244bfe6f 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -635,6 +635,22 @@ of the two branches), each output within float64's range at its bf16 points, and `contract_attn.zig`'s float64 reference (`audio-contract`; eight controls built from `nemo_audio.cuh` with one thing dropped each). +Metal also checks MiniMax-H3-Image's kernels, each compiled at load with the options its tool uses: +- The edit encoder (`h3_image_encoder.metal`, fp32 with precise functions): its convolution at every layer geometry of + the released encoder (3x3, 3x3 adding its residual in place, 3x3 downsampling, 1x1), GroupNorm's partial sums (plain + and centred) and their finish, and the norm's SiLU, each within float64's range through its fp32 steps (nine + controls). +- The prompt path (`h3_prompt.metal`): the bf16 product at every projection of Qwen3-VL to layer 50 and of the token + refiner, with and without a bias; both norms and both head layouts in the Qwen and H3 rounding orders; causal and full + attention within `attention_range`'s bound, with entries that plant an infinite value at a padded row's last key; + both gates, the residual add and the vision rows' scatter (fifteen controls). +- The image decoder (`image_decoder.metal`, bf16): post_quant, the embedding with its registers, both norms, the + product plain and with LayerScale in place, the heads with their half-width rotary, attention over a 261-token tile + and a batch of 16 tiles, and SwiGLU, each at its bf16 points (ten controls). + +Every launch reserves its group size in its source. `zig build h3-image-contract` (`tf-h3-image-contract [--only TEXT]`) +runs these kernels, their controls and their records' limits on any Mac, with no Metal compiler. + CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn, diff --git a/docs/recipes/minimax-h3-image-metal.md b/docs/recipes/minimax-h3-image-metal.md index 1182697dfb6..44fb5f635d2 100644 --- a/docs/recipes/minimax-h3-image-metal.md +++ b/docs/recipes/minimax-h3-image-metal.md @@ -435,7 +435,6 @@ the United States of America. Read it before use. - **Edits end to end:** the encoder makes a reference's rows and the prompt path places its vision rows, but Qwen3-VL's vision tower is not here, so an edit's prompt rows still come from a case. No one tool runs an edit. - **Serving:** no `/v1/images/generations` or `/v1/images/edits` route for it, and no CUDA path. -- **Kernel contract:** the new kernels are gated by each tool's `selftest`, not registered with `tf-kernel-contract`. - **Machines:** the transformer runs on an M5 only; chips without tensor units are refused. ## Host checks @@ -449,3 +448,15 @@ the United States of America. Read it before use. - the case reader's picture admission. `zig build compile-h3-host` compiles both H3 tools without the Metal compiler. + +## Kernel contract + +The edit encoder's, prompt path's and image decoder's kernels are registered with the kernel contract +([kernel-contract.md](../kernel-contract.md)): 31 registrations with 34 planted controls, and every launch's limits. +They are checked against float64 at their rounding points, beside each tool's own `selftest`. `zig build +h3-image-contract` runs them on any Mac, with no Metal compiler; `tf-kernel-contract` runs them with every other kernel. +On an M3 Ultra all 31 pass gates 1 to 4 and every control goes red as planted. + +The contract found one fault, now fixed: the prompt path's attention filled a row's last block of 4 keys with its last +key at weight 0, so an infinite value there gave 0 x Inf = NaN where float64 keeps the infinity. A padded key now adds +nothing; finite outputs keep their bytes. From a025bdca7c8a2edc4e65bbe09d88b4de26531a05 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:07:40 +0000 Subject: [PATCH 011/361] h3: keep the full Metal contract behind owner hooks --- docs/kernel-contract-cuda.md | 67 +++++++++++++++ docs/kernel-contract.md | 86 ++------------------ docs/recipes/minimax-h3-image-metal.md | 16 ++++ zig/tests/contract/metal_h3_image_suites.zig | 30 +++++++ zig/tests/contract/metal_main.zig | 8 +- 5 files changed, 121 insertions(+), 86 deletions(-) create mode 100644 docs/kernel-contract-cuda.md create mode 100644 zig/tests/contract/metal_h3_image_suites.zig diff --git a/docs/kernel-contract-cuda.md b/docs/kernel-contract-cuda.md new file mode 100644 index 00000000000..c6289cf7977 --- /dev/null +++ b/docs/kernel-contract-cuda.md @@ -0,0 +1,67 @@ +# CUDA kernel contract owners + +## CUDA records per nvcc release + +nvcc allocates registers differently from one release to the next, so the CUDA records are kept per release. +`registry.cuda` holds what nvcc 13.0 compiles, the compiler of the release fatbins. `registry.cuda_sets` lists what +each later release compiles differently from the release before it: nvcc 13.2's set holds `tf_rms_rows`, `lane_gemv` +and its split-K form, prompt16's FP8 tile, qmmf's FP4 32-row cluster tile and its FP4 and MXFP8 16-row cluster +tiles, five 64-row fused-slice tiles of the MXFP8 +and FP32-output paths, FP8G's 32-row cluster tile with FP32 output, the common EXL3 prompt products, Super's +decode-sized latent top-k and NVFP4 up experts, the Mamba scan and Super's NVFP4 prompt down kernels, three of +GLM-5.3-Flash's packed matmuls and three of its DFlash2 launches, and the training launches it compiles differently, +and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches, +its wide decode select and the span scan `tf_glm_dsel_scan`. `kernel-contract` and +`kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image against the newest set +at or below that release (13.0's when an image names none), and print which set they used. A release with no set of +its own is checked against the one below it, so its differences show as stale records: re-derive them with +`kernel-contract-limits` and add a set for that release rather than loosening the audit. Launch dimensions, dynamic +shared memory, the device's limits and the planted controls are checked the same way under every release. + +`-Dnative-fp-decode` (off by default; nvcc 13.2 or later) builds prompt16, qmmf and fp8_experts for `sm_a` from +sm_120 on and decodes their FP4/FP8 weight pairs with PTX ISA 9.2's `cvt.rn.bf16x2.e2m1x2`/`.e4m3x2` (qmmf: FP4 only). +Known finding: the hardware decode equals `fp4pair` on all 256 e2m1 bytes and `fp8pair` on every e4m3 pair without a +NaN code; the 1,020 pairs holding `0x7F` or `0xFF` decode to NaN, where the software gives ±480 (`tf-cuda-test +native-fp`). Those codes are NaN in e4m3, so only a broken checkpoint can tell the two apart. Default images keep the +software decode. + +A restored 13.0 receipt can arrive after the later compiler sets. Such records mark `later_pending` so 13.0 and +13.1 use their base usage, while 13.2 and later keep their independently measured or pending selection. +A missing later receipt remains pending; a 13.0 measurement never substitutes for it. + +Gemma 4 CUDA tower QKV norms and nine-term pooling register FP32 sums and BF16 outputs. +Their contract keeps the exact FP32 mirror and adds independent FP64 ranges at the BF16 nodes. +The sum fixtures use integers with exact FP32 partials below 2^24, including pooling cancellation near 2^20; +FP16 and BF16 simulations must fail in each of the three accumulator orders. Pooling declares its nine-term +reduction separately from the physical grid width, so the small stress grid remains a valid launch. +NaN and both infinity signs have explicit class controls. These registrations still require the device gates. + +## Shared M5 attention products + +The shared `attention_nax` defaults to the relaxed tensor P x V: float P is truncated to ten fraction bits. +`TF_ATTENTION_PV_FP32=1` opts into full float P with FP32 FMA accumulation on M5; unset preserves the old arithmetic. +The cut registration's independent formula includes the operand cut, while the full registration uses the full P. +A third registration executes the real cut kernel against the full FP32 bound and must fail the shapes gate. +The product fixture writes float output so BF16 rounding cannot conceal that control. +Both modes still require exceptional-class, repeat, guard, shape, accumulator and separate launch checks. +See [the mode's scope and device checks](recipes/m5-attention-precision.md); other families' rounding is unchanged. + +Flash Next's BF16 shared-down entries `tf_qmmf_shared16_half`, `tf_qmmf_shared16`, `tf_qmmf_shared32` and +`tf_qmmf_shared64` preserve the contiguous projection's FP32 result and store it directly in expert slot 10. +The baseline shared expert has all 640 intermediate channels and runs only on rank 0 at two ranks. +The contract checks all four geometries, nonfinite inputs, output bytes and untouched routed slots. +`moetile_records.zig` holds launch geometry and measured nvcc 13.0 resources on all five served SMs. +Later compiler receipts remain pending. Check each build with `tf-cuda-test kernel-contract-limits zig-out/fatbin`. +`tf-cuda-test moetile` compares the direct slot and the BF16 prompt tile plus scatter with the lane's contiguous +product and scatter at 1, 16, 17, 32, 64, 65, 1536 and 4218 rows, five repeats with guards. +`moetile-contract` runs the replacement gates and planted control. +`moetile-bench` rotates GPU event timings of the three at 64 to 4218 rows; no timing is a gate. + +BF16 prompt K32 staging registers two unfused 128x128 entries, one for BF16 output and one for FP32 output. +They read the parent's K64 weight packs in two K32 halves and keep the K16 MMA order and output rounding. +Only unsplit prompt calls select K32; fused slices retain the parent K64 tile. +`qmmf-prompt` compares each new output directly with the parent's 128x128 K64 output, including forced small rows. +`qmmf-prompt-contract` keeps the four parent entries and adds both K32 replacements and their scaled controls. +Each new control launches K32 for its output type at small and production row counts. +`qmmf-prompt-bench` times the 64-row lane, prompt16, the parent K64 tile and K32 on each Flash Next BF16 shape. +Measured nvcc 13.0 resources cover both K32 entries on sm_120 and sm_121; later compiler receipts remain pending. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index c4d244bfe6f..a76b74b1170 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -635,21 +635,8 @@ of the two branches), each output within float64's range at its bf16 points, and `contract_attn.zig`'s float64 reference (`audio-contract`; eight controls built from `nemo_audio.cuh` with one thing dropped each). -Metal also checks MiniMax-H3-Image's kernels, each compiled at load with the options its tool uses: -- The edit encoder (`h3_image_encoder.metal`, fp32 with precise functions): its convolution at every layer geometry of - the released encoder (3x3, 3x3 adding its residual in place, 3x3 downsampling, 1x1), GroupNorm's partial sums (plain - and centred) and their finish, and the norm's SiLU, each within float64's range through its fp32 steps (nine - controls). -- The prompt path (`h3_prompt.metal`): the bf16 product at every projection of Qwen3-VL to layer 50 and of the token - refiner, with and without a bias; both norms and both head layouts in the Qwen and H3 rounding orders; causal and full - attention within `attention_range`'s bound, with entries that plant an infinite value at a padded row's last key; - both gates, the residual add and the vision rows' scatter (fifteen controls). -- The image decoder (`image_decoder.metal`, bf16): post_quant, the embedding with its registers, both norms, the - product plain and with LayerScale in place, the heads with their half-width rotary, attention over a 261-token tile - and a batch of 16 tiles, and SwiGLU, each at its bf16 points (ten controls). - -Every launch reserves its group size in its source. `zig build h3-image-contract` (`tf-h3-image-contract [--only TEXT]`) -runs these kernels, their controls and their records' limits on any Mac, with no Metal compiler. +Metal also checks MiniMax-H3-Image's 19 kernels in 31 registrations with 34 planted controls; the +[recipe](recipes/minimax-h3-image-metal.md#kernel-contract) holds their per-path coverage and runner details. CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's @@ -669,68 +656,7 @@ reading the next head's column, the plain rope one position late, the YaRN rope forms and expand_v reading the next head's weights, the chunks the next head's queries, the split chunks reading a rank's page z as chunk z, and the per-rank merge one chunk short). -## CUDA records per nvcc release - -nvcc allocates registers differently from one release to the next, so the CUDA records are kept per release. -`registry.cuda` holds what nvcc 13.0 compiles, the compiler of the release fatbins. `registry.cuda_sets` lists what -each later release compiles differently from the release before it: nvcc 13.2's set holds `tf_rms_rows`, `lane_gemv` -and its split-K form, prompt16's FP8 tile, qmmf's FP4 32-row cluster tile and its FP4 and MXFP8 16-row cluster -tiles, five 64-row fused-slice tiles of the MXFP8 -and FP32-output paths, FP8G's 32-row cluster tile with FP32 output, the common EXL3 prompt products, Super's -decode-sized latent top-k and NVFP4 up experts, the Mamba scan and Super's NVFP4 prompt down kernels, three of -GLM-5.3-Flash's packed matmuls and three of its DFlash2 launches, and the training launches it compiles differently, -and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches, -its wide decode select and the span scan `tf_glm_dsel_scan`. `kernel-contract` and -`kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image against the newest set -at or below that release (13.0's when an image names none), and print which set they used. A release with no set of -its own is checked against the one below it, so its differences show as stale records: re-derive them with -`kernel-contract-limits` and add a set for that release rather than loosening the audit. Launch dimensions, dynamic -shared memory, the device's limits and the planted controls are checked the same way under every release. - -`-Dnative-fp-decode` (off by default; nvcc 13.2 or later) builds prompt16, qmmf and fp8_experts for `sm_a` from -sm_120 on and decodes their FP4/FP8 weight pairs with PTX ISA 9.2's `cvt.rn.bf16x2.e2m1x2`/`.e4m3x2` (qmmf: FP4 only). -Known finding: the hardware decode equals `fp4pair` on all 256 e2m1 bytes and `fp8pair` on every e4m3 pair without a -NaN code; the 1,020 pairs holding `0x7F` or `0xFF` decode to NaN, where the software gives ±480 (`tf-cuda-test -native-fp`). Those codes are NaN in e4m3, so only a broken checkpoint can tell the two apart. Default images keep the -software decode. - -A restored 13.0 receipt can arrive after the later compiler sets. Such records mark `later_pending` so 13.0 and -13.1 use their base usage, while 13.2 and later keep their independently measured or pending selection. -A missing later receipt remains pending; a 13.0 measurement never substitutes for it. - -Gemma 4 CUDA tower QKV norms and nine-term pooling register FP32 sums and BF16 outputs. -Their contract keeps the exact FP32 mirror and adds independent FP64 ranges at the BF16 nodes. -The sum fixtures use integers with exact FP32 partials below 2^24, including pooling cancellation near 2^20; -FP16 and BF16 simulations must fail in each of the three accumulator orders. Pooling declares its nine-term -reduction separately from the physical grid width, so the small stress grid remains a valid launch. -NaN and both infinity signs have explicit class controls. These registrations still require the device gates. - -## Shared M5 attention products - -The shared `attention_nax` defaults to the relaxed tensor P x V: float P is truncated to ten fraction bits. -`TF_ATTENTION_PV_FP32=1` opts into full float P with FP32 FMA accumulation on M5; unset preserves the old arithmetic. -The cut registration's independent formula includes the operand cut, while the full registration uses the full P. -A third registration executes the real cut kernel against the full FP32 bound and must fail the shapes gate. -The product fixture writes float output so BF16 rounding cannot conceal that control. -Both modes still require exceptional-class, repeat, guard, shape, accumulator and separate launch checks. -See [the mode's scope and device checks](recipes/m5-attention-precision.md); other families' rounding is unchanged. - -Flash Next's BF16 shared-down entries `tf_qmmf_shared16_half`, `tf_qmmf_shared16`, `tf_qmmf_shared32` and -`tf_qmmf_shared64` preserve the contiguous projection's FP32 result and store it directly in expert slot 10. -The baseline shared expert has all 640 intermediate channels and runs only on rank 0 at two ranks. -The contract checks all four geometries, nonfinite inputs, output bytes and untouched routed slots. -`moetile_records.zig` holds launch geometry and measured nvcc 13.0 resources on all five served SMs. -Later compiler receipts remain pending. Check each build with `tf-cuda-test kernel-contract-limits zig-out/fatbin`. -`tf-cuda-test moetile` compares the direct slot and the BF16 prompt tile plus scatter with the lane's contiguous -product and scatter at 1, 16, 17, 32, 64, 65, 1536 and 4218 rows, five repeats with guards. -`moetile-contract` runs the replacement gates and planted control. -`moetile-bench` rotates GPU event timings of the three at 64 to 4218 rows; no timing is a gate. - -BF16 prompt K32 staging registers two unfused 128x128 entries, one for BF16 output and one for FP32 output. -They read the parent's K64 weight packs in two K32 halves and keep the K16 MMA order and output rounding. -Only unsplit prompt calls select K32; fused slices retain the parent K64 tile. -`qmmf-prompt` compares each new output directly with the parent's 128x128 K64 output, including forced small rows. -`qmmf-prompt-contract` keeps the four parent entries and adds both K32 replacements and their scaled controls. -Each new control launches K32 for its output type at small and production row counts. -`qmmf-prompt-bench` times the 64-row lane, prompt16, the parent K64 tile and K32 on each Flash Next BF16 shape. -Measured nvcc 13.0 resources cover both K32 entries on sm_120 and sm_121; later compiler receipts remain pending. +## CUDA contract owners + +CUDA's release-specific records and shared M5/Flash Next products retain their coverage and validation details in +[CUDA kernel contract owners](kernel-contract-cuda.md). diff --git a/docs/recipes/minimax-h3-image-metal.md b/docs/recipes/minimax-h3-image-metal.md index 44fb5f635d2..6369891060f 100644 --- a/docs/recipes/minimax-h3-image-metal.md +++ b/docs/recipes/minimax-h3-image-metal.md @@ -451,6 +451,22 @@ the United States of America. Read it before use. ## Kernel contract +Metal compiles each kernel at load with the options its tool uses. Its contract coverage is: + +- The edit encoder (`h3_image_encoder.metal`, fp32 with precise functions): its convolution at every layer geometry of + the released encoder (3x3, 3x3 adding its residual in place, 3x3 downsampling, 1x1), GroupNorm's partial sums (plain + and centred) and their finish, and the norm's SiLU, each within float64's range through its fp32 steps (nine + controls). +- The prompt path (`h3_prompt.metal`): the bf16 product at every projection of Qwen3-VL to layer 50 and of the token + refiner, with and without a bias; both norms and both head layouts in the Qwen and H3 rounding orders; causal and full + attention within `attention_range`'s bound, with entries that plant an infinite value at a padded row's last key; + both gates, the residual add and the vision rows' scatter (fifteen controls). +- The image decoder (`image_decoder.metal`, bf16): post_quant, the embedding with its registers, both norms, the + product plain and with LayerScale in place, the heads with their half-width rotary, attention over a 261-token tile + and a batch of 16 tiles, and SwiGLU, each at its bf16 points (ten controls). + +Every launch reserves its group size in its source. + The edit encoder's, prompt path's and image decoder's kernels are registered with the kernel contract ([kernel-contract.md](../kernel-contract.md)): 31 registrations with 34 planted controls, and every launch's limits. They are checked against float64 at their rounding points, beside each tool's own `selftest`. `zig build diff --git a/zig/tests/contract/metal_h3_image_suites.zig b/zig/tests/contract/metal_h3_image_suites.zig new file mode 100644 index 00000000000..3f88ac9af7b --- /dev/null +++ b/zig/tests/contract/metal_h3_image_suites.zig @@ -0,0 +1,30 @@ +//! MiniMax-H3-Image's suites in the full Metal kernel-contract runner. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const g = contract.gates; +const encoder = @import("metal_h3_image_encoder.zig"); +const prompt = @import("metal_h3_image_prompt.zig"); +const decoder = @import("metal_h3_image_decoder.zig"); + +/// All three H3 Image suites, registered in the same order as the source-only runner. +pub const Suites = struct { + encoder: *encoder.Suite, + prompt: *prompt.Suite, + decoder: *decoder.Suite, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !Suites { + const e = try encoder.Suite.create(a, device, queue, kernels, only); + errdefer e.destroy(); + const p = try prompt.Suite.create(a, device, queue, kernels, only); + errdefer p.destroy(); + const d = try decoder.Suite.create(a, device, queue, kernels, only); + return .{ .encoder = e, .prompt = p, .decoder = d }; + } + + pub fn destroy(s: *Suites) void { + s.decoder.destroy(); + s.prompt.destroy(); + s.encoder.destroy(); + } +}; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 23dcfc498ae..604655a31d8 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -566,12 +566,8 @@ pub fn main(init: std.process.Init) !u8 { defer moss_image.destroy(); const moss_image_decoder = try @import("metal_moss_image_decoder.zig").Suite.create(a, device, queue, &kernels, o.only); defer moss_image_decoder.destroy(); - const h3_image_encoder = try @import("metal_h3_image_encoder.zig").Suite.create(a, device, queue, &kernels, o.only); - defer h3_image_encoder.destroy(); - const h3_image_prompt = try @import("metal_h3_image_prompt.zig").Suite.create(a, device, queue, &kernels, o.only); - defer h3_image_prompt.destroy(); - const h3_image_decoder = try @import("metal_h3_image_decoder.zig").Suite.create(a, device, queue, &kernels, o.only); - defer h3_image_decoder.destroy(); + var h3_image_suites = try @import("metal_h3_image_suites.zig").Suites.create(a, device, queue, &kernels, o.only); + defer h3_image_suites.destroy(); var dsv41_suites = try @import("metal_dsv41_main.zig").Suites.create(a, device, queue, &kernels, o.only); defer dsv41_suites.destroy(); const idol = try @import("metal_idol.zig").Suite.create(a, device, queue, &kernels, o.only); From 5a303a4e304b07233f45034e9b4be58a4ae349d9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:22:50 +0000 Subject: [PATCH 012/361] docs: kernel-contract.md stays whole (docs are not under the 600-line cap) --- docs/kernel-contract-cuda.md | 67 --------------------------------- docs/kernel-contract.md | 72 ++++++++++++++++++++++++++++++++---- 2 files changed, 65 insertions(+), 74 deletions(-) delete mode 100644 docs/kernel-contract-cuda.md diff --git a/docs/kernel-contract-cuda.md b/docs/kernel-contract-cuda.md deleted file mode 100644 index c6289cf7977..00000000000 --- a/docs/kernel-contract-cuda.md +++ /dev/null @@ -1,67 +0,0 @@ -# CUDA kernel contract owners - -## CUDA records per nvcc release - -nvcc allocates registers differently from one release to the next, so the CUDA records are kept per release. -`registry.cuda` holds what nvcc 13.0 compiles, the compiler of the release fatbins. `registry.cuda_sets` lists what -each later release compiles differently from the release before it: nvcc 13.2's set holds `tf_rms_rows`, `lane_gemv` -and its split-K form, prompt16's FP8 tile, qmmf's FP4 32-row cluster tile and its FP4 and MXFP8 16-row cluster -tiles, five 64-row fused-slice tiles of the MXFP8 -and FP32-output paths, FP8G's 32-row cluster tile with FP32 output, the common EXL3 prompt products, Super's -decode-sized latent top-k and NVFP4 up experts, the Mamba scan and Super's NVFP4 prompt down kernels, three of -GLM-5.3-Flash's packed matmuls and three of its DFlash2 launches, and the training launches it compiles differently, -and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches, -its wide decode select and the span scan `tf_glm_dsel_scan`. `kernel-contract` and -`kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image against the newest set -at or below that release (13.0's when an image names none), and print which set they used. A release with no set of -its own is checked against the one below it, so its differences show as stale records: re-derive them with -`kernel-contract-limits` and add a set for that release rather than loosening the audit. Launch dimensions, dynamic -shared memory, the device's limits and the planted controls are checked the same way under every release. - -`-Dnative-fp-decode` (off by default; nvcc 13.2 or later) builds prompt16, qmmf and fp8_experts for `sm_a` from -sm_120 on and decodes their FP4/FP8 weight pairs with PTX ISA 9.2's `cvt.rn.bf16x2.e2m1x2`/`.e4m3x2` (qmmf: FP4 only). -Known finding: the hardware decode equals `fp4pair` on all 256 e2m1 bytes and `fp8pair` on every e4m3 pair without a -NaN code; the 1,020 pairs holding `0x7F` or `0xFF` decode to NaN, where the software gives ±480 (`tf-cuda-test -native-fp`). Those codes are NaN in e4m3, so only a broken checkpoint can tell the two apart. Default images keep the -software decode. - -A restored 13.0 receipt can arrive after the later compiler sets. Such records mark `later_pending` so 13.0 and -13.1 use their base usage, while 13.2 and later keep their independently measured or pending selection. -A missing later receipt remains pending; a 13.0 measurement never substitutes for it. - -Gemma 4 CUDA tower QKV norms and nine-term pooling register FP32 sums and BF16 outputs. -Their contract keeps the exact FP32 mirror and adds independent FP64 ranges at the BF16 nodes. -The sum fixtures use integers with exact FP32 partials below 2^24, including pooling cancellation near 2^20; -FP16 and BF16 simulations must fail in each of the three accumulator orders. Pooling declares its nine-term -reduction separately from the physical grid width, so the small stress grid remains a valid launch. -NaN and both infinity signs have explicit class controls. These registrations still require the device gates. - -## Shared M5 attention products - -The shared `attention_nax` defaults to the relaxed tensor P x V: float P is truncated to ten fraction bits. -`TF_ATTENTION_PV_FP32=1` opts into full float P with FP32 FMA accumulation on M5; unset preserves the old arithmetic. -The cut registration's independent formula includes the operand cut, while the full registration uses the full P. -A third registration executes the real cut kernel against the full FP32 bound and must fail the shapes gate. -The product fixture writes float output so BF16 rounding cannot conceal that control. -Both modes still require exceptional-class, repeat, guard, shape, accumulator and separate launch checks. -See [the mode's scope and device checks](recipes/m5-attention-precision.md); other families' rounding is unchanged. - -Flash Next's BF16 shared-down entries `tf_qmmf_shared16_half`, `tf_qmmf_shared16`, `tf_qmmf_shared32` and -`tf_qmmf_shared64` preserve the contiguous projection's FP32 result and store it directly in expert slot 10. -The baseline shared expert has all 640 intermediate channels and runs only on rank 0 at two ranks. -The contract checks all four geometries, nonfinite inputs, output bytes and untouched routed slots. -`moetile_records.zig` holds launch geometry and measured nvcc 13.0 resources on all five served SMs. -Later compiler receipts remain pending. Check each build with `tf-cuda-test kernel-contract-limits zig-out/fatbin`. -`tf-cuda-test moetile` compares the direct slot and the BF16 prompt tile plus scatter with the lane's contiguous -product and scatter at 1, 16, 17, 32, 64, 65, 1536 and 4218 rows, five repeats with guards. -`moetile-contract` runs the replacement gates and planted control. -`moetile-bench` rotates GPU event timings of the three at 64 to 4218 rows; no timing is a gate. - -BF16 prompt K32 staging registers two unfused 128x128 entries, one for BF16 output and one for FP32 output. -They read the parent's K64 weight packs in two K32 halves and keep the K16 MMA order and output rounding. -Only unsplit prompt calls select K32; fused slices retain the parent K64 tile. -`qmmf-prompt` compares each new output directly with the parent's 128x128 K64 output, including forced small rows. -`qmmf-prompt-contract` keeps the four parent entries and adds both K32 replacements and their scaled controls. -Each new control launches K32 for its output type at small and production row counts. -`qmmf-prompt-bench` times the 64-row lane, prompt16, the parent K64 tile and K32 on each Flash Next BF16 shape. -Measured nvcc 13.0 resources cover both K32 entries on sm_120 and sm_121; later compiler receipts remain pending. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index a76b74b1170..4841b24f5be 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -635,9 +635,6 @@ of the two branches), each output within float64's range at its bf16 points, and `contract_attn.zig`'s float64 reference (`audio-contract`; eight controls built from `nemo_audio.cuh` with one thing dropped each). -Metal also checks MiniMax-H3-Image's 19 kernels in 31 registrations with 34 planted controls; the -[recipe](recipes/minimax-h3-image-metal.md#kernel-contract) holds their per-path coverage and runner details. - CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn, @@ -656,7 +653,68 @@ reading the next head's column, the plain rope one position late, the YaRN rope forms and expand_v reading the next head's weights, the chunks the next head's queries, the split chunks reading a rank's page z as chunk z, and the per-rank merge one chunk short). -## CUDA contract owners - -CUDA's release-specific records and shared M5/Flash Next products retain their coverage and validation details in -[CUDA kernel contract owners](kernel-contract-cuda.md). +## CUDA records per nvcc release + +nvcc allocates registers differently from one release to the next, so the CUDA records are kept per release. +`registry.cuda` holds what nvcc 13.0 compiles, the compiler of the release fatbins. `registry.cuda_sets` lists what +each later release compiles differently from the release before it: nvcc 13.2's set holds `tf_rms_rows`, `lane_gemv` +and its split-K form, prompt16's FP8 tile, qmmf's FP4 32-row cluster tile and its FP4 and MXFP8 16-row cluster +tiles, five 64-row fused-slice tiles of the MXFP8 +and FP32-output paths, FP8G's 32-row cluster tile with FP32 output, the common EXL3 prompt products, Super's +decode-sized latent top-k and NVFP4 up experts, the Mamba scan and Super's NVFP4 prompt down kernels, three of +GLM-5.3-Flash's packed matmuls and three of its DFlash2 launches, and the training launches it compiles differently, +and nvcc 13.3 keeps 13.2's and changes four of GLM-5.3-Flash's KV page launches, its two prompt-indexer launches, +its wide decode select and the span scan `tf_glm_dsel_scan`. `kernel-contract` and +`kernel-contract-limits` read the release from each image's `.note.nv.tkinfo`, check the image against the newest set +at or below that release (13.0's when an image names none), and print which set they used. A release with no set of +its own is checked against the one below it, so its differences show as stale records: re-derive them with +`kernel-contract-limits` and add a set for that release rather than loosening the audit. Launch dimensions, dynamic +shared memory, the device's limits and the planted controls are checked the same way under every release. + +`-Dnative-fp-decode` (off by default; nvcc 13.2 or later) builds prompt16, qmmf and fp8_experts for `sm_a` from +sm_120 on and decodes their FP4/FP8 weight pairs with PTX ISA 9.2's `cvt.rn.bf16x2.e2m1x2`/`.e4m3x2` (qmmf: FP4 only). +Known finding: the hardware decode equals `fp4pair` on all 256 e2m1 bytes and `fp8pair` on every e4m3 pair without a +NaN code; the 1,020 pairs holding `0x7F` or `0xFF` decode to NaN, where the software gives ±480 (`tf-cuda-test +native-fp`). Those codes are NaN in e4m3, so only a broken checkpoint can tell the two apart. Default images keep the +software decode. + +A restored 13.0 receipt can arrive after the later compiler sets. Such records mark `later_pending` so 13.0 and +13.1 use their base usage, while 13.2 and later keep their independently measured or pending selection. +A missing later receipt remains pending; a 13.0 measurement never substitutes for it. + +Gemma 4 CUDA tower QKV norms and nine-term pooling register FP32 sums and BF16 outputs. +Their contract keeps the exact FP32 mirror and adds independent FP64 ranges at the BF16 nodes. +The sum fixtures use integers with exact FP32 partials below 2^24, including pooling cancellation near 2^20; +FP16 and BF16 simulations must fail in each of the three accumulator orders. Pooling declares its nine-term +reduction separately from the physical grid width, so the small stress grid remains a valid launch. +NaN and both infinity signs have explicit class controls. These registrations still require the device gates. + +## Shared M5 attention products + +The shared `attention_nax` defaults to the relaxed tensor P x V: float P is truncated to ten fraction bits. +`TF_ATTENTION_PV_FP32=1` opts into full float P with FP32 FMA accumulation on M5; unset preserves the old arithmetic. +The cut registration's independent formula includes the operand cut, while the full registration uses the full P. +A third registration executes the real cut kernel against the full FP32 bound and must fail the shapes gate. +The product fixture writes float output so BF16 rounding cannot conceal that control. +Both modes still require exceptional-class, repeat, guard, shape, accumulator and separate launch checks. +See [the mode's scope and device checks](recipes/m5-attention-precision.md); other families' rounding is unchanged. + +Flash Next's BF16 shared-down entries `tf_qmmf_shared16_half`, `tf_qmmf_shared16`, `tf_qmmf_shared32` and +`tf_qmmf_shared64` preserve the contiguous projection's FP32 result and store it directly in expert slot 10. +The baseline shared expert has all 640 intermediate channels and runs only on rank 0 at two ranks. +The contract checks all four geometries, nonfinite inputs, output bytes and untouched routed slots. +`moetile_records.zig` holds launch geometry and measured nvcc 13.0 resources on all five served SMs. +Later compiler receipts remain pending. Check each build with `tf-cuda-test kernel-contract-limits zig-out/fatbin`. +`tf-cuda-test moetile` compares the direct slot and the BF16 prompt tile plus scatter with the lane's contiguous +product and scatter at 1, 16, 17, 32, 64, 65, 1536 and 4218 rows, five repeats with guards. +`moetile-contract` runs the replacement gates and planted control. +`moetile-bench` rotates GPU event timings of the three at 64 to 4218 rows; no timing is a gate. + +BF16 prompt K32 staging registers two unfused 128x128 entries, one for BF16 output and one for FP32 output. +They read the parent's K64 weight packs in two K32 halves and keep the K16 MMA order and output rounding. +Only unsplit prompt calls select K32; fused slices retain the parent K64 tile. +`qmmf-prompt` compares each new output directly with the parent's 128x128 K64 output, including forced small rows. +`qmmf-prompt-contract` keeps the four parent entries and adds both K32 replacements and their scaled controls. +Each new control launches K32 for its output type at small and production row counts. +`qmmf-prompt-bench` times the 64-row lane, prompt16, the parent K64 tile and K32 on each Flash Next BF16 shape. +Measured nvcc 13.0 resources cover both K32 entries on sm_120 and sm_121; later compiler receipts remain pending. From 2752a6bdb14a01017f3d9f927361850faf8c586a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:12:10 +0000 Subject: [PATCH 013/361] h3: Metal contract main back to 600 lines after main's Idol DINO suite Format only: combine the existing mixed-kernel predicates after main filled the runner. The short-circuit and append behavior are unchanged. --- zig/tests/contract/metal_main.zig | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 604655a31d8..edb0c193a02 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -204,9 +204,7 @@ pub fn main(init: std.process.Init) !u8 { for (embeddings[0..embed_made]) |*p| try kernels.append(a, p.kernel()); var mixed = gemma_mixed.Probe.init(a, device, queue); defer mixed.deinit(); - if (wanted(o, mixed.kernel().spec.name)) { - if (@import("metal_support.zig").tensor(tensor, mixed.kernel().spec.name)) try kernels.append(a, mixed.kernel()); - } + if (wanted(o, mixed.kernel().spec.name) and @import("metal_support.zig").tensor(tensor, mixed.kernel().spec.name)) try kernels.append(a, mixed.kernel()); var lfm2: @import("metal_lfm2_suite.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer lfm2.deinit(); try lfm2.collect(o.only); From fa2358c39c91ae8937f1afbff9bf7345fafabc23 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:59:34 +0000 Subject: [PATCH 014/361] changelog: #2808 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b77d1a701af..1198b6c78cf 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 +- Kernel contract: MiniMax-H3-Image's 19 Metal kernels register with the contract, in 31 registrations with 34 planted controls, instead of being gated only by each tool's own self-test (#2808). + - MiniMax-H3-Image on Metal: `tf-h3-image-prompt` writes a whole text-to-image case from a size and a seed (the canvas, the size and the seed's starting rows), so text to image runs end to end with TensorFold's own tools, and `tf-h3-image ... free` exits 0 when there is no reference to gate against (#2781). From d79f5b4f3012199dae30be2e51cd883510dc9b29 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:14:15 +0000 Subject: [PATCH 015/361] qwen3_5 CUDA: save shared prefixes at page boundaries Round shared-prefix save marks to the page grid and make those marks real cold-pass cuts, including solo passes. Fresh and resumed prompts now stop at the same page edges without requiring the page size to divide the compute grid. --- zig/src/families/qwen3_5/cuda_admit_test.zig | 6 ++- zig/src/families/qwen3_5/cuda_native.zig | 4 +- .../families/qwen3_5/cuda_native_explain.zig | 2 +- zig/src/families/qwen3_5/cuda_prefill.zig | 19 +++++++-- .../qwen3_5/cuda_prefill_page_grid_test.zig | 40 +++++++++++++++++++ .../families/qwen3_5/cuda_prefill_test.zig | 27 +++++++++---- zig/src/families/qwen3_5/cuda_prefix.zig | 16 +++++++- .../qwen3_5/cuda_prefix_fault_test.zig | 6 +-- 8 files changed, 99 insertions(+), 21 deletions(-) create mode 100644 zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig diff --git a/zig/src/families/qwen3_5/cuda_admit_test.zig b/zig/src/families/qwen3_5/cuda_admit_test.zig index 830622dd114..39e59dadd71 100644 --- a/zig/src/families/qwen3_5/cuda_admit_test.zig +++ b/zig/src/families/qwen3_5/cuda_admit_test.zig @@ -108,11 +108,13 @@ fn refused(slide: bool, kv_pages: ?[:0]const u8, share: ?[:0]const u8) !void { _ = try native.open(t.allocator, t.io, &ctx, "/nonexistent", null, o); } -/// A set switch's refusal needs no model: it stops before the weights load, as the other switch checks do. +/// Early switch refusals need no model; a non-divisible page size proceeds to the ordinary model load. pub fn refusals() !void { try t.expectError(error.QwenPagesNoLearner, refused(true, "256", null)); try t.expectError(error.QwenShareNeedsPages, refused(false, null, "16")); - try t.expectError(error.QwenShareNeedsPages, refused(false, "100", "16")); + if (refused(false, "100", "16")) |_| return error.UnexpectedNonexistentModel else |err| { + try t.expect(err != error.QwenShareNeedsPages); + } } test "Qwen share faults: --parallel N admits N streams at once with every stream on pages" { diff --git a/zig/src/families/qwen3_5/cuda_native.zig b/zig/src/families/qwen3_5/cuda_native.zig index c421e5d1e14..1d3ce08362f 100644 --- a/zig/src/families/qwen3_5/cuda_native.zig +++ b/zig/src/families/qwen3_5/cuda_native.zig @@ -191,8 +191,8 @@ pub fn openLanes(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, d if (kv_host_mod.onHost()) try kv_host_mod.checkDevice(try ctx.attribute(.integrated) != 0, page_tokens, engine_paged); const share_snaps = try prefix_mod.sharing(); if (kv_host_mod.onHost()) try kv_host_mod.checkShared(share_snaps); - // a kept state sits on a cold pass's chunk cut, so later chunks keep a cold pass's bits: pages divide the chunk - if (share_snaps > 0 and (page_tokens == 0 or E.grid_rows % page_tokens != 0)) return error.QwenShareNeedsPages; + // shared save marks are page edges and become cold-pass cuts independent of the compute chunk grid + if (share_snaps > 0 and page_tokens == 0) return error.QwenShareNeedsPages; if (kv_host_mod.onHost() and share_snaps == 0) std.log.warn("TF_QWEN_KV_HOST pins the KV pages in host memory; the prompt cache would pin more beside them: set --prompt-cache-gib to bound it", .{}); const e = try E.Engine.init(gpa, io, ctx, dir, o.kv8, fitOf(o), o.context); errdefer e.deinit(); diff --git a/zig/src/families/qwen3_5/cuda_native_explain.zig b/zig/src/families/qwen3_5/cuda_native_explain.zig index 1fdf4129642..3fb24966fa4 100644 --- a/zig/src/families/qwen3_5/cuda_native_explain.zig +++ b/zig/src/families/qwen3_5/cuda_native_explain.zig @@ -9,7 +9,7 @@ pub fn explain(ctx: ?*anyopaque, err: anyerror) ?[]const u8 { error.NoQwenVision => "--vision: this checkpoint has no image tower (no vision_config): serve it without --vision", error.QwenPagesNoLearner => "TF_QWEN_KV_PAGES: the learner reads whole windows, not pages; drop --slide or unset it", error.QwenRequestStartsWithSharedKv => "TF_QWEN_REQUEST_STARTS=1 cannot be used with TF_QWEN_KV_SHARE above 0; unset request starts or disable shared KV", - error.QwenShareNeedsPages => "TF_QWEN_KV_SHARE keeps prompts as pool pages: set TF_QWEN_KV_PAGES to a divisor of the 4096-row prompt chunk", + error.QwenShareNeedsPages => "TF_QWEN_KV_SHARE keeps prompts as pool pages: set TF_QWEN_KV_PAGES to a positive page size", error.BadQwenKvShare => "TF_QWEN_KV_SHARE takes the most recurrent-state snapshots the prompt cache keeps (0 or unset: off)", error.QwenYarnNoLearner => "--slide: the learner's attention ropes without YaRN; serve without --slide, or without --rope-yarn and a YaRN config", error.BadChunkSolo => "TF_QWEN35_CHUNK_SOLO: a solo prompt pass's rows, 4096 (off) or 8192", diff --git a/zig/src/families/qwen3_5/cuda_prefill.zig b/zig/src/families/qwen3_5/cuda_prefill.zig index e94560eb2b8..5e0c43118cd 100644 --- a/zig/src/families/qwen3_5/cuda_prefill.zig +++ b/zig/src/families/qwen3_5/cuda_prefill.zig @@ -107,9 +107,20 @@ test "direct-normalized MTP keeps the target's original stepped chunk boundary" try std.testing.expectEqual(@as(usize, 8192), targetForwardEnd(4096, 8192, 6143, false, false)); } +/// The shared prefix's page-edge marks join the cold pass's cuts; ordinary reuse keeps its old schedule. +fn keptCut(len: usize, chunks: []const u32, f: *const Fill, at: usize) usize { + var end = nextCut(len, chunks, at, 0); + const marks = if (f.kept) |k| k.marks else &.{}; + for (marks) |mark| if (mark > at) { + end = @min(end, mark); + break; + }; + return end; +} + /// The end of `f`'s next step under `max_rows` (0: the cold cut), its cold cut renewed once the last one landed. fn capped(len: usize, chunks: []const u32, f: *Fill, max_rows: u32) usize { - if (f.cold <= f.at) f.cold = nextCut(len, chunks, f.at, 0); + if (f.cold <= f.at) f.cold = keptCut(len, chunks, f, f.at); return lanes.step_cap.end(f.at, f.cold, max_rows, cap_grid); } @@ -218,7 +229,7 @@ fn soloEnd(len: usize, chunks: []const u32, f: *Fill, rows: usize, marks: []cons var end = capped(len, chunks, f, 0); if (end - f.at < solo_min_rows) return end; // a short chunk runs alone, as in a cold pass while (end < len and std.mem.indexOfScalar(u32, marks, @intCast(end)) == null) { - const next = nextCut(len, chunks, end, 0); + const next = keptCut(len, chunks, f, end); if (next - end < solo_min_rows or next - f.at > rows) break; end = next; } @@ -429,8 +440,8 @@ pub fn chunk(self: anytype, stream: *lanes.Stream, f: *Fill, max_rows: u32) !boo lanes.prefill_widths.completed(self.gpa, stream, forward_end - f.at); f.at = forward_end; stream.fill_at.store(@intCast(forward_end), .monotonic); - // a mark the store asked for, where the cold pass cuts (a resume's only place): the lane host copies the state here - const cold = forward_end == f.cold; // a capped step's end inside a cold chunk keeps nothing: no pass resumes there + // shared page-edge marks are cold cuts too, so their lane-host state is exactly resumable + const cold = forward_end == f.cold; // a capped step's end inside a cold chunk keeps nothing if (f.kept) |k| { if (cold and forward_end < ids.len and std.mem.indexOfScalar(u32, k.marks, @intCast(forward_end)) != null) self.prefix.?.keep(cache, if (stream.key.len != 0) stream.key else ids, stream.cache_salt, forward_end) catch |err| { diff --git a/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig b/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig new file mode 100644 index 00000000000..3f07082698f --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig @@ -0,0 +1,40 @@ +const std = @import("std"); +const t = std.testing; +const prefill = @import("cuda_prefill.zig"); +const E = @import("cuda_engine.zig"); +const lanes = @import("lanes"); +const Fake = @import("cuda_prefill_test.zig").Fake; + +test "Qwen stepped prefill: shared page marks cut fresh and resumed passes at the same boundaries" { + const m = E.grid_rows; + const ids = try t.allocator.alloc(u32, m + 1000); + defer t.allocator.free(ids); + @memset(ids, 3); + + var fresh_engine: Fake.Engine = .{}; + defer fresh_engine.rows.deinit(t.allocator); + defer fresh_engine.keeps.deinit(t.allocator); + var fresh: Fake = .{ .e = &fresh_engine }; + defer fresh.deinit(); + var fresh_prefix: Fake.Prefix = .{ .cache = &fresh.cache, .marks = &.{ 256, m } }; + fresh.prefix = &fresh_prefix; + var cold = try lanes.Stream.init(t.allocator, .{ .id = "fresh-page-grid", .prompt = ids, .max_new = 1 }); + defer cold.deinit(t.allocator); + while (!try prefill.step(&fresh, &cold, 512)) {} + try t.expectEqualSlices(usize, &.{ 256, 512, 512, 512, 512, 512, 512, 512, 256, 512, 488 }, fresh_engine.rows.items); + try t.expectEqual(@as(usize, 2), fresh_prefix.n); + try t.expectEqualSlices(usize, &.{ 256, m }, fresh_prefix.kept[0..fresh_prefix.n]); + + var resumed_engine: Fake.Engine = .{}; + defer resumed_engine.rows.deinit(t.allocator); + defer resumed_engine.keeps.deinit(t.allocator); + var resumed: Fake = .{ .e = &resumed_engine }; + defer resumed.deinit(); + var resumed_prefix: Fake.Prefix = .{ .cache = &resumed.cache, .from = 256, .marks = &.{m} }; + resumed.prefix = &resumed_prefix; + var restored = try lanes.Stream.init(t.allocator, .{ .id = "resumed-page-grid", .prompt = ids, .max_new = 1 }); + defer restored.deinit(t.allocator); + while (!try prefill.step(&resumed, &restored, 512)) {} + try t.expectEqualSlices(usize, fresh_engine.rows.items[1..], resumed_engine.rows.items); + try t.expectEqual(@as(usize, 256), restored.cached); +} diff --git a/zig/src/families/qwen3_5/cuda_prefill_test.zig b/zig/src/families/qwen3_5/cuda_prefill_test.zig index 35b80273beb..09199751210 100644 --- a/zig/src/families/qwen3_5/cuda_prefill_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefill_test.zig @@ -41,7 +41,7 @@ pub fn cancelled(comptime Lanes: type, backend: anytype) !void { } /// Lanes' parts a stepped pass touches, with a forward that records each cut's rows and nothing on a device. -const Fake = struct { +pub const Fake = struct { const reuse = @import("cuda_reuse.zig"); const Cache = struct { untaught: bool = false, @@ -53,11 +53,20 @@ const Fake = struct { } }; const Plan = struct { from: usize, marks: []u32 }; - const Prefix = struct { - pub fn open(_: *Prefix, _: []const u32, _: usize, _: u32, _: []const u32, _: ?u64) !?struct { cache: *Cache, plan: Plan } { - return null; + pub const Prefix = struct { + cache: ?*Cache = null, + from: usize = 0, + marks: []const u32 = &.{}, + kept: [8]usize = undefined, + n: usize = 0, + pub fn open(p: *Prefix, _: []const u32, _: usize, _: u32, _: []const u32) !?struct { cache: *Cache, plan: Plan } { + if (p.cache == null) return null; + return .{ .cache = p.cache.?, .plan = .{ .from = p.from, .marks = try t.allocator.dupe(u32, p.marks) } }; + } + pub fn keep(p: *Prefix, _: *Cache, _: []const u32, at: usize) error{QwenLaneTable}!void { + p.kept[p.n] = at; + p.n += 1; } - pub fn keep(_: *Prefix, _: *Cache, _: []const u32, _: ?u64, _: usize) error{QwenLaneTable}!void {} }; const Pages = struct { pub fn log(_: *Pages, _: usize, _: usize) void {} @@ -70,7 +79,7 @@ const Fake = struct { }; const Int8 = struct { on: bool = false }; const Keep = @import("cuda_engine.zig").Keep; - const Engine = struct { + pub const Engine = struct { const MtpPrompt = @import("cuda_mtp_prompt.zig").State; const PromptTapMode = @import("cuda_mtp_prompt.zig").Mode; const Call = struct { rows: usize, mode: PromptTapMode, tap_from: ?usize }; @@ -139,7 +148,7 @@ const Fake = struct { pub fn restoreKept(f: *Fake, _: *Cache, _: *anyopaque, _: []const reuse.Seen) !void { if (!f.restore_ok) return error.FakeRestore; } - fn deinit(f: *Fake) void { + pub fn deinit(f: *Fake) void { var it = f.seen.valueIterator(); while (it.next()) |v| f.gpa.free(v.*); f.seen.deinit(f.gpa); @@ -576,3 +585,7 @@ test "MTP suffix filtering is disabled for chunked, resumed, and reuse-marked pr try t.expectEqual(Fake.Engine.PromptTapMode.mtp, resumed_engine.calls.items[0].mode); try t.expectEqual(@as(?usize, null), resumed_engine.calls.items[0].tap_from); } + +test { + _ = @import("cuda_prefill_page_grid_test.zig"); +} diff --git a/zig/src/families/qwen3_5/cuda_prefix.zig b/zig/src/families/qwen3_5/cuda_prefix.zig index 2674e6df082..d58e4a92118 100644 --- a/zig/src/families/qwen3_5/cuda_prefix.zig +++ b/zig/src/families/qwen3_5/cuda_prefix.zig @@ -145,17 +145,29 @@ pub const Prefix = struct { return .{ .cache = owner.cache.?, .plan = plan }; } - /// The plan's marks down to the cold pass's chunk grid, where a pass cuts and so can keep; the plan's freed. + /// The plan's page-edge marks become real cold-pass cuts, independent of the compute chunk grid; the plan's freed. fn onGrid(x: *Prefix, plan: radix.Plan) ![]const u32 { defer x.gpa.free(plan.marks); var out: std.ArrayList(u32) = .empty; errdefer out.deinit(x.gpa); for (plan.marks) |m| { - const g = m - m % engine.grid_rows; + const g = m - m % x.pages.layout.page_tokens; if (g > plan.from and (out.items.len == 0 or out.items[out.items.len - 1] != g)) try out.append(x.gpa, g); } return out.toOwnedSlice(x.gpa); } + test "Qwen share faults: save marks use the page grid, not the compute grid" { + const t = std.testing; + var p: pages_mod.Pages = undefined; + p.layout.page_tokens = 256; + var x: Prefix = undefined; + x.gpa = t.allocator; + x.pages = &p; + const plan: radix.Plan = .{ .from = 256, .marks = try t.allocator.dupe(u32, &.{ 512, 768, 1024, 4096 }) }; + const marks = try x.onGrid(plan); + defer t.allocator.free(marks); + try t.expectEqualSlices(u32, &.{ 512, 768, 1024, 4096 }, marks); + } fn of(ptr: *anyopaque) *Prefix { return @ptrCast(@alignCast(ptr)); diff --git a/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig b/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig index 84d2a4ca2e0..9b435fe963d 100644 --- a/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig @@ -37,7 +37,7 @@ fn prompt(a: std.mem.Allocator, n: usize) ![]u32 { return out; } -/// The pool, its store, a cold pass's pages kept at 4096, and a longer prompt whose resume there keeps a cut at 8192. +/// The pool keeps cold state at 4096 and a longer prompt's page-edge state at 8960. const World = struct { d: cuda.Driver, e: E, @@ -77,12 +77,12 @@ const World = struct { try t.expectEqual(@as(usize, 0), D.hosts); } - /// A resume of `next` that succeeds: from the kept 4096, a mark at 8192, its lane closed again. + /// A resume of `next` succeeds from 4096, keeps a page-edge mark at 8960, and closes its lane again. fn resumes(w: *World) !void { const r = try w.x.open(w.next, 16, 9100, &.{}, null); defer w.x.gpa.free(r.plan.marks); try t.expectEqual(@as(u32, 4096), r.plan.from); - try t.expectEqualSlices(u32, &.{8192}, r.plan.marks); + try t.expectEqualSlices(u32, &.{8960}, r.plan.marks); try t.expect(w.p.close(r.cache)); try settled(w.p); } From da90c61beb3c2eaf9d1f95897580eb34a2184f18 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:14:15 +0000 Subject: [PATCH 016/361] qwen3_5 CUDA: keep prefix snapshots on device by option TF_QWEN_KV_SNAPSHOT_GPU=1 keeps the radix store's bounded recurrent snapshots in device memory and restores them D2D. Device allocation failure selects the existing pinned-host path before copying; failed copies drain or quarantine before release. The fake device now transfers real bytes so host tests compare fresh, resumed and rebuilt state and inject allocation, copy and wait failures. --- docs/environment.md | 2 + zig/src/cuda/paging_test_device.zig | 52 ++++++-- zig/src/families/qwen3_5/cuda_prefix.zig | 44 +++++-- .../qwen3_5/cuda_prefix_fault_test.zig | 122 ++++++++++++++++-- 4 files changed, 194 insertions(+), 26 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index ea44573afd3..64a9b96eb81 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -242,6 +242,8 @@ These settings retain their existing boolean policies rather than gaining new al and `TF_SLIDE_FIT_REDUCE` its exact `tree` reduction selection. These developer switches keep their existing semantics. - GLM: `GLM_EHPROJ_NAX` retains its first-character `0` disabling rule, `TF_GLM_DFLASH2_PROF` enables by presence, even empty or `0`, and `TF_KV_POISON` (also read by Nemotron) is on only for exact `1`. +- Qwen shared-prefix snapshots: `TF_QWEN_KV_SNAPSHOT_GPU` opts in only for exact `1`. With `TF_QWEN_KV_SHARE=n`, + at most `n` states occupy device memory; a failed device allocation retains the pinned-host fallback. Unset keeps host snapshots. - The existing tool-grammar, rows-sync, log-time, memory-pressure and XPU-MTP boolean policies are unchanged. - Flash Next keeps its lenient readers where they are: `TF_FLASHNEXT_TP` and `TF_FLASHNEXT_LOGITS` take a path, `TF_FLASHNEXT_OWNED` a list, `TF_FLASHNEXT_DEPTH_LOG` and `TF_TP_TRACE`/`TF_TP_LOCAL`/`TF_TP_STATS` select by presence, diff --git a/zig/src/cuda/paging_test_device.zig b/zig/src/cuda/paging_test_device.zig index 8d6d73d4b8d..f417ec89c86 100644 --- a/zig/src/cuda/paging_test_device.zig +++ b/zig/src/cuda/paging_test_device.zig @@ -5,6 +5,10 @@ const Driver = @import("driver.zig").Driver; const t = std.testing; pub const Device = struct { pub const stream: abi.Stream = @ptrFromInt(17); + pub const Copy = struct { dst: u64, src: u64, len: usize }; + pub fn bytes(ptr: u64, len: usize) []u8 { + return @as([*]u8, @ptrFromInt(ptr))[0..len]; + } pub var observe: ?*const fn () bool = null; pub var expected: usize = 0; pub var early = false; @@ -15,17 +19,30 @@ pub const Device = struct { pub var freed_pending: usize = 0; pub var fail_wait_in: usize = 0; // > 0: the stream wait this many waits on fails, once pub var hosts: usize = 0; // pinned buffers held - var next: u64 = 0x10000; + pub var devices: usize = 0; + pub var fail_alloc = false; + pub var fail_dtod = false; + pub var dtods: usize = 0; + pub var last_dtod: Copy = .{ .dst = 0, .src = 0, .len = 0 }; fn alloc(out: *u64, len: usize) callconv(.c) c_int { - out.* = next; - next += len + 256; + if (fail_alloc) { + fail_alloc = false; + return abi.error_not_ready; + } + const all = t.allocator.alignedAlloc(u8, .@"16", len + 16) catch return abi.error_not_ready; + std.mem.writeInt(usize, all[0..@sizeOf(usize)], len, .little); + out.* = @intFromPtr(all.ptr + 16); + devices += 1; return 0; } - fn free(_: u64) callconv(.c) c_int { + fn free(ptr: u64) callconv(.c) c_int { freed_pending += @intFromBool(pending); + const at: [*]align(16) u8 = @ptrCast(@alignCast(@as([*]u8, @ptrFromInt(ptr)) - 16)); + t.allocator.free(at[0 .. std.mem.readInt(usize, at[0..@sizeOf(usize)], .little) + 16]); + devices -= 1; return 0; } - fn fill(_: u64, _: u8, _: usize, s: abi.Stream) callconv(.c) c_int { + fn fill(dst: u64, v: u8, n: usize, s: abi.Stream) callconv(.c) c_int { _ = s; pending = true; if (fail_fill) { @@ -33,6 +50,7 @@ pub const Device = struct { fail_wait = true; return abi.error_not_ready; } + @memset(bytes(dst, n), v); return 0; } fn legacyFill(dst: u64, v: u8, n: usize) callconv(.c) c_int { @@ -58,12 +76,25 @@ pub const Device = struct { proof(); return 0; } - fn copy(_: u64, _: ?*const anyopaque, _: usize, _: abi.Stream) callconv(.c) c_int { + fn copy(dst: u64, src: ?*const anyopaque, len: usize, _: abi.Stream) callconv(.c) c_int { pending = true; + if (len > 0) @memcpy(bytes(dst, len), @as([*]const u8, @ptrCast(src.?))[0..len]); return 0; } - fn copyOut(_: ?*anyopaque, _: u64, _: usize, _: abi.Stream) callconv(.c) c_int { + fn copyOut(dst: ?*anyopaque, src: u64, len: usize, _: abi.Stream) callconv(.c) c_int { pending = true; + if (len > 0) @memcpy(@as([*]u8, @ptrCast(dst.?))[0..len], bytes(src, len)); + return 0; + } + fn dtod(dst: u64, src: u64, len: usize, _: abi.Stream) callconv(.c) c_int { + pending = true; + dtods += 1; + last_dtod = .{ .dst = dst, .src = src, .len = len }; + if (fail_dtod) { + fail_dtod = false; + return abi.error_not_ready; + } + @memcpy(bytes(dst, len), bytes(src, len)); return 0; } // each buffer's length in the 16 bytes before it @@ -105,7 +136,11 @@ pub const Device = struct { freed_pending = 0; fail_wait_in = 0; hosts = 0; - next = 0x10000; + devices = 0; + fail_alloc = false; + fail_dtod = false; + dtods = 0; + last_dtod = .{ .dst = 0, .src = 0, .len = 0 }; var d: Driver = .{ .lib = undefined, .api = undefined }; d.api.cuMemAlloc_v2 = alloc; d.api.cuMemFree_v2 = free; @@ -115,6 +150,7 @@ pub const Device = struct { d.api.cuCtxSynchronize = context; d.api.cuMemcpyHtoDAsync_v2 = copy; d.api.cuMemcpyDtoHAsync_v2 = copyOut; + d.api.cuMemcpyDtoDAsync_v2 = dtod; d.api.cuMemHostAlloc = hostAlloc; d.api.cuMemFreeHost = hostFree; d.api.cuEventCreate = eventCreate; diff --git a/zig/src/families/qwen3_5/cuda_prefix.zig b/zig/src/families/qwen3_5/cuda_prefix.zig index d58e4a92118..c71282b7b09 100644 --- a/zig/src/families/qwen3_5/cuda_prefix.zig +++ b/zig/src/families/qwen3_5/cuda_prefix.zig @@ -64,21 +64,27 @@ test "TF_QWEN_KV_SHARE: unset, empty or whitespace-only text is off, a count kee /// A stream the store keeps from or restores into: its lane's cache, or (before the lane opens) the state to restore. pub const Owner = struct { cache: ?*Cache = null, pending: ?radix.Saved = null }; -/// A kept recurrent state: the cache's state block (recurrences and convolution tails) in pinned host memory. -const Snap = struct { host: cuda.HostBuffer }; +/// A kept recurrent state in one bounded device buffer, or the existing pinned-host fallback. +const Snap = struct { host: cuda.HostBuffer, dev: ?cuda.DeviceBuffer = null }; + +fn deviceSnapshots() bool { + const v = @import("core").profile.lookup("TF_QWEN_KV_SNAPSHOT_GPU") orelse return false; + return std.mem.eql(u8, v, "1"); +} pub const Prefix = struct { gpa: std.mem.Allocator, e: *Engine, pages: *pages_mod.Pages, store: radix.Store, + gpu: bool, pub fn init(gpa: std.mem.Allocator, e: *Engine, p: *pages_mod.Pages, snaps: usize) !*Prefix { const x = try gpa.create(Prefix); errdefer gpa.destroy(x); const rules: radix.Rules = .{ .page = p.layout.page_tokens, .min_gap = 256, .min_prompt = 0, .tail = true }; const pool_pages = radix.pagesOf(kv.Pool, &p.pool, p.layout.pageBytes()); - x.* = .{ .gpa = gpa, .e = e, .pages = p, .store = try radix.Store.init(gpa, .{ .ptr = x, .vtable = &family }, pool_pages, rules) }; + x.* = .{ .gpa = gpa, .e = e, .pages = p, .gpu = deviceSnapshots(), .store = try radix.Store.init(gpa, .{ .ptr = x, .vtable = &family }, pool_pages, rules) }; errdefer x.store.deinit(); x.store.limit(.{ .pages = p.pool.total(), .snaps = snaps }); try p.pool.joinReclaim(.{ .ctx = x, .call = reclaim }); // a promise evicts its idle pages before it fails @@ -108,7 +114,10 @@ pub const Prefix = struct { const cache = owner.cache.?; const e = x.e; try cache.flush(e); - try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(cache.state.ptr, s.host.bytes.ptr, e.g.stateBytes(), e.stream.handle), "cuMemcpyHtoDAsync"); + if (s.dev) |dev| + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(cache.state.ptr, dev.ptr, e.g.stateBytes(), e.stream.handle), "cuMemcpyDtoDAsync") + else + try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(cache.state.ptr, s.host.bytes.ptr, e.g.stateBytes(), e.stream.handle), "cuMemcpyHtoDAsync"); try e.stream.synchronize(); } @@ -177,6 +186,20 @@ pub const Prefix = struct { return of(ptr).e.g.stateBytes(); } + fn freeFailedSave(e: *Engine, s: *Snap) void { + if (s.dev) |*dev| { + cuda.completion.drain(e.d, e.stream, "qwen3_5: a failed prefix snapshot's device copy did not drain"); + dev.free(); + return; + } + e.stream.synchronize() catch { + std.log.warn("qwen3_5: a failed prefix snapshot's pinned copy goes to the copy-source quarantine", .{}); + cuda.copy_source.retainPinned(e.d, s.host, e.stream); + return; + }; + s.host.free(); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, _: u32) anyerror!radix.Saved { const x = of(ptr); const o: *Owner = @ptrCast(@alignCast(owner orelse return error.NoQwenOwner)); @@ -184,10 +207,15 @@ pub const Prefix = struct { const e = x.e; const s = try x.gpa.create(Snap); errdefer x.gpa.destroy(s); - s.* = .{ .host = try cuda.HostBuffer.alloc(e.d, e.g.stateBytes()) }; - errdefer s.host.free(); + const dev: ?cuda.DeviceBuffer = if (x.gpu) cuda.DeviceBuffer.alloc(e.d, e.g.stateBytes()) catch null else null; + const host: cuda.HostBuffer = if (dev) |_| .{ .d = e.d, .bytes = &.{} } else try cuda.HostBuffer.alloc(e.d, e.g.stateBytes()); + s.* = .{ .host = host, .dev = dev }; + errdefer freeFailedSave(e, s); try cache.flush(e); - try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(s.host.bytes.ptr, cache.state.ptr, e.g.stateBytes(), e.stream.handle), "cuMemcpyDtoHAsync"); + if (s.dev) |saved| + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(saved.ptr, cache.state.ptr, e.g.stateBytes(), e.stream.handle), "cuMemcpyDtoDAsync") + else + try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(s.host.bytes.ptr, cache.state.ptr, e.g.stateBytes(), e.stream.handle), "cuMemcpyDtoHAsync"); try e.stream.synchronize(); return @ptrCast(s); } @@ -200,7 +228,7 @@ pub const Prefix = struct { fn drop(ptr: *anyopaque, saved: radix.Saved) void { const x = of(ptr); const s: *Snap = @ptrCast(@alignCast(saved)); - s.host.free(); + if (s.dev) |*dev| dev.free() else s.host.free(); x.gpa.destroy(s); } diff --git a/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig b/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig index 9b435fe963d..2d834010695 100644 --- a/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig @@ -45,12 +45,38 @@ const World = struct { x: *Prefix, ids: []u32, next: []u32, + initial: []u8, + state: []u8, + base_devices: usize, + + const SaveFault = enum { none, device_alloc, copy, wait }; + + fn seed(w: *World, ptr: u64, ids: []const u32) void { + for (D.bytes(ptr, w.e.g.stateBytes()), 0..) |*b, i| { + const token = ids[i % ids.len] ^ @as(u32, @truncate(i * 31)); + b.* = @truncate(token); + } + } fn init(w: *World, gpa: std.mem.Allocator) !void { + try w.start(gpa, false, .none); + } + + fn gpu(w: *World, gpa: std.mem.Allocator, fault: SaveFault) !void { + try w.start(gpa, true, fault); + } + + fn start(w: *World, gpa: std.mem.Allocator, use_gpu: bool, fault: SaveFault) !void { + const env = @import("sys").env; + const name = "TF_QWEN_KV_SNAPSHOT_GPU"; + _ = env.unsetenv(name); + if (use_gpu) _ = env.setenv(name, "1", 1); + defer _ = env.unsetenv(name); w.d = D.driver(); w.e = engine(&w.d); const l = pages.layout(&w.e, capacity, page, 0, 0); w.p = try pages.Pages.init(gpa, &w.e, l, capacity, 0, 2, 3 * l.need(capacity, 0, pages.window_rows)); + w.base_devices = D.devices; errdefer w.p.deinit(); w.x = try Prefix.init(gpa, &w.e, w.p, 4); errdefer w.x.deinit(); @@ -60,14 +86,33 @@ const World = struct { errdefer t.allocator.free(w.next); const r = try w.x.open(w.ids, 16, 9000, &.{}, null); defer w.x.gpa.free(r.plan.marks); - try w.x.keep(r.cache, w.ids, null, 4096); + w.initial = try t.allocator.dupe(u8, D.bytes(r.cache.state.ptr, w.e.g.stateBytes())); + errdefer t.allocator.free(w.initial); + w.seed(r.cache.state.ptr, w.ids[0..4096]); + w.state = try t.allocator.dupe(u8, D.bytes(r.cache.state.ptr, w.e.g.stateBytes())); + errdefer t.allocator.free(w.state); + switch (fault) { + .none => {}, + .device_alloc => D.fail_alloc = true, + .copy => D.fail_dtod = true, + .wait => D.fail_wait_in = 2, + } + try w.x.keep(r.cache, w.ids, 4096); + if (fault == .copy or fault == .wait) { + try t.expectEqual(@as(usize, 0), w.x.store.tree.snaps); + try t.expectEqual(@as(usize, 1), w.x.store.tree.counts.failed); + try t.expectEqual(@as(usize, 0), D.freed_pending); + try w.x.keep(r.cache, w.ids, 4096); + } try t.expect(w.p.close(r.cache)); try settled(w.p); try t.expectEqual(@as(usize, 4096 / page), w.p.pool.census().kept); } - /// The store's pages back with its states: every page free, every pinned copy gone. + /// The store's pages back with its states: every page free and every snapshot buffer gone. fn deinit(w: *World) !void { + defer t.allocator.free(w.initial); + defer t.allocator.free(w.state); defer t.allocator.free(w.ids); defer t.allocator.free(w.next); defer w.p.deinit(); @@ -75,6 +120,7 @@ const World = struct { try t.expectEqual(w.p.pool.total(), w.p.pool.census().free); for (w.p.pool.refs) |r| try t.expectEqual(@as(u32, 0), r); try t.expectEqual(@as(usize, 0), D.hosts); + try t.expectEqual(w.base_devices, D.devices); } /// A resume of `next` succeeds from 4096, keeps a page-edge mark at 8960, and closes its lane again. @@ -83,6 +129,7 @@ const World = struct { defer w.x.gpa.free(r.plan.marks); try t.expectEqual(@as(u32, 4096), r.plan.from); try t.expectEqualSlices(u32, &.{8960}, r.plan.marks); + try t.expectEqualSlices(u8, w.state, D.bytes(r.cache.state.ptr, w.e.g.stateBytes())); try t.expect(w.p.close(r.cache)); try settled(w.p); } @@ -182,15 +229,70 @@ test "Qwen share faults: a keep whose swapped table fails to upload leaves the l try w.deinit(); } -test "Qwen share faults: an unsalted snapshot is not restored under a salt" { +test "Qwen share faults: device snapshots restore D2D and eviction frees their bounded buffer" { var w: World = undefined; - try w.init(t.allocator); - const r = try w.x.open(w.next, 16, 9100, &.{}, 1); - const gpa = w.x.gpa; - defer gpa.free(r.plan.marks); - try t.expectEqual(@as(u32, 0), r.plan.from); - try t.expect(w.p.close(r.cache)); + try w.gpu(t.allocator, .none); + try t.expectEqual(@as(usize, 0), D.hosts); + try t.expectEqual(@as(usize, 1), D.dtods); + const saved = D.last_dtod; + try w.resumes(); + try t.expectEqual(@as(usize, 2), D.dtods); + try t.expectEqual(saved.src, D.last_dtod.dst); + try t.expectEqual(saved.dst, D.last_dtod.src); + try t.expectEqual(saved.len, D.last_dtod.len); + + const live = D.devices; + w.x.store.limit(.{ .pages = w.p.pool.total(), .snaps = 0 }); + try t.expectEqual(@as(usize, 0), w.x.store.tree.snaps); + try t.expectEqual(live - 1, D.devices); + const fresh = try w.x.open(w.next, 16, 9100, &.{}); + defer w.x.gpa.free(fresh.plan.marks); + try t.expectEqual(@as(u32, 0), fresh.plan.from); + try t.expectEqual(@as(usize, 2), D.dtods); + try t.expectEqualSlices(u8, w.initial, D.bytes(fresh.cache.state.ptr, w.e.g.stateBytes())); + w.seed(fresh.cache.state.ptr, w.next[0..4096]); + try t.expectEqualSlices(u8, w.state, D.bytes(fresh.cache.state.ptr, w.e.g.stateBytes())); + try t.expect(w.p.close(fresh.cache)); + try settled(w.p); + try w.deinit(); +} + +test "Qwen share faults: snapshot device allocation failure falls back to pinned host" { + var w: World = undefined; + try w.gpu(t.allocator, .device_alloc); + try t.expectEqual(@as(usize, 1), D.hosts); + try t.expectEqual(@as(usize, 0), D.dtods); + try t.expectEqual(@as(usize, 1), w.x.store.tree.snaps); + try w.resumes(); + try t.expectEqual(@as(usize, 0), D.dtods); try settled(w.p); - try w.resumes(); // the unsalted request still resumes its own state + try w.deinit(); +} + +test "Qwen share faults: failed device snapshot copies drain before retry without stale leases" { + inline for (.{ World.SaveFault.copy, World.SaveFault.wait }) |fault| { + var w: World = undefined; + try w.gpu(t.allocator, fault); + try t.expectEqual(@as(usize, 0), D.hosts); + try t.expectEqual(@as(usize, 1), w.x.store.tree.snaps); + try t.expectEqual(@as(usize, 1), w.x.store.tree.counts.failed); + try t.expectEqual(@as(usize, 0), D.freed_pending); + try t.expectEqual(@as(usize, 2), D.dtods); + try w.resumes(); + try t.expectEqual(@as(usize, 3), D.dtods); + try w.deinit(); + } +} + +test "Qwen share faults: a failed D2D restore keeps its snapshot and settles every page lease" { + var w: World = undefined; + try w.gpu(t.allocator, .none); + D.fail_dtod = true; + try t.expectError(error.NotReady, w.x.open(w.next, 16, 9100, &.{})); + try t.expectEqual(@as(usize, 1), w.x.store.tree.snaps); + try t.expectEqual(@as(usize, 0), D.freed_pending); + try settled(w.p); + try w.resumes(); + try t.expectEqual(@as(usize, 3), D.dtods); try w.deinit(); } From aaf528bce893d06a87e0aa7e19f53b6576d5e5c3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:26:55 +0000 Subject: [PATCH 017/361] qwen3_5: adapt snapshot tests to salted prefixes --- .../families/qwen3_5/cuda_prefill_test.zig | 4 ++-- .../qwen3_5/cuda_prefix_fault_test.zig | 21 +++++++++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/zig/src/families/qwen3_5/cuda_prefill_test.zig b/zig/src/families/qwen3_5/cuda_prefill_test.zig index 09199751210..1a7be8edc53 100644 --- a/zig/src/families/qwen3_5/cuda_prefill_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefill_test.zig @@ -59,11 +59,11 @@ pub const Fake = struct { marks: []const u32 = &.{}, kept: [8]usize = undefined, n: usize = 0, - pub fn open(p: *Prefix, _: []const u32, _: usize, _: u32, _: []const u32) !?struct { cache: *Cache, plan: Plan } { + pub fn open(p: *Prefix, _: []const u32, _: usize, _: u32, _: []const u32, _: ?u64) !?struct { cache: *Cache, plan: Plan } { if (p.cache == null) return null; return .{ .cache = p.cache.?, .plan = .{ .from = p.from, .marks = try t.allocator.dupe(u32, p.marks) } }; } - pub fn keep(p: *Prefix, _: *Cache, _: []const u32, at: usize) error{QwenLaneTable}!void { + pub fn keep(p: *Prefix, _: *Cache, _: []const u32, _: ?u64, at: usize) error{QwenLaneTable}!void { p.kept[p.n] = at; p.n += 1; } diff --git a/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig b/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig index 2d834010695..7c4786907c3 100644 --- a/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefix_fault_test.zig @@ -97,12 +97,12 @@ const World = struct { .copy => D.fail_dtod = true, .wait => D.fail_wait_in = 2, } - try w.x.keep(r.cache, w.ids, 4096); + try w.x.keep(r.cache, w.ids, null, 4096); if (fault == .copy or fault == .wait) { try t.expectEqual(@as(usize, 0), w.x.store.tree.snaps); try t.expectEqual(@as(usize, 1), w.x.store.tree.counts.failed); try t.expectEqual(@as(usize, 0), D.freed_pending); - try w.x.keep(r.cache, w.ids, 4096); + try w.x.keep(r.cache, w.ids, null, 4096); } try t.expect(w.p.close(r.cache)); try settled(w.p); @@ -229,6 +229,19 @@ test "Qwen share faults: a keep whose swapped table fails to upload leaves the l try w.deinit(); } +test "Qwen share faults: an unsalted snapshot is not restored under a salt" { + var w: World = undefined; + try w.init(t.allocator); + const r = try w.x.open(w.next, 16, 9100, &.{}, 1); + const gpa = w.x.gpa; + defer gpa.free(r.plan.marks); + try t.expectEqual(@as(u32, 0), r.plan.from); + try t.expect(w.p.close(r.cache)); + try settled(w.p); + try w.resumes(); // the unsalted request still resumes its own state + try w.deinit(); +} + test "Qwen share faults: device snapshots restore D2D and eviction frees their bounded buffer" { var w: World = undefined; try w.gpu(t.allocator, .none); @@ -245,7 +258,7 @@ test "Qwen share faults: device snapshots restore D2D and eviction frees their b w.x.store.limit(.{ .pages = w.p.pool.total(), .snaps = 0 }); try t.expectEqual(@as(usize, 0), w.x.store.tree.snaps); try t.expectEqual(live - 1, D.devices); - const fresh = try w.x.open(w.next, 16, 9100, &.{}); + const fresh = try w.x.open(w.next, 16, 9100, &.{}, null); defer w.x.gpa.free(fresh.plan.marks); try t.expectEqual(@as(u32, 0), fresh.plan.from); try t.expectEqual(@as(usize, 2), D.dtods); @@ -288,7 +301,7 @@ test "Qwen share faults: a failed D2D restore keeps its snapshot and settles eve var w: World = undefined; try w.gpu(t.allocator, .none); D.fail_dtod = true; - try t.expectError(error.NotReady, w.x.open(w.next, 16, 9100, &.{})); + try t.expectError(error.NotReady, w.x.open(w.next, 16, 9100, &.{}, null)); try t.expectEqual(@as(usize, 1), w.x.store.tree.snaps); try t.expectEqual(@as(usize, 0), D.freed_pending); try settled(w.p); From 6dcca2b458f4a134373e1e6ec57e40662ab7a69b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:06:45 +0000 Subject: [PATCH 018/361] qwen3_5: map host KV fixture to its real backing --- zig/src/families/qwen3_5/cuda_kv_host_test.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zig/src/families/qwen3_5/cuda_kv_host_test.zig b/zig/src/families/qwen3_5/cuda_kv_host_test.zig index 3cb3c159c80..a7a22e3f82f 100644 --- a/zig/src/families/qwen3_5/cuda_kv_host_test.zig +++ b/zig/src/families/qwen3_5/cuda_kv_host_test.zig @@ -9,8 +9,8 @@ const D = cuda.paging_test_device.Device; const t = std.testing; const env = @import("sys").env; -fn mapped(out: *u64, _: ?*anyopaque, _: c_uint) callconv(.c) c_int { - out.* = 0x800000; +fn mapped(out: *u64, ptr: ?*anyopaque, _: c_uint) callconv(.c) c_int { + out.* = @intFromPtr(ptr.?); return 0; } fn noMap(_: *u64, _: ?*anyopaque, _: c_uint) callconv(.c) c_int { @@ -59,6 +59,8 @@ test "kv safety: Qwen host KV pool contains only KV and maps its separately size const count = l.pages(64 + pages.window_rows); const before = cuda.usage(false); const p = try pages.Pages.init(t.allocator, &e, l, 64, 0, 1, count); + try t.expectEqual(@intFromPtr(p.host.?.bytes.ptr), p.base); + for (p.host.?.bytes) |byte| try t.expectEqual(@as(u8, 0), byte); try t.expectEqual(count * l.pageBytes(), p.host.?.bytes.len); try t.expectEqual(l.runPages() * l.pageBytes(), p.run_dev.?.len); try t.expectEqual(count, p.pool.total()); From 514f26f2139bd53b714dd60dbe885fb3e429dea2 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:46:03 +0000 Subject: [PATCH 019/361] qwen3_5: test unaligned shared-prefix resume schedule --- .../qwen3_5/cuda_prefill_page_grid_test.zig | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig b/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig index 3f07082698f..2d906f3f51b 100644 --- a/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig +++ b/zig/src/families/qwen3_5/cuda_prefill_page_grid_test.zig @@ -38,3 +38,56 @@ test "Qwen stepped prefill: shared page marks cut fresh and resumed passes at th try t.expectEqualSlices(usize, fresh_engine.rows.items[1..], resumed_engine.rows.items); try t.expectEqual(@as(usize, 256), restored.cached); } + +fn cutEnds(rows: []const usize, from: usize, out: []usize) []usize { + var at = from; + for (rows, 0..) |n, i| { + at += n; + out[i] = at; + } + return out[0..rows.len]; +} + +test "Qwen stepped prefill: a 300-to-10000 resume retains the fresh state schedule" { + const m = E.grid_rows; + const page = 256; + const previous_len = 300; + const restore = previous_len / page * page; + const prompt_len = 10000; + const history_len = 9998; // stable = 300 is below history_len / 2, so no stable-prefix mark realigns the grid + const tail = 9984; + const ids = try t.allocator.alloc(u32, prompt_len); + defer t.allocator.free(ids); + @memset(ids, 2); + + var fresh_engine: Fake.Engine = .{}; + defer fresh_engine.rows.deinit(t.allocator); + defer fresh_engine.keeps.deinit(t.allocator); + var fresh: Fake = .{ .e = &fresh_engine }; + defer fresh.deinit(); + var fresh_prefix: Fake.Prefix = .{ .cache = &fresh.cache, .marks = &.{tail} }; + fresh.prefix = &fresh_prefix; + var cold = try lanes.Stream.init(t.allocator, .{ .id = "fresh-10000", .prompt = ids, .max_new = 1, .history_len = history_len }); + defer cold.deinit(t.allocator); + while (!try prefill.step(&fresh, &cold, 0)) {} + + var resumed_engine: Fake.Engine = .{}; + defer resumed_engine.rows.deinit(t.allocator); + defer resumed_engine.keeps.deinit(t.allocator); + var resumed: Fake = .{ .e = &resumed_engine }; + defer resumed.deinit(); + var resumed_prefix: Fake.Prefix = .{ .cache = &resumed.cache, .from = restore, .marks = &.{tail} }; + resumed.prefix = &resumed_prefix; + var restored = try lanes.Stream.init(t.allocator, .{ .id = "resumed-300-to-10000", .prompt = ids, .max_new = 1, .history_len = history_len }); + defer restored.deinit(t.allocator); + while (!try prefill.step(&resumed, &restored, 0)) {} + + const want = [_]usize{ m, 2 * m, tail, prompt_len }; + var fresh_buf: [want.len]usize = undefined; + var resumed_buf: [want.len]usize = undefined; + try t.expectEqualSlices(usize, &want, cutEnds(fresh_engine.rows.items, 0, &fresh_buf)); + try t.expectEqualSlices(usize, &want, cutEnds(resumed_engine.rows.items, restore, &resumed_buf)); + // The keep passed to forward controls each cut's recurrent-state writes as well as its reduction schedule. + try t.expectEqualSlices(E.Keep, fresh_engine.keeps.items, resumed_engine.keeps.items); + try t.expectEqual(@as(usize, restore), restored.cached); +} From 8733dd5434793dafa54ac0d2a74c156815ba0673 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:56:12 +0000 Subject: [PATCH 020/361] qwen3_5: keep shared resumes on the fresh compute grid --- zig/src/families/qwen3_5/cuda_prefill.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zig/src/families/qwen3_5/cuda_prefill.zig b/zig/src/families/qwen3_5/cuda_prefill.zig index 5e0c43118cd..1edc6b9d101 100644 --- a/zig/src/families/qwen3_5/cuda_prefill.zig +++ b/zig/src/families/qwen3_5/cuda_prefill.zig @@ -107,9 +107,10 @@ test "direct-normalized MTP keeps the target's original stepped chunk boundary" try std.testing.expectEqual(@as(usize, 8192), targetForwardEnd(4096, 8192, 6143, false, false)); } -/// The shared prefix's page-edge marks join the cold pass's cuts; ordinary reuse keeps its old schedule. +/// Shared page-edge marks join a 0-based compute grid, so fresh and resumed passes cut identically. fn keptCut(len: usize, chunks: []const u32, f: *const Fill, at: usize) usize { var end = nextCut(len, chunks, at, 0); + if (f.kept != null) end = @min(end, at + E.grid_rows - at % E.grid_rows); const marks = if (f.kept) |k| k.marks else &.{}; for (marks) |mark| if (mark > at) { end = @min(end, mark); From e6588c3d584bb37def416e191a6791b00a0a229c Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:04:33 +0000 Subject: [PATCH 021/361] qwen3_5: test resumed request-chunk grid continuation --- zig/src/families/qwen3_5/cuda_prefill.zig | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/zig/src/families/qwen3_5/cuda_prefill.zig b/zig/src/families/qwen3_5/cuda_prefill.zig index 1edc6b9d101..3a0f6bc178d 100644 --- a/zig/src/families/qwen3_5/cuda_prefill.zig +++ b/zig/src/families/qwen3_5/cuda_prefill.zig @@ -119,6 +119,11 @@ fn keptCut(len: usize, chunks: []const u32, f: *const Fill, at: usize) usize { return end; } +test "Qwen stepped prefill: a shared resume continues the latest request chunk's compute grid" { + var f: Fill = .{ .at = 3500, .media = null, .kept = .{ .gpa = std.testing.allocator, .marks = &.{} } }; + try std.testing.expectEqual(@as(usize, 3000 + E.grid_rows), keptCut(3 * E.grid_rows, &.{3000}, &f, 3500)); +} + /// The end of `f`'s next step under `max_rows` (0: the cold cut), its cold cut renewed once the last one landed. fn capped(len: usize, chunks: []const u32, f: *Fill, max_rows: u32) usize { if (f.cold <= f.at) f.cold = keptCut(len, chunks, f, f.at); From f9e71d5cf32c71a3dd95449e4bf487984c70cb64 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:04:37 +0000 Subject: [PATCH 022/361] qwen3_5: anchor shared resumes to request chunks --- zig/src/families/qwen3_5/cuda_prefill.zig | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/zig/src/families/qwen3_5/cuda_prefill.zig b/zig/src/families/qwen3_5/cuda_prefill.zig index 3a0f6bc178d..c3aca5de8e1 100644 --- a/zig/src/families/qwen3_5/cuda_prefill.zig +++ b/zig/src/families/qwen3_5/cuda_prefill.zig @@ -107,10 +107,18 @@ test "direct-normalized MTP keeps the target's original stepped chunk boundary" try std.testing.expectEqual(@as(usize, 8192), targetForwardEnd(4096, 8192, 6143, false, false)); } -/// Shared page-edge marks join a 0-based compute grid, so fresh and resumed passes cut identically. +/// Shared page-edge marks join each fresh request chunk's compute grid, so resumed passes cut identically. fn keptCut(len: usize, chunks: []const u32, f: *const Fill, at: usize) usize { var end = nextCut(len, chunks, at, 0); - if (f.kept != null) end = @min(end, at + E.grid_rows - at % E.grid_rows); + if (f.kept != null) { + var anchor: usize = 0; + for (chunks) |boundary| { + if (boundary > at) break; + anchor = boundary; + } + const since = at - anchor; + end = @min(end, anchor + since + E.grid_rows - since % E.grid_rows); + } const marks = if (f.kept) |k| k.marks else &.{}; for (marks) |mark| if (mark > at) { end = @min(end, mark); From 1a14bb121c17605de8a54660247ed1ec8a424c94 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:20:27 +0000 Subject: [PATCH 023/361] changelog: #4473 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1198b6c78cf..29928c3a540 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.5 on CUDA: shared prefixes are saved at page boundaries, and `TF_QWEN_KV_SNAPSHOT_GPU=1` keeps prefix snapshots on the device instead of pinned host memory, falling back to host snapshots when device memory is short (#4473). + - Kernel contract: MiniMax-H3-Image's 19 Metal kernels register with the contract, in 31 registrations with 34 planted controls, instead of being gated only by each tool's own self-test (#2808). - MiniMax-H3-Image on Metal: `tf-h3-image-prompt` writes a whole text-to-image case from a size and a seed (the canvas, the size and the seed's starting rows), so text to image runs end to end with TensorFold's own tools, and `tf-h3-image ... free` exits 0 when there is no reference to gate against (#2781). From d8ac0440820bd1c4744272e685ac2ac36f6f8906 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:20:27 +0000 Subject: [PATCH 024/361] changelog: #4473 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29928c3a540..e84efd56008 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.5 on CUDA: shared prefixes are saved at page boundaries, and `TF_QWEN_KV_SNAPSHOT_GPU=1` keeps prefix snapshots on the device instead of pinned host memory, falling back to host snapshots when device memory is short (#4473). + + - Kernel contract: MiniMax-H3-Image's 19 Metal kernels register with the contract, in 31 registrations with 34 planted controls, instead of being gated only by each tool's own self-test (#2808). - MiniMax-H3-Image on Metal: `tf-h3-image-prompt` writes a whole text-to-image case from a size and a seed (the canvas, the size and the seed's starting rows), so text to image runs end to end with TensorFold's own tools, and `tf-h3-image ... free` exits 0 when there is no reference to gate against (#2781). From 83549b0724399becee6e1344f905609c086c32a9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:45:13 +0000 Subject: [PATCH 025/361] flashnext: count window graph calls Count every cache attempt alongside captures, updates and replays so steady-state graph behavior has a per-round denominator. --- zig/src/families/flashnext/cuda_window_graph.zig | 5 ++++- zig/src/families/flashnext/cuda_window_graph_test.zig | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/zig/src/families/flashnext/cuda_window_graph.zig b/zig/src/families/flashnext/cuda_window_graph.zig index 3e11f1a7352..3b2fdd13d8e 100644 --- a/zig/src/families/flashnext/cuda_window_graph.zig +++ b/zig/src/families/flashnext/cuda_window_graph.zig @@ -209,6 +209,8 @@ pub fn Cache(comptime K: type) type { map: std.AutoHashMapUnmanaged(K, Held) = .empty, /// Slots run once eagerly and are captured the second time (a one-off pass would never pay its capture back). seen: std.AutoHashMapUnmanaged(K, void) = .empty, + /// Every run, including eager warm-ups and disabled-graph fallbacks; updates and replays split graph launches. + calls: u64 = 0, captures: u64 = 0, replays: u64 = 0, /// Held graphs re-recorded at a new length, for a new sequence or on other buffers and updated in place. @@ -225,6 +227,7 @@ pub fn Cache(comptime K: type) type { /// `pass.run()` (kernels only: its uploads already queued) as `key`'s graph, captured first when new. pub fn run(c: *Self, gpa: std.mem.Allocator, stream: cuda.Stream, key: K, pass: anytype) !void { + c.calls += 1; if (c.off) return pass.run(); const slot = slotOf(key); if (c.map.getPtr(slot)) |h| { @@ -247,7 +250,7 @@ pub fn Cache(comptime K: type) type { errdefer exec.deinit(); try c.map.put(gpa, slot, .{ .key = key, .exec = exec }); c.captures += 1; - if (c.captures % 64 == 1) std.log.info("{s} graphs: {d} captured, {d} updated, {d} replayed, {d} held", .{ @typeName(K), c.captures, c.updates, c.replays, c.map.count() }); + if (c.captures % 64 == 1) std.log.info("{s} graphs: {d} calls, {d} captured, {d} updated, {d} replayed, {d} held", .{ @typeName(K), c.calls, c.captures, c.updates, c.replays, c.map.count() }); try exec.launchOn(stream); } diff --git a/zig/src/families/flashnext/cuda_window_graph_test.zig b/zig/src/families/flashnext/cuda_window_graph_test.zig index cdfb06c4d48..ca74e07c9e3 100644 --- a/zig/src/families/flashnext/cuda_window_graph_test.zig +++ b/zig/src/families/flashnext/cuda_window_graph_test.zig @@ -103,7 +103,7 @@ test "window graphs: a held graph takes a new length or sequence in place; new l try expectAfter(&c, stream, key(4, 3, 7), .{ 4, 2, 3, 1, 7 }); try expectAfter(&c, stream, key(4, 4, 7), .{ 4, 2, 3, 2, 7 }); // another row count is another slot try expectAfter(&c, stream, key(4, 3, 8), .{ 4, 2, 3, 3, 7 }); // and another shape - try t.expectEqual([3]u64{ 1, 3, 3 }, [3]u64{ c.captures, c.updates, c.replays }); + try t.expectEqual([4]u64{ 10, 1, 3, 3 }, [4]u64{ c.calls, c.captures, c.updates, c.replays }); c.clear(t.allocator); try t.expectEqual(@as(usize, 2), Fake.destroyed); } From 9c59d0ecaa7cab768889d4fe540dc8b7aa8fe3ec Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:54:08 +0000 Subject: [PATCH 026/361] flashnext: retain both settle graph parities Opt into separate graph slots for the two whole-accept state/spare directions. Compare replayed argument bytes, target tokens and full acceptance lengths on the fake CUDA graph driver. --- docs/environment.md | 3 +- .../families/flashnext/cuda_window_graph.zig | 16 ++ .../flashnext/cuda_window_graph_test.zig | 164 ++++++++++++++++-- zig/src/platform/environment.zig | 1 + 4 files changed, 166 insertions(+), 18 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 64a9b96eb81..c5fe4ae1369 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -177,13 +177,14 @@ Windows uses the same proxy routes and timeout settings through native asynchron ## Flash Next -Flash Next checks these 39 settings when its engine loads, before any device or checkpoint work: a malformed value +Flash Next checks these 40 settings when its engine loads, before any device or checkpoint work: a malformed value stops the start with the variable, the supplied text and the accepted forms. | Variable | Accepted explicit value | | --- | --- | | `TF_FLASHNEXT_PROMPT_BF16` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_WINDOW_GRAPH` | Exactly `0` or `1`; default on | +| `TF_FLASHNEXT_WINDOW_GRAPH_PARITY` | Exactly `0` or `1`; default off. `1` keeps CUDA graphs for both sequence-state/draft-spare pointer orientations, avoiding recapture after whole-window accepts | | `TF_FLASHNEXT_LANE_PARTS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_KEEP_INPASS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_FIRST_EARLY` | Exactly `0` or `1`; default on | diff --git a/zig/src/families/flashnext/cuda_window_graph.zig b/zig/src/families/flashnext/cuda_window_graph.zig index 3b2fdd13d8e..c02795cece9 100644 --- a/zig/src/families/flashnext/cuda_window_graph.zig +++ b/zig/src/families/flashnext/cuda_window_graph.zig @@ -22,6 +22,11 @@ pub fn enabled() bool { return @import("sys").environment.read(bool, "TF_FLASHNEXT_WINDOW_GRAPH", true) catch true; } +/// TF_FLASHNEXT_WINDOW_GRAPH_PARITY=1: retain both whole-accept state/spare pointer directions. +pub fn retainSettleGraphs() bool { + return @import("sys").environment.read(bool, "TF_FLASHNEXT_WINDOW_GRAPH_PARITY", false) catch false; +} + /// attnRows' host values for rows ending at `ends` in a `cap`-token cache: dense chunks, the score grid (0: none). pub const Geometry = struct { chunks: u32, @@ -113,6 +118,17 @@ pub const Key = struct { var h: Hash = .{}; h.geometry(.at(pos0 + rows, seq.cap)); h.values(&[_]u64{ seq.gen, seq.cap, pieces(seq), s.h, s.cap, scores, model, hooks.logits_out, hooks.streams }); + if (retainSettleGraphs()) { + var parity: u64 = 0; + if (hooks.keep) |keep| if (seq.state.len != 0) { + for (keep.layers) |layer| { + if (layer.state_out == 0) continue; + parity = @intFromBool(seq.state[0].ptr < layer.state_out); + break; + } + }; + h.fixed(parity); // a shape bucket: the full pointers still move in place below + } h.keep(hooks.keep); return .{ .rows = @intCast(rows), .shape = h.shape.final(), .moving = h.moving.final() }; } diff --git a/zig/src/families/flashnext/cuda_window_graph_test.zig b/zig/src/families/flashnext/cuda_window_graph_test.zig index ca74e07c9e3..4183d94e9fe 100644 --- a/zig/src/families/flashnext/cuda_window_graph_test.zig +++ b/zig/src/families/flashnext/cuda_window_graph_test.zig @@ -15,27 +15,69 @@ const Fake = struct { var eager: usize = 0; var destroyed: usize = 0; var verdict: abi.ExecUpdateResult = .success; + var current: [2]u64 = .{ 0, 0 }; + var graphs: [16][2]u64 = @splat(.{ 0, 0 }); + var execs: [16][2]u64 = @splat(.{ 0, 0 }); + var out: [16][2]u64 = undefined; + var emitted: usize = 0; + + fn reset() void { + capturing = false; + records = 0; + instantiates = 0; + updates = 0; + launches = 0; + eager = 0; + destroyed = 0; + verdict = .success; + current = .{ 0, 0 }; + graphs = @splat(.{ 0, 0 }); + execs = @splat(.{ 0, 0 }); + emitted = 0; + } + + fn install(d: *cuda.Driver) void { + d.api.cuStreamBeginCapture_v2 = begin; + d.api.cuStreamEndCapture = end; + d.api.cuStreamIsCapturing = status; + d.api.cuGraphInstantiateWithFlags = instantiate; + d.api.cuGraphExecUpdate_v2 = update; + d.api.cuGraphDestroy = graphDestroy; + d.api.cuGraphUpload = upload; + d.api.cuGraphLaunch = launch; + d.api.cuGraphExecDestroy = execDestroy; + } + + fn emit(payload: [2]u64) void { + std.debug.assert(emitted < out.len); + out[emitted] = payload; + emitted += 1; + } + fn begin(_: abi.Stream, _: abi.CaptureMode) callconv(.c) abi.Result { capturing = true; return 0; } - fn end(_: abi.Stream, out: *abi.Graph) callconv(.c) abi.Result { + fn end(_: abi.Stream, out_graph: *abi.Graph) callconv(.c) abi.Result { capturing = false; records += 1; - out.* = @ptrFromInt(1); + out_graph.* = @ptrFromInt(1); + graphs[@intFromPtr(out_graph.*)] = current; return 0; } fn status(_: abi.Stream, s: *abi.CaptureStatus) callconv(.c) abi.Result { s.* = if (capturing) .active else .none; return 0; } - fn instantiate(e: *abi.GraphExec, _: abi.Graph, _: u64) callconv(.c) abi.Result { + fn instantiate(e: *abi.GraphExec, graph: abi.Graph, _: u64) callconv(.c) abi.Result { instantiates += 1; e.* = @ptrFromInt(instantiates); + execs[@intFromPtr(e.*)] = graphs[@intFromPtr(graph)]; return 0; } - fn update(_: abi.GraphExec, _: abi.Graph, info: *abi.ExecUpdateResultInfo) callconv(.c) abi.Result { + fn update(exec: abi.GraphExec, graph: abi.Graph, info: *abi.ExecUpdateResultInfo) callconv(.c) abi.Result { updates += 1; + execs[@intFromPtr(exec)] = graphs[@intFromPtr(graph)]; info.result = verdict; return if (verdict == .success) 0 else 910; // CUDA_ERROR_GRAPH_EXEC_UPDATE_FAILURE } @@ -45,8 +87,9 @@ const Fake = struct { fn upload(_: abi.GraphExec, _: abi.Stream) callconv(.c) abi.Result { return 0; } - fn launch(_: abi.GraphExec, _: abi.Stream) callconv(.c) abi.Result { + fn launch(exec: abi.GraphExec, _: abi.Stream) callconv(.c) abi.Result { launches += 1; + emit(execs[@intFromPtr(exec)]); return 0; } fn execDestroy(_: abi.GraphExec) callconv(.c) abi.Result { @@ -55,10 +98,15 @@ const Fake = struct { } }; -/// A pass whose kernels the fake counts: run outside a capture, it ran eagerly. +/// A pass whose argument pair is kept in its graph; eager runs emit it directly. const Pass = struct { - pub fn run(_: Pass) !void { - if (!Fake.capturing) Fake.eager += 1; + payload: [2]u64 = .{ 0, 0 }, + pub fn run(p: Pass) !void { + Fake.current = p.payload; + if (!Fake.capturing) { + Fake.eager += 1; + Fake.emit(p.payload); + } } }; @@ -74,16 +122,9 @@ fn expectAfter(c: *wg.Cache(wg.Key), stream: cuda.Stream, k: wg.Key, counts: [5] } test "window graphs: a held graph takes a new length or sequence in place; new launches get a new executable" { + Fake.reset(); var d: cuda.Driver = undefined; - d.api.cuStreamBeginCapture_v2 = Fake.begin; - d.api.cuStreamEndCapture = Fake.end; - d.api.cuStreamIsCapturing = Fake.status; - d.api.cuGraphInstantiateWithFlags = Fake.instantiate; - d.api.cuGraphExecUpdate_v2 = Fake.update; - d.api.cuGraphDestroy = Fake.graphDestroy; - d.api.cuGraphUpload = Fake.upload; - d.api.cuGraphLaunch = Fake.launch; - d.api.cuGraphExecDestroy = Fake.execDestroy; + Fake.install(&d); const previous = cuda.copy_source.current(); cuda.copy_source.setCurrent(@ptrFromInt(0x3254)); defer cuda.copy_source.setCurrent(previous); @@ -216,6 +257,95 @@ test "window graph keys: equal tables give equal keys; a kept window's swapped s try t.expectEqual(windowKey(a, 9000, 3, hooks0), windowKey(b, 9000, 3, hooks0)); } +const SettleOutcome = struct { + args: [6][2]u64, + tokens: [18]u32, + kept: [6]usize, + counts: [4]u64, // calls, captures, replays, updates + fake: [5]usize, + held: usize, +}; + +/// Six whole-window accepts: each direction repeats after one intervening settle of the other direction. +fn runSettles() !SettleOutcome { + const accept = @import("lanes").accept; + Fake.reset(); + var d: cuda.Driver = undefined; + Fake.install(&d); + const previous = cuda.copy_source.current(); + cuda.copy_source.setCurrent(@ptrFromInt(0x3254)); + defer cuda.copy_source.setCurrent(previous); + const stream: cuda.Stream = .{ .d = &d, .handle = @ptrFromInt(1) }; + var c: wg.Cache(wg.Key) = .{}; + defer c.clear(t.allocator); + var q: Seq = .at(7, 0x1000_0000); + var spare: [linear_n]Buf = undefined; + for (&spare, 0..) |*x, i| x.ptr = 0x3000_0000 + i * 0x10000; + var out: SettleOutcome = undefined; + var keys: [2]?wg.Key = .{ null, null }; + for (0..6) |round| { + var keep: parts.Keep = .{}; + keep.layers[0].state_out = spare[0].ptr; + const hooks: parts.Hooks = .{ .logits = .all, .logits_out = 0x6000, .keep = &keep, .host_logits = false }; + const k = windowKey(q, 9000, 3, hooks); + const parity = round % 2; + if (keys[parity]) |old| try t.expectEqual(old, k) else keys[parity] = k; + const payload = [2]u64{ q.state[0].ptr, spare[0].ptr }; + try c.run(t.allocator, stream, k, Pass{ .payload = payload }); + const base: u32 = @intCast(40 + 3 * round); + const drafts = [3]u32{ base, base + 1, base + 2 }; + const picks = [3]u32{ base + 1, base + 2, base + 3 }; + const parents = try accept.rowParents(t.allocator, 3, null); + defer t.allocator.free(parents); + const path = try accept.acceptPath(t.allocator, &drafts, parents, &picks); + defer t.allocator.free(path); + out.kept[round] = path.len; + var emitted: usize = 0; + for (path[1..]) |row| { + out.tokens[3 * round + emitted] = accept.targetPick(&picks, parents, row); + emitted += 1; + } + out.tokens[3 * round + emitted] = picks[path[path.len - 1]]; + out.args[round] = Fake.out[round]; + for (&q.state, &spare) |*a, *b| std.mem.swap(Buf, a, b); + } + out.counts = .{ c.calls, c.captures, c.replays, c.updates }; + out.fake = .{ Fake.records, Fake.instantiates, Fake.updates, Fake.eager, Fake.launches }; + out.held = c.map.count(); + return out; +} + +test "window graph parity: both settle directions replay identical payload bytes, tokens and full accepts" { + const env = @import("sys").env; + const name = "TF_FLASHNEXT_WINDOW_GRAPH_PARITY"; + _ = env.unsetenv(name); + defer _ = env.unsetenv(name); + try t.expect(!wg.retainSettleGraphs()); + const off = try runSettles(); + try t.expectEqual([4]u64{ 6, 1, 0, 4 }, off.counts); + try t.expectEqual([5]usize{ 5, 1, 4, 1, 5 }, off.fake); + try t.expectEqual(@as(usize, 1), off.held); + + try t.expectEqual(@as(c_int, 0), env.setenv(name, "1", 1)); + try t.expect(wg.retainSettleGraphs()); + const on = try runSettles(); + try t.expectEqual([4]u64{ 6, 2, 2, 0 }, on.counts); + try t.expectEqual([5]usize{ 2, 2, 0, 2, 4 }, on.fake); + try t.expectEqual(@as(usize, 2), on.held); + + try t.expectEqualSlices(u8, std.mem.asBytes(&off.args), std.mem.asBytes(&on.args)); + try t.expectEqualSlices(u32, &off.tokens, &on.tokens); + try t.expectEqualSlices(usize, &off.kept, &on.kept); + for (off.tokens, 0..) |token, i| try t.expectEqual(@as(u32, @intCast(41 + i)), token); + for (off.kept) |kept| try t.expectEqual(@as(usize, 3), kept); + for (1..6) |i| try t.expect(!std.meta.eql(off.args[i - 1], off.args[i])); + var off_hash: [32]u8 = undefined; + var on_hash: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(std.mem.asBytes(&off.tokens), &off_hash, .{}); + std.crypto.hash.sha2.Sha256.hash(std.mem.asBytes(&on.tokens), &on_hash, .{}); + try t.expectEqualSlices(u8, &off_hash, &on_hash); +} + var history: [2]i64 = .{ 0, 0 }; /// A shared pass's lane over device buffers at `seq`'s addresses (a fake driver: nothing is called). diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 92d4bfd7687..6ac566e7a3a 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -273,6 +273,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSV41_ROWS_CAP", .scope = .dsv41, .kind = .u32, .only = &.{ 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 24, 32, 48, 64 }, .forms = "1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 24, 32, 48 or 64" }, .{ .name = "TF_FLASHNEXT_PROMPT_BF16", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_WINDOW_GRAPH", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, + .{ .name = "TF_FLASHNEXT_WINDOW_GRAPH_PARITY", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_LANE_PARTS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_KEEP_INPASS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_FIRST_EARLY", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, From 25ebea439854ff49e0239090bbb67f4669912398 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:35:58 +0000 Subject: [PATCH 027/361] docs: scope settle graph parity to one stream --- docs/environment.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/environment.md b/docs/environment.md index c5fe4ae1369..adacafbe024 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -184,7 +184,7 @@ stops the start with the variable, the supplied text and the accepted forms. | --- | --- | | `TF_FLASHNEXT_PROMPT_BF16` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_WINDOW_GRAPH` | Exactly `0` or `1`; default on | -| `TF_FLASHNEXT_WINDOW_GRAPH_PARITY` | Exactly `0` or `1`; default off. `1` keeps CUDA graphs for both sequence-state/draft-spare pointer orientations, avoiding recapture after whole-window accepts | +| `TF_FLASHNEXT_WINDOW_GRAPH_PARITY` | Exactly `0` or `1`; default off. For one stream, `1` keeps CUDA graphs for both sequence-state/draft-spare pointer orientations, avoiding recapture after whole-window accepts | | `TF_FLASHNEXT_LANE_PARTS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_KEEP_INPASS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_FIRST_EARLY` | Exactly `0` or `1`; default on | From cb4e0c62e8e16d109900bbc4d867b4b51f121281 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:45:37 +0000 Subject: [PATCH 028/361] test: retain main Flash Next setting alongside graph parity Main already registers the batch GDN switch. Count it and the parity switch together in the strict environment inventory; parsing and inference stay unchanged. --- zig/src/platform/environment_flashnext_test.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index 82ef4864a33..8f0e235a87f 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -33,13 +33,13 @@ fn check(name: []const u8, raw: []const u8, valid: bool) !void { try t.expect(std.mem.endsWith(u8, why.?, e.rule(name).forms)); } -test "Flash Next strict env: the table holds all 39 settings: 27 switches, 9 integers, 1 real, 2 structured" { +test "Flash Next strict env: the table holds all 40 settings: 28 switches, 9 integers, 1 real, 2 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .flashnext) { try t.expect(std.mem.startsWith(u8, r.name, "TF_FLASHNEXT_")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 27, 9, 1, 2 }, counts); + try t.expectEqual([4]usize{ 28, 9, 1, 2 }, counts); } test "Flash Next strict env: unset and blank settings both read as the caller's default" { From c8c8c30fe16040756a95acd12f22f189ff1c767b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:20:29 +0000 Subject: [PATCH 029/361] changelog: #4492 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e84efd56008..67a43168015 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 +- Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_GRAPH_PARITY=1` keys the verify-window CUDA graph on which of the two swapped state buffers a round uses, so full-accept rounds replay a resident graph instead of refreshing it; a counter reports graph updates and replays; off by default (#4492). + - Qwen3.5 on CUDA: shared prefixes are saved at page boundaries, and `TF_QWEN_KV_SNAPSHOT_GPU=1` keeps prefix snapshots on the device instead of pinned host memory, falling back to host snapshots when device memory is short (#4473). From d13b9aa0cf33289d79de01280094a7a675069aab Mon Sep 17 00:00:00 2001 From: GrgaPalcic <26028466+GrgaPalcic@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:14:42 +0100 Subject: [PATCH 030/361] perf(fabric/tp): eager half-forwarding in 4-rank RoCE ring relay --- zig/src/fabric/tp/README.md | 4 +-- zig/src/fabric/tp/roce_relay.zig | 44 ++++++++++++++++----------- zig/src/fabric/tp/roce_relay_test.zig | 19 ++++++++++++ 3 files changed, 48 insertions(+), 19 deletions(-) diff --git a/zig/src/fabric/tp/README.md b/zig/src/fabric/tp/README.md index 05746e7c006..01184872034 100644 --- a/zig/src/fabric/tp/README.md +++ b/zig/src/fabric/tp/README.md @@ -145,8 +145,8 @@ the connection table and the existing NCCL byte probe must agree before the wire Default mesh and two- and three-rank paths keep their existing protocol. Each neighbour receives both halves and forwards one to the opposite rank. Consumers wait for six flags. -The proxy completes each forward before posting the other direction and posts sequence s only after consuming -s-2 and receiving every rank's s-1. Variable-length shards carry their padded length beside each half flag. +The proxy forwards each half as soon as it lands, the two directions independently, and posts sequence s only +after every post of s-1 has completed, consuming s-2 and receiving every rank's s-1. Variable-length shards carry their padded length beside each half flag. A producer must use the existing sequential stream contract: its preceding consumer completes before staging another collective. One proxy owns every QP. Wait failures report the source rank and sequence. diff --git a/zig/src/fabric/tp/roce_relay.zig b/zig/src/fabric/tp/roce_relay.zig index a8cb6a58e44..b8f58cad263 100644 --- a/zig/src/fabric/tp/roce_relay.zig +++ b/zig/src/fabric/tp/roce_relay.zig @@ -1,4 +1,4 @@ -//! Four-rank ring: two half flags a source, alternating completed relays, and two-slot custody. +//! Four-rank ring: two half flags a source, relays posted as each half lands, and two-slot custody. const std = @import("std"); const guard = @import("roce_multi_guard.zig"); pub const Error = error{ BadRelay, WrongSequence, Timeout }; @@ -42,7 +42,6 @@ pub const Relay = struct { last: u32 = 0, started: bool = false, sent: [2]bool = .{ false, false }, - direction: u32 = 0, waiting_at: ?u64 = null, fault: Fault = .{}, @@ -74,28 +73,36 @@ pub const Relay = struct { }; return true; } - /// The producer starts a collective only after its preceding consumer returns (the existing CUDA stream contract). + /// One collective at a time (the CUDA stream contract); a half is forwarded as it lands, s+1 waits for completions. pub fn progress(r: *Relay, wire: anytype, doorbell: u32, consumed: u32, padded: u32, now: u64) !bool { r.fault = .{ .rank = r.me, .sequence = r.last, .stage = .forwarding }; try wire.reap(); - if (!wire.idle()) return r.wait(now, r.fault); - // Both forwards of the previous op complete before any new op posts. Only this owner touches queue pairs. if (r.started) { - if (!r.sent[r.direction]) { - const source = neighbour(r.me, 1 - r.direction); - const seen = r.flag(source, r.last, r.direction); - r.fault = .{ .rank = source, .sequence = r.last, .seen = seen, .stage = .forwarding }; + var posted = false; + var pending: ?Fault = null; + for (0..2) |d| { + if (r.sent[d]) continue; + const direction: u32 = @intCast(d); + const source = neighbour(r.me, 1 - direction); + const seen = r.flag(source, r.last, direction); if (seen != r.last) { - if (newer(seen, r.last)) return error.WrongSequence; - return r.wait(now, r.fault); + pending = .{ .rank = source, .sequence = r.last, .seen = seen, .stage = .forwarding }; + if (newer(seen, r.last)) { + r.fault = pending.?; + return error.WrongSequence; + } + continue; } - const total = r.word(r.layout.flagAt(source, r.last & 1, r.direction) + 4).load(.acquire); - try wire.segment(.{ .dst = neighbour(r.me, r.direction), .source = source, .seq = r.last, .direction = r.direction, .total = total }); - r.sent[r.direction] = true; - r.direction = 1 - r.direction; + const total = r.word(r.layout.flagAt(source, r.last & 1, direction) + 4).load(.acquire); + try wire.segment(.{ .dst = neighbour(r.me, direction), .source = source, .seq = r.last, .direction = direction, .total = total }); + r.sent[d] = true; + posted = true; + } + if (posted) { r.waiting_at = null; return true; } + if (pending) |f| return r.wait(now, f); if (!try r.allSeen(r.last, now)) return false; } if (doorbell == r.last) { @@ -103,15 +110,18 @@ pub const Relay = struct { return false; } const seq = r.last +% 1; + // Rank q's s+2 overwrites a forward's source and needs our forward of s+1, so every post of s completes first. + if (!wire.idle()) return r.wait(now, .{ .rank = r.me, .sequence = r.last, .stage = .forwarding }); r.fault = .{ .rank = r.me, .sequence = seq, .seen = doorbell, .stage = .producer }; if (doorbell -% r.last > 2) return error.WrongSequence; // A published s-1 proves that producer consumed s-2. Waiting for every s-1 protects all receive-slot readers. if (r.started and newer(seq -% 2, consumed)) return r.wait(now, .{ .rank = r.me, .sequence = seq -% 2, .seen = consumed, .stage = .custody }); - for (0..2) |d| for (0..2) |h| { + // Neighbour d forwards half d to the opposite rank, the longest path: both of those leave first. + for (0..2) |pass| for (0..2) |d| { const dst = neighbour(r.me, @intCast(d)); r.fault = .{ .rank = dst, .sequence = seq, .stage = .forwarding }; - try wire.segment(.{ .dst = dst, .source = r.me, .seq = seq, .direction = @intCast(h), .total = padded }); + try wire.segment(.{ .dst = dst, .source = r.me, .seq = seq, .direction = @intCast(if (pass == 0) d else 1 - d), .total = padded }); }; r.last = seq; r.started = true; diff --git a/zig/src/fabric/tp/roce_relay_test.zig b/zig/src/fabric/tp/roce_relay_test.zig index 866a0d18e7c..f66f8206f63 100644 --- a/zig/src/fabric/tp/roce_relay_test.zig +++ b/zig/src/fabric/tp/roce_relay_test.zig @@ -293,3 +293,22 @@ test "relay custody: a fresh flag over stale payload is rejected by the every-wo try t.expect(h.ready(0, 1)); try t.expectError(error.StaleWord, h.check(0, 1)); } + +test "relay eager: half 1 forwards immediately when half 0 has not landed yet" { + var h: Harness = undefined; + try h.init(4096); + defer h.deinit(); + h.fabric.deferred = false; + try h.stage(0, 1, 16); + // Advance rank 0 past staging sequence 1 so both initial neighbour halves are sent. + try t.expect(try h.states[0].progress(&h.fabric.wires[0], 1, 0, 16, h.ticks)); + // Deliver only half 1 from rank 1 (neighbour 0 -> direction 1) while half 0 from rank 3 is still missing. + const f1 = h.fabric.layout.flagAt(1, 1, 1); + h.states[0].word(f1 + 4).store(16, .release); + h.states[0].word(f1).store(1, .release); + const before = h.fabric.wires[0].posted; + try t.expect(try h.states[0].progress(&h.fabric.wires[0], 1, 0, 16, h.ticks)); + try t.expectEqual(before + 1, h.fabric.wires[0].posted); + try t.expect(h.states[0].sent[1]); + try t.expect(!h.states[0].sent[0]); +} From 539930bf7cc2e47b291c5c7956e7219e95eb1ba3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:31:13 +0000 Subject: [PATCH 031/361] changelog: #4798 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67a43168015..26e0e914259 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 +- TP: the 4-rank RoCE ring relay forwards each half as soon as it arrives, lowering gather latency with the opt-in relay; bytes are unchanged (#4798). Thanks @GrgaPalcic. + - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_GRAPH_PARITY=1` keys the verify-window CUDA graph on which of the two swapped state buffers a round uses, so full-accept rounds replay a resident graph instead of refreshing it; a counter reports graph updates and replays; off by default (#4492). - Qwen3.5 on CUDA: shared prefixes are saved at page boundaries, and `TF_QWEN_KV_SNAPSHOT_GPU=1` keeps prefix snapshots on the device instead of pinned host memory, falling back to host snapshots when device memory is short (#4473). From 08df825129024a809d96cc655a0d6030880ad8df Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:31:13 +0000 Subject: [PATCH 032/361] changelog: #4798 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26e0e914259..16c3e3108d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - TP: the 4-rank RoCE ring relay forwards each half as soon as it arrives, lowering gather latency with the opt-in relay; bytes are unchanged (#4798). Thanks @GrgaPalcic. + + - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_GRAPH_PARITY=1` keys the verify-window CUDA graph on which of the two swapped state buffers a round uses, so full-accept rounds replay a resident graph instead of refreshing it; a counter reports graph updates and replays; off by default (#4492). - Qwen3.5 on CUDA: shared prefixes are saved at page boundaries, and `TF_QWEN_KV_SNAPSHOT_GPU=1` keeps prefix snapshots on the device instead of pinned host memory, falling back to host snapshots when device memory is short (#4473). From c4a500568f622a951dd3fad99bb88ee9868198f3 Mon Sep 17 00:00:00 2001 From: GrgaPalcic <26028466+GrgaPalcic@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:51:39 +0100 Subject: [PATCH 033/361] hy4_flash: host W8A16 FP8 weight map, TP=1/2/4 partition, and Engram FP8 row format --- zig/src/families/hy4_flash/engram_fp8.zig | 135 +++++++ zig/src/families/hy4_flash/fp8_partition.zig | 225 ++++++++++++ zig/src/families/hy4_flash/fp8_weights.zig | 296 ++++++++++++++++ .../families/hy4_flash/fp8_weights_test.zig | 330 ++++++++++++++++++ zig/src/families/hy4_flash/host_tests.zig | 1 + 5 files changed, 987 insertions(+) create mode 100644 zig/src/families/hy4_flash/engram_fp8.zig create mode 100644 zig/src/families/hy4_flash/fp8_partition.zig create mode 100644 zig/src/families/hy4_flash/fp8_weights.zig create mode 100644 zig/src/families/hy4_flash/fp8_weights_test.zig diff --git a/zig/src/families/hy4_flash/engram_fp8.zig b/zig/src/families/hy4_flash/engram_fp8.zig new file mode 100644 index 00000000000..aca89dce36e --- /dev/null +++ b/zig/src/families/hy4_flash/engram_fp8.zig @@ -0,0 +1,135 @@ +//! Hy4-flash 100-byte FP8 Engram row format (96 e4m3fn codes from fp64 + fp32 row scale, 4 KiB HY4ENGR1 header). +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const engram = @import("engram.zig"); + +const Text = config.Text; +const fp8 = core.quant.fp8; + +pub const magic: u64 = 0x3152474E45345948; // "HY4ENGR1" little-endian +pub const header_bytes: u64 = 4096; +pub const dim: usize = 96; +pub const row_bytes: usize = dim + 4; +pub const fp8_max: f64 = 448.0; + +pub fn fileName(buf: []u8, layer: usize) ![]u8 { + return std.fmt.bufPrint(buf, "engram_layer{d}.hy4e", .{layer}); +} + +pub const Header = struct { + layer: u32, + layer_id: u32, + seed: u64, + rows: u64, + sizes: [engram.columns]u64, + + pub fn of(text: Text, layer_id: u32) !Header { + if (layer_id == 0) return error.BadEngramGeometry; + var key_buf: [10]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buf, "{d}", .{layer_id}); + const groups = text.engram_layer_head_vocab_sizes.map.get(key) orelse return error.BadEngramGeometry; + var sizes: [engram.columns]u64 = undefined; + var total: u64 = 0; + var at: usize = 0; + for (groups) |g| for (g) |prime| { + if (at >= sizes.len or prime < 2) return error.BadEngramGeometry; + sizes[at] = prime; + total = try std.math.add(u64, total, prime); + at += 1; + }; + if (at != sizes.len) return error.BadEngramGeometry; + return .{ + .layer = layer_id - 1, + .layer_id = layer_id, + .seed = text.engram_seed, + .rows = total, + .sizes = sizes, + }; + } + + pub fn encode(h: Header) [header_bytes]u8 { + var b: [header_bytes]u8 = @splat(0); + const words = [8]u64{ magic, h.layer, h.layer_id, h.seed, h.rows, dim, row_bytes, engram.columns }; + for (words, 0..) |w, i| std.mem.writeInt(u64, b[8 * i ..][0..8], w, .little); + for (h.sizes, 0..) |s, i| std.mem.writeInt(u64, b[64 + 8 * i ..][0..8], s, .little); + return b; + } + + pub fn parse(b: *const [header_bytes]u8, file_size: u64) !Header { + var w: [8]u64 = undefined; + for (&w, 0..) |*x, i| x.* = std.mem.readInt(u64, b[8 * i ..][0..8], .little); + if (w[0] != magic) return error.NotHy4EngramPack; + if (w[5] != dim or w[6] != row_bytes or w[7] != engram.columns) return error.BadHy4EngramPack; + if (w[1] + 1 != w[2] or w[2] > std.math.maxInt(u32) or w[4] == 0) return error.BadHy4EngramPack; + var sizes: [engram.columns]u64 = undefined; + var sum: u64 = 0; + for (&sizes, 0..) |*s, i| { + s.* = std.mem.readInt(u64, b[64 + 8 * i ..][0..8], .little); + if (s.* == 0) return error.BadHy4EngramPack; + sum = std.math.add(u64, sum, s.*) catch return error.BadHy4EngramPack; + } + if (sum != w[4]) return error.BadHy4EngramPack; + const payload = std.math.mul(u64, w[4], row_bytes) catch return error.BadHy4EngramPack; + const want = std.math.add(u64, header_bytes, payload) catch return error.BadHy4EngramPack; + if (file_size != want) return error.BadHy4EngramPack; + return .{ .layer = @intCast(w[1]), .layer_id = @intCast(w[2]), .seed = w[3], .rows = w[4], .sizes = sizes }; + } + + pub fn checkConfig(h: Header, text: Text, layer_id: u32) !void { + const want = try Header.of(text, layer_id); + if (h.layer_id != want.layer_id or h.seed != want.seed or h.rows != want.rows) return error.UnsupportedEngram; + if (!std.mem.eql(u64, &h.sizes, &want.sizes)) return error.UnsupportedEngram; + } +}; + +/// Exact float32 -> float8_e4m3fn round-to-nearest-even matching PyTorch `.float().to(torch.float8_e4m3fn)`. +pub fn e4m3Rne(x: f32) u8 { + const bits: u32 = @bitCast(x); + const sign: u8 = @intCast((bits >> 31) << 7); + const ab: u32 = bits & 0x7fff_ffff; + if (ab > 0x43e8_0000) return sign | 0x7f; + if (ab < 0x3a80_0000) return sign; + if (ab < 0x3c80_0000) { + const exp = ab >> 23; + const sig: u32 = 0x80_0000 | (ab & 0x7f_ffff); + const shift: u5 = @intCast(141 - exp); + var q: u32 = sig >> shift; + const rem: u32 = sig & ((@as(u32, 1) << shift) - 1); + const half: u32 = @as(u32, 1) << (shift - 1); + if (rem > half or (rem == half and (q & 1) == 1)) q += 1; + return sign | @as(u8, @intCast(q)); + } + const exp = ab >> 23; + const mant = ab & 0x7f_ffff; + var q: u32 = ((exp - 120) << 3) | (mant >> 20); + const rem = mant & 0x0f_ffff; + if (rem > 0x08_0000 or (rem == 0x08_0000 and (q & 1) == 1)) q += 1; + return sign | @as(u8, @intCast(q)); +} + +/// Pack one 96-wide bf16 row into 96 e4m3fn codes + fp32(amax / 448) using fp64 scaling. +pub fn packRow(bf16_bytes: *const [dim * 2]u8, out: *[row_bytes]u8) void { + var x64: [dim]f64 = undefined; + var amax: f64 = 1e-12; + for (0..dim) |j| { + const u = std.mem.readInt(u16, bf16_bytes[2 * j ..][0..2], .little); + const v: f64 = @as(f32, @bitCast(@as(u32, u) << 16)); + x64[j] = v; + const a = @abs(v); + if (a > amax) amax = a; + } + const s64: f64 = amax / fp8_max; + for (0..dim) |j| { + const clamped = std.math.clamp(x64[j] / s64, -fp8_max, fp8_max); + out[j] = e4m3Rne(@floatCast(clamped)); + } + const s32: f32 = @floatCast(s64); + std.mem.writeInt(u32, out[dim..][0..4], @bitCast(s32), .little); +} + +/// Decode one 100-byte packed row as `code[j] * scale` in fp32. +pub fn unpackRowF32(rec: *const [row_bytes]u8, out: *[dim]f32) void { + const scale: f32 = @bitCast(std.mem.readInt(u32, rec[dim..][0..4], .little)); + for (0..dim) |j| out[j] = @as(f32, @floatCast(fp8.e4m3(rec[j]))) * scale; +} diff --git a/zig/src/families/hy4_flash/fp8_partition.zig b/zig/src/families/hy4_flash/fp8_partition.zig new file mode 100644 index 00000000000..b174576cf61 --- /dev/null +++ b/zig/src/families/hy4_flash/fp8_partition.zig @@ -0,0 +1,225 @@ +//! W8A16 tensor-parallel partitioning (world 1/2/4 on 128-row FP8 blocks) and per-rank memory floor for Hy4-flash. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const engram = @import("engram.zig"); + +const Text = config.Text; +const Why = core.modelopt.Why; + +pub const max_world = 4; +pub const block = core.quant.fp8.block; + +pub const Share = struct { + lo: usize, + len: usize, + + pub fn scaled(s: Share, by: usize) Share { + return .{ .lo = s.lo * by, .len = s.len * by }; + } +}; + +/// Partition `count` items into `world` (1, 2 or 4) equal shares aligned to `unit`. +pub fn even(count: usize, unit: usize, rank: usize, world: usize) !Share { + if ((world != 1 and world != 2 and world != 4) or rank >= world) return error.UnsupportedWorld; + if (unit == 0 or count % (world * unit) != 0) return error.SplitNotOnBlocks; + const len = count / world; + return .{ .lo = rank * len, .len = len }; +} + +/// Per-rank attention slices: whole heads with q_b, linear_gate and o_proj aligned to 128-element FP8 blocks. +pub const Attn = struct { + heads: Share, + q_rows: Share, + gate_rows: Share, + kv_rows: Share, + o_cols: Share, + + pub fn of(text: Text, layer: usize, rank: usize, world: usize) !Attn { + const h = text.headShape(@intCast(layer)); + const heads = try even(h.heads, 1, rank, world); + const a: Attn = .{ + .heads = heads, + .q_rows = heads.scaled(@as(usize, h.non_rotary) + h.rotary), + .gate_rows = heads.scaled(h.value), + .kv_rows = heads.scaled(@as(usize, h.non_rotary) + h.value), + .o_cols = heads.scaled(h.value), + }; + for ([_]Share{ a.q_rows, a.gate_rows, a.o_cols }) |s| { + if (s.lo % block != 0 or s.len % block != 0) return error.SplitNotOnBlocks; + } + return a; + } +}; + +/// Per-rank FFN intermediate slice aligned to 128-row FP8 blocks. +pub fn ffn(width: usize, rank: usize, world: usize) !Share { + return even(width, block, rank, world); +} + +/// Per-rank routed expert intermediate slice (every rank holds every expert's inner slice). +pub fn expert(text: Text, rank: usize, world: usize) !Share { + return ffn(text.moe_intermediate_size, rank, world); +} + +/// Per-rank Engram slice: whole hash heads, their contiguous table rows and projection input columns. +pub const Engram = struct { + heads: Share, + cols: Share, + bias: bool, + + pub fn of(text: Text, rank: usize, world: usize) !Engram { + const heads = try even(engram.columns, 1, rank, world); + const head_dim = text.engram_n_embed_per_ngram / text.engram_n_head_per_ngram; + return .{ .heads = heads, .cols = heads.scaled(head_dim), .bias = rank == 0 }; + } + + /// Contiguous table rows owned by this rank's heads in one-based Engram `layer_id`. + pub fn rows(e: Engram, text: Text, layer_id: u32) !Share { + var key_buf: [10]u8 = undefined; + const key = try std.fmt.bufPrint(&key_buf, "{d}", .{layer_id}); + const groups = text.engram_layer_head_vocab_sizes.map.get(key) orelse return error.BadEngramGeometry; + var flat: [engram.columns]u32 = undefined; + var at: usize = 0; + for (groups) |g| for (g) |prime| { + if (at >= flat.len) return error.BadEngramGeometry; + flat[at] = prime; + at += 1; + }; + if (at != flat.len) return error.BadEngramGeometry; + var lo: usize = 0; + for (flat[0..e.heads.lo]) |p| lo += p; + var len: usize = 0; + for (flat[e.heads.lo..][0..e.heads.len]) |p| len += p; + return .{ .lo = lo, .len = len }; + } +}; + +/// Per-rank lm_head vocabulary slice. +pub fn vocab(text: Text, rank: usize, world: usize) !Share { + return even(text.vocab_size, 1, rank, world); +} + +/// Validate every TP split required at `world` across all ranks and layers before loading weights. +pub fn check(text: Text, world: usize, why: *Why) !void { + if (world != 1 and world != 2 and world != 4) { + why.set("world {d} is not supported (expected 1, 2 or 4)", .{world}); + return error.UnsupportedWorld; + } + const shared_w: usize = @as(usize, text.moe_intermediate_size) * text.n_shared_experts; + for (0..world) |r| { + for (0..text.num_hidden_layers) |l| _ = Attn.of(text, l, r, world) catch |e| { + why.set("layer {d}: {d} heads do not split over {d} ranks on {d}-row blocks", .{ l, text.headShape(@intCast(l)).heads, world, block }); + return e; + }; + _ = expert(text, r, world) catch |e| return refuse(why, "routed expert width", text.moe_intermediate_size, world, e); + _ = ffn(shared_w, r, world) catch |e| return refuse(why, "shared expert width", shared_w, world, e); + _ = ffn(text.intermediate_size, r, world) catch |e| return refuse(why, "dense FFN width", text.intermediate_size, world, e); + _ = Engram.of(text, r, world) catch |e| return refuse(why, "Engram heads", engram.columns, world, e); + _ = vocab(text, r, world) catch |e| return refuse(why, "vocabulary", text.vocab_size, world, e); + } +} + +fn refuse(why: *Why, what: []const u8, n: usize, world: usize, e: anyerror) anyerror { + why.set("{s} {d} does not split over {d} ranks", .{ what, n, world }); + return e; +} + +/// Bytes per 128x128 FP8 block scale: bf16 as stored on disk, or fp32 in packed GPU buffers. +pub const Scale = enum(usize) { stored = 2, packed_ = 4 }; +pub const Format = enum { bf16, fp8 }; + +/// Projection [n, k] byte size in bf16 or e4m3 + block scales. +pub fn projBytes(f: Format, n: usize, k: usize, scale: Scale) usize { + return switch (f) { + .bf16 => n * k * 2, + .fp8 => n * k + core.quant.fp8.blocks(n) * core.quant.fp8.blocks(k) * @backingInt(scale), + }; +} + +fn attnBytes(text: Text, layer: usize, rank: usize, world: usize, scale: Scale) !usize { + const d: usize = text.hidden_size; + const h = text.headShape(@intCast(layer)); + const a = try Attn.of(text, layer, rank, world); + const f: Format = if (layer == 0) .bf16 else .fp8; + var n: usize = 2 * (@as(usize, text.q_lora_rank) * d + text.q_lora_rank + (@as(usize, text.kv_lora_rank) + h.rotary) * d + text.kv_lora_rank + d); + n += 2 * a.kv_rows.len * text.kv_lora_rank + 4 * a.heads.len; + n += projBytes(f, a.q_rows.len, text.q_lora_rank, scale) + projBytes(f, a.gate_rows.len, d, scale) + projBytes(f, d, a.o_cols.len, scale); + if (text.layer_types[layer] == .deepseek_sparse_attention) { + const t: usize = text.compressed_indexer_head_dim; + const ih: usize = text.compressed_indexer_num_attention_heads; + n += 2 * (ih * d + ih * t * text.q_lora_rank + t + t * d) + 4 * (@as(usize, text.compressed_indexer_compress_ratio) * t + 2 * t * t + t); + } + return n; +} + +fn ffnBytes(text: Text, layer: usize, rank: usize, world: usize, scale: Scale) !usize { + const d: usize = text.hidden_size; + if (text.mlp_layer_types[layer] == .dense) return 2 * 3 * (try ffn(text.intermediate_size, rank, world)).len * d + 2 * d; + const w = (try expert(text, rank, world)).len; + const l: usize = text.routed_expert_hidden_size; + const shared_w: usize = @as(usize, text.moe_intermediate_size) * text.n_shared_experts; + var n: usize = 2 * @as(usize, text.n_routed_experts) * d + 4 * @as(usize, text.n_routed_experts) + 2 * 2 * l * d; + n += 2 * 3 * (try ffn(shared_w, rank, world)).len * d + 2 * d; + return n + @as(usize, text.n_routed_experts) * (projBytes(.fp8, 2 * w, l, scale) + projBytes(.fp8, l, w, scale)); +} + +fn engramBytes(text: Text, rank: usize, world: usize) !usize { + const d: usize = text.hidden_size; + const head_dim: usize = text.engram_n_embed_per_ngram / text.engram_n_head_per_ngram; + const e = try Engram.of(text, rank, world); + const projections: usize = 1 + text.hc_mult; + return 4 * @as(usize, text.engram_lookup_table_size) + 2 * e.heads.len * head_dim + projections * 2 * (d * e.cols.len + d) + 2 * d * (3 * @as(usize, text.hc_mult) + 1); +} + +/// One decoder layer's weight bytes on a rank, excluding the large Engram embedding table. +pub fn layerBytes(text: Text, layer: usize, rank: usize, world: usize, scale: Scale) !usize { + const d: usize = text.hidden_size; + const hc: usize = text.hc_mult; + var n = 2 * 2 * d + 2 * (4 * 2 * hc * hc * d + 4 * 2 * hc + 4 * 2); + n += try attnBytes(text, layer, rank, world, scale) + try ffnBytes(text, layer, rank, world, scale); + if (std.mem.indexOfScalar(u32, text.engram_layer_ids, @intCast(layer + 1)) != null) n += try engramBytes(text, rank, world); + return n; +} + +/// Top-level weights on a rank: replicated embeddings, vocabulary-split lm_head, final norm and hc_head. +pub fn topBytes(text: Text, rank: usize, world: usize) !usize { + const d: usize = text.hidden_size; + const hc: usize = text.hc_mult; + return 2 * @as(usize, text.vocab_size) * d + 2 * (try vocab(text, rank, world)).len * d + 2 * d + 4 * (hc * hc * d + hc + 1); +} + +/// Total GPU-resident backbone weight bytes on a rank (excluding Engram tables, DFly2 and vision). +pub fn weightBytes(text: Text, rank: usize, world: usize, scale: Scale) !usize { + var n = try topBytes(text, rank, world); + for (0..text.num_hidden_layers) |l| n += try layerBytes(text, l, rank, world, scale); + return n; +} + +/// A rank's Engram table bytes across all Engram layers: bf16 as stored (192 B/row) or packed FP8 (100 B/row). +pub fn engramTableBytes(text: Text, rank: usize, world: usize, row: enum { stored, packed_ }) !usize { + const e = try Engram.of(text, rank, world); + const head_dim: usize = text.engram_n_embed_per_ngram / text.engram_n_head_per_ngram; + const per_row = if (row == .stored) 2 * head_dim else head_dim + 4; + var n: usize = 0; + for (text.engram_layer_ids) |layer_id| n += (try e.rows(text, layer_id)).len * per_row; + return n; +} + +/// BF16 KV cache bytes per token on each rank across all sparse-indexed layers. +pub fn tokenBytes(text: Text) usize { + var n: usize = 0; + for (text.layer_types) |k| if (k == .deepseek_sparse_attention) { + n += 2 * (@as(usize, text.kv_lora_rank) + text.qk_rope_head_dim + text.compressed_indexer_head_dim); + }; + return n; +} + +/// Per-stream BF16 sliding-window ring bytes across all sliding attention layers. +pub fn ringBytes(text: Text) usize { + var n: usize = 0; + for (text.layer_types) |k| if (k == .sliding_attention) { + n += 2 * (@as(usize, text.kv_lora_rank) + text.swa_qk_rope_head_dim) * text.sliding_window; + }; + return n; +} diff --git a/zig/src/families/hy4_flash/fp8_weights.zig b/zig/src/families/hy4_flash/fp8_weights.zig new file mode 100644 index 00000000000..068f2702ac8 --- /dev/null +++ b/zig/src/families/hy4_flash/fp8_weights.zig @@ -0,0 +1,296 @@ +//! Official Hy4-flash-FP8 (W8A16) checkpoint tensor map; each projection's format comes from its stored tensors. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const engram = @import("engram.zig"); + +const Text = config.Text; +const Tensor = core.checkpoint.Tensor; +const Checkpoint = core.checkpoint.Checkpoint; +const fp8 = core.quant.fp8; + +/// A projection [n, k] as stored: bf16 alone, or e4m3 codes with bf16 scale_inv [ceil(n/128), ceil(k/128)]. +pub const Proj = union(enum) { + bf16: Tensor, + fp8: fp8.Host, + + pub fn rows(p: Proj) usize { + return switch (p) { + .bf16 => |t| t.dim(0), + .fp8 => |f| f.weight.dim(0), + }; + } +}; + +/// One iHC site: fn [2*hc, hc*hidden] fp32, base [2*hc] fp32, scale [2] fp32 (pre, post). +pub const Hc = struct { fn_: Tensor, base: Tensor, scale: Tensor }; + +pub const Indexer = struct { + query: Tensor, + head_weights: Tensor, + token_key: Tensor, + token_key_norm: Tensor, + values: Tensor, + gates: Tensor, + key_norm: Tensor, + ape: Tensor, +}; + +pub const Attn = struct { + q_a: Tensor, + q_a_norm: Tensor, + q_b: Proj, + kv_a: Tensor, + kv_a_norm: Tensor, + kv_b: Tensor, + gate: Proj, + o: Proj, + post_norm: Tensor, + sinks: Tensor, + indexer: ?Indexer, +}; + +pub const Dense = struct { gate: Tensor, up: Tensor, down: Tensor, post_norm: Tensor }; + +pub const Moe = struct { + router: Tensor, + bias: Tensor, + latent_down: Tensor, + latent_up: Tensor, + gate_up: Tensor, + gate_up_s: Tensor, + down: Tensor, + down_s: Tensor, + shared: Dense, +}; + +pub const Engram = struct { + table: Tensor, + map: Tensor, + head_norms: [engram.columns]Tensor, + value: Tensor, + value_bias: Tensor, + keys: [4]Tensor, + key_biases: [4]Tensor, + norm_keys: [4]Tensor, + norm_queries: [4]Tensor, + pre_gamma: Tensor, + stream_scales: [4]Tensor, +}; + +pub const Layer = struct { + input_norm: Tensor, + post_attn_norm: Tensor, + hc_attn: Hc, + hc_mlp: Hc, + attn: Attn, + mlp: union(enum) { dense: Dense, moe: Moe }, + engram: ?Engram, +}; + +/// The tensors outside the decoder layers. +pub const Top = struct { embed: Tensor, norm: Tensor, head: Tensor, hc_head: Hc }; + +pub const Map = struct { + gpa: std.mem.Allocator, + top: Top, + layers: []Layer, + + pub fn deinit(m: *Map) void { + m.gpa.free(m.layers); + m.* = undefined; + } +}; + +const Names = struct { + ck: *Checkpoint, + i: usize, + buf: [192]u8 = undefined, + + fn name(self: *Names, comptime fmt: []const u8, args: anytype) ![]const u8 { + return std.fmt.bufPrint(&self.buf, "model.layers.{d}." ++ fmt, .{self.i} ++ args); + } + + fn t(self: *Names, dtype: core.checkpoint.DType, shape: []const usize, comptime fmt: []const u8, args: anytype) !Tensor { + return self.ck.expect(try self.name(fmt, args), dtype, shape); + } + + fn bf(self: *Names, shape: []const usize, comptime fmt: []const u8, args: anytype) !Tensor { + return self.t(.bf16, shape, fmt, args); + } + + fn f32s(self: *Names, shape: []const usize, comptime fmt: []const u8, args: anytype) !Tensor { + return self.t(.f32, shape, fmt, args); + } + + /// Read `module` [n, k] in whichever format its tensors store: bf16 alone, or e4m3 with bf16 scale_inv. + fn proj(self: *Names, n: usize, k: usize, comptime module: []const u8) !Proj { + const w = try self.ck.get(try self.name(module ++ ".weight", .{})); + switch (w.dtype) { + .bf16 => { + if (self.ck.has(try self.name(module ++ ".weight_scale_inv", .{}))) return error.UnexpectedTensor; + return .{ .bf16 = try self.bf(&.{ n, k }, module ++ ".weight", .{}) }; + }, + .f8_e4m3 => { + const prefix = try self.name(module, .{}); + var own: [192]u8 = undefined; + @memcpy(own[0..prefix.len], prefix); + return .{ .fp8 = try fp8.read(self.ck, own[0..prefix.len], n, k, .bf16, null) }; + }, + else => return error.UnsupportedQuantization, + } + } + + fn hc(self: *Names, text: Text, comptime site: []const u8) !Hc { + const m: usize = text.hc_mult; + const d: usize = text.hidden_size; + return .{ + .fn_ = try self.f32s(&.{ 2 * m, m * d }, site ++ ".hc_pre.hc_fn", .{}), + .base = try self.f32s(&.{2 * m}, site ++ ".hc_pre.hc_base", .{}), + .scale = try self.f32s(&.{2}, site ++ ".hc_pre.hc_scale", .{}), + }; + } +}; + +fn attn(nm: *Names, text: Text) !Attn { + const h = text.headShape(@intCast(nm.i)); + const d: usize = text.hidden_size; + const p = "self_attn."; + return .{ + .q_a = try nm.bf(&.{ text.q_lora_rank, d }, p ++ "q_a_proj.weight", .{}), + .q_a_norm = try nm.bf(&.{text.q_lora_rank}, p ++ "q_a_layernorm.weight", .{}), + .q_b = try nm.proj(h.queryRows(), text.q_lora_rank, p ++ "q_b_proj"), + .kv_a = try nm.bf(&.{ @as(usize, text.kv_lora_rank) + h.rotary, d }, p ++ "kv_a_proj_with_mqa.weight", .{}), + .kv_a_norm = try nm.bf(&.{text.kv_lora_rank}, p ++ "kv_a_layernorm.weight", .{}), + .kv_b = try nm.bf(&.{ h.kvRows(), text.kv_lora_rank }, p ++ "kv_b_proj.weight", .{}), + .gate = try nm.proj(@as(usize, h.heads) * h.value, d, p ++ "linear_gate"), + .o = try nm.proj(d, @as(usize, h.heads) * h.value, p ++ "o_proj"), + .post_norm = try nm.bf(&.{d}, p ++ "post_proj_norm.weight", .{}), + .sinks = try nm.f32s(&.{h.heads}, p ++ "learnable_sink_param", .{}), + .indexer = if (text.layer_types[nm.i] == .deepseek_sparse_attention) try indexer(nm, text) else null, + }; +} + +fn indexer(nm: *Names, text: Text) !Indexer { + const p = "self_attn.compressed_indexer."; + const n: usize = text.compressed_indexer_head_dim; + const d: usize = text.hidden_size; + return .{ + .query = try nm.bf(&.{ @as(usize, text.compressed_indexer_num_attention_heads) * n, text.q_lora_rank }, p ++ "query_projection.weight", .{}), + .head_weights = try nm.bf(&.{ text.compressed_indexer_num_attention_heads, d }, p ++ "head_weight_projection.weight", .{}), + .token_key = try nm.bf(&.{ n, d }, p ++ "token_key_projection.weight", .{}), + .token_key_norm = try nm.bf(&.{n}, p ++ "token_key_norm.weight", .{}), + .values = try nm.f32s(&.{ n, n }, p ++ "key_value_projection.weight", .{}), + .gates = try nm.f32s(&.{ n, n }, p ++ "key_gate_projection.weight", .{}), + .key_norm = try nm.f32s(&.{n}, p ++ "key_norm.weight", .{}), + .ape = try nm.f32s(&.{ text.compressed_indexer_compress_ratio, n }, p ++ "intra_group_ape", .{}), + }; +} + +fn moe(nm: *Names, text: Text) !Moe { + const e: usize = text.n_routed_experts; + const w: usize = text.moe_intermediate_size; + const l: usize = text.routed_expert_hidden_size; + const d: usize = text.hidden_size; + const shared_w: usize = @as(usize, text.moe_intermediate_size) * text.n_shared_experts; + return .{ + .router = try nm.bf(&.{ e, d }, "mlp.gate.weight", .{}), + .bias = try nm.f32s(&.{e}, "mlp.gate.e_score_correction_bias", .{}), + .latent_down = try nm.bf(&.{ l, d }, "mlp.routed_expert_down_proj.weight", .{}), + .latent_up = try nm.bf(&.{ d, l }, "mlp.routed_expert_up_proj.weight", .{}), + .gate_up = try nm.t(.f8_e4m3, &.{ e, 2 * w, l }, "mlp.experts.gate_up_proj", .{}), + .gate_up_s = try nm.bf(&.{ e, fp8.blocks(2 * w), fp8.blocks(l) }, "mlp.experts.gate_up_proj_scale_inv", .{}), + .down = try nm.t(.f8_e4m3, &.{ e, l, w }, "mlp.experts.down_proj", .{}), + .down_s = try nm.bf(&.{ e, fp8.blocks(l), fp8.blocks(w) }, "mlp.experts.down_proj_scale_inv", .{}), + .shared = .{ + .gate = try nm.bf(&.{ shared_w, d }, "mlp.shared_experts.gate_proj.weight", .{}), + .up = try nm.bf(&.{ shared_w, d }, "mlp.shared_experts.up_proj.weight", .{}), + .down = try nm.bf(&.{ d, shared_w }, "mlp.shared_experts.down_proj.weight", .{}), + .post_norm = try nm.bf(&.{d}, "mlp.combine_output_norm.weight", .{}), + }, + }; +} + +fn engramTensors(nm: *Names, text: Text, number: u32) !Engram { + if (text.hc_mult != 4) return error.BadArchitecture; + const p = "engram_layer."; + const d: usize = text.hidden_size; + const head_dim: usize = text.engram_n_embed_per_ngram / text.engram_n_head_per_ngram; + const k: usize = engram.columns * head_dim; + const rows = try text.engramRows(number); + var g: Engram = undefined; + g.table = try nm.bf(&.{ rows, head_dim }, p ++ "multi_head_embedding.embedding.weight", .{}); + g.map = try nm.t(.i32, &.{text.engram_lookup_table_size}, p ++ "lookup_table", .{}); + for (&g.head_norms, 0..) |*n, h| n.* = try nm.bf(&.{head_dim}, p ++ "lookup_per_head_norms.{d}.weight", .{h}); + g.value = try nm.bf(&.{ d, k }, p ++ "value_proj.weight", .{}); + g.value_bias = try nm.bf(&.{d}, p ++ "value_proj.bias", .{}); + for (0..4) |s| { + g.keys[s] = try nm.bf(&.{ d, k }, p ++ "key_projs.{d}.weight", .{s}); + g.key_biases[s] = try nm.bf(&.{d}, p ++ "key_projs.{d}.bias", .{s}); + g.norm_keys[s] = try nm.bf(&.{d}, p ++ "norm_key.{d}.weight", .{s}); + g.norm_queries[s] = try nm.bf(&.{d}, p ++ "norm_query.{d}.weight", .{s}); + g.stream_scales[s] = try nm.bf(&.{d}, p ++ "unified_per_hc_scales.{d}", .{s}); + } + g.pre_gamma = try nm.bf(&.{d}, p ++ "unified_pre_gamma", .{}); + return g; +} + +/// Read zero-based layer `i`'s W8A16 checkpoint tensors. +pub fn layer(ck: *Checkpoint, text: Text, i: usize) !Layer { + var nm: Names = .{ .ck = ck, .i = i }; + const d: usize = text.hidden_size; + const one_based: u32 = @intCast(i + 1); + const has_engram = std.mem.indexOfScalar(u32, text.engram_layer_ids, one_based) != null; + return .{ + .input_norm = try nm.bf(&.{d}, "input_layernorm.weight", .{}), + .post_attn_norm = try nm.bf(&.{d}, "post_attention_layernorm.weight", .{}), + .hc_attn = try nm.hc(text, "hc_attn_layer"), + .hc_mlp = try nm.hc(text, "hc_mlp_layer"), + .attn = try attn(&nm, text), + .mlp = if (text.mlp_layer_types[i] == .dense) .{ .dense = .{ + .gate = try nm.bf(&.{ text.intermediate_size, d }, "mlp.gate_proj.weight", .{}), + .up = try nm.bf(&.{ text.intermediate_size, d }, "mlp.up_proj.weight", .{}), + .down = try nm.bf(&.{ d, text.intermediate_size }, "mlp.down_proj.weight", .{}), + .post_norm = try nm.bf(&.{d}, "mlp.post_fc2_norm.weight", .{}), + } } else .{ .moe = try moe(&nm, text) }, + .engram = if (has_engram) try engramTensors(&nm, text, one_based) else null, + }; +} + +/// Read the top-level embeddings, final norm, lm_head, and hc_head tensors. +pub fn top(ck: *Checkpoint, text: Text) !Top { + const m: usize = text.hc_mult; + const d: usize = text.hidden_size; + return .{ + .embed = try ck.expect("model.embed_tokens.weight", .bf16, &.{ text.vocab_size, d }), + .norm = try ck.expect("model.norm.weight", .bf16, &.{d}), + .head = try ck.expect("lm_head.weight", .bf16, &.{ text.vocab_size, d }), + .hc_head = .{ + .fn_ = try ck.expect("model.hc_head.hc_head_fn", .f32, &.{ m, m * d }), + .base = try ck.expect("model.hc_head.hc_head_base", .f32, &.{m}), + .scale = try ck.expect("model.hc_head.hc_head_scale", .f32, &.{1}), + }, + }; +} + +/// Map every backbone tensor and mark DFly2 and vision prefixes as skipped on purpose. +pub fn mapped(gpa: std.mem.Allocator, ck: *Checkpoint, text: Text) !Map { + const m: Map = .{ .gpa = gpa, .top = try top(ck, text), .layers = try gpa.alloc(Layer, text.num_hidden_layers) }; + errdefer gpa.free(m.layers); + for (m.layers, 0..) |*l, i| l.* = try layer(ck, text, i); + try ck.skip("model.dfly_layers."); + try ck.skip("vit."); + return m; +} + +/// Map the W8A16 backbone and refuse any unmapped checkpoint tensor, naming it in `why` when given. +pub fn map(gpa: std.mem.Allocator, ck: *Checkpoint, text: Text, why: ?*core.modelopt.Why) !Map { + var m = try mapped(gpa, ck, text); + errdefer m.deinit(); + if (why) |w| for (ck.files.items) |*file| for (file.names.keys()) |key| if (!ck.used.contains(key)) { + w.set("unused checkpoint tensor {s}", .{key}); + return error.UnusedTensors; + }; + if (ck.unused() != 0) return error.UnusedTensors; + return m; +} diff --git a/zig/src/families/hy4_flash/fp8_weights_test.zig b/zig/src/families/hy4_flash/fp8_weights_test.zig new file mode 100644 index 00000000000..f0c9416525d --- /dev/null +++ b/zig/src/families/hy4_flash/fp8_weights_test.zig @@ -0,0 +1,330 @@ +//! Host tests for Hy4-flash W8A16 weight mapping, TP=1/2/4 partitioning/memory floors, and 100-byte FP8 Engram rows. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const engram = @import("engram.zig"); +const fp8_weights = @import("fp8_weights.zig"); +const part = @import("fp8_partition.zig"); +const ep = @import("engram_fp8.zig"); + +const testing = std.testing; +const io = testing.io; +const Entry = core.checkpoint_fixture.Entry; +const GiB = 1 << 30; + +fn release() !std.json.Parsed(config.Model) { + return config.parse(testing.allocator, @embedFile("config_fixture.json")); +} + +const Fixture = struct { + a: std.mem.Allocator, + list: std.ArrayList(Entry) = .empty, + + fn add(f: *Fixture, dtype: []const u8, shape: []const usize, comptime fmt: []const u8, args: anytype) !void { + var n: usize = if (std.mem.eql(u8, dtype, "BF16")) 2 else if (std.mem.eql(u8, dtype, "F8_E4M3")) 1 else 4; + for (shape) |x| n *= x; + const bytes = try f.a.alloc(u8, n); + @memset(bytes, 0); + try f.list.append(f.a, .{ + .name = try std.fmt.allocPrint(f.a, fmt, args), + .dtype = dtype, + .shape = try f.a.dupe(usize, shape), + .bytes = bytes, + }); + } + + fn proj(f: *Fixture, q: bool, n: usize, k: usize, comptime fmt: []const u8, args: anytype) !void { + if (!q) return f.add("BF16", &.{ n, k }, fmt ++ ".weight", args); + try f.add("F8_E4M3", &.{ n, k }, fmt ++ ".weight", args); + try f.add("BF16", &.{ core.quant.fp8.blocks(n), core.quant.fp8.blocks(k) }, fmt ++ ".weight_scale_inv", args); + } +}; + +fn tinyText(a: std.mem.Allocator, base: config.Text) !config.Text { + var t = base; + t.num_hidden_layers = 4; + t.hidden_size = 256; + t.vocab_size = 8; + t.q_lora_rank = 128; + t.num_attention_heads = 1; + t.swa_num_attention_heads = 2; + t.layer_types = &.{ .deepseek_sparse_attention, .sliding_attention, .deepseek_sparse_attention, .sliding_attention }; + t.mlp_layer_types = &.{ .dense, .sparse, .sparse, .sparse }; + t.intermediate_size = 128; + t.n_routed_experts = 2; + t.moe_intermediate_size = 128; + t.routed_expert_hidden_size = 128; + t.engram_layer_ids = &.{ 1, 2, 3, 4 }; + t.engram_lookup_table_size = 16; + var vocab: @FieldType(config.Text, "engram_layer_head_vocab_sizes") = .{}; + const row8 = try a.dupe(u32, &.{ 2, 2, 2, 2, 2, 2, 2, 2 }); + const orders = try a.dupe([]const u32, &.{ row8, row8 }); + for ([_][]const u8{ "1", "2", "3", "4" }) |k| try vocab.map.put(a, k, orders); + t.engram_layer_head_vocab_sizes = vocab; + return t; +} + +const BadMode = enum { none, extra_tensor, stray_scale, bad_dtype }; + +fn writeTiny(a: std.mem.Allocator, tmp: testing.TmpDir, t: config.Text, bad: BadMode) !void { + var f: Fixture = .{ .a = a }; + const d: usize = t.hidden_size; + const m: usize = t.hc_mult; + try f.add("BF16", &.{ t.vocab_size, d }, "model.embed_tokens.weight", .{}); + try f.add("BF16", &.{d}, "model.norm.weight", .{}); + try f.add("BF16", &.{ t.vocab_size, d }, "lm_head.weight", .{}); + try f.add("F32", &.{ m, m * d }, "model.hc_head.hc_head_fn", .{}); + try f.add("F32", &.{m}, "model.hc_head.hc_head_base", .{}); + try f.add("F32", &.{1}, "model.hc_head.hc_head_scale", .{}); + try f.add("BF16", &.{ 2, 2 }, "model.dfly_layers.0.mlp.up_proj.weight", .{}); + try f.add("BF16", &.{ 2, 2 }, "vit.embeddings.patch_embedding.weight", .{}); + if (bad == .extra_tensor) try f.add("BF16", &.{2}, "model.layers.0.self_attn.q_norm.weight", .{}); + for (0..t.num_hidden_layers) |i| { + const h = t.headShape(@intCast(i)); + const q = i > 0; + for ([_][]const u8{ "input_layernorm", "post_attention_layernorm" }) |n| try f.add("BF16", &.{d}, "model.layers.{d}.{s}.weight", .{ i, n }); + for ([_][]const u8{ "hc_attn_layer", "hc_mlp_layer" }) |s| { + try f.add("F32", &.{ 2 * m, m * d }, "model.layers.{d}.{s}.hc_pre.hc_fn", .{ i, s }); + try f.add("F32", &.{2 * m}, "model.layers.{d}.{s}.hc_pre.hc_base", .{ i, s }); + try f.add("F32", &.{2}, "model.layers.{d}.{s}.hc_pre.hc_scale", .{ i, s }); + } + const a_ = "model.layers.{d}.self_attn."; + try f.add("BF16", &.{ t.q_lora_rank, d }, a_ ++ "q_a_proj.weight", .{i}); + try f.add("BF16", &.{t.q_lora_rank}, a_ ++ "q_a_layernorm.weight", .{i}); + if (i == 0 and bad == .bad_dtype) { + try f.add("F32", &.{ h.queryRows(), t.q_lora_rank }, a_ ++ "q_b_proj.weight", .{i}); + } else { + try f.proj(q, h.queryRows(), t.q_lora_rank, a_ ++ "q_b_proj", .{i}); + if (i == 0 and bad == .stray_scale) try f.add("BF16", &.{ 2, 1 }, a_ ++ "q_b_proj.weight_scale_inv", .{i}); + } + try f.add("BF16", &.{ @as(usize, t.kv_lora_rank) + h.rotary, d }, a_ ++ "kv_a_proj_with_mqa.weight", .{i}); + try f.add("BF16", &.{t.kv_lora_rank}, a_ ++ "kv_a_layernorm.weight", .{i}); + try f.add("BF16", &.{ h.kvRows(), t.kv_lora_rank }, a_ ++ "kv_b_proj.weight", .{i}); + try f.proj(q, @as(usize, h.heads) * h.value, d, a_ ++ "linear_gate", .{i}); + try f.proj(q, d, @as(usize, h.heads) * h.value, a_ ++ "o_proj", .{i}); + try f.add("BF16", &.{d}, a_ ++ "post_proj_norm.weight", .{i}); + try f.add("F32", &.{h.heads}, a_ ++ "learnable_sink_param", .{i}); + if (t.layer_types[i] == .deepseek_sparse_attention) { + const x = a_ ++ "compressed_indexer."; + const n: usize = t.compressed_indexer_head_dim; + try f.add("BF16", &.{ @as(usize, t.compressed_indexer_num_attention_heads) * n, t.q_lora_rank }, x ++ "query_projection.weight", .{i}); + try f.add("BF16", &.{ t.compressed_indexer_num_attention_heads, d }, x ++ "head_weight_projection.weight", .{i}); + try f.add("BF16", &.{ n, d }, x ++ "token_key_projection.weight", .{i}); + try f.add("BF16", &.{n}, x ++ "token_key_norm.weight", .{i}); + try f.add("F32", &.{ n, n }, x ++ "key_value_projection.weight", .{i}); + try f.add("F32", &.{ n, n }, x ++ "key_gate_projection.weight", .{i}); + try f.add("F32", &.{n}, x ++ "key_norm.weight", .{i}); + try f.add("F32", &.{ t.compressed_indexer_compress_ratio, n }, x ++ "intra_group_ape", .{i}); + } + const p = "model.layers.{d}.mlp."; + if (t.mlp_layer_types[i] == .dense) { + try f.add("BF16", &.{ t.intermediate_size, d }, p ++ "gate_proj.weight", .{i}); + try f.add("BF16", &.{ t.intermediate_size, d }, p ++ "up_proj.weight", .{i}); + try f.add("BF16", &.{ d, t.intermediate_size }, p ++ "down_proj.weight", .{i}); + try f.add("BF16", &.{d}, p ++ "post_fc2_norm.weight", .{i}); + } else { + const e: usize = t.n_routed_experts; + const w: usize = t.moe_intermediate_size; + const l: usize = t.routed_expert_hidden_size; + try f.add("BF16", &.{ e, d }, p ++ "gate.weight", .{i}); + try f.add("F32", &.{e}, p ++ "gate.e_score_correction_bias", .{i}); + try f.add("BF16", &.{ l, d }, p ++ "routed_expert_down_proj.weight", .{i}); + try f.add("BF16", &.{ d, l }, p ++ "routed_expert_up_proj.weight", .{i}); + try f.add("F8_E4M3", &.{ e, 2 * w, l }, p ++ "experts.gate_up_proj", .{i}); + try f.add("BF16", &.{ e, 2 * w / 128, l / 128 }, p ++ "experts.gate_up_proj_scale_inv", .{i}); + try f.add("F8_E4M3", &.{ e, l, w }, p ++ "experts.down_proj", .{i}); + try f.add("BF16", &.{ e, l / 128, w / 128 }, p ++ "experts.down_proj_scale_inv", .{i}); + try f.add("BF16", &.{ w, d }, p ++ "shared_experts.gate_proj.weight", .{i}); + try f.add("BF16", &.{ w, d }, p ++ "shared_experts.up_proj.weight", .{i}); + try f.add("BF16", &.{ d, w }, p ++ "shared_experts.down_proj.weight", .{i}); + try f.add("BF16", &.{d}, p ++ "combine_output_norm.weight", .{i}); + } + const g = "model.layers.{d}.engram_layer."; + const head_dim: usize = t.engram_n_embed_per_ngram / t.engram_n_head_per_ngram; + const rows = try t.engramRows(@intCast(i + 1)); + const k = engram.columns * head_dim; + try f.add("BF16", &.{ rows, head_dim }, g ++ "multi_head_embedding.embedding.weight", .{i}); + try f.add("I32", &.{t.engram_lookup_table_size}, g ++ "lookup_table", .{i}); + for (0..engram.columns) |head| try f.add("BF16", &.{head_dim}, g ++ "lookup_per_head_norms.{d}.weight", .{ i, head }); + try f.add("BF16", &.{ d, k }, g ++ "value_proj.weight", .{i}); + try f.add("BF16", &.{d}, g ++ "value_proj.bias", .{i}); + for (0..4) |j| { + try f.add("BF16", &.{ d, k }, g ++ "key_projs.{d}.weight", .{ i, j }); + try f.add("BF16", &.{d}, g ++ "key_projs.{d}.bias", .{ i, j }); + try f.add("BF16", &.{d}, g ++ "norm_key.{d}.weight", .{ i, j }); + try f.add("BF16", &.{d}, g ++ "norm_query.{d}.weight", .{ i, j }); + try f.add("BF16", &.{d}, g ++ "unified_per_hc_scales.{d}", .{ i, j }); + } + try f.add("BF16", &.{d}, g ++ "unified_pre_gamma", .{i}); + } + try core.checkpoint_fixture.write(a, io, tmp.dir, "model.safetensors", f.list.items); +} + +fn tmpPath(a: std.mem.Allocator, tmp: testing.TmpDir) ![]u8 { + return tmp.dir.realPathFileAlloc(io, ".", a); +} + +test "W8A16 checkpoint map admits bf16 and e4m3 projections and refuses leftover or invalid tensors" { + const parsed = try release(); + defer parsed.deinit(); + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const t = try tinyText(a, parsed.value.text_config); + + { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeTiny(a, tmp, t, .none); + var ck = try core.checkpoint.Checkpoint.openModel(testing.allocator, io, try tmpPath(a, tmp)); + defer ck.close(); + var why: core.modelopt.Why = .{}; + var m = try fp8_weights.map(testing.allocator, &ck, t, &why); + defer m.deinit(); + try testing.expect(m.layers[0].attn.q_b == .bf16 and m.layers[1].attn.q_b == .fp8 and m.layers[3].attn.o == .fp8); + try testing.expectEqual(core.checkpoint.DType.bf16, m.layers[1].attn.o.fp8.scale_inv.dtype); + try testing.expect(m.layers[0].attn.indexer != null and m.layers[1].attn.indexer == null); + try testing.expect(m.layers[0].mlp == .dense and m.layers[1].mlp == .moe); + try testing.expectEqual(@as(usize, 32), m.layers[2].engram.?.table.dim(0)); + try testing.expectEqual(@as(usize, 2 * 256), m.layers[3].attn.q_b.rows()); + } + for ([_]struct { bad: BadMode, err: anyerror }{ + .{ .bad = .extra_tensor, .err = error.UnusedTensors }, + .{ .bad = .stray_scale, .err = error.UnexpectedTensor }, + .{ .bad = .bad_dtype, .err = error.UnsupportedQuantization }, + }) |case| { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeTiny(a, tmp, t, case.bad); + var ck = try core.checkpoint.Checkpoint.openModel(testing.allocator, io, try tmpPath(a, tmp)); + defer ck.close(); + var why: core.modelopt.Why = .{}; + try testing.expectError(case.err, fp8_weights.map(testing.allocator, &ck, t, &why)); + if (case.bad == .extra_tensor) { + try testing.expect(std.mem.indexOf(u8, why.text(), "model.layers.0.self_attn.q_norm.weight") != null); + } + } +} + +test "W8A16 TP=1/2/4 splits and memory floors match official Hy4-flash-FP8 byte totals" { + const parsed = try release(); + defer parsed.deinit(); + const t = parsed.value.text_config; + const experts_bytes: usize = 3_624_321_024; + const engram_bytes: usize = 47_782_856; + try testing.expectEqual(@as(usize, 402_782_160), try part.layerBytes(t, 0, 0, 1, .stored)); + try testing.expectEqual(@as(usize, 139_598_800 + experts_bytes + engram_bytes), try part.layerBytes(t, 1, 0, 1, .stored)); + try testing.expectEqual(@as(usize, 207_793_488 + experts_bytes), try part.layerBytes(t, 2, 0, 1, .stored)); + try testing.expectEqual(@as(usize, 139_598_800 + experts_bytes), try part.layerBytes(t, 5, 0, 1, .stored)); + try testing.expectEqual(@as(usize, 158_445_453_396), try part.weightBytes(t, 0, 1, .stored)); + try testing.expectEqual(@as(usize, 126_721_231_872), try part.engramTableBytes(t, 0, 1, .stored)); + try testing.expectEqual(@as(usize, 12 * (1_152 + 256)), part.tokenBytes(t)); + try testing.expectEqual(@as(usize, 30 * 512 * 1_152), part.ringBytes(t)); + + var why: core.modelopt.Why = .{}; + for ([_]usize{ 2, 4 }) |world| { + try part.check(t, world, &why); + const w0 = try part.weightBytes(t, 0, world, .packed_); + var row_sum: usize = 0; + for (0..world) |r| { + try testing.expectEqual(w0, try part.weightBytes(t, r, world, .packed_)); + const e = try part.Engram.of(t, r, world); + try testing.expectEqual(r == 0, e.bias); + row_sum += try part.engramTableBytes(t, r, world, .packed_); + } + try testing.expectEqual(@as(usize, 660_006_416 * 100), row_sum); + if (world == 2) try testing.expect(w0 > 74 * GiB and w0 < 76 * GiB); + if (world == 4) try testing.expect(w0 > 38 * GiB and w0 < 39 * GiB); + } + try testing.expectEqual(part.Share{ .lo = 24, .len = 8 }, (try part.Attn.of(t, 0, 3, 4)).heads); + try testing.expectEqual(part.Share{ .lo = 48, .len = 16 }, (try part.Attn.of(t, 2, 3, 4)).heads); + try testing.expectEqual(part.Share{ .lo = 1_152, .len = 384 }, try part.expert(t, 3, 4)); + try testing.expectEqual(part.Share{ .lo = 90_624, .len = 30_208 }, try part.vocab(t, 3, 4)); + + try testing.expectError(error.UnsupportedWorld, part.check(t, 0, &why)); + try testing.expectError(error.UnsupportedWorld, part.check(t, 3, &why)); + try testing.expectError(error.UnsupportedWorld, part.check(t, 5, &why)); + var bad = t; + bad.moe_intermediate_size = 1_408; + try testing.expectError(error.SplitNotOnBlocks, part.check(bad, 2, &why)); + try testing.expect(std.mem.indexOf(u8, why.text(), "routed expert width 1408") != null); +} + +fn refE4m3Rne(x: f32) u8 { + if (std.math.isNan(x)) return if (@as(u32, @bitCast(x)) >> 31 != 0) 0xff else 0x7f; + const sign: u8 = if (@as(u32, @bitCast(x)) >> 31 != 0) 0x80 else 0x00; + const a: f64 = @abs(@as(f64, x)); + if (a > 464.0) return sign | 0x7f; + if (a == 0.0) return sign; + var best_code: u8 = 0; + var best_dist: f64 = a; + for (1..0x7f) |code| { + const c: u8 = @intCast(code); + const d = @abs(a - @abs(core.quant.fp8.e4m3(c))); + if (d < best_dist or (d == best_dist and (c & 1) == 0)) { + best_dist = d; + best_code = c; + } + } + return sign | best_code; +} + +test "Engram 100-byte FP8 rows match exact e4m3fn RNE, fp64 scaling, HY4ENGR1 headers, and layer tiling" { + try testing.expectEqual(@as(u8, 0x00), ep.e4m3Rne(0.0)); + try testing.expectEqual(@as(u8, 0x80), ep.e4m3Rne(-0.0)); + try testing.expectEqual(@as(u8, 0x7e), ep.e4m3Rne(448.0)); + try testing.expectEqual(@as(u8, 0x7f), ep.e4m3Rne(464.0001)); + try testing.expectEqual(@as(u8, 0x38), ep.e4m3Rne(1.0625)); + try testing.expectEqual(@as(u8, 0x3a), ep.e4m3Rne(1.1875)); + for (0..65536) |u| { + const x: f32 = @bitCast(@as(u32, @intCast(u)) << 16); + try testing.expectEqual(refE4m3Rne(x), ep.e4m3Rne(x)); + } + + var raw: [ep.dim * 2]u8 = @splat(0); + var rec: [ep.row_bytes]u8 = undefined; + ep.packRow(&raw, &rec); + for (rec[0..ep.dim]) |b| try testing.expectEqual(@as(u8, 0), b); + var prng = std.Random.DefaultPrng.init(2026); + for (0..128) |_| { + var amax: f64 = 1e-12; + for (0..ep.dim) |j| { + const u: u16 = @intCast(prng.random().uintLessThan(u32, 0x7f00) | (prng.random().uintLessThan(u32, 2) << 15)); + std.mem.writeInt(u16, raw[2 * j ..][0..2], u, .little); + amax = @max(amax, @abs(@as(f64, @as(f32, @bitCast(@as(u32, u) << 16))))); + } + ep.packRow(&raw, &rec); + var vals: [ep.dim]f32 = undefined; + ep.unpackRowF32(&rec, &vals); + const s64 = amax / ep.fp8_max; + for (0..ep.dim) |j| try testing.expect(@abs(@as(f64, vals[j]) - core.quant.fp8.e4m3(rec[j]) * s64) / amax <= 1e-6); + } + + const parsed = try release(); + defer parsed.deinit(); + const t = parsed.value.text_config; + const expected_rows = [_]u64{ 164_994_380, 164_999_008, 165_004_086, 165_008_942 }; + for (t.engram_layer_ids, expected_rows) |layer_id, want_rows| { + _ = try engram.Layer.open(t, layer_id); + const h = try ep.Header.of(t, layer_id); + try testing.expectEqual(want_rows, h.rows); + const enc = h.encode(); + const got = try ep.Header.parse(&enc, ep.header_bytes + want_rows * ep.row_bytes); + try got.checkConfig(t, layer_id); + try testing.expectError(error.BadHy4EngramPack, ep.Header.parse(&enc, ep.header_bytes + want_rows * ep.row_bytes - 1)); + var bad_magic = enc; + bad_magic[0] ^= 1; + try testing.expectError(error.NotHy4EngramPack, ep.Header.parse(&bad_magic, ep.header_bytes + want_rows * ep.row_bytes)); + var tiled: usize = 0; + for (0..4) |r| { + const sh = try (try part.Engram.of(t, r, 4)).rows(t, layer_id); + try testing.expectEqual(tiled, sh.lo); + tiled += sh.len; + } + try testing.expectEqual(@as(usize, @intCast(want_rows)), tiled); + } + var seeded = t; + seeded.engram_seed = 1; + const h2 = try ep.Header.of(t, 2); + try testing.expectError(error.UnsupportedEngram, h2.checkConfig(seeded, 2)); +} diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig index e117a5990a1..de2e65af13a 100644 --- a/zig/src/families/hy4_flash/host_tests.zig +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -15,6 +15,7 @@ test { _ = @import("index_recall.zig"); _ = @import("forward.zig"); _ = @import("exl3_weights.zig"); + _ = @import("fp8_weights_test.zig"); if (@import("builtin").os.tag == .linux) _ = @import("bf16_rows_test.zig"); } From 683c66fe3f9f7ae87847fd80ac72bc9a5ae42755 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:31:14 +0000 Subject: [PATCH 034/361] changelog: #4827 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16c3e3108d5..cf9351d9308 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 +- 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. + - TP: the 4-rank RoCE ring relay forwards each half as soon as it arrives, lowering gather latency with the opt-in relay; bytes are unchanged (#4798). Thanks @GrgaPalcic. From f4cbf92880d4e98afcbc05b766e4113e447b7b72 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:28:57 +0800 Subject: [PATCH 035/361] h3: products walk 64 row tiles under each weight tile (swizzle 6) (cherry picked from commit cf06d04a6ee18c6f302361d8a1a161424d023439) --- zig/src/families/h3/block.zig | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/zig/src/families/h3/block.zig b/zig/src/families/h3/block.zig index 2e7022b5ab0..eddf986bfe9 100644 --- a/zig/src/families/h3/block.zig +++ b/zig/src/families/h3/block.zig @@ -8,19 +8,24 @@ const kernels = @import("h3_kernels"); const Model = h3.Model; const Ref = h3.Ref; +/// Threadgroups walk 2^swizzle row tiles under one weight tile before the next, so 64 row tiles (4,096 rows) read a +/// weight tile while it is still cached; MLX's 2 read every weight 16 times a product at 2048 x 2048. Sums unchanged. +const swizzle = 6; + /// d (rows, n) = x (rows, k) w^T for w (n, k) in bf16. fn gemm(m: *const Model, enc: mtl.ComputeEncoder, x: mtl.Buffer, w: Ref, d: mtl.Buffer, n: usize, k: usize) void { + const band = 1 << swizzle; const tn = n / 128; const tm = (m.rows + 63) / 64; enc.setPipeline(if (m.rows % 64 == 0) m.pipeline(kernels.gemm_whole) else m.pipeline(kernels.gemm_ragged)); enc.setBuffer(x, 0, 0); enc.setBuffer(w.buffer, w.offset, 1); var p: [16]i32 = @splat(0); - const values = [_]usize{ m.rows, n, k, k, k, n, tn, tm, 2, k / 256 }; + const values = [_]usize{ m.rows, n, k, k, k, n, tn, tm, swizzle, k / 256 }; for (values, 0..) |v, i| p[i] = @intCast(v); enc.setBytes(std.mem.asBytes(&p), 2); enc.setBuffer(d, 0, 3); - enc.dispatchThreads(mtl.Size.of(tn * 4 * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); + enc.dispatchGroups(mtl.Size.of(tn * band, (tm + band - 1) / band, 1), mtl.Size.of(32, 4, 2)); } /// The stream's modulated norm to bf16 rows in xn; with `gates` it first adds the branch in `y` gated by that part. From 334ed3978a8285dbad88f0f8a003afdb0c00d51d Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:55:48 +0800 Subject: [PATCH 036/361] h3: test the 64-tile product bands against MLX's band of 4 past a band edge and a ragged tile (cherry picked from commit 0470bc06e6fd1ca403a5b48a825dc766351c3669) --- zig/build/h3_host.zig | 7 +++- zig/src/families/h3/block.zig | 64 ++++++++++++++++++++++++++++++++--- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index c5cd3409142..532f422a9ea 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -18,7 +18,8 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu @import("h3_image_encoder.zig").compileHost(b, target, metal); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); - const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = .Debug }) } } }); + const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = .Debug }) } }; + const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports }); const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) }); const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core } } }) }); const compile = b.step("compile-h3-host", "Compile the actual H3 tools (tf-h3-dit, tf-h3-image) without compiling or executing shaders"); @@ -28,6 +29,10 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const rounding = b.addRunArtifact(b.addTest(.{ .root_module = modulation, .filters = &.{"modulation bf16:"} })); b.step("test-h3-modulation-bf16", "H3's host bf16 rounding against the copy it replaced, no GPU").dependOn(&rounding.step); test_step.dependOn(&rounding.step); + const block = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/block.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports }); + const bands = b.addRunArtifact(b.addTest(.{ .root_module = block, .filters = &.{"h3 gemm:"} })); + b.step("test-h3-gemm", "H3's transformer products in 64-tile bands against MLX's band of 4, on the GPU").dependOn(&bands.step); + test_step.dependOn(&bands.step); const ahead = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/read_ahead.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} }); const read_test = b.addTest(.{ .root_module = ahead }); const read_step = b.step("test-h3-read-ahead", "H3 whole-shard reads, truncated or missing files, and prefetch disabled"); diff --git a/zig/src/families/h3/block.zig b/zig/src/families/h3/block.zig index eddf986bfe9..3359f554cdc 100644 --- a/zig/src/families/h3/block.zig +++ b/zig/src/families/h3/block.zig @@ -14,14 +14,19 @@ const swizzle = 6; /// d (rows, n) = x (rows, k) w^T for w (n, k) in bf16. fn gemm(m: *const Model, enc: mtl.ComputeEncoder, x: mtl.Buffer, w: Ref, d: mtl.Buffer, n: usize, k: usize) void { - const band = 1 << swizzle; + const pipe = if (m.rows % 64 == 0) m.pipeline(kernels.gemm_whole) else m.pipeline(kernels.gemm_ragged); + product(enc, pipe, swizzle, x, w, d, m.rows, n, k); +} + +fn product(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, s: usize, x: mtl.Buffer, w: Ref, d: mtl.Buffer, rows: usize, n: usize, k: usize) void { + const band = @as(usize, 1) << @intCast(s); const tn = n / 128; - const tm = (m.rows + 63) / 64; - enc.setPipeline(if (m.rows % 64 == 0) m.pipeline(kernels.gemm_whole) else m.pipeline(kernels.gemm_ragged)); + const tm = (rows + 63) / 64; + enc.setPipeline(pipe); enc.setBuffer(x, 0, 0); enc.setBuffer(w.buffer, w.offset, 1); var p: [16]i32 = @splat(0); - const values = [_]usize{ m.rows, n, k, k, k, n, tn, tm, swizzle, k / 256 }; + const values = [_]usize{ rows, n, k, k, k, n, tn, tm, s, k / 256 }; for (values, 0..) |v, i| p[i] = @intCast(v); enc.setBytes(std.mem.asBytes(&p), 2); enc.setBuffer(d, 0, 3); @@ -135,3 +140,54 @@ pub fn run(m: *Model, pass: *h3.Pass, index: usize) void { gemm(m, enc.*, m.act, b.fc2, m.y, m.hidden, m.mlp); m.lap(pass, "mlp out"); } + +test "h3 gemm: 64-tile bands write every tile, as MLX's band of 4 does, across a band edge and a ragged tile" { + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + if (!device.tensorUnits()) return error.SkipZigTest; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const queue = try device.queue(); + defer queue.deinit(); + const a = std.testing.allocator; + const text = try @import("source.zig").library(a, 56, 18432, 288, ""); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const n = 256; + const k = 512; + const guard = 64 * n; // one more row tile than the product writes, which must stay untouched + var prng = std.Random.DefaultPrng.init(81); + // 65 whole tiles put one tile past the first band; 65 tiles and 24 rows end the second band ragged + for ([_]usize{ 64 * 65, 64 * 65 + 24 }) |rows| { + const pipe = try mtl.Pipeline.init(device, lib, if (rows % 64 == 0) kernels.gemm_whole else kernels.gemm_ragged, false); + defer pipe.deinit(); + const shared = mtl.ResourceOptions.shared; + const x = try device.buffer(rows * k * 2, shared); + defer x.deinit(); + const w = try device.buffer(n * k * 2, shared); + defer w.deinit(); + // bf16 values of magnitude [1, 2): seven random mantissa bits and a random sign + for ([_][]u16{ x.slice(u16, rows * k), w.slice(u16, n * k) }) |values| { + for (values) |*v| v.* = 0x3f80 | (prng.random().int(u16) & 0x807f); + } + const old = try device.buffer((rows * n + guard) * 2, shared); + defer old.deinit(); + const new = try device.buffer((rows * n + guard) * 2, shared); + defer new.deinit(); + for ([_]mtl.Buffer{ old, new }, [_]usize{ 2, swizzle }) |d, s| { + @memset(d.slice(u16, rows * n + guard), 0xffff); // a NaN no product of these inputs makes + const cb = queue.commandBuffer(); + const enc = cb.compute(.concurrent); + product(enc, pipe, s, x, .{ .buffer = w }, d, rows, n, k); + enc.end(); + cb.commit(); + cb.wait(); + try std.testing.expect(cb.failure() == null); + } + const after = new.slice(u16, rows * n + guard); + try std.testing.expectEqualSlices(u16, old.slice(u16, rows * n + guard), after); + try std.testing.expect(std.mem.indexOfScalar(u16, after[0 .. rows * n], 0xffff) == null); + for (after[rows * n ..]) |v| try std.testing.expectEqual(@as(u16, 0xffff), v); + } +} From 3e2a70033a65a4d97843b69c1f8b6af420ecfee3 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:00:05 +0800 Subject: [PATCH 037/361] h3 image: the products on H3's own 32x64-warp kernel Each threadgroup is 64 x 128 with four warps of 32 x 64, so a loaded fragment feeds two MMAs where MLX's 32 x 32 warp feeds one, and the K chain is MLX's own: 32-deep steps in order. Every output's sums, the latent and the PNG are unchanged; test-h3-gemm holds the new kernel against MLX's bit for bit across a band edge, a whole band and a ragged tail. At 4,120 rows the shapes run at 116, 116, 108 and 103 TFLOP/s against MLX's 118, 118, 113 and 89, so the products sit at the tensor units' rate and only the 14,336-deep fc2 gains (0.3 s of the six steps); warm 2048 pictures took 12.12 and 12.13 s against 12.30 s. (cherry picked from commit 8d6f94ca4f1643434745c418a7dd13aa50c8df3a) --- zig/kernels/metal/h3/h3_gemm.metal | 111 +++++++++++++++++++++++++++++ zig/kernels/metal/h3/kernels.zig | 7 +- zig/src/core/contract/registry.zig | 2 + zig/src/families/h3/block.zig | 47 ++++++++---- 4 files changed, 150 insertions(+), 17 deletions(-) create mode 100644 zig/kernels/metal/h3/h3_gemm.metal diff --git a/zig/kernels/metal/h3/h3_gemm.metal b/zig/kernels/metal/h3/h3_gemm.metal new file mode 100644 index 00000000000..3075bb04d89 --- /dev/null +++ b/zig/kernels/metal/h3/h3_gemm.metal @@ -0,0 +1,111 @@ +// H3's products at 64 rows x 128 columns a threadgroup, each warp 32 x 64: every loaded fragment feeds two MMAs +// instead of one. Each output's K chain is MLX's, 32-deep steps in order. +namespace tfp { + +template +inline void h3_step(thread frag (&acc)[2][4], const device bfloat* A, const device bfloat* B, int lda, int ldb, + int kk, int kn, int rows, int cols, short2 home) { + frag a[2][2], b[2][4]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + if (BOUND) frag_get_in(a[m][k], A, lda, 16 * m, kk + 16 * k, home, rows, kk + kn); + else frag_get(a[m][k], A, lda, 16 * m, kk + 16 * k, home); + } + } + TF_UNROLL + for (short k = 0; k < 2; k++) { + TF_UNROLL + for (short n = 0; n < 4; n++) { + if (BOUND) frag_get_in(b[k][n], B, ldb, 16 * n, kk + 16 * k, home, cols, kk + kn); + else frag_get(b[k][n], B, ldb, 16 * n, kk + 16 * k, home); + } + } + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + mma_16x32(acc[m][0], acc[m][1], a[m][k], b[k][0], b[k][1]); + mma_16x32(acc[m][2], acc[m][3], a[m][k], b[k][2], b[k][3]); + } + } +} + +// D [P[0], P[1]] = A [P[0], P[2]] * B^T [P[1], P[2]], N a multiple of 128; AM false bounds the rows. +template +inline void h3_gemm(const device bfloat* A, const device bfloat* B, device bfloat* D, const device int* P, uint3 tg, + uint sg, uint lane) { + const int swz = P[8]; + const int ty = (int(tg.y) << swz) + (int(tg.x) & ((1 << swz) - 1)), tx = int(tg.x) >> swz; + if (tx >= P[6] || ty >= P[7]) return; + const int lda = P[3], ldb = P[4], ldd = P[5]; + const int row = ty * 64 + 32 * int(sg / 2), col = tx * 128 + 64 * int(sg % 2); + A += long(P[13]) + long(P[10]) * tg.z + long(row) * lda; + B += long(P[14]) + long(P[11]) * tg.z + long(col) * ldb; + D += long(P[12]) * tg.z + long(row) * ldd + col; + const int rows = AM ? 32 : min(32, P[0] - row), cols = 64; + const bool full = AM || rows == 32; + const bool live = rows > 0; + const short2 home = frag_home(ushort(lane)); + frag acc[2][4]; + TF_UNROLL + for (short m = 0; m < 2; m++) TF_UNROLL for (short n = 0; n < 4; n++) acc[m][n] = frag(0); + const int kblocks = P[9]; +#pragma clang loop unroll(disable) + for (int kb = 0; kb < kblocks; kb++) { + threadgroup_barrier(mem_flags::mem_none); + if (full) { +#pragma clang loop unroll(disable) + for (int kk = 0; kk < 256; kk += 32) h3_step(acc, A, B, lda, ldb, kk, 32, rows, cols, home); + } else if (live) { +#pragma clang loop unroll(disable) + for (int kk = 0; kk < 256; kk += 32) h3_step(acc, A, B, lda, ldb, kk, 32, rows, cols, home); + } + A += 256; + B += 256; + } + const int rest = P[2] - kblocks * 256; + if (rest > 0) { + simdgroup_barrier(mem_flags::mem_none); + if (live) { +#pragma clang loop unroll(disable) + for (int kk = 0; kk < rest; kk += 32) h3_step(acc, A, B, lda, ldb, kk, max(0, rest - kk), rows, cols, home); + } + } + if (!live) return; + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short n = 0; n < 4; n++) { + if (full) frag_put(acc[m][n], D, ldd, 16 * m, 16 * n, home); + else frag_put_in(acc[m][n], D, ldd, 16 * m, 16 * n, home, rows, cols); + } + } +} + +} // namespace tfp + +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void h3_gemm_32x64( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::h3_gemm(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); +} + +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void h3_gemm_32x64_ragged( + const device bfloat16_t* A [[buffer(0)]], + const device bfloat16_t* B [[buffer(1)]], + const device int32_t* P [[buffer(2)]], + device bfloat16_t* D [[buffer(3)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { + tfp::h3_gemm(A, B, D, P, threadgroup_position_in_grid, simdgroup_index_in_threadgroup, thread_index_in_simdgroup); +} diff --git a/zig/kernels/metal/h3/kernels.zig b/zig/kernels/metal/h3/kernels.zig index 855e4b13ba3..019cccd13c0 100644 --- a/zig/kernels/metal/h3/kernels.zig +++ b/zig/kernels/metal/h3/kernels.zig @@ -1,6 +1,9 @@ //! MiniMax H3's Metal kernels: three sources joined and compiled at load, after the prefill kernels' gemm_nax. -pub const source = @embedFile("h3_rows.metal") ++ @embedFile("h3_routing.metal") ++ @embedFile("h3_attention.metal"); +pub const source = @embedFile("h3_rows.metal") ++ @embedFile("h3_routing.metal") ++ @embedFile("h3_attention.metal") ++ @embedFile("h3_gemm.metal"); /// MLX's bf16 GEMM, x w^T with N a multiple of 128 and M a multiple of 64 (whole) or not (ragged). pub const gemm_whole = "custom_kernel_tf_gemm_nax_bf16_n_t_t_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"; pub const gemm_ragged = "custom_kernel_tf_gemm_nax_bf16_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"; -pub const names = [_][:0]const u8{ "h3_rows_in", "h3_norm", "h3_gate_add", "h3_gate_mix", "h3_swiglu", "h3_final_norm", "h3_rows_out", "h3_heads", "h3_pool", "h3_tile_scores", "h3_topk", "h3_coarse", "h3_attention", "h3_modulation", gemm_whole, gemm_ragged }; +/// H3's products at 64 x 128 a threadgroup and 32 x 64 a warp. +pub const gemm_32x64 = "h3_gemm_32x64"; +pub const gemm_32x64_ragged = "h3_gemm_32x64_ragged"; +pub const names = [_][:0]const u8{ "h3_rows_in", "h3_norm", "h3_gate_add", "h3_gate_mix", "h3_swiglu", "h3_final_norm", "h3_rows_out", "h3_heads", "h3_pool", "h3_tile_scores", "h3_topk", "h3_coarse", "h3_attention", "h3_modulation", gemm_32x64, gemm_32x64_ragged }; diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 5e6ee728304..c4830015eb4 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -359,6 +359,8 @@ pub const metal = joins.metal_before ++ [_]M{ .{ .name = "h3 routed attention h3_attention", .threads = 256, .tg_memory = 25856, .offline = false }, .{ .name = "h3 gemm whole custom_kernel_tf_gemm_nax_bf16_n_t_t_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "h3 gemm ragged custom_kernel_tf_gemm_nax_bf16_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "h3 product 32x64 h3_gemm_32x64", .threads = 128, .tg_memory = 0, .reserved = 128 }, + .{ .name = "h3 product 32x64 ragged h3_gemm_32x64_ragged", .threads = 128, .tg_memory = 0, .reserved = 128 }, .{ .name = "qwen vision qwv_gemm_bf16_nt_00", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "qwen vision qwv_gemm_bf16_nt_01", .threads = 256, .tg_memory = 0, .reserved = 256 }, .{ .name = "qwen vision qwv_gemm_bf16_nt_10", .threads = 256, .tg_memory = 0, .reserved = 256 }, diff --git a/zig/src/families/h3/block.zig b/zig/src/families/h3/block.zig index 3359f554cdc..90cb21ce190 100644 --- a/zig/src/families/h3/block.zig +++ b/zig/src/families/h3/block.zig @@ -14,11 +14,11 @@ const swizzle = 6; /// d (rows, n) = x (rows, k) w^T for w (n, k) in bf16. fn gemm(m: *const Model, enc: mtl.ComputeEncoder, x: mtl.Buffer, w: Ref, d: mtl.Buffer, n: usize, k: usize) void { - const pipe = if (m.rows % 64 == 0) m.pipeline(kernels.gemm_whole) else m.pipeline(kernels.gemm_ragged); - product(enc, pipe, swizzle, x, w, d, m.rows, n, k); + const pipe = if (m.rows % 64 == 0) m.pipeline(kernels.gemm_32x64) else m.pipeline(kernels.gemm_32x64_ragged); + product(enc, pipe, swizzle, x, w, d, m.rows, n, k, 128); } -fn product(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, s: usize, x: mtl.Buffer, w: Ref, d: mtl.Buffer, rows: usize, n: usize, k: usize) void { +fn product(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, s: usize, x: mtl.Buffer, w: Ref, d: mtl.Buffer, rows: usize, n: usize, k: usize, comptime threads: usize) void { const band = @as(usize, 1) << @intCast(s); const tn = n / 128; const tm = (rows + 63) / 64; @@ -30,7 +30,7 @@ fn product(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, s: usize, x: mtl.Buffer, for (values, 0..) |v, i| p[i] = @intCast(v); enc.setBytes(std.mem.asBytes(&p), 2); enc.setBuffer(d, 0, 3); - enc.dispatchGroups(mtl.Size.of(tn * band, (tm + band - 1) / band, 1), mtl.Size.of(32, 4, 2)); + enc.dispatchGroups(mtl.Size.of(tn * band, (tm + band - 1) / band, 1), mtl.Size.of(32, 4, threads / 128)); } /// The stream's modulated norm to bf16 rows in xn; with `gates` it first adds the branch in `y` gated by that part. @@ -141,7 +141,7 @@ pub fn run(m: *Model, pass: *h3.Pass, index: usize) void { m.lap(pass, "mlp out"); } -test "h3 gemm: 64-tile bands write every tile, as MLX's band of 4 does, across a band edge and a ragged tile" { +test "h3 gemm: 32x64-warp products write every tile as MLX's 32x32 band of 4 does, across a band edge and a ragged tile" { const device = mtl.Device.init() catch return error.SkipZigTest; defer device.deinit(); if (!device.tensorUnits()) return error.SkipZigTest; @@ -154,14 +154,21 @@ test "h3 gemm: 64-tile bands write every tile, as MLX's band of 4 does, across a defer a.free(text); const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); + const whole_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_whole, false); + defer whole_pipe.deinit(); + const ragged_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_ragged, false); + defer ragged_pipe.deinit(); + const wide_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_32x64, false); + defer wide_pipe.deinit(); + const wide_ragged_pipe = try mtl.Pipeline.init(device, lib, kernels.gemm_32x64_ragged, false); + defer wide_ragged_pipe.deinit(); const n = 256; const k = 512; const guard = 64 * n; // one more row tile than the product writes, which must stay untouched var prng = std.Random.DefaultPrng.init(81); - // 65 whole tiles put one tile past the first band; 65 tiles and 24 rows end the second band ragged - for ([_]usize{ 64 * 65, 64 * 65 + 24 }) |rows| { - const pipe = try mtl.Pipeline.init(device, lib, if (rows % 64 == 0) kernels.gemm_whole else kernels.gemm_ragged, false); - defer pipe.deinit(); + // a whole band of 64 tiles, one tile past it, and 65 tiles plus a ragged tail + for ([_]usize{ 64 * 64 + 24, 64 * 65, 64 * 65 + 24 }) |rows| { + const whole = rows % 64 == 0; const shared = mtl.ResourceOptions.shared; const x = try device.buffer(rows * k * 2, shared); defer x.deinit(); @@ -173,19 +180,29 @@ test "h3 gemm: 64-tile bands write every tile, as MLX's band of 4 does, across a } const old = try device.buffer((rows * n + guard) * 2, shared); defer old.deinit(); - const new = try device.buffer((rows * n + guard) * 2, shared); - defer new.deinit(); - for ([_]mtl.Buffer{ old, new }, [_]usize{ 2, swizzle }) |d, s| { - @memset(d.slice(u16, rows * n + guard), 0xffff); // a NaN no product of these inputs makes + const wide = try device.buffer((rows * n + guard) * 2, shared); + defer wide.deinit(); + for ([_]mtl.Buffer{ old, wide }) |d| @memset(d.slice(u16, rows * n + guard), 0xffff); // a NaN no product of these inputs makes + // MLX's geometry: 32 x 32 a warp, 256 threads; ours: 32 x 64, 128 threads + { const cb = queue.commandBuffer(); const enc = cb.compute(.concurrent); - product(enc, pipe, s, x, .{ .buffer = w }, d, rows, n, k); + product(enc, if (whole) whole_pipe else ragged_pipe, 2, x, .{ .buffer = w }, old, rows, n, k, 256); enc.end(); cb.commit(); cb.wait(); try std.testing.expect(cb.failure() == null); } - const after = new.slice(u16, rows * n + guard); + { + const cb = queue.commandBuffer(); + const enc = cb.compute(.concurrent); + product(enc, if (whole) wide_pipe else wide_ragged_pipe, swizzle, x, .{ .buffer = w }, wide, rows, n, k, 128); + enc.end(); + cb.commit(); + cb.wait(); + try std.testing.expect(cb.failure() == null); + } + const after = wide.slice(u16, rows * n + guard); try std.testing.expectEqualSlices(u16, old.slice(u16, rows * n + guard), after); try std.testing.expect(std.mem.indexOfScalar(u16, after[0 .. rows * n], 0xffff) == null); for (after[rows * n ..]) |v| try std.testing.expectEqual(@as(u16, 0xffff), v); From c154f3e7c22d68f7dbca67c4869b9a7f1b38655f Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:49:36 +0800 Subject: [PATCH 038/361] h3 image: decode tiles 64 a pass The image decoder decodes up to its scratch's 64 tiles a pass instead of 16, two passes at 2048x2048 instead of eight; every tile's pixels are independent, so the latent and PNG are byte-identical. (cherry picked from commit b6b209f8f32b3c6d9ed2c20c3cecee3097587068, decoder part only) --- zig/src/families/h3/image.zig | 1 + zig/tests/h3_image_decoder.zig | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/zig/src/families/h3/image.zig b/zig/src/families/h3/image.zig index 30f8f320991..1004c1fb7e5 100644 --- a/zig/src/families/h3/image.zig +++ b/zig/src/families/h3/image.zig @@ -19,5 +19,6 @@ pub const Runner = prompt.Runner; pub const Vision = prompt.Vision; pub const Decoder = decoder.Decoder; +pub const most_batch = decoder.most_batch; pub const host = decoder.host; pub const vae = decoder.vae; diff --git a/zig/tests/h3_image_decoder.zig b/zig/tests/h3_image_decoder.zig index ae761d999cd..9a96bce0112 100644 --- a/zig/tests/h3_image_decoder.zig +++ b/zig/tests/h3_image_decoder.zig @@ -18,8 +18,8 @@ const usage = \\ ; -/// Tiles a pass decodes at most. -const batch = 16; +/// Tiles a pass decodes at most: the decoder's scratch is sized for this many, and every tile's pixels are independent. +const batch = dec.most_batch; fn read(init: std.process.Init, a: std.mem.Allocator, path: []const u8, most: usize) ![]u8 { return std.Io.Dir.cwd().readFileAlloc(init.io, path, a, .limited(most)) catch |err| { From 90162ee2bddb5df24afa38821d31a1738d3fc121 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:06:25 +0800 Subject: [PATCH 039/361] h3: name the block's product kernel, h3_gemm_32x64 --- zig/src/families/h3/block.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/h3/block.zig b/zig/src/families/h3/block.zig index 90cb21ce190..49b0bfea2f3 100644 --- a/zig/src/families/h3/block.zig +++ b/zig/src/families/h3/block.zig @@ -1,4 +1,4 @@ -//! One FastH3 block in bf16: products on tfp::gemm_nax (MLX's GEMM, fp32 sums), FastH3's routed attention in bf16. +//! One FastH3 block in bf16: products on h3_gemm_32x64 (fp32 sums, tested against MLX's gemm_nax), FastH3's routed attention in bf16. const std = @import("std"); const mtl = @import("metal"); const h3 = @import("h3.zig"); From 91cb764d499023472e98c1964c8f7317060f5abc Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:45:58 +0800 Subject: [PATCH 040/361] h3: keep h3_gemm out of the shared kernel source; the contract compiles it after gemm_nax's fragments --- zig/kernels/metal/h3/kernels.zig | 4 +++- zig/runtime_sources/modes_test.zig | 2 +- zig/src/families/h3/source.zig | 2 +- zig/tests/contract/metal_limits.zig | 5 +++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/zig/kernels/metal/h3/kernels.zig b/zig/kernels/metal/h3/kernels.zig index 019cccd13c0..6c564556add 100644 --- a/zig/kernels/metal/h3/kernels.zig +++ b/zig/kernels/metal/h3/kernels.zig @@ -1,5 +1,7 @@ //! MiniMax H3's Metal kernels: three sources joined and compiled at load, after the prefill kernels' gemm_nax. -pub const source = @embedFile("h3_rows.metal") ++ @embedFile("h3_routing.metal") ++ @embedFile("h3_attention.metal") ++ @embedFile("h3_gemm.metal"); +pub const source = @embedFile("h3_rows.metal") ++ @embedFile("h3_routing.metal") ++ @embedFile("h3_attention.metal"); +/// H3's own products, after `source`: they need gemm_nax's fragments ahead of them. +pub const gemm_source = @embedFile("h3_gemm.metal"); /// MLX's bf16 GEMM, x w^T with N a multiple of 128 and M a multiple of 64 (whole) or not (ragged). pub const gemm_whole = "custom_kernel_tf_gemm_nax_bf16_n_t_t_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"; pub const gemm_ragged = "custom_kernel_tf_gemm_nax_bf16_n_t_n_t_n_64_128_256_2_4_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"; diff --git a/zig/runtime_sources/modes_test.zig b/zig/runtime_sources/modes_test.zig index 2eea128df64..e258527a620 100644 --- a/zig/runtime_sources/modes_test.zig +++ b/zig/runtime_sources/modes_test.zig @@ -65,7 +65,7 @@ test "Metal runtime source modes: H3 preserves the loader's complete prefix and const gemm = try std.mem.replaceOwned(u8, a, gemm_text, "#include \"../nax.h\"", sources.nax); for ([_]usize{ 56, 16 }, [_]usize{ 288, 4 }, [_][]const u8{ "", "#define H3_TEST 1\n" }) |heads, tiles, defines| { const sizes = try std.fmt.allocPrint(a, "#define H3_HEADS {d}\n#define H3_SLOTS {d}\n#define H3_TILES {d}\n{s}\n{s}", .{ heads, tiles * 64, tiles, defines, kernels.source }); - const before = try std.mem.concat(a, u8, &.{ gemm, sizes }); + const before = try std.mem.concat(a, u8, &.{ gemm, sizes, kernels.gemm_source }); const after = try h3.library(a, heads, tiles * 64, tiles, defines); try t.expect(std.mem.eql(u8, before, after)); } diff --git a/zig/src/families/h3/source.zig b/zig/src/families/h3/source.zig index 59f2f03b8d5..407ab3d21d6 100644 --- a/zig/src/families/h3/source.zig +++ b/zig/src/families/h3/source.zig @@ -13,7 +13,7 @@ pub fn library(a: std.mem.Allocator, heads: usize, slots: usize, tiles: usize, d defer a.free(source); const gemm = try std.mem.replaceOwned(u8, a, gemmSource(), "#include \"../nax.h\"", sources.nax); defer a.free(gemm); - return std.mem.concat(a, u8, &.{ gemm, source }); + return std.mem.concat(a, u8, &.{ gemm, source, kernels.gemm_source }); } fn gemmSource() []const u8 { diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index c1c9451b274..80256bff275 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -294,11 +294,12 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp if (!assemble) return undefined; text = sources.core_contract_controls; if (has(fun, "big_tg")) head = "#define TF_CTL_BIG_TG 1\n"; - } else if (std.mem.startsWith(u8, d.name, "h3 gemm ") or std.mem.startsWith(u8, d.name, "nemotron ssd gemm ")) { + } else if (std.mem.startsWith(u8, d.name, "h3 gemm ") or std.mem.startsWith(u8, d.name, "h3 product ") or std.mem.startsWith(u8, d.name, "nemotron ssd gemm ")) { if (!assemble) return undefined; - text = for (sources.prefill) |f| { + const gemm = for (sources.prefill) |f| { if (std.mem.eql(u8, f.name, "gemm_nax")) break f.text; } else return error.UnknownLaunch; + text = if (std.mem.startsWith(u8, d.name, "h3 product ")) try std.mem.concat(a, u8, &.{ gemm, @import("h3_kernels").gemm_source }) else gemm; frags = true; } else if (std.mem.startsWith(u8, d.name, "flashnext prompt attention ")) { if (!assemble) return undefined; From 664a46a5d655f7ee96d9e3db6099406d86d8fbc8 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:40:05 +0800 Subject: [PATCH 041/361] h3: the contract gates both products, bit-equal to MLX's gemm_nax at FastH3's and the picture model's shapes --- docs/recipes/minimax-h3-metal.md | 9 ++--- zig/tests/contract/metal_h3.zig | 53 +++++++++++++++++++++++++--- zig/tests/contract/metal_h3_prep.zig | 52 ++++++++++++++++++++++++++- 3 files changed, 105 insertions(+), 9 deletions(-) diff --git a/docs/recipes/minimax-h3-metal.md b/docs/recipes/minimax-h3-metal.md index 2da4ef6e197..a8ecd9ee6ae 100644 --- a/docs/recipes/minimax-h3-metal.md +++ b/docs/recipes/minimax-h3-metal.md @@ -26,8 +26,9 @@ request can finish between polls. The generation checks bracket the entire wall ## Arithmetic -- Block projections: the prefill kernels' `tfp::gemm_nax` (MLX 0.32.3's NAX GEMM), bf16 x w^T as the checkpoint - stores w, fp32 sums, bf16 out. The SwiGLU's first projection is one product over its stored [value; gate] rows. +- Block projections: H3's own `h3_gemm_32x64` (64 x 128 a threadgroup, 32 x 64 a warp), bf16 x w^T as the checkpoint + stores w, fp32 sums in MLX 0.32.3's NAX GEMM order, bf16 out: bit-equal to `tfp::gemm_nax`. Threadgroups walk 64 + row tiles under each weight tile. The SwiGLU's first projection is one product over its stored [value; gate] rows. - Norms, rotary, the gated adds and the SwiGLU round to bf16 where the reference's bf16 MLX arithmetic rounds. - Attention is FastH3's video sparse attention over 64-row tiles: a text, keyframe or audio tile attends every tile; a video tile attends the prefix tiles and its top 20% of video tiles by pooled score; the pooled branch is @@ -37,8 +38,8 @@ request can finish between polls. The generation checks bracket the entire wall ## Kernel contract -Thirteen kernels are registered (`zig/tests/contract/metal_h3*.zig`), each against its formula in float64, and their -launches in `registry.zig`. The two GEMM entry points are the prefill source's own and are registered as launches. +The kernels are registered (`zig/tests/contract/metal_h3*.zig`), each against its formula in float64, and their +launches in `registry.zig`. The two products also match MLX's gemm_nax byte for byte at the served shapes. Kernels whose outputs pass through intermediate bf16 roundings declare them as `mids`; their test inputs are of one sign where a sum could cancel, so no rounding hides behind a small result. diff --git a/zig/tests/contract/metal_h3.zig b/zig/tests/contract/metal_h3.zig index 76f28aa2984..e54fad945e7 100644 --- a/zig/tests/contract/metal_h3.zig +++ b/zig/tests/contract/metal_h3.zig @@ -2,6 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); +const sources = @import("kernel_sources"); const h3k = @import("h3_kernels"); const rig_ = @import("rig.zig"); const ref = @import("metal_h3_ref.zig"); @@ -9,7 +10,7 @@ const ref = @import("metal_h3_ref.zig"); const c = contract.spec; const g = contract.gates; -pub const Which = enum { rows_in, rows_out, norm, final_norm, gate_add, gate_mix, swiglu, swiglu_gate_first, heads, pool, tile_scores, coarse, attention, modulation }; +pub const Which = enum { rows_in, rows_out, norm, final_norm, gate_add, gate_mix, swiglu, swiglu_gate_first, heads, pool, tile_scores, coarse, attention, modulation, product, product_ragged }; /// The geometry the test kernels are compiled for: two heads, up to 16 tiles of 64 slots. const heads = 2; @@ -42,6 +43,7 @@ fn none(_: c.Shape) usize { } const soft_why = "softmax weights in [0, 1], rounded to bf16 before the value product: the bf16 output hides the sums' error"; +const mlx_gemm = "MLX's gemm_nax (32 x 32 a warp, swizzle 2)"; const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; pub fn spec(w: Which) c.Spec { @@ -61,6 +63,9 @@ pub fn spec(w: Which) c.Spec { .coarse => .{ .name = "metal h3 pooled branch h3_coarse", .accum = .f32, .depth = tileChain, .ops = 6, .out = .f32, .tiles = .{ .{ .size = 4 }, .{}, .{} }, .served = &.{.{ .rows = tiles, .n = 128, .k = tiles }}, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = soft_why } }, .modulation => .{ .name = "metal h3 AdaLN tables h3_modulation", .accum = .f32, .depth = laneChain, .ops = 1, .out = .bf16, .tiles = .{ .{}, .{ .size = 18 * 32, .step = 18, .min = 18 }, .{ .size = 32 } }, .served = &.{ .{ .rows = 16, .n = 18 * 64, .k = 2688 }, .{ .rows = 3, .n = 18 * 16, .k = 2688 } } }, .attention => .{ .name = "metal h3 routed attention h3_attention", .accum = .f32, .depth = attnChain, .ops = 8, .mids = 1, .out = .bf16, .tiles = .{ .{}, .{}, .{ .size = 256, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = tiles, .n = 128, .k = tiles * 64 }, .{ .rows = tiles, .n = 128, .k = 6 * 64 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = soft_why } }, + // q at 65 row tiles, one past a band of 64; attention out at one tile (FastH3 and MiniMax-H3-Image alike) + .product => .{ .name = "metal h3 product h3_gemm_32x64", .accum = .f32, .depth = kChain, .out = .bf16, .replaces = mlx_gemm, .served = &.{ .{ .rows = 4160, .n = 7168, .k = 5376 }, .{ .rows = 64, .n = 5376, .k = 7168 } } }, + .product_ragged => .{ .name = "metal h3 product ragged h3_gemm_32x64_ragged", .accum = .f32, .depth = kChain, .out = .bf16, .replaces = mlx_gemm, .tiles = .{ .{ .size = 64 }, .{}, .{} }, .served = &.{ .{ .rows = 4184, .n = 7168, .k = 5376 }, .{ .rows = 24, .n = 5376, .k = 7168 } } }, }; } @@ -80,6 +85,17 @@ fn function(w: Which) []const u8 { .coarse => "h3_coarse", .attention => "h3_attention", .modulation => "h3_modulation", + .product => h3k.gemm_32x64, + .product_ragged => h3k.gemm_32x64_ragged, + }; +} + +/// The MLX entry point a product replaced, launched beside it on the same inputs. +fn baseline(w: Which) ?[]const u8 { + return switch (w) { + .product => h3k.gemm_whole, + .product_ragged => h3k.gemm_ragged, + else => null, }; } @@ -90,6 +106,8 @@ pub const H3 = struct { rig: rig_.Rig, which: Which, pipe: mtl.Pipeline, + /// A product's replaced MLX kernel. + base: ?mtl.Pipeline = null, shape: c.Shape = undefined, arena: std.heap.ArenaAllocator, in: ref.In = .{ .rows = 0, .n = 0, .k = 0 }, @@ -100,14 +118,31 @@ pub const H3 = struct { outs: usize = 0, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which) !H3 { - const src = try std.mem.concat(a, u8, &.{ defines, h3k.source }); + const rig: rig_.Rig = .{ .a = a, .device = device, .queue = queue }; + const mlx = baseline(which) orelse { + const src = try std.mem.concat(a, u8, &.{ defines, h3k.source }); + defer a.free(src); + return .{ .a = a, .rig = rig, .which = which, .pipe = try rig_.pipeline(device, src, function(which)), .arena = std.heap.ArenaAllocator.init(a) }; + }; + // the products' library as source.zig builds it: gemm_nax with nax.h inlined, then h3_gemm + const gemm = for (sources.prefill) |f| { + if (std.mem.eql(u8, f.name, "gemm_nax")) break f.text; + } else return error.UnknownSource; + const nax = try std.mem.replaceOwned(u8, a, gemm, "#include \"../nax.h\"", sources.nax); + defer a.free(nax); + const src = try std.mem.concat(a, u8, &.{ nax, h3k.gemm_source }); defer a.free(src); - return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .which = which, .pipe = try rig_.pipeline(device, src, function(which)), .arena = std.heap.ArenaAllocator.init(a) }; + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const pipe = try mtl.Pipeline.init(device, lib, function(which), false); + errdefer pipe.deinit(); + return .{ .a = a, .rig = rig, .which = which, .pipe = pipe, .base = try mtl.Pipeline.init(device, lib, mlx, false), .arena = std.heap.ArenaAllocator.init(a) }; } pub fn deinit(self: *H3) void { self.rig.deinit(); self.pipe.deinit(); + if (self.base) |b| b.deinit(); self.arena.deinit(); } @@ -163,6 +198,12 @@ pub const H3 = struct { self.nbufs += 1; } + /// The replaced kernel's output: device memory the gates neither feed nor read. + pub fn baseOutput(self: *H3, bytes: usize) !void { + self.bufs[self.nbufs] = try self.rig.scratch(bytes); + self.nbufs += 1; + } + pub fn prepare(self: *H3, shape: c.Shape, fill: g.Fill, seed: u64) !bool { self.rig.reset(); _ = self.arena.reset(.retain_capacity); @@ -188,7 +229,7 @@ pub const H3 = struct { const scratch = try self.a.alloc(f64, @max(2 * self.in.n, 1024) + self.in.k); defer self.a.free(scratch); switch (self.which) { - .rows_in, .rows_out => ref.dot(self.in, s, scratch, want, mag), + .rows_in, .rows_out, .product, .product_ragged => ref.dot(self.in, s, scratch, want, mag), .norm => ref.norm(self.in, s, scratch, want, mag), .final_norm => ref.finalNorm(self.in, s, scratch, want, mag), .gate_add => ref.gated(self.in, false, want, mag), @@ -213,6 +254,10 @@ pub const H3 = struct { defer self.a.free(mag); return self.compute(.{ .acc = acc, .order = order }, out, mag); } + + pub fn replaced(self: *H3) ![]const u8 { + return @import("metal_h3_prep.zig").replaced(self); + } }; /// Every H3 kernel, on a device with tensor units: metal_main.zig's registration. diff --git a/zig/tests/contract/metal_h3_prep.zig b/zig/tests/contract/metal_h3_prep.zig index 30ab6fabcbb..d295cb6bfed 100644 --- a/zig/tests/contract/metal_h3_prep.zig +++ b/zig/tests/contract/metal_h3_prep.zig @@ -25,6 +25,11 @@ fn mirror(x: []f64, w: []f64, k: usize, rows: usize, n: usize) void { }; } +/// A product's launched rows: the whole kernel runs whole 64-row tiles, past the rows a gate checks. +fn launched(self: *const H3) usize { + return if (self.which == .product) (self.shape.rows + 63) / 64 * 64 else self.shape.rows; +} + /// Tile sizes: most whole, some short (the last rows of a segment), never empty. fn sizes(self: *H3, n: usize, rng: std.Random) ![]i32 { const v = try self.arena.allocator().alloc(i32, n); @@ -211,9 +216,26 @@ pub fn prepare(self: *H3, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { self.outs = rows * heads * 128; return true; }, + .product, .product_ragged => { + // gate 4's mirror stays exact in fp32 (|terms| <= 32^2, k / 2 of one sign) and passes fp16's range + const lo: f64 = if (stress) -4 else -1; + const x = try self.values(s.rows * s.k, lo, -lo, fill, rng, true, true); + const w = try self.values(s.n * s.k, lo, -lo, fill, rng, true, false); + if (stress) mirror(x, w, s.k, s.rows, s.n); + const pad = try self.values((launched(self) - s.rows) * s.k, lo, -lo, .random, rng, true, false); + const bias = try al.alloc(f64, s.n); + @memset(bias, 0); + self.in.a = x; + self.in.b = w; + self.in.d = bias; + try self.upload(try std.mem.concat(al, f64, &.{ x, pad }), true); + try self.upload(w, true); + try self.output(launched(self) * s.n * 2); + try self.baseOutput(launched(self) * s.n * 2); + }, } self.outs = switch (self.which) { - .rows_in, .rows_out, .swiglu, .swiglu_gate_first, .modulation => s.rows * s.n, + .rows_in, .rows_out, .swiglu, .swiglu_gate_first, .modulation, .product, .product_ragged => s.rows * s.n, .norm => 2 * s.rows * s.n, .final_norm, .gate_add, .gate_mix => s.rows * s.n, .heads => 3 * heads * slots * 128, @@ -314,5 +336,33 @@ pub fn launch(self: *H3, e: mtl.ComputeEncoder) !void { bind(self, e, 6, 8); e.dispatchGroups(mtl.Size.of(s.rows, heads, 1), mtl.Size.of(256, 1, 1)); }, + .product, .product_ragged => product(self, e, self.pipe, 2, 6, 128), } } + +/// block.zig's product launch: x, w, the sizes, d into buffer `out`; `swizzle` and `threads` as the kernel runs them. +fn product(self: *H3, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, out: usize, swizzle: u5, threads: usize) void { + const s = self.shape; + const band = @as(usize, 1) << swizzle; + const tn = s.n / 128; + const tm = (launched(self) + 63) / 64; + var p: [16]i32 = @splat(0); + for ([_]usize{ launched(self), s.n, s.k, s.k, s.k, s.n, tn, tm, swizzle, s.k / 256 }, 0..) |v, i| p[i] = @intCast(v); + e.setPipeline(pipe); + bind(self, e, 0, 0); + bind(self, e, 1, 1); + e.setBytes(std.mem.asBytes(&p), 2); + bind(self, e, out, 3); + e.dispatchGroups(mtl.Size.of(tn * band, (tm + band - 1) / band, 1), mtl.Size.of(32, 4, threads / 128)); +} + +/// The replaced MLX kernel's bytes on the prepared inputs, written to the scratch buffer. +pub fn replaced(self: *H3) ![]const u8 { + const len = launched(self) * self.shape.n * 2; + const out = self.rig.bytes(self.bufs[3], len); + @memset(out, 0xff); + const p = self.rig.begin(); + product(self, p.e, self.base.?, 3, 2, 256); + try self.rig.finish(p); + return out; +} From 9b3b8f755f5a5f0ff68ca516c7feab0cdf97d257 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:20:00 +0800 Subject: [PATCH 042/361] h3 contract: upload the product input as is when the launch needs no padding rows --- zig/tests/contract/metal_h3_prep.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/contract/metal_h3_prep.zig b/zig/tests/contract/metal_h3_prep.zig index d295cb6bfed..74907c714ad 100644 --- a/zig/tests/contract/metal_h3_prep.zig +++ b/zig/tests/contract/metal_h3_prep.zig @@ -228,7 +228,7 @@ pub fn prepare(self: *H3, s: c.Shape, fill: g.Fill, rng: std.Random) !bool { self.in.a = x; self.in.b = w; self.in.d = bias; - try self.upload(try std.mem.concat(al, f64, &.{ x, pad }), true); + try self.upload(if (pad.len == 0) x else try std.mem.concat(al, f64, &.{ x, pad }), true); try self.upload(w, true); try self.output(launched(self) * s.n * 2); try self.baseOutput(launched(self) * s.n * 2); From fdb52d4f5462c28c4efcfab46b74ab405f4a2257 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:24:28 +0800 Subject: [PATCH 043/361] h3: one-line comments on the products, and no unused most_batch re-export --- zig/kernels/metal/h3/h3_gemm.metal | 3 +-- zig/src/families/h3/block.zig | 5 ++--- zig/src/families/h3/image.zig | 1 - 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/zig/kernels/metal/h3/h3_gemm.metal b/zig/kernels/metal/h3/h3_gemm.metal index 3075bb04d89..972956c9764 100644 --- a/zig/kernels/metal/h3/h3_gemm.metal +++ b/zig/kernels/metal/h3/h3_gemm.metal @@ -1,5 +1,4 @@ -// H3's products at 64 rows x 128 columns a threadgroup, each warp 32 x 64: every loaded fragment feeds two MMAs -// instead of one. Each output's K chain is MLX's, 32-deep steps in order. +// H3's products, 64 x 128 a threadgroup and 32 x 64 a warp; each output's K chain is MLX's, 32-deep steps in order. namespace tfp { template diff --git a/zig/src/families/h3/block.zig b/zig/src/families/h3/block.zig index 49b0bfea2f3..4f33f6f2fcb 100644 --- a/zig/src/families/h3/block.zig +++ b/zig/src/families/h3/block.zig @@ -1,4 +1,4 @@ -//! One FastH3 block in bf16: products on h3_gemm_32x64 (fp32 sums, tested against MLX's gemm_nax), FastH3's routed attention in bf16. +//! One FastH3 block in bf16: products on h3_gemm_32x64 (fp32 sums, MLX's K order), routed attention in bf16. const std = @import("std"); const mtl = @import("metal"); const h3 = @import("h3.zig"); @@ -8,8 +8,7 @@ const kernels = @import("h3_kernels"); const Model = h3.Model; const Ref = h3.Ref; -/// Threadgroups walk 2^swizzle row tiles under one weight tile before the next, so 64 row tiles (4,096 rows) read a -/// weight tile while it is still cached; MLX's 2 read every weight 16 times a product at 2048 x 2048. Sums unchanged. +/// Threadgroups walk 2^swizzle row tiles under each weight tile: 64 keep it cached, where MLX's swizzle 2 walks 4. const swizzle = 6; /// d (rows, n) = x (rows, k) w^T for w (n, k) in bf16. diff --git a/zig/src/families/h3/image.zig b/zig/src/families/h3/image.zig index 1004c1fb7e5..30f8f320991 100644 --- a/zig/src/families/h3/image.zig +++ b/zig/src/families/h3/image.zig @@ -19,6 +19,5 @@ pub const Runner = prompt.Runner; pub const Vision = prompt.Vision; pub const Decoder = decoder.Decoder; -pub const most_batch = decoder.most_batch; pub const host = decoder.host; pub const vae = decoder.vae; From ce16cc7c691cdafeec9bcdf386b2d91e76a4a70f Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:24:29 +0800 Subject: [PATCH 044/361] h3 contract: a planted control for each product, its K steps reversed, red at shapes --- zig/tests/contract/metal_bolt.zig | 2 +- zig/tests/contract/metal_h3.zig | 40 +++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/zig/tests/contract/metal_bolt.zig b/zig/tests/contract/metal_bolt.zig index 16bbefd8946..f0d96be4beb 100644 --- a/zig/tests/contract/metal_bolt.zig +++ b/zig/tests/contract/metal_bolt.zig @@ -24,7 +24,7 @@ fn gemvDepth(s: c.Shape) usize { pub const Mut = struct { name: []const u8, find: []const u8, with: []const u8, gate: g.Gate }; /// `text` with every `m.find` replaced (the substitution must land, or the control proves nothing). -fn mutated(a: std.mem.Allocator, text: []const u8, m: Mut) ![]u8 { +pub fn mutated(a: std.mem.Allocator, text: []const u8, m: Mut) ![]u8 { if (std.mem.indexOf(u8, text, m.find) == null) return error.ControlDidNotApply; return std.mem.replaceOwned(u8, a, text, m.find, m.with); } diff --git a/zig/tests/contract/metal_h3.zig b/zig/tests/contract/metal_h3.zig index e54fad945e7..cc26857f5f4 100644 --- a/zig/tests/contract/metal_h3.zig +++ b/zig/tests/contract/metal_h3.zig @@ -6,6 +6,7 @@ const sources = @import("kernel_sources"); const h3k = @import("h3_kernels"); const rig_ = @import("rig.zig"); const ref = @import("metal_h3_ref.zig"); +const bolt = @import("metal_bolt.zig"); const c = contract.spec; const g = contract.gates; @@ -99,6 +100,17 @@ fn baseline(w: Which) ?[]const u8 { }; } +/// A product's planted control: its 32-deep K steps reversed, so its bytes must leave MLX's at the shapes gate. +fn control(w: Which) ?bolt.Mut { + const ks = "for (int kk = 0; kk < 256; kk += 32) h3_step<"; + const back = "for (int kk = 224; kk >= 0; kk -= 32) h3_step<"; + return switch (w) { + .product => .{ .name = "control: metal h3 product h3_gemm_32x64, whole tiles' K steps reversed", .find = ks ++ "false>", .with = back ++ "false>", .gate = .shapes }, + .product_ragged => .{ .name = "control: metal h3 product ragged h3_gemm_32x64_ragged, edge tile's K steps reversed", .find = ks ++ "true>", .with = back ++ "true>", .gate = .shapes }, + else => null, + }; +} + const Slot = struct { ref: rig_.Ref, len: usize }; pub const H3 = struct { @@ -106,6 +118,7 @@ pub const H3 = struct { rig: rig_.Rig, which: Which, pipe: mtl.Pipeline, + mut: ?bolt.Mut = null, /// A product's replaced MLX kernel. base: ?mtl.Pipeline = null, shape: c.Shape = undefined, @@ -117,7 +130,7 @@ pub const H3 = struct { fresh: []const u8 = &.{}, outs: usize = 0, - pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which) !H3 { + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: Which, mut: ?bolt.Mut) !H3 { const rig: rig_.Rig = .{ .a = a, .device = device, .queue = queue }; const mlx = baseline(which) orelse { const src = try std.mem.concat(a, u8, &.{ defines, h3k.source }); @@ -130,13 +143,15 @@ pub const H3 = struct { } else return error.UnknownSource; const nax = try std.mem.replaceOwned(u8, a, gemm, "#include \"../nax.h\"", sources.nax); defer a.free(nax); - const src = try std.mem.concat(a, u8, &.{ nax, h3k.gemm_source }); - defer a.free(src); + const both = try std.mem.concat(a, u8, &.{ nax, h3k.gemm_source }); + defer a.free(both); + const src = if (mut) |m| try bolt.mutated(a, both, m) else both; + defer if (mut != null) a.free(src); const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); defer lib.deinit(); const pipe = try mtl.Pipeline.init(device, lib, function(which), false); errdefer pipe.deinit(); - return .{ .a = a, .rig = rig, .which = which, .pipe = pipe, .base = try mtl.Pipeline.init(device, lib, mlx, false), .arena = std.heap.ArenaAllocator.init(a) }; + return .{ .a = a, .rig = rig, .which = which, .pipe = pipe, .mut = mut, .base = try mtl.Pipeline.init(device, lib, mlx, false), .arena = std.heap.ArenaAllocator.init(a) }; } pub fn deinit(self: *H3) void { @@ -147,7 +162,7 @@ pub const H3 = struct { } pub fn kernel(self: *H3) g.Kernel { - return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + return .{ .spec = bolt.under(spec(self.which), self.mut), .ctx = self, .vt = &vt, .control = if (self.mut) |m| m.gate else null }; } const vt = g.hooks(H3); @@ -272,14 +287,19 @@ pub const Suite = struct { if (!s.device.tensorUnits()) return; for (std.enums.values(Which)) |w| { if (only) |o| if (std.mem.indexOf(u8, spec(w).name, o) == null) continue; - const x = try s.a.create(H3); - errdefer s.a.destroy(x); - x.* = try H3.init(s.a, s.device, s.queue, w); - try s.list.append(s.a, x); - try s.kernels.append(s.a, x.kernel()); + try s.add(w, null); + if (control(w)) |m| try s.add(w, m); } } + fn add(s: *Suite, w: Which, mut: ?bolt.Mut) !void { + const x = try s.a.create(H3); + errdefer s.a.destroy(x); + x.* = try H3.init(s.a, s.device, s.queue, w, mut); + try s.list.append(s.a, x); + try s.kernels.append(s.a, x.kernel()); + } + pub fn deinit(s: *Suite) void { for (s.list.items) |x| { x.deinit(); From 8393f937cf2e2ff3b14561dcbd667b35ff477423 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:11:28 +0800 Subject: [PATCH 045/361] h3 image: export the decoder's most_batch, which the image server's decoder tool reads --- zig/src/families/h3/image.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/families/h3/image.zig b/zig/src/families/h3/image.zig index 30f8f320991..1004c1fb7e5 100644 --- a/zig/src/families/h3/image.zig +++ b/zig/src/families/h3/image.zig @@ -19,5 +19,6 @@ pub const Runner = prompt.Runner; pub const Vision = prompt.Vision; pub const Decoder = decoder.Decoder; +pub const most_batch = decoder.most_batch; pub const host = decoder.host; pub const vae = decoder.vae; From d1a734784af046e21feba6c6658a5dde5d9fbb79 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:11:28 +0800 Subject: [PATCH 046/361] h3 recipe: the decoder runs up to 64 tiles a command buffer --- docs/recipes/minimax-h3-image-metal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/recipes/minimax-h3-image-metal.md b/docs/recipes/minimax-h3-image-metal.md index 6369891060f..2504dbc78e3 100644 --- a/docs/recipes/minimax-h3-image-metal.md +++ b/docs/recipes/minimax-h3-image-metal.md @@ -310,7 +310,7 @@ tensor units. 3. Each tile runs `post_quant_conv`, then its cells become tokens through `x_embedder`, with the 4 registers and one zero token appended. 4. The 2D rotary table is built, and the 24 blocks run, then `norm_out` and `proj_out`. -5. Each token's 768 values are unpatchified to its 16 x 16 pixels. Up to 16 tiles run in one command buffer. +5. Each token's 768 values are unpatchified to its 16 x 16 pixels. Up to 64 tiles run in one command buffer. 6. Tiles are blended in float32: the top band against the tile above, then the left band against the tile to the left, both as decoded. 7. The result is mapped to [0, 1] with ImageNet's statistics, clamped and truncated to bytes. From 3890372a667c12c930d233314395f1d7167c33d2 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:13:10 +0000 Subject: [PATCH 047/361] changelog: #4641 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf9351d9308..6ba6b06e142 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 +- 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. - TP: the 4-rank RoCE ring relay forwards each half as soon as it arrives, lowering gather latency with the opt-in relay; bytes are unchanged (#4798). Thanks @GrgaPalcic. From ec97d0e4fdb784389b1c80478325e78d0807b963 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:44:59 +0000 Subject: [PATCH 048/361] feat(server): add multipart and query readers for POST /ocr The /ocr clients post multipart/form-data and pass options as query parameters, which the server never read before. multipart.zig parses a body already read into parts that are slices of it, keeping the raw Content-Type and a normalized media type, with bounded headers and part counts; query.zig decodes one parameter, refuses a name sent twice so a repeated option cannot mean two things, and reads pydantic's boolean words. --- zig/src/server/multipart.zig | 207 ++++++++++++++++++++++++++++++ zig/src/server/multipart_test.zig | 191 +++++++++++++++++++++++++++ zig/src/server/query.zig | 66 ++++++++++ zig/src/server/query_test.zig | 67 ++++++++++ zig/src/server/root.zig | 2 + 5 files changed, 533 insertions(+) create mode 100644 zig/src/server/multipart.zig create mode 100644 zig/src/server/multipart_test.zig create mode 100644 zig/src/server/query.zig create mode 100644 zig/src/server/query_test.zig diff --git a/zig/src/server/multipart.zig b/zig/src/server/multipart.zig new file mode 100644 index 00000000000..b3eedd8092a --- /dev/null +++ b/zig/src/server/multipart.zig @@ -0,0 +1,207 @@ +//! RFC 7578 multipart/form-data over a body already read: parts as slices of the body, no copies of part bodies. +const std = @import("std"); +const Allocator = std.mem.Allocator; + +/// The most parts one body may hold; one more is malformed. +pub const max_parts = 256; +/// The most header bytes one part may carry, its blank line included. +pub const max_header_bytes = 8 * 1024; + +pub const Part = struct { + /// The `name` parameter of `Content-Disposition: form-data`. + name: []const u8, + /// The `filename` parameter, or null when the part sends none (`filename*=` is ignored). + filename: ?[]const u8, + /// The `Content-Type` header value exactly as sent, trimmed; docTR checks and quotes it. + content_type: ?[]const u8, + /// The lower-cased type/subtype without parameters; null when the header is absent or empty. + media: ?[]const u8, + body: []const u8, +}; + +/// The `boundary` parameter of a Content-Type header (quoted or token, 1..70 characters), or null. +pub fn boundary(content_type: []const u8) ?[]const u8 { + const semi = std.mem.indexOfScalar(u8, content_type, ';') orelse return null; + var it: Params = .{ .text = content_type[semi..] }; + while (it.next() catch return null) |p| { + if (!std.ascii.eqlIgnoreCase(p.key, "boundary")) continue; + if (p.value.len == 0 or p.value.len > 70 or p.value[p.value.len - 1] == ' ') return null; + for (p.value) |ch| if (!boundaryChar(ch) or (ch == ' ' and !p.quoted)) return null; + return p.value; + } + return null; +} + +/// RFC 2046 bchars: a quoted boundary may also hold spaces, but not as its last character. +fn boundaryChar(ch: u8) bool { + return std.ascii.isAlphanumeric(ch) or std.mem.indexOfScalar(u8, "'()+_,-./:=? ", ch) != null; +} + +/// The parts of `body` in order; the slice and unescaped names come from `a`, which should be a request arena. +pub fn parse(a: Allocator, body: []const u8, bound: []const u8) error{ Malformed, OutOfMemory }![]Part { + if (bound.len == 0) return error.Malformed; + var parts: std.ArrayList(Part) = .empty; + errdefer parts.deinit(a); + var d = delimiter(body, 0, bound) orelse return error.Malformed; + while (!d.close) { + if (parts.items.len == max_parts) return error.Malformed; + var head = try headers(a, body, d.next); + const next = delimiter(body, head.start, bound) orelse return error.Malformed; + head.part.body = body[head.start..bodyEnd(body, head.start, next.line)]; + try parts.append(a, head.part); + d = next; + } + return parts.toOwnedSlice(a); +} + +const Delimiter = struct { + /// Where the `--boundary` line starts. + line: usize, + /// Where the next part's headers start (after the line break). + next: usize, + /// Whether this is the close delimiter `--boundary--`. + close: bool, +}; + +/// The first `--boundary` at a line start that `--`, or blanks and a CRLF or LF, follows; other such text is body. +fn delimiter(body: []const u8, from: usize, bound: []const u8) ?Delimiter { + var pos = from + 2; + while (std.mem.indexOfPos(u8, body, pos, bound)) |at| : (pos = at + 1) { + const line = at - 2; + if (!std.mem.eql(u8, body[line..at], "--")) continue; + if (line != 0 and body[line - 1] != '\n') continue; + const end = at + bound.len; + if (std.mem.startsWith(u8, body[end..], "--")) return .{ .line = line, .next = end + 2, .close = true }; + var i = end; + while (i < body.len and (body[i] == ' ' or body[i] == '\t')) i += 1; + if (std.mem.startsWith(u8, body[i..], "\r\n")) return .{ .line = line, .next = i + 2, .close = false }; + if (std.mem.startsWith(u8, body[i..], "\n")) return .{ .line = line, .next = i + 1, .close = false }; + } + return null; +} + +/// Where a part body that starts at `start` ends, given the next delimiter line: before its CRLF or LF. +fn bodyEnd(body: []const u8, start: usize, line: usize) usize { + if (line <= start) return start; // the blank line after the headers was the delimiter's own line break + var end = line - 1; + if (end > start and body[end - 1] == '\r') end -= 1; + return end; +} + +const Head = struct { part: Part, start: usize }; + +/// One part's headers from `at`: the part without its body, and where its body starts. +fn headers(a: Allocator, body: []const u8, at: usize) error{ Malformed, OutOfMemory }!Head { + var part: Part = .{ .name = "", .filename = null, .content_type = null, .media = null, .body = "" }; + var disposition = false; + var typed = false; + var pos = at; + while (true) { + const window = body[0..@min(body.len, at + max_header_bytes)]; + const nl = std.mem.indexOfScalarPos(u8, window, pos, '\n') orelse return error.Malformed; + const line = std.mem.trimEnd(u8, body[pos..nl], "\r"); + pos = nl + 1; + if (line.len == 0) break; + if (line[0] == ' ' or line[0] == '\t') return error.Malformed; // no obsolete header folding + const colon = std.mem.indexOfScalar(u8, line, ':') orelse return error.Malformed; + const name = line[0..colon]; + const value = std.mem.trim(u8, line[colon + 1 ..], " \t"); + if (std.ascii.eqlIgnoreCase(name, "Content-Disposition")) { + if (disposition) return error.Malformed; + disposition = true; + try formData(a, value, &part); + } else if (std.ascii.eqlIgnoreCase(name, "Content-Type")) { + if (typed) return error.Malformed; + typed = true; + part.content_type = value; + part.media = try media(a, value); + } + } + if (!disposition) return error.Malformed; + return .{ .part = part, .start = pos }; +} + +/// The `name` and `filename` of a `form-data` disposition into `part`. +fn formData(a: Allocator, value: []const u8, part: *Part) error{ Malformed, OutOfMemory }!void { + const semi = std.mem.indexOfScalar(u8, value, ';') orelse value.len; + if (!std.ascii.eqlIgnoreCase(std.mem.trim(u8, value[0..semi], " \t"), "form-data")) return error.Malformed; + var named = false; + var it: Params = .{ .text = value[semi..] }; + while (try it.next()) |p| { + if (std.ascii.eqlIgnoreCase(p.key, "name")) { + if (named) return error.Malformed; + named = true; + part.name = try unescape(a, p); + } else if (std.ascii.eqlIgnoreCase(p.key, "filename")) { + if (part.filename != null) return error.Malformed; + part.filename = try unescape(a, p); + } + } + if (!named) return error.Malformed; +} + +/// The lower-cased type/subtype of a Content-Type value, or null when it is empty. +fn media(a: Allocator, value: []const u8) Allocator.Error!?[]const u8 { + const semi = std.mem.indexOfScalar(u8, value, ';') orelse value.len; + const kind = std.mem.trim(u8, value[0..semi], " \t"); + if (kind.len == 0) return null; + for (kind) |ch| { + if (std.ascii.isUpper(ch)) return std.ascii.lowerString(try a.alloc(u8, kind.len), kind); + } + return kind; +} + +/// A quoted value with `\"` and `\\` decoded; other backslashes stay, as Windows paths arrive unescaped. +fn unescape(a: Allocator, p: Param) Allocator.Error![]const u8 { + if (!p.quoted or std.mem.indexOfScalar(u8, p.value, '\\') == null) return p.value; + var out = try std.ArrayList(u8).initCapacity(a, p.value.len); + var i: usize = 0; + while (i < p.value.len) : (i += 1) { + const ch = p.value[i]; + if (ch == '\\' and i + 1 < p.value.len and (p.value[i + 1] == '"' or p.value[i + 1] == '\\')) i += 1; + out.appendAssumeCapacity(p.value[i]); + } + return out.toOwnedSlice(a); +} + +const Param = struct { key: []const u8, value: []const u8, quoted: bool }; + +/// `; key=value` parameters, values as tokens or quoted strings (still escaped). +const Params = struct { + text: []const u8, + pos: usize = 0, + + fn skip(it: *Params) void { + while (it.pos < it.text.len and (it.text[it.pos] == ' ' or it.text[it.pos] == '\t')) it.pos += 1; + } + + fn next(it: *Params) error{Malformed}!?Param { + it.skip(); + while (it.pos < it.text.len and it.text[it.pos] == ';') : (it.skip()) it.pos += 1; + if (it.pos == it.text.len) return null; + const key_start = it.pos; + while (it.pos < it.text.len and std.mem.indexOfScalar(u8, "=; \t", it.text[it.pos]) == null) it.pos += 1; + const key = it.text[key_start..it.pos]; + it.skip(); + if (key.len == 0 or it.pos == it.text.len or it.text[it.pos] != '=') return error.Malformed; + it.pos += 1; + it.skip(); + if (it.pos < it.text.len and it.text[it.pos] == '"') { + const start = it.pos + 1; + var i = start; + while (i < it.text.len and it.text[i] != '"') : (i += 1) { + if (it.text[i] == '\\' and i + 1 < it.text.len) i += 1; + } + if (i == it.text.len) return error.Malformed; + it.pos = i + 1; + it.skip(); + if (it.pos < it.text.len and it.text[it.pos] != ';') return error.Malformed; + return .{ .key = key, .value = it.text[start..i], .quoted = true }; + } + const start = it.pos; + while (it.pos < it.text.len and it.text[it.pos] != ';') it.pos += 1; + const value = std.mem.trimEnd(u8, it.text[start..it.pos], " \t"); + if (value.len == 0) return error.Malformed; + return .{ .key = key, .value = value, .quoted = false }; + } +}; diff --git a/zig/src/server/multipart_test.zig b/zig/src/server/multipart_test.zig new file mode 100644 index 00000000000..e385a609321 --- /dev/null +++ b/zig/src/server/multipart_test.zig @@ -0,0 +1,191 @@ +//! multipart/form-data reader: boundaries, part headers, line-break edges and limits. +const std = @import("std"); +const mp = @import("multipart.zig"); +const t = std.testing; + +fn parse(arena: *std.heap.ArenaAllocator, body: []const u8) ![]mp.Part { + return mp.parse(arena.allocator(), body, "XyZ"); +} + +test "ocr multipart: boundary from quoted and token parameters" { + try t.expectEqualStrings("abc-123", mp.boundary("multipart/form-data; boundary=abc-123").?); + try t.expectEqualStrings("abc-123", mp.boundary("multipart/form-data;boundary=abc-123 ; charset=x").?); + try t.expectEqualStrings("a b:c", mp.boundary("multipart/form-data; BOUNDARY=\"a b:c\"").?); + try t.expectEqualStrings("q", mp.boundary("multipart/form-data; x=\"y;boundary=z\"; boundary=q").?); + const seventy: [70]u8 = @splat('b'); + try t.expectEqualStrings(&seventy, mp.boundary("multipart/form-data; boundary=" ++ seventy).?); +} + +test "ocr multipart: boundary refusals" { + const too_long: [71]u8 = @splat('b'); + try t.expect(mp.boundary("multipart/form-data") == null); + try t.expect(mp.boundary("multipart/form-data; charset=utf-8") == null); + try t.expect(mp.boundary("multipart/form-data; boundary=" ++ too_long) == null); + try t.expect(mp.boundary("multipart/form-data; boundary=") == null); + try t.expect(mp.boundary("multipart/form-data; boundary=\"\"") == null); + try t.expect(mp.boundary("multipart/form-data; boundary=\"ends in space \"") == null); + try t.expect(mp.boundary("multipart/form-data; boundary=\"unterminated") == null); + try t.expect(mp.boundary("multipart/form-data; boundary=a\"b") == null); + try t.expect(mp.boundary("boundary=abc") == null); +} + +test "ocr multipart: CRLF parts with a preamble and an epilogue" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = "preamble line\r\n--XyZ\r\n" ++ + "Content-Disposition: form-data; name=\"files\"; filename=\"a.jpg\"\r\n" ++ + "Content-Type: image/jpeg\r\n\r\n" ++ + "\xff\xd8\r\nbinary\r\n" ++ + "\r\n--XyZ\r\n" ++ + "Content-Disposition: form-data; name=language\r\n\r\n" ++ + "eng\r\n--XyZ--\r\nepilogue --XyZ\r\n"; + const parts = try parse(&arena, body); + try t.expectEqual(@as(usize, 2), parts.len); + try t.expectEqualStrings("files", parts[0].name); + try t.expectEqualStrings("a.jpg", parts[0].filename.?); + try t.expectEqualStrings("image/jpeg", parts[0].content_type.?); + try t.expectEqualStrings("image/jpeg", parts[0].media.?); + try t.expectEqualStrings("\xff\xd8\r\nbinary\r\n", parts[0].body); + try t.expectEqualStrings("language", parts[1].name); + try t.expect(parts[1].filename == null); + try t.expect(parts[1].content_type == null and parts[1].media == null); + try t.expectEqualStrings("eng", parts[1].body); + const base = @intFromPtr(body.ptr); + try t.expect(@intFromPtr(parts[0].body.ptr) > base and @intFromPtr(parts[0].body.ptr) < base + body.len); +} + +test "ocr multipart: bare LF delimiters and headers" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = "--XyZ\ncontent-disposition: form-data; name=\"file\"; filename=\"p.png\"\n" ++ + "CONTENT-TYPE: image/png\n\nPNG\n--XyZ \t\ncontent-disposition: form-data; name=empty\n\n\n--XyZ--"; + const parts = try parse(&arena, body); + try t.expectEqual(@as(usize, 2), parts.len); + try t.expectEqualStrings("PNG", parts[0].body); + try t.expectEqualStrings("image/png", parts[0].media.?); + try t.expectEqualStrings("empty", parts[1].name); + try t.expectEqualStrings("", parts[1].body); +} + +test "ocr multipart: an empty body right after the header block" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const parts = try parse(&arena, "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n--XyZ--"); + try t.expectEqual(@as(usize, 1), parts.len); + try t.expectEqualStrings("", parts[0].body); + try t.expectEqual(@as(usize, 0), (try parse(&arena, "--XyZ--\r\n")).len); +} + +test "ocr multipart: boundary-like text inside a body stays in the body" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const inner = "a --XyZ\r\n mid\r\n--XyZW not a line\r\n--XyZ- one dash\r\n-XyZ\r\ntail--XyZ"; + const body = "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n" ++ inner ++ "\r\n--XyZ--"; + const parts = try parse(&arena, body); + try t.expectEqual(@as(usize, 1), parts.len); + try t.expectEqualStrings(inner, parts[0].body); +} + +test "ocr multipart: missing delimiters are malformed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const head = "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n"; + try t.expectError(error.Malformed, parse(&arena, "")); + try t.expectError(error.Malformed, parse(&arena, "no delimiter at all")); + try t.expectError(error.Malformed, parse(&arena, head ++ "body without a close")); + try t.expectError(error.Malformed, parse(&arena, head ++ "body\r\n--XyZ")); + try t.expectError(error.Malformed, parse(&arena, head ++ "body\r\n--XyZ\r\n")); + try t.expectError(error.Malformed, parse(&arena, "--XyZ\r\nContent-Disposition: form-data; name=a\r\n")); + try t.expectError(error.Malformed, mp.parse(arena.allocator(), head ++ "x\r\n--XyZ--", "")); +} + +test "ocr multipart: Content-Disposition is required with form-data and a name" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const cases = [_][]const u8{ + "Content-Type: text/plain\r\n", + "Content-Disposition: attachment; name=a\r\n", + "Content-Disposition: form-data; filename=\"a.png\"\r\n", + "Content-Disposition: form-data; name=\"a\r\n", + "Content-Disposition: form-data; name\r\n", + "Content-Disposition: form-data; name=a; name=b\r\n", + "Content-Disposition: form-data; name=a\r\nContent-Disposition: form-data; name=b\r\n", + "Content-Disposition: form-data; name=a\r\nContent-Type: a/b\r\ncontent-type: c/d\r\n", + "Content-Disposition: form-data;\r\n name=a\r\n", + "Content-Disposition form-data; name=a\r\n", + }; + for (cases) |hdr| { + const body = try std.mem.concat(arena.allocator(), u8, &.{ "--XyZ\r\n", hdr, "\r\nx\r\n--XyZ--" }); + try t.expectError(error.Malformed, parse(&arena, body)); + } +} + +test "ocr multipart: quoted parameters with escapes, tokens and filename star" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = "--XyZ\r\nContent-Disposition: Form-Data ; name = \"a \\\"q\\\" ; b\" ; " ++ + "filename*=UTF-8''x.png; filename=\"C:\\dir\\\\f.png\"; other=1\r\n\r\nx\r\n--XyZ--"; + const parts = try parse(&arena, body); + try t.expectEqualStrings("a \"q\" ; b", parts[0].name); + try t.expectEqualStrings("C:\\dir\\f.png", parts[0].filename.?); + const blank = "--XyZ\r\nContent-Disposition: form-data; name=\"\"; filename=\"\"\r\n\r\nx\r\n--XyZ--"; + const empty = try parse(&arena, blank); + try t.expectEqualStrings("", empty[0].name); + try t.expectEqualStrings("", empty[0].filename.?); +} + +test "ocr multipart: Content-Type keeps the raw value and a lower-cased media type" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = "--XyZ\r\nContent-Disposition: form-data; name=files\r\n" ++ + "Content-Type: Image/PNG; charset=binary \r\n\r\nx\r\n" ++ + "--XyZ\r\nContent-Disposition: form-data; name=files\r\ncontent-type:\r\n\r\ny\r\n--XyZ--"; + const parts = try parse(&arena, body); + try t.expectEqualStrings("Image/PNG; charset=binary", parts[0].content_type.?); + try t.expectEqualStrings("image/png", parts[0].media.?); + try t.expectEqualStrings("", parts[1].content_type.?); + try t.expect(parts[1].media == null); +} + +test "ocr multipart: part headers stop at 8 KiB" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const disposition = "Content-Disposition: form-data; name=a\r\n"; + const filler_head = "X-Pad: "; + // the header block (with its blank line) at exactly the limit passes; one byte more is malformed + const fit = mp.max_header_bytes - disposition.len - filler_head.len - 4; + for ([_]usize{ fit, fit + 1 }, [_]bool{ true, false }) |pad, ok| { + const filler = try a.alloc(u8, pad); + @memset(filler, 'p'); + const tail = "\r\n\r\nx\r\n--XyZ--"; + const body = try std.mem.concat(a, u8, &.{ "--XyZ\r\n", disposition, filler_head, filler, tail }); + if (ok) { + try t.expectEqualStrings("x", (try parse(&arena, body))[0].body); + } else try t.expectError(error.Malformed, parse(&arena, body)); + } +} + +test "ocr multipart: at most 256 parts" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const one = "--XyZ\r\nContent-Disposition: form-data; name=files\r\n\r\nx\r\n"; + var body: std.ArrayList(u8) = .empty; + for (0..mp.max_parts) |_| try body.appendSlice(a, one); + const fits = try std.mem.concat(a, u8, &.{ body.items, "--XyZ--" }); + try t.expectEqual(@as(usize, mp.max_parts), (try parse(&arena, fits)).len); + try body.appendSlice(a, one); + try body.appendSlice(a, "--XyZ--"); + try t.expectError(error.Malformed, parse(&arena, body.items)); +} + +test "ocr multipart: other part headers and transfer encodings are not interpreted" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const body = "--XyZ\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: form-data; name=a\r\n" ++ + "Content-Type: multipart/mixed; boundary=inner\r\n\r\naGk=\r\n--XyZ--"; + const parts = try parse(&arena, body); + try t.expectEqualStrings("aGk=", parts[0].body); + try t.expectEqualStrings("multipart/mixed", parts[0].media.?); +} diff --git a/zig/src/server/query.zig b/zig/src/server/query.zig new file mode 100644 index 00000000000..7abc8a1f0fa --- /dev/null +++ b/zig/src/server/query.zig @@ -0,0 +1,66 @@ +//! Query parameters of a request path, decoded as form fields are (`+` is a space, `%XX` a byte). +const std = @import("std"); +const Allocator = std.mem.Allocator; + +/// What a query read refuses: a bad `%` escape in the value, or the name sent more than once. +pub const Error = error{ Malformed, Repeated, OutOfMemory }; + +/// The value of `name` after the `?` (`""` without `=`), or null; a name sent twice is error.Repeated. +pub fn get(a: Allocator, raw_path: []const u8, name: []const u8) Error!?[]const u8 { + const q = std.mem.indexOfScalar(u8, raw_path, '?') orelse return null; + var it = std.mem.splitScalar(u8, raw_path[q + 1 ..], '&'); + var value: ?[]const u8 = null; + while (it.next()) |field| { + const eq = std.mem.indexOfScalar(u8, field, '=') orelse field.len; + if (!named(field[0..eq], name)) continue; + if (value != null) return error.Repeated; + value = if (eq == field.len) "" else field[eq + 1 ..]; + } + return if (value) |v| try decode(a, v) else null; +} + +/// A query word as pydantic reads a boolean (`true/t/yes/y/on/1` and `false/f/no/n/off/0`, any case), else null. +pub fn boolean(text: []const u8) ?bool { + for ([_][]const u8{ "true", "t", "yes", "y", "on", "1" }) |word| if (std.ascii.eqlIgnoreCase(text, word)) return true; + for ([_][]const u8{ "false", "f", "no", "n", "off", "0" }) |word| if (std.ascii.eqlIgnoreCase(text, word)) return false; + return null; +} + +/// Whether an encoded key decodes to `name`, without allocating; a key with a malformed escape never matches. +fn named(key: []const u8, name: []const u8) bool { + var i: usize = 0; + var n: usize = 0; + while (i < key.len) : (n += 1) { + const ch = (byte(key, &i) catch return false); + if (n == name.len or name[n] != ch) return false; + } + return n == name.len; +} + +/// The byte at `i.*`, decoded, with `i.*` moved past it. +fn byte(text: []const u8, i: *usize) error{Malformed}!u8 { + const ch = text[i.*]; + if (ch == '+') { + i.* += 1; + return ' '; + } + if (ch != '%') { + i.* += 1; + return ch; + } + if (i.* + 2 >= text.len) return error.Malformed; + const hi = std.fmt.charToDigit(text[i.* + 1], 16) catch return error.Malformed; + const lo = std.fmt.charToDigit(text[i.* + 2], 16) catch return error.Malformed; + i.* += 3; + return hi * 16 + lo; +} + +/// The decoded value: a slice of `text` when nothing is escaped, else a copy from `a`. +fn decode(a: Allocator, text: []const u8) error{ Malformed, OutOfMemory }![]const u8 { + if (std.mem.indexOfAny(u8, text, "+%") == null) return text; + var out = try std.ArrayList(u8).initCapacity(a, text.len); + errdefer out.deinit(a); + var i: usize = 0; + while (i < text.len) out.appendAssumeCapacity(try byte(text, &i)); + return out.toOwnedSlice(a); +} diff --git a/zig/src/server/query_test.zig b/zig/src/server/query_test.zig new file mode 100644 index 00000000000..c7975e24ff6 --- /dev/null +++ b/zig/src/server/query_test.zig @@ -0,0 +1,67 @@ +//! Query parameters: the one match, a repeated name, form decoding, malformed escapes and pydantic booleans. +const std = @import("std"); +const query = @import("query.zig"); +const t = std.testing; + +test "ocr query: the one match after the question mark" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const path = "/ocr?det_arch=db_resnet50&resolve_blocks=true&flag&empty="; + try t.expectEqualStrings("true", (try query.get(a, path, "resolve_blocks")).?); + try t.expectEqualStrings("db_resnet50", (try query.get(a, path, "det_arch")).?); + try t.expectEqualStrings("", (try query.get(a, path, "flag")).?); + try t.expectEqualStrings("", (try query.get(a, path, "empty")).?); + try t.expect(try query.get(a, path, "missing") == null); + try t.expect(try query.get(a, path, "resolve") == null); + try t.expect(try query.get(a, "/ocr", "format") == null); + try t.expect(try query.get(a, "/ocr?", "format") == null); + try t.expectEqualStrings("doctr", (try query.get(a, "/ocr/?&&format=doctr", "format")).?); +} + +test "ocr query: plus and percent escapes decode in names and values" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const path = "/ocr?a+b=c+d&path=x%2Fy%2fz&n%61me=%41%20B&raw=plain"; + try t.expectEqualStrings("c d", (try query.get(a, path, "a b")).?); + try t.expectEqualStrings("x/y/z", (try query.get(a, path, "path")).?); + try t.expectEqualStrings("A B", (try query.get(a, path, "name")).?); + const raw = (try query.get(a, path, "raw")).?; + try t.expect(@intFromPtr(raw.ptr) == @intFromPtr(path.ptr) + path.len - "plain".len); +} + +test "ocr query: a malformed escape in the matched value is malformed" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try t.expectError(error.Malformed, query.get(a, "/ocr?x=%G1", "x")); + try t.expectError(error.Malformed, query.get(a, "/ocr?x=ab%4", "x")); + try t.expectError(error.Malformed, query.get(a, "/ocr?x=%", "x")); + try t.expectEqualStrings("1", (try query.get(a, "/ocr?y=%G1&x=1", "x")).?); + try t.expect(try query.get(a, "/ocr?x%G1=1", "x") == null); +} + +test "ocr query: a name sent twice is refused, whatever the values or their spelling" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_][2][]const u8{ + .{ "/ocr?resolve_lines=true&resolve_lines=false", "resolve_lines" }, + .{ "/ocr?x=1&y=2&x=1", "x" }, + .{ "/ocr?x&x=", "x" }, + .{ "/ocr?x=1&%78=1", "x" }, + .{ "/ocr?x=%G1&x=1", "x" }, + }; + for (cases) |c| try t.expectError(error.Repeated, query.get(a, c[0], c[1])); + try t.expectEqualStrings("2", (try query.get(a, "/ocr?x=1&y=2&x=1", "y")).?); +} + +test "ocr query: pydantic boolean words" { + const yes = [_][]const u8{ "true", "TRUE", "True", "t", "T", "1", "yes", "YeS", "y", "on", "ON" }; + const no = [_][]const u8{ "false", "False", "f", "F", "0", "no", "NO", "n", "off", "Off" }; + const neither = [_][]const u8{ "", "2", "tru", "truee", " true", "maybe", "none", "null" }; + for (yes) |w| try t.expectEqual(true, query.boolean(w).?); + for (no) |w| try t.expectEqual(false, query.boolean(w).?); + for (neither) |w| try t.expect(query.boolean(w) == null); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 5561de29db2..97f9e843a51 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -363,6 +363,8 @@ test { test { _ = @import("request_starts_turns_test.zig"); _ = @import("thinking_request_test.zig"); + _ = @import("multipart_test.zig"); + _ = @import("query_test.zig"); _ = @import("voice_cli.zig"); _ = @import("drama_voice_store.zig"); if (comptime @import("builtin").os.tag != .windows) _ = @import("speech_voice_http_test.zig"); // over a Unix socket pair From 81bfee14ca742bed3a43dc6095817f441b0038c1 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:45:18 +0000 Subject: [PATCH 049/361] feat(ocr): estimate text lines and words from reader blocks The line contracts on /ocr carry plain-text lines, while block readers give one box a block, so markdown.zig reads a block's normalized Markdown as plain-text lines, table rows included, and lines.zig divides the block's box into equal bands along its reading edges, one per line, and a line's box into words in proportion to each word's character count, splitting on the whitespace Python's str.split uses. Every derived quad passes the shared validation, so no encoder sees a zero-area box. --- zig/src/core/ocr_html.zig | 24 ++++ zig/src/core/ocr_html_test.zig | 21 ++- zig/src/server/ocr/lines.zig | 123 ++++++++++++++++++ zig/src/server/ocr/lines_test.zig | 154 ++++++++++++++++++++++ zig/src/server/ocr/markdown.zig | 160 ++++++++++++++++++++--- zig/src/server/ocr/markdown_test.zig | 187 ++++++++++++++++++++------- zig/src/server/ocr/types.zig | 10 +- zig/src/server/root.zig | 1 + 8 files changed, 613 insertions(+), 67 deletions(-) create mode 100644 zig/src/server/ocr/lines.zig create mode 100644 zig/src/server/ocr/lines_test.zig diff --git a/zig/src/core/ocr_html.zig b/zig/src/core/ocr_html.zig index 39dab703d1a..83bacb8397d 100644 --- a/zig/src/core/ocr_html.zig +++ b/zig/src/core/ocr_html.zig @@ -99,6 +99,30 @@ pub fn normalized(a: Allocator, t: Table) Allocator.Error![]const u8 { return out.toOwnedSlice(a); } +/// One line a grid row, its cells joined by '\t'; a spanned cell's text at its top-left only, trailing cells kept. +pub fn rowsText(a: Allocator, t: Table) Allocator.Error![][]const u8 { + const lines = try a.alloc([]const u8, t.rows); + var done: usize = 0; + errdefer { + for (lines[0..done]) |l| a.free(l); + a.free(lines); + } + var line: std.ArrayList(u8) = .empty; + defer line.deinit(a); + var k: usize = 0; + for (lines, 0..) |*l, r| { + line.clearRetainingCapacity(); + for (0..t.cols) |c| { + if (c > 0) try line.append(a, '\t'); + const text = if (topLeft(t, &k, r, c)) |cell| cell.text else ""; + for (text) |ch| try line.append(a, if (ch == '\n') ' ' else ch); + } + l.* = try a.dupe(u8, line.items); + done += 1; + } + return lines; +} + /// A cell's text in a pipe row: math as written (only `|` escaped), markup escaped elsewhere, to read back literally. fn cellText(a: Allocator, out: *std.ArrayList(u8), text: []const u8) Allocator.Error!void { var no_close = false; // a `$` found no closer, so no later `$` in the cell can (markdown.zig's rule) diff --git a/zig/src/core/ocr_html_test.zig b/zig/src/core/ocr_html_test.zig index 6ec8517cbf8..dafaf11bf34 100644 --- a/zig/src/core/ocr_html_test.zig +++ b/zig/src/core/ocr_html_test.zig @@ -21,6 +21,12 @@ fn expectCell(got: html.Cell, text: []const u8, row: u32, col: u32, rows: u32, c try t.expectEqualDeep(want, got); } +fn expectRows(a: std.mem.Allocator, table: html.Table, want: []const []const u8) !void { + const got = try html.rowsText(a, table); + try t.expectEqual(want.len, got.len); + for (want, got) |w, g| try t.expectEqualStrings(w, g); +} + test "ocr html: the dots.mocr table keeps its spans" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); @@ -34,6 +40,12 @@ test "ocr html: the dots.mocr table keeps its spans" { try t.expectEqualDeep(nhl, table.cells[3]); try expectCell(table.cells[4], "Cases", 1, 2, 1, 1, true); try t.expect(!table.cells[10].head); + try expectRows(a, table, &.{ + "\tControls\tHodgkin lymphoma\t\t\tNon-Hodgkin lymphoma\t\t", + "\t\tCases\tOR\t95% CI\tCases\tOR\t95% CI", + "Never Exposed (reference group)\t2,273\t315\t1.00\t—\t1,823\t1.00\t—", + ">1 year\t90\t7\t0.84\t0.37-1.91\t86\t1.17\t0.87-1.59", + }); } test "ocr html: the GLM-OCR table has no header row and becomes a pipe table with its first row the header" { @@ -73,7 +85,7 @@ test "ocr html: other tags drop and keep their text; names and attributes in any try expectCell(table.cells[2], "y", 1, 1, 1, 2, false); } -test "ocr html:
is a line break in the cell and a space in pipe cells" { +test "ocr html:
is a line break in the cell and a space in pipe cells and text rows" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -81,6 +93,7 @@ test "ocr html:
is a line break in the cell and a space in pipe cells" { const table = try html.parse(a, src); try t.expectEqualStrings("line one\nline two\nthree", table.cells[0].text); try t.expectEqualStrings("| line one line two three | b |\n| --- | --- |", try html.pipe(a, table)); + try expectRows(a, table, &.{"line one line two three\tb"}); const clean = "
line one
line two
three
b
"; try t.expectEqualStrings(clean, try html.normalized(a, table)); } @@ -179,7 +192,7 @@ test "ocr html: spans clip to the grid and to columns earlier rows cover" { try t.expect(!lone.spanned and lone.rows == 1 and lone.cols == 1); } -test "ocr html: pipe rows place a spanned cell's text once and keep trailing cells" { +test "ocr html: text rows place a spanned cell's text once and keep trailing cells" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -187,6 +200,7 @@ test "ocr html: pipe rows place a spanned cell's text once and keep trailing cel "e"; const table = try html.parse(a, src); try t.expectEqual(@as(u32, 3), table.cols); + try expectRows(a, table, &.{ "A\tB\t", "\tc\td", "e\t\t" }); try t.expectEqualStrings("| A | B | |\n| --- | --- | --- |\n| | c | d |\n| e | | |", try html.pipe(a, table)); } @@ -213,6 +227,9 @@ fn everyWriter(a: std.mem.Allocator, src: []const u8) !void { defer table.deinit(a); a.free(try html.pipe(a, table)); a.free(try html.normalized(a, table)); + const rows = try html.rowsText(a, table); + for (rows) |r| a.free(r); + a.free(rows); } test "ocr html: every allocation failure is returned and nothing leaks" { diff --git a/zig/src/server/ocr/lines.zig b/zig/src/server/ocr/lines.zig new file mode 100644 index 00000000000..89680f05e59 --- /dev/null +++ b/zig/src/server/ocr/lines.zig @@ -0,0 +1,123 @@ +//! A page's blocks as plain-text lines with estimated quads, and a line's estimated words (docs/api.md OCR: Estimates). +const std = @import("std"); +const Allocator = std.mem.Allocator; +const api = @import("engine_api"); +const types = @import("types.zig"); +const geometry = @import("geometry.zig"); +const markdown = @import("markdown.zig"); +const Quad = api.ocr.Quad; +const OcrLine = types.OcrLine; + +/// One whitespace-separated word of a line and its estimated quad (null when the line has none). +pub const Word = struct { text: []const u8, quad: ?Quad }; + +/// The page's lines in reading order, allocated in ``a``; error.Unreadable only for a block quad that is not finite. +pub fn fromBlocks(a: Allocator, page: *const types.OcrPage, geo: api.ocr.Geometry) (Allocator.Error || error{Unreadable})![]OcrLine { + var out: std.ArrayList(OcrLine) = .empty; + for (page.blocks, 0..) |b, i| { + if (b.kind == .picture) continue; + const block: u32 = @intCast(i); + const texts = try markdown.plainLines(a, b.content); + if (texts.len == 0) continue; + const quad = if (geo == .none) null else b.quad; + const n: f32 = @floatFromInt(texts.len); + for (texts, 0..) |text, k| { + const band: ?Quad = if (quad) |q| blk: { + const t0 = @as(f32, @floatFromInt(k)) / n; + const t1 = @as(f32, @floatFromInt(k + 1)) / n; + break :blk .{ lerp(q[0], q[3], t0), lerp(q[1], q[2], t0), lerp(q[1], q[2], t1), lerp(q[0], q[3], t1) }; + } else null; + try out.append(a, .{ .text = text, .quad = try check(band, page.width, page.height), .block = block }); + } + } + return out.toOwnedSlice(a); +} + +/// The line's words, its quad cut along TL→TR and BL→BR in proportion to each word's Unicode scalar count. +pub fn words(a: Allocator, line: OcrLine, width: u32, height: u32) (Allocator.Error || error{Unreadable})![]Word { + var out: std.ArrayList(Word) = .empty; + var total: usize = 0; + var it: Split = .{ .s = line.text }; + while (it.next()) |w| { + try out.append(a, .{ .text = w, .quad = null }); + total += scalars(w); + } + const q = line.quad orelse return out.toOwnedSlice(a); + const sum: f32 = @floatFromInt(total); + var done: usize = 0; + for (out.items) |*w| { + const t0 = @as(f32, @floatFromInt(done)) / sum; + done += scalars(w.text); + const t1 = @as(f32, @floatFromInt(done)) / sum; + w.quad = try check(.{ lerp(q[0], q[1], t0), lerp(q[0], q[1], t1), lerp(q[3], q[2], t1), lerp(q[3], q[2], t0) }, width, height); + } + return out.toOwnedSlice(a); +} + +fn check(q: ?Quad, w: u32, h: u32) error{Unreadable}!?Quad { + return if (q) |v| try geometry.validate(v, w, h) else null; +} + +/// The point at ``t`` from ``p`` to ``r``; exactly ``p`` at 0 and ``r`` at 1. +fn lerp(p: [2]f32, r: [2]f32, t: f32) [2]f32 { + return .{ (1 - t) * p[0] + t * r[0], (1 - t) * p[1] + t * r[1] }; +} + +/// ``s`` without the leading and trailing whitespace Python's ``str.strip()`` removes (Unicode, as ``Split``'s). +pub fn trimSpace(s: []const u8) []const u8 { + var i: usize = 0; + var start: ?usize = null; + var end: usize = 0; + while (i < s.len) { + const n = Split.space(s[i..]); + const step = if (n > 0) n else Split.charLen(s[i..]); + if (n == 0) { + if (start == null) start = i; + end = i + step; + } + i += step; + } + return if (start) |b| s[b..end] else s[s.len..]; +} + +/// Words between runs of the whitespace Python's ``str.split()`` splits on; a byte that is not UTF-8 is a word byte. +const Split = struct { + s: []const u8, + i: usize = 0, + + fn next(it: *Split) ?[]const u8 { + while (it.i < it.s.len) { + const n = space(it.s[it.i..]); + if (n == 0) break; + it.i += n; + } + if (it.i == it.s.len) return null; + const start = it.i; + while (it.i < it.s.len and space(it.s[it.i..]) == 0) it.i += charLen(it.s[it.i..]); + return it.s[start..it.i]; + } + + /// The byte length of the whitespace character that starts ``s``, or 0. + fn space(s: []const u8) usize { + const n = charLen(s); + if (n == 1 and s[0] >= 0x80) return 0; // a stray byte, not U+0080..U+00FF + const cp: u21 = if (n == 1) s[0] else std.unicode.utf8Decode(s[0..n]) catch return 0; + return switch (cp) { + 0x09...0x0d, 0x1c...0x20, 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => n, + else => 0, + }; + } + + /// The bytes of the UTF-8 character that starts ``s``; 1 for a byte that does not start a whole one. + fn charLen(s: []const u8) usize { + const n = std.unicode.utf8ByteSequenceLength(s[0]) catch return 1; + if (n > s.len) return 1; + _ = std.unicode.utf8Decode(s[0..n]) catch return 1; + return n; + } +}; + +/// Unicode scalar values in ``s``; bytes when it is not valid UTF-8. +fn scalars(s: []const u8) usize { + return std.unicode.utf8CountCodepoints(s) catch s.len; +} diff --git a/zig/src/server/ocr/lines_test.zig b/zig/src/server/ocr/lines_test.zig new file mode 100644 index 00000000000..4c9902e0ce3 --- /dev/null +++ b/zig/src/server/ocr/lines_test.zig @@ -0,0 +1,154 @@ +//! Blocks to lines and words, with every derived quad validated (docs/api.md OCR: Estimates). +const std = @import("std"); +const api = @import("engine_api"); +const types = @import("types.zig"); +const lines = @import("lines.zig"); +const g = @import("geometry.zig"); +const t = std.testing; +const Quad = api.ocr.Quad; +const OcrBlock = api.ocr.OcrBlock; + +fn rect(x0: f32, y0: f32, x1: f32, y1: f32) Quad { + return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } }; +} + +fn expectQuad(want: Quad, got: ?Quad) !void { + const q = got orelse return error.TestExpectedEqual; + for (want, q) |w, p| { + try t.expectApproxEqAbs(w[0], p[0], 1e-4); + try t.expectApproxEqAbs(w[1], p[1], 1e-4); + } +} + +/// Every quad passes validation unchanged against the page: simple, convex, 1 px² or more, inside the frame. +fn expectValid(q: ?Quad, w: u32, h: u32) !void { + const v = q orelse return; + try t.expect(g.isSimpleConvex(v)); + try t.expectEqual(v, try g.validate(v, w, h)); +} + +fn page(blocks: []OcrBlock, w: u32, h: u32) types.OcrPage { + return .{ .index = 0, .width = w, .height = h, .dpi = 72, .blocks = blocks }; +} + +test "ocr lines: a block reader's lines split the block into equal bands, first line at the top edge" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + var blocks = [_]OcrBlock{ + .{ .content = "# Title", .quad = rect(10, 0, 110, 12), .kind = .title }, + .{ .content = "", .quad = rect(0, 20, 50, 60), .kind = .picture }, + .{ .content = "one\n**two**\n\nthree", .quad = rect(0, 30, 100, 60), .kind = .text }, + }; + const p = page(&blocks, 200, 100); + const got = try lines.fromBlocks(arena.allocator(), &p, .block); + try t.expectEqual(@as(usize, 4), got.len); + try t.expectEqualStrings("Title", got[0].text); + try expectQuad(rect(10, 0, 110, 12), got[0].quad); + try t.expectEqual(@as(u32, 0), got[0].block); + const want = [_][]const u8{ "one", "two", "three" }; + for (got[1..], want, 0..) |l, text, k| { + try t.expectEqualStrings(text, l.text); + try t.expectEqual(@as(u32, 2), l.block); + try t.expectEqual(@as(f32, 1.0), l.score); + const y: f32 = 30 + 10 * @as(f32, @floatFromInt(k)); + try expectQuad(rect(0, y, 100, y + 10), l.quad); + } + for (got) |l| try expectValid(l.quad, 200, 100); +} + +test "ocr lines: a rotated block splits along its TL→BL edge, in reading order" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + // text turned 90° clockwise: reading runs down, the first line is the rightmost column + var blocks = [_]OcrBlock{.{ .content = "first\nsecond", .quad = .{ .{ 30, 0 }, .{ 30, 100 }, .{ 0, 100 }, .{ 0, 0 } }, .kind = .text }}; + const p = page(&blocks, 100, 100); + const got = try lines.fromBlocks(arena.allocator(), &p, .block); + try t.expectEqual(@as(usize, 2), got.len); + try expectQuad(.{ .{ 30, 0 }, .{ 30, 100 }, .{ 15, 100 }, .{ 15, 0 } }, got[0].quad); + try expectQuad(.{ .{ 15, 0 }, .{ 15, 100 }, .{ 0, 100 }, .{ 0, 0 } }, got[1].quad); + for (got) |l| try expectValid(l.quad, 100, 100); +} + +test "ocr lines: an f32 band that collapses is repaired to 1 px" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + // one f32 step tall at y 8191: exactly 1 px² of block, so either band can round to zero height + var blocks = [_]OcrBlock{.{ .content = "a\nb", .quad = rect(0, 8191, 2048, 8191.00048828125), .kind = .text }}; + const p = page(&blocks, 2048, 8192); + try t.expect(g.isSimpleConvex(blocks[0].quad.?)); + const got = try lines.fromBlocks(arena.allocator(), &p, .block); + try t.expectEqual(@as(usize, 2), got.len); + var repaired: usize = 0; + for (got) |l| { + try expectValid(l.quad, 2048, 8192); + const b = g.minMax(l.quad.?); + if (b[3] - b[1] == 1) repaired += 1; + try t.expect(b[1] >= 8191 and b[3] <= 8192); + } + try t.expect(repaired >= 1); // the band that rounded to zero height +} + +test "ocr lines: a geometry-less reader's lines keep a null quad" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + var blocks = [_]OcrBlock{.{ .content = "# Page\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n$$\nx^2\n$$", .quad = null, .kind = .page }}; + const p = page(&blocks, 100, 100); + const got = try lines.fromBlocks(arena.allocator(), &p, .none); + const want = [_][]const u8{ "Page", "a\tb", "1\t2", "x^2" }; + try t.expectEqual(want.len, got.len); + for (got, want) |l, text| { + try t.expectEqualStrings(text, l.text); + try t.expect(l.quad == null); + try t.expectEqual(@as(u32, 0), l.block); + } +} + +test "ocr lines: words split the line by Unicode scalar count, not bytes" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const line: types.OcrLine = .{ .text = "héllo wörld\tab", .quad = rect(0, 0, 120, 10), .block = 0 }; + const got = try lines.words(arena.allocator(), line, 200, 100); + try t.expectEqual(@as(usize, 3), got.len); + try t.expectEqualStrings("héllo", got[0].text); + try t.expectEqualStrings("wörld", got[1].text); + try t.expectEqualStrings("ab", got[2].text); + try expectQuad(rect(0, 0, 50, 10), got[0].quad); + try expectQuad(rect(50, 0, 100, 10), got[1].quad); + try expectQuad(rect(100, 0, 120, 10), got[2].quad); + for (got) |w| try expectValid(w.quad, 200, 100); +} + +test "ocr lines: words follow the reading direction and keep a null quad" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + // upside-down text: TL is bottom right, reading runs right to left + const turned: types.OcrLine = .{ .text = "ab cd", .quad = .{ .{ 100, 10 }, .{ 0, 10 }, .{ 0, 0 }, .{ 100, 0 } }, .block = 1 }; + const got = try lines.words(arena.allocator(), turned, 100, 100); + try expectQuad(.{ .{ 100, 10 }, .{ 50, 10 }, .{ 50, 0 }, .{ 100, 0 } }, got[0].quad); + try expectQuad(.{ .{ 50, 10 }, .{ 0, 10 }, .{ 0, 0 }, .{ 50, 0 } }, got[1].quad); + const bare = try lines.words(arena.allocator(), .{ .text = "x y", .quad = null, .block = 0 }, 100, 100); + try t.expectEqual(@as(usize, 2), bare.len); + for (bare) |w| try t.expect(w.quad == null); + // a one-pixel-wide line of many words: each word's sliver is widened to 1 px inside the page + const thin = try lines.words(arena.allocator(), .{ .text = "a b c d", .quad = rect(99, 0, 100, 10), .block = 0 }, 100, 100); + for (thin) |w| try expectValid(w.quad, 100, 100); +} + +test "ocr lines: words split on Unicode whitespace as Python's str.split does" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const nbsp = try lines.words(a, .{ .text = "one\u{00A0}two", .quad = rect(0, 0, 60, 10), .block = 0 }, 100, 100); + try t.expectEqual(@as(usize, 2), nbsp.len); + try t.expectEqualStrings("one", nbsp[0].text); + try t.expectEqualStrings("two", nbsp[1].text); + try expectQuad(rect(0, 0, 30, 10), nbsp[0].quad); + try expectQuad(rect(30, 0, 60, 10), nbsp[1].quad); + const text = "a\u{3000}b\u{2009}c\x0bd\x0ce\u{85}f\u{202F}g\u{2028}h \xffi\x85j"; + const got = try lines.words(a, .{ .text = text, .quad = null, .block = 0 }, 100, 100); + const want = [_][]const u8{ "a", "b", "c", "d", "e", "f", "g", "h", "\xffi\x85j" }; + try t.expectEqual(want.len, got.len); + for (got, want) |w, s| try t.expectEqualStrings(s, w.text); + // zero-width space (U+200B) is not whitespace to Python either + try t.expectEqual(@as(usize, 1), (try lines.words(a, .{ .text = "a\u{200B}b", .quad = null, .block = 0 }, 100, 100)).len); +} diff --git a/zig/src/server/ocr/markdown.zig b/zig/src/server/ocr/markdown.zig index a313e3ae711..f057faa04d0 100644 --- a/zig/src/server/ocr/markdown.zig +++ b/zig/src/server/ocr/markdown.zig @@ -1,4 +1,4 @@ -//! A block's tables as byte ranges, and a pipe table read back as cells (docs/api.md OCR: Reader Markdown). +//! A block's normalized Markdown as plain-text lines, and its tables' byte ranges (docs/api.md OCR: Estimates). const std = @import("std"); const Allocator = std.mem.Allocator; const api = @import("engine_api"); @@ -7,11 +7,26 @@ const html = api.ocr.html; /// The byte range of one table in the content; ``html``: an HTML , else a GFM pipe table. pub const Found = struct { start: usize, end: usize, html: bool }; -/// Every table in the content in order, found by a line scanner (none inside code or math). +/// The content's plain-text lines, allocated in ``a`` (the request arena): markup gone, blank lines dropped. +pub fn plainLines(a: Allocator, content: []const u8) Allocator.Error![][]const u8 { + var out: std.ArrayList([]const u8) = .empty; + var sc: Scanner = .{ .src = content }; + while (sc.next()) |item| switch (item) { + .text => |line| try keep(a, &out, try textLine(a, line), true), + .verbatim => |line| try keep(a, &out, try a.dupe(u8, line), false), + .table => |f| if (f.html) try htmlRows(a, &out, content[f.start..f.end]) else try pipeRows(a, &out, content[f.start..f.end]), + }; + return out.toOwnedSlice(a); +} + +/// Every table in the content in order, found by the scanner ``plainLines`` uses (none inside code or math). pub fn tables(a: Allocator, content: []const u8) Allocator.Error![]Found { var out: std.ArrayList(Found) = .empty; var sc: Scanner = .{ .src = content }; - while (sc.next()) |f| try out.append(a, f); + while (sc.next()) |item| switch (item) { + .table => |f| try out.append(a, f), + else => {}, + }; return out.toOwnedSlice(a); } @@ -34,7 +49,7 @@ pub fn pipeTable(a: Allocator, table: []const u8) html.ParseError!html.Table { var cs = Cells.init(row); // GFM: a short row is padded, cells past the header's count are dropped for (0..cols) |c| { // the cell's own text: math keeps its dollars, as the HTML cell it came from held them - const text = if (cs.next()) |cell| try cellText(a, cell) else try a.alloc(u8, 0); + const text = if (cs.next()) |cell| try cellText(a, cell, true) else try a.alloc(u8, 0); cells[done] = .{ .text = text, .row = @intCast(r), .col = @intCast(c), .rows = 1, .cols = 1, .head = r == 0 }; done += 1; } @@ -42,6 +57,98 @@ pub fn pipeTable(a: Allocator, table: []const u8) html.ParseError!html.Table { return .{ .rows = @intCast(rows.items.len), .cols = @intCast(cols), .cells = cells, .spanned = false }; } +fn keep(a: Allocator, out: *std.ArrayList([]const u8), line: []u8, trimmed: bool) Allocator.Error!void { + const t = std.mem.trim(u8, line, " \t"); + if (t.len == 0) return a.free(line); + try out.append(a, if (trimmed) t else line); +} + +/// One ordinary line: heading markers dropped, a list marker kept, the rest through the inline cleaner. +fn textLine(a: Allocator, raw: []const u8) Allocator.Error![]u8 { + var t = trim(raw); + if (heading(t)) |rest| t = rest; + const marker = listMarker(t); + const body = try clean(a, t[marker.len..], 0, false); + defer a.free(body); + return std.mem.concat(a, u8, &.{ marker, body }); +} + +/// The heading text after 1-6 `#` and a space, its closing `#` run removed; null when the line is no ATX heading. +fn heading(t: []const u8) ?[]const u8 { + var n: usize = 0; + while (n < t.len and t[n] == '#') n += 1; + if (n == 0 or n > 6 or (n < t.len and t[n] != ' ' and t[n] != '\t')) return null; + var rest = trim(t[n..]); + const close = std.mem.trimEnd(u8, rest, "#"); + if (close.len == 0) return ""; + if (close.len < rest.len and (close[close.len - 1] == ' ' or close[close.len - 1] == '\t')) rest = trim(close); + return rest; +} + +/// A leading `-`, `*`, `+` or `1.`/`1)` list marker with its space (kept: it is on the page), or "". +fn listMarker(t: []const u8) []const u8 { + if (t.len >= 2 and std.mem.indexOfScalar(u8, "-*+", t[0]) != null and (t[1] == ' ' or t[1] == '\t')) return t[0..2]; + var n: usize = 0; + while (n < t.len and n < 9 and std.ascii.isDigit(t[n])) n += 1; + if (n > 0 and n + 1 < t.len and (t[n] == '.' or t[n] == ')') and (t[n + 1] == ' ' or t[n + 1] == '\t')) return t[0 .. n + 2]; + return ""; +} + +fn pipeRows(a: Allocator, out: *std.ArrayList([]const u8), table: []const u8) Allocator.Error!void { + var it = std.mem.splitScalar(u8, table, '\n'); + var row: usize = 0; + while (it.next()) |raw| : (row += 1) { + if (row == 1) continue; // the delimiter row + var line: std.ArrayList(u8) = .empty; + defer line.deinit(a); + var cells = Cells.init(trim(raw)); + var first = true; + while (cells.next()) |cell| : (first = false) { + if (!first) try line.append(a, '\t'); + const text = try cellText(a, cell, false); + defer a.free(text); + try line.appendSlice(a, text); + } + try keep(a, out, try line.toOwnedSlice(a), false); + } +} + +/// An HTML table's rows through ``ocr_html``; one it cannot parse is read as ordinary lines instead. +fn htmlRows(a: Allocator, out: *std.ArrayList([]const u8), table: []const u8) Allocator.Error!void { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const parsed = html.parse(arena.allocator(), table) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Malformed => { + var it = std.mem.splitScalar(u8, table, '\n'); + while (it.next()) |line| try keep(a, out, try textLine(a, line), true); + return; + }, + }; + // per cell, before the cells join: a `$` never pairs across cells, as in a pipe row + for (parsed.cells) |*c| c.text = try withoutMath(arena.allocator(), c.text); + for (try html.rowsText(arena.allocator(), parsed)) |row| try keep(a, out, try a.dupe(u8, row), false); +} + +/// HTML cell text as line replies carry it: literal (no Markdown escapes), only math losing its `$`/`$$`. +fn withoutMath(a: Allocator, text: []const u8) Allocator.Error![]const u8 { + if (std.mem.indexOfScalar(u8, text, '$') == null) return text; + var out: std.ArrayList(u8) = .empty; + var no_close = false; // the pairing rule of a pipe cell's math (``mathSpan``), so both table forms read alike + var i: usize = 0; + while (i < text.len) { + if (text[i] != '$') { + try out.append(a, text[i]); + i += 1; + continue; + } + const span = mathSpan(text, i, &no_close); + try out.appendSlice(a, span.body); + i = span.end; + } + return out.items; +} + /// The cells of one pipe-table row, its outer pipes dropped; as cmark-gfm, a `|` right after a `\` is escaped. const Cells = struct { rest: ?[]const u8, @@ -75,7 +182,7 @@ const Cells = struct { }; /// One pipe-table cell's text: GFM drops the backslash before each `|` (in code and math too), then inline rules. -fn cellText(a: Allocator, cell: []const u8) Allocator.Error![]u8 { +fn cellText(a: Allocator, cell: []const u8, keep_math: bool) Allocator.Error![]u8 { const t = trim(cell); const bare = try a.alloc(u8, t.len); defer a.free(bare); @@ -85,7 +192,7 @@ fn cellText(a: Allocator, cell: []const u8) Allocator.Error![]u8 { bare[n] = ch; n += 1; } - return clean(a, bare[0..n], 0); + return clean(a, bare[0..n], 0, keep_math); } /// GFM's table rule (cmark-gfm `escaped_char = [\\][|]`): the `|` at ``s[i]`` is escaped when `\` is right before it. @@ -104,7 +211,10 @@ fn trim(s: []const u8) []const u8 { return std.mem.trim(u8, s, " \t\r"); } -/// A line scanner over docs/api.md OCR: Reader Markdown that yields the tables outside fenced code and `$$` blocks. +/// What the scanner yields: an ordinary line, a code or math line kept as written, or a table's byte range. +const Item = union(enum) { text: []const u8, verbatim: []const u8, table: Found }; + +/// A line scanner over docs/api.md OCR: Reader Markdown: fenced code, `$$` blocks, HTML and pipe tables, other lines. const Scanner = struct { src: []const u8, pos: usize = 0, @@ -125,18 +235,26 @@ const Scanner = struct { return @intFromPtr(part.ptr) - @intFromPtr(s.src.ptr); } - fn next(s: *Scanner) ?Found { + fn next(s: *Scanner) ?Item { while (s.pos < s.src.len) { const l = s.lineAt(s.pos); const t = trim(l.text); s.pos = l.next; if (s.fence) |f| { - if (t.len >= f.len and std.mem.allEqual(u8, t, f.ch)) s.fence = null; - continue; + if (t.len >= f.len and std.mem.allEqual(u8, t, f.ch)) { + s.fence = null; + continue; + } + return .{ .verbatim = l.text }; } if (s.math) { - if (std.mem.endsWith(u8, t, "$$")) s.math = false; - continue; + if (std.mem.endsWith(u8, t, "$$")) { + s.math = false; + const inner = trim(t[0 .. t.len - 2]); + if (inner.len > 0) return .{ .verbatim = inner }; + continue; + } + return .{ .verbatim = t }; } if (fenceOpen(t)) |f| { s.fence = .{ .ch = t[0], .len = f }; @@ -144,14 +262,15 @@ const Scanner = struct { } if (std.mem.startsWith(u8, t, "$$")) { const rest = t[2..]; - if (!std.mem.endsWith(u8, rest, "$$")) s.math = true; - continue; + if (std.mem.endsWith(u8, rest, "$$")) return .{ .verbatim = trim(rest[0 .. rest.len - 2]) }; + s.math = true; + return .{ .verbatim = trim(rest) }; } if (startsHtmlTable(t) and !s.no_table_close) { const start = s.offset(t); if (indexOfIgnoreCase(s.src, start, "
")) |close| { s.pos = close + "".len; - return .{ .start = start, .end = s.pos, .html = true }; + return .{ .table = .{ .start = start, .end = s.pos, .html = true } }; } s.no_table_close = true; } @@ -168,9 +287,10 @@ const Scanner = struct { end = r.next; } s.pos = end; - return .{ .start = s.offset(t), .end = last, .html = false }; + return .{ .table = .{ .start = s.offset(t), .end = last, .html = false } }; } } + return .{ .text = l.text }; } return null; } @@ -218,8 +338,8 @@ const max_depth = 4; /// One emphasis delimiter run in the output: where it sits, its length, what it may do and how much a match removed. const Run = struct { at: usize, len: usize, ch: u8, open: bool, close: bool, left: usize, remove: usize = 0 }; -/// Inline markup removed: emphasis, code ticks, link syntax, escapes, entities; math kept as written, dollars too. -fn clean(a: Allocator, s: []const u8, depth: u8) Allocator.Error![]u8 { +/// Inline markup removed: emphasis, code ticks, math dollars (unless ``keep_math``), link syntax, escapes, entities. +fn clean(a: Allocator, s: []const u8, depth: u8, keep_math: bool) Allocator.Error![]u8 { var out: std.ArrayList(u8) = .empty; defer out.deinit(a); var runs: std.ArrayList(Run) = .empty; @@ -239,12 +359,12 @@ fn clean(a: Allocator, s: []const u8, depth: u8) Allocator.Error![]u8 { i = span.end; } else if (ch == '$') { const span = mathSpan(s, i, &no_dollar_close); - try out.appendSlice(a, s[i..span.end]); + try out.appendSlice(a, if (keep_math) s[i..span.end] else span.body); i = span.end; } else if ((ch == '[' or (ch == '!' and i + 1 < s.len and s[i + 1] == '[')) and depth < max_depth) { const open = if (ch == '!') i + 1 else i; if (link(s, pairs, open)) |l| { - const text = try clean(a, l.text, depth + 1); + const text = try clean(a, l.text, depth + 1, keep_math); defer a.free(text); try out.appendSlice(a, text); i = l.end; diff --git a/zig/src/server/ocr/markdown_test.zig b/zig/src/server/ocr/markdown_test.zig index cf04a8e2b03..121369d7aa7 100644 --- a/zig/src/server/ocr/markdown_test.zig +++ b/zig/src/server/ocr/markdown_test.zig @@ -1,14 +1,90 @@ -//! The table finder and the pipe-table reader over the reader Markdown subset (docs/api.md OCR: Reader Markdown). +//! Markdown to plain-text lines over the reader Markdown subset, and the table finder (docs/api.md OCR: Estimates). const std = @import("std"); const md = @import("markdown.zig"); const t = std.testing; -/// ``cell`` as the one body cell of a pipe table, read back: its text after the inline clean-up. -fn cellBack(a: std.mem.Allocator, cell: []const u8) ![]const u8 { - const table = try std.mem.concat(a, u8, &.{ "| h |\n| --- |\n| ", cell, " |" }); - const back = try md.pipeTable(a, table); - try t.expectEqual(@as(u32, 2), back.rows); - return back.cells[1].text; +fn expectLines(content: []const u8, want: []const []const u8) !void { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const got = try md.plainLines(arena.allocator(), content); + if (got.len != want.len) { + std.debug.print("want {d} lines, got {d}:\n", .{ want.len, got.len }); + for (got) |l| std.debug.print(" [{s}]\n", .{l}); + return error.TestExpectedEqual; + } + for (want, got) |w, g| try t.expectEqualStrings(w, g); +} + +test "ocr markdown: heading markers are removed" { + try expectLines("# Title", &.{"Title"}); + try expectLines("## Section two ##", &.{"Section two"}); + try expectLines("###### Six", &.{"Six"}); + try expectLines("####### seven is text", &.{"####### seven is text"}); + try expectLines("#hashtag and C#", &.{"#hashtag and C#"}); + try expectLines("## **Bold** heading", &.{"Bold heading"}); +} + +test "ocr markdown: emphasis markers are removed, literal stars and underscores kept" { + try expectLines("**bold** and *it* and _u_ and __s__ and ***both***", &.{"bold and it and u and s and both"}); + try expectLines("snake_case_name stays", &.{"snake_case_name stays"}); + try expectLines("5 * 3 = 15", &.{"5 * 3 = 15"}); + try expectLines("an *unclosed star", &.{"an *unclosed star"}); + try expectLines("a **nested *inner* run** ends", &.{"a nested inner run ends"}); + try expectLines("escaped \\*not emphasis\\*", &.{"escaped *not emphasis*"}); +} + +test "ocr markdown: inline code keeps its text without ticks" { + try expectLines("use `a*b_c` here", &.{"use a*b_c here"}); + try expectLines("double `` a ` b `` ticks", &.{"double a ` b ticks"}); + try expectLines("an `unclosed tick", &.{"an `unclosed tick"}); +} + +test "ocr markdown: links and images keep their text" { + try expectLines("see [the *docs*](http://x/y_(z)) now", &.{"see the docs now"}); + try expectLines("![alt text](img.png)", &.{"alt text"}); + try expectLines("a [1] reference and [x] (y) stay", &.{"a [1] reference and [x] (y) stay"}); + try expectLines("a <b> & é€", &.{"a & é€"}); +} + +test "ocr markdown: list markers are kept" { + try expectLines("- item **one**\n* star\n+ plus\n1. first\n12) twelfth", &.{ "- item one", "* star", "+ plus", "1. first", "12) twelfth" }); + try expectLines(" - indented", &.{"- indented"}); +} + +test "ocr markdown: fenced code keeps its lines verbatim" { + try expectLines("before\n```zig\nconst x = *y_z*;\n\n indented `tick`\n```\nafter", &.{ "before", "const x = *y_z*;", " indented `tick`", "after" }); + try expectLines("~~~~\n| not | a |\n|---|---|\n~~~~", &.{ "| not | a |", "|---|---|" }); + try expectLines("```inline code``` stays text", &.{"inline code stays text"}); +} + +test "ocr markdown: math keeps its LaTeX without dollars" { + try expectLines("$$\nE = mc^2\n\\frac{a}{b}\n$$", &.{ "E = mc^2", "\\frac{a}{b}" }); + try expectLines("$$x^2 + y_1$$", &.{"x^2 + y_1"}); + try expectLines("$$ a_1\nb_2 $$", &.{ "a_1", "b_2" }); + try expectLines("area $\\pi r^2$ and $$\\sum_i x_i$$ here", &.{"area \\pi r^2 and \\sum_i x_i here"}); + try expectLines("costs $5 and $10 today", &.{"costs $5 and $10 today"}); +} + +test "ocr markdown: a pipe table is one line a row, cells joined by tabs" { + try expectLines("| A | B |\n| --- | :-: |\n| 1 | **2** |\n| | x \\| y |", &.{ "A\tB", "1\t2", "\tx | y" }); + try expectLines("Name | Qty\n-|-\napple | 3\n\nafter", &.{ "Name\tQty", "apple\t3", "after" }); + try expectLines("| a <b | c |\n| --- | --- |", &.{"a Head\nab & c", + &.{ "Head\t", "a\tb & c" }, + ); + try expectLines("\n\n
x1
2
tail", &.{ "x\t1", "\t2", "tail" }); +} + +test "ocr markdown: lines empty after trimming are dropped" { + try expectLines("a\n\n \n\t\nb\r\n \t \n", &.{ "a", "b" }); + try expectLines("", &.{}); + try expectLines("# \n- ", &.{"-"}); } test "ocr markdown: tables are found as byte ranges, none inside code" { @@ -26,24 +102,8 @@ test "ocr markdown: tables are found as byte ranges, none inside code" { try t.expectEqual(@as(usize, 0), (try md.tables(arena.allocator(), "no tables | here\njust text")).len); } -test "ocr markdown: a pipe cell loses emphasis, code ticks and link syntax, keeping literal stars and underscores" { - var arena = std.heap.ArenaAllocator.init(t.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const Case = struct { []const u8, []const u8 }; - for ([_]Case{ - .{ "**bold** and *it* and _u_ and __s__ and ***both***", "bold and it and u and s and both" }, - .{ "snake_case_name stays", "snake_case_name stays" }, - .{ "5 * 3 = 15", "5 * 3 = 15" }, - .{ "an *unclosed star", "an *unclosed star" }, - .{ "a **nested *inner* run** ends", "a nested inner run ends" }, - .{ "escaped \\*not emphasis\\*", "escaped *not emphasis*" }, - .{ "use `a*b_c` here", "use a*b_c here" }, - .{ "double `` a ` b `` ticks", "double a ` b ticks" }, - .{ "an `unclosed tick", "an `unclosed tick" }, - .{ "see [the *docs*](http://x/y_(z)) now", "see the docs now" }, - .{ "![alt text](img.png)", "alt text" }, - }) |c| try t.expectEqualStrings(c[1], try cellBack(a, c[0])); +test "ocr markdown: an HTML table that does not parse is read as text" { + try expectLines("\n
\nafter", &.{ "", "
", "after" }); } test "ocr markdown: many unclosed dollars and tables stay literal in one pass" { @@ -52,7 +112,9 @@ test "ocr markdown: many unclosed dollars and tables stay literal in one pass" { const a = arena.allocator(); var line: std.ArrayList(u8) = .empty; for (0..40_000) |_| try line.appendSlice(a, "$x \n"); try t.expectEqual(@as(usize, 0), (try md.tables(a, tables.items)).len); @@ -64,17 +126,21 @@ test "ocr markdown: many unmatched brackets and ampersands stay literal in one p const a = arena.allocator(); // 100k `[`, then `[a](` with a `(` that never closes, then `&` with no `;` near it const units = [_][]const u8{ "[", "[a](", "&", "& x" }; + var content: std.ArrayList(u8) = .empty; for (units) |unit| { - var cell: std.ArrayList(u8) = .empty; - for (0..100_000) |_| try cell.appendSlice(a, unit); - try t.expectEqualStrings(std.mem.trim(u8, cell.items, " "), try cellBack(a, cell.items)); + for (0..100_000) |_| try content.appendSlice(a, unit); + try content.append(a, '\n'); } + const got = try md.plainLines(a, content.items); + try t.expectEqual(units.len, got.len); + var it = std.mem.splitScalar(u8, content.items, '\n'); + for (got) |l| try t.expectEqualStrings(std.mem.trim(u8, it.next().?, " "), l); // links still pair across nesting and escapes after the one-pass change - try t.expectEqualStrings("a b d [x](y) p", try cellBack(a, "[a [b](c) d](e) \\[x](y) [p](q(r)s)")); - try t.expectEqualStrings("\u{1F600} &< &abcdefghij;", try cellBack(a, "😀 &< &abcdefghij;")); + try expectLines("[a [b](c) d](e) \\[x](y) [p](q(r)s)", &.{"a b d [x](y) p"}); + try expectLines("😀 &< &abcdefghij;", &.{"\u{1F600} &< &abcdefghij;"}); } -test "ocr markdown: table cell text survives the pipe form, read back as HTML" { +test "ocr markdown: table cell text survives the pipe form, as lines and read back as HTML" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -84,6 +150,10 @@ test "ocr markdown: table cell text survives the pipe form, read back as HTML" { for (&cells, texts, 0..) |*c, text, k| c.* = .{ .text = text, .row = 0, .col = @intCast(k), .rows = 1, .cols = 1, .head = true }; const table: html.Table = .{ .rows = 1, .cols = texts.len, .cells = &cells, .spanned = false }; const md_table = try html.pipe(a, table); + // the line dialects: each cell's literal text, math without its dollars (docs/api.md OCR: Estimates) + const lines = try md.plainLines(a, md_table); + try t.expectEqual(@as(usize, 1), lines.len); + try t.expectEqualStrings("[x](y)\ta\\|b\t*not bold*\t`tick`\tback\\slash\tsnake_case _x_\tx_{1}|y and a*b\tcosts $5\ta Date: Sat, 21 Nov 2026 15:47:03 +0000 Subject: [PATCH 050/361] feat(ocr): POST /ocr in LiteParse's HTTP OCR contract LiteParse's --ocr-server-url sends one page image as a multipart file part and reads text items with boxes in the image's pixels, so POST /ocr now chooses its contract from ?format=, the media type and the part names, and answers LiteParse with one result a line: text, an axis-aligned bbox and confidence 1.0, the fields LiteParse's published OCR API spec defines. A reader without boxes and a PDF are refused, files parts are refused on every path rather than dropped, a repeated format is refused, and the client's captured request is replayed. Refusals made before the contract is known use the OpenAI envelope, and a model without a reader or a server without --vision gives the gate's refusal on every path. --- zig/src/core/engine_api.zig | 2 +- zig/src/hip_serve/offer.zig | 2 +- zig/src/server/auth_scope.zig | 8 +- zig/src/server/ocr/fixtures/README.md | 1 + .../ocr/fixtures/lit-2514f8e-ocr.multipart | Bin 0 -> 585 bytes zig/src/server/ocr/liteparse.zig | 154 ++++++++++++ zig/src/server/ocr/liteparse_test.zig | 233 ++++++++++++++++++ zig/src/server/ocr/route.zig | 95 ++++++- zig/src/server/ocr/route_test.zig | 137 ++++++++++ zig/src/server/ocr/run.zig | 10 +- zig/src/server/root.zig | 2 + zig/src/server/routes.zig | 4 +- 12 files changed, 631 insertions(+), 17 deletions(-) create mode 100644 zig/src/server/ocr/fixtures/lit-2514f8e-ocr.multipart create mode 100644 zig/src/server/ocr/liteparse.zig create mode 100644 zig/src/server/ocr/liteparse_test.zig create mode 100644 zig/src/server/ocr/route_test.zig diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index af9cf2e24f7..7d351e9cd5a 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -181,7 +181,7 @@ pub const Info = struct { pictures: bool = false, /// Image input (--vision); null: text only. vision: ?Vision = null, - ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr; null: no OCR route + ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr and /ocr; null: no OCR routes /// The engine decodes greedily only: the server refuses a request with a temperature before admitting it. greedy_only: bool = false, /// The learner reads conversation prompts at any length through taps. diff --git a/zig/src/hip_serve/offer.zig b/zig/src/hip_serve/offer.zig index 74ddcc14a95..1793c6eaa1d 100644 --- a/zig/src/hip_serve/offer.zig +++ b/zig/src/hip_serve/offer.zig @@ -18,7 +18,7 @@ pub const Offer = struct { window: ?usize = null, /// Built by the family; null: text only. vision: ?api.Vision = null, - /// The family's OCR reader (/v1/ocr); null: no OCR route. + /// The family's OCR reader (/v1/ocr and /ocr); null: no OCR routes. ocr: ?api.ocr.Ocr = null, /// The family's own store; null whenever its cache is off (no budget or no slots). cache: ?*api.prompt_cache.Store = null, diff --git a/zig/src/server/auth_scope.zig b/zig/src/server/auth_scope.zig index fd353e6cdce..1d0103cf16d 100644 --- a/zig/src/server/auth_scope.zig +++ b/zig/src/server/auth_scope.zig @@ -64,10 +64,10 @@ const inferring = [_][]const u8{ "/responses", "/v1/responses", "/tokenize", "/v1/tokenize", "/detokenize", "/v1/detokenize", "/v1/audio/speech", "/v1/embeddings", "/v1/images/generations", "/decisions", "/v1/decisions", "/systemone", - "/v1/systemone", "/rerank", "/v1/rerank", "/v1/ocr", - "/v2/rerank", "/score", "/v1/score", "/api/chat", - "/api/generate", "/api/embed", "/api/show", "/apply-template", - "/v1/apply-template", + "/v1/systemone", "/rerank", "/v1/rerank", "/ocr", + "/v1/ocr", "/v2/rerank", "/score", "/v1/score", + "/api/chat", "/api/generate", "/api/embed", "/api/show", + "/apply-template", "/v1/apply-template", }; /// A gated request a key may make: the route as the dispatcher reads it, matched exactly, never by suffix. diff --git a/zig/src/server/ocr/fixtures/README.md b/zig/src/server/ocr/fixtures/README.md index 4271d7e1857..e3be2900dca 100644 --- a/zig/src/server/ocr/fixtures/README.md +++ b/zig/src/server/ocr/fixtures/README.md @@ -3,3 +3,4 @@ Request bodies captured byte for byte from the unmodified clients by a local recording server that replied a canned 200. - `mistral-python-3.7.0-ocr-image.json`: `mistralai` 3.7.0 (Python 3.12, `MISTRAL_API_KEY` unset), `Mistral(server_url=URL).ocr.process(model="mistral-ocr-latest", document={"type": "image_url", "image_url": "data:image/png;base64,..."}, include_image_base64=True)` on a 48x24 RGB PNG; `POST /v1/ocr`, `Content-Type: application/json`, `Accept: application/json`, `user-agent: mistral-client-python/3.7.0`. +- `lit-2514f8e-ocr.multipart`: LiteParse 2514f8e (`cargo build --release -p liteparse --bin lit`), `lit parse --ocr-server-url http://127.0.0.1:PORT/ocr --num-workers 1 --format json page.png` on the same PNG; `POST /ocr`, `Content-Type: multipart/form-data; boundary=58d2094fd455366b-9209308a2fdfd403-4cb870f78f225bb5-840e3d54fef15603`, `accept: */*`. diff --git a/zig/src/server/ocr/fixtures/lit-2514f8e-ocr.multipart b/zig/src/server/ocr/fixtures/lit-2514f8e-ocr.multipart new file mode 100644 index 0000000000000000000000000000000000000000..68ddf57bbea1720707e483604c18e7c0be1b7042 GIT binary patch literal 585 zcmdPZHMK}FGO#pBOEEDuH8wL#(zOI~jSVakjnYzpf(FLACdo+_<_2lz7HLLCrb$Vr zx)vq|sm3X$CTXc@hNfl)#=Kn4`FSO&c_q3onZ*V9#hE3U`FU0fY57IDx+#eziPj2v ziMgq^N@Yq!q6y8hO)dV!|@ksSZh6@SccJ;m(tDE_3`|A|ok zgL*N9B!siVrXly=?7*M=UoGcsYUJAJU{KKNe;!fDF+Y|jDV zedym;%CCQO^_RUs$1-@j`njxgN@(Kc(xqnv$mjZ(v7~H&Esi456iuJm>yj%b= C+s()T literal 0 HcmV?d00001 diff --git a/zig/src/server/ocr/liteparse.zig b/zig/src/server/ocr/liteparse.zig new file mode 100644 index 00000000000..f3e4ec60b35 --- /dev/null +++ b/zig/src/server/ocr/liteparse.zig @@ -0,0 +1,154 @@ +//! POST /ocr in LiteParse's HTTP OCR contract: a page image in, a text item a line out (docs/api.md OCR: LiteParse). +const std = @import("std"); +const Allocator = std.mem.Allocator; +const api = @import("engine_api"); +const json = @import("json"); +const picture = @import("core").picture; +const images = @import("../images.zig"); +const multipart = @import("../multipart.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Server = @import("../server.zig").Server; +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const geometry = @import("geometry.zig"); +const lines = @import("lines.zig"); +const run = @import("run.zig"); +const route = @import("route.zig"); +const Value = json.Value; +const Quad = api.ocr.Quad; +const Fault = types.Fault; +const Step = run.Step; + +/// The refusal for a reader without boxes: a whole-page box would place no text on the page. +pub const no_boxes = "this model gives no text boxes; LiteParse needs them"; +/// The refusal for a PDF: LiteParse's OCR API spec sends an image file in the `file` field. +pub const no_pdf = "LiteParse sends page images; send the page as a PNG, JPEG or WebP file, not a PDF"; + +/// Answers one LiteParse request whose body has been read; ``parts`` is null when ``?format=`` chose the dialect. +pub fn post(srv: *Server, conn: *Conn, a: Allocator, parts: ?[]const multipart.Part, content_type: ?[]const u8, body: []const u8, gone: anytype) void { + var fault: Fault = .{ .class = .internal, .message = "" }; + const out = handle(srv, a, parts, content_type, body, gone, &fault) catch |e| switch (e) { + error.Faulted => return sendFault(conn, a, fault), + error.OutOfMemory => return sendFault(conn, a, .{ .class = .internal, .message = "out of memory" }), + error.Cancelled => { + conn.close = true; + return; + }, + }; + conn.sendJson(200, out); +} + +fn handle(srv: *Server, a: Allocator, parts: ?[]const multipart.Part, content_type: ?[]const u8, body: []const u8, gone: anytype, fault: *Fault) Step![]const u8 { + try run.gate(srv, a, fault); + const geo = srv.info.ocr.?.geometry; + if (geo == .none) return fault.fail(a, .bad_input, "{s}", .{no_boxes}); + const source = try decode(a, parts orelse try parseParts(a, content_type, body, fault), fault); + var enc: Encoder = .{ .geometry = geo }; + try run.run(srv, a, &.{source}, enc.sink(), fault, gone); + return enc.reply(a); +} + +/// The multipart parts of a body whose dialect the ``format`` query chose. +fn parseParts(a: Allocator, content_type: ?[]const u8, body: []const u8, fault: *Fault) Step![]const multipart.Part { + const ct = content_type orelse ""; + const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t"); + if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) return fault.fail(a, .bad_input, "LiteParse sends multipart/form-data with one file part", .{}); + const bound = multipart.boundary(ct) orelse return fault.fail(a, .bad_input, "multipart/form-data needs a boundary parameter", .{}); + return multipart.parse(a, body, bound) catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Malformed => fault.fail(a, .bad_input, "the multipart body is malformed", .{}), + }; +} + +/// The one ``file`` part as an image source; ``language`` and other parts are ignored (no reader takes a hint). +pub fn decode(a: Allocator, parts: []const multipart.Part, fault: *Fault) Step!types.Source { + if (route.hasFiles(parts)) return fault.fail(a, .bad_input, "{s}", .{route.files_parts}); + var file: ?multipart.Part = null; + for (parts) |p| if (std.mem.eql(u8, p.name, "file")) { + if (file != null) return fault.fail(a, .bad_input, "a LiteParse request has exactly one file part", .{}); + file = p; + }; + const f = file orelse return fault.fail(a, .bad_input, "a LiteParse request has exactly one file part", .{}); + if (f.body.len == 0) return fault.fail(a, .bad_input, "the file part is empty", .{}); + // the image signature first: a PNG text chunk or a JPEG comment may hold "%PDF-" + switch (images.sniff(f.body)) { + .png, .jpeg, .webp => {}, + else => { + if (std.mem.indexOf(u8, f.body[0..@min(f.body.len, 1024)], "%PDF-") != null) return fault.fail(a, .bad_input, "{s}", .{no_pdf}); + return fault.fail(a, .bad_input, "the file is not a PNG, JPEG or WebP image", .{}); + }, + } + return .{ .bytes = f.body, .kind = .image, .sel = .{ .all_within = 1 } }; +} + +/// The page sink: each line of the page as one LiteParse result. +pub const Encoder = struct { + geometry: api.ocr.Geometry, + results: std.ArrayList(Value) = .empty, + + pub fn sink(e: *Encoder) run.PageSink { + return .{ .ctx = e, .page = onPage }; + } + + fn onPage(ctx: *anyopaque, a: Allocator, page: *const types.OcrPage, _: picture.Rgb, _: *budget.Encodes, fault: *Fault) Step!void { + const e: *Encoder = @ptrCast(@alignCast(ctx)); + const got = lines.fromBlocks(a, page, e.geometry) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Unreadable => return fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{page.index}), + }; + for (got) |l| try e.results.append(a, try result(a, l.text, l.quad, page.width, page.height)); + } + + /// ``{"results": [...]}``, an empty list for a page without text. + pub fn reply(e: *Encoder, a: Allocator) Allocator.Error![]const u8 { + const o = try json.newObject(a); + try o.put(a, "results", .{ .array = e.results.items }); + return json.stringify(a, .{ .object = o }, .{}); + } +}; + +/// One result: ``text``, ``bbox`` (min/max) and ``confidence`` 1.0; the spec's optional ``polygon`` is never sent. +pub fn result(a: Allocator, text: []const u8, quad: ?Quad, w: u32, h: u32) Allocator.Error!Value { + // a line without a box is unreachable here (a .none reader is refused); it would cover the page + const q = quad orelse Quad{ .{ 0, 0 }, .{ @floatFromInt(w), 0 }, .{ @floatFromInt(w), @floatFromInt(h) }, .{ 0, @floatFromInt(h) } }; + const b = geometry.minMax(q); + const bbox = try a.alloc(Value, 4); + for (b, bbox) |x, *v| v.* = number(x); + const o = try json.newObject(a); + try o.put(a, "text", .{ .string = text }); + try o.put(a, "bbox", .{ .array = bbox }); + try o.put(a, "confidence", .{ .float = 1.0 }); // the spec: "If your OCR engine doesn't provide confidence, use 1.0" + return .{ .object = o }; +} + +/// A coordinate as its shortest f32 decimal (33.333332, not 33.33333206176758). +fn number(x: f32) Value { + var buf: [32]u8 = undefined; + const text = std.fmt.bufPrint(&buf, "{d}", .{x}) catch return .{ .float = x }; + return .{ .float = std.fmt.parseFloat(f64, text) catch x }; +} + +/// A fault's HTTP status: 400, 422, 503 or 500 (docs/api.md OCR: Failures; the spec names 400 and 500). +pub fn status(class: types.Class) u16 { + return switch (class) { + .bad_input => 400, + .unreadable => 422, + .capacity => 503, + .internal => 500, + }; +} + +/// ``{"error": msg}`` with the fault's status, the error format of LiteParse's OCR API spec. +pub fn sendFault(conn: *Conn, a: Allocator, fault: Fault) void { + const body = errorBody(a, fault.message) catch return conn.sendJson(500, "{\"error\": \"out of memory\"}"); + if (fault.class != .capacity) return conn.sendJson(status(fault.class), body); + var buf: [16]u8 = undefined; + const retry = std.fmt.bufPrint(&buf, "{d}", .{fault.retry_after orelse 1}) catch unreachable; + conn.sendJsonWith(status(fault.class), body, &.{.{ "Retry-After", retry }}); +} + +pub fn errorBody(a: Allocator, message: []const u8) Allocator.Error![]const u8 { + const o = try json.newObject(a); + try o.put(a, "error", .{ .string = message }); + return json.stringify(a, .{ .object = o }, .{}); +} diff --git a/zig/src/server/ocr/liteparse_test.zig b/zig/src/server/ocr/liteparse_test.zig new file mode 100644 index 00000000000..753ef2d57b1 --- /dev/null +++ b/zig/src/server/ocr/liteparse_test.zig @@ -0,0 +1,233 @@ +//! LiteParse on POST /ocr: results as its published OCR API spec gives them, the file part, replies and errors. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const multipart = @import("../multipart.zig"); +const routes = @import("../routes.zig"); +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const run = @import("run.zig"); +const lp = @import("liteparse.zig"); +const route = @import("route.zig"); +const harness = @import("harness_test.zig"); +const Harness = harness.Harness; +const t = std.testing; +const Allocator = std.mem.Allocator; +const Quad = api.ocr.Quad; + +fn rect(x0: f32, y0: f32, x1: f32, y1: f32) Quad { + return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } }; +} + +test "ocr liteparse: a result has text, a float min/max bbox and confidence 1.0, and never a polygon" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const r = try lp.result(a, "Total\t12", .{ .{ 140, 45 }, .{ 30, 45 }, .{ 30, 15 }, .{ 140, 15 } }, 200, 100); + try t.expectEqualStrings("Total\t12", r.strField("text").?); + const bbox = r.get("bbox").?.array; + for (bbox, [_]f64{ 30, 15, 140, 45 }) |v, want| try t.expectEqual(want, v.float); + try t.expectEqual(@as(f64, 1.0), r.get("confidence").?.float); + const text = try json.stringify(a, r, .{}); + // a 180-degree quad and a tall band alike: bbox only, as the spec allows (polygon is optional) + try t.expectEqualStrings("{\"text\": \"Total\\t12\", \"bbox\": [30.0, 15.0, 140.0, 45.0], \"confidence\": 1.0}", text); + try t.expect((try lp.result(a, "tall", rect(10, 10, 20, 90), 200, 100)).get("polygon") == null); + // a coordinate is written as its shortest f32 decimal + const third = try lp.result(a, "y", rect(0, 0, 100.0 / 3.0, 5), 200, 100); + try t.expectEqual(@as(f64, 33.333332), third.get("bbox").?.array[2].float); +} + +fn part(name: []const u8, body: []const u8) multipart.Part { + return .{ .name = name, .filename = "image.png", .content_type = "image/png", .media = "image/png", .body = body }; +} + +test "ocr liteparse: the one file part is the page; a PDF, an empty or unknown file and two files are refused" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fault: types.Fault = undefined; + const png = try harness.png(a, 4, 3); + const s = try lp.decode(a, &.{ part("language", "en"), part("file", png), part("other", "x") }, &fault); + try t.expectEqual(.image, s.kind); + try t.expectEqual(png.len, s.bytes.len); + const cases = [_]struct { []const multipart.Part, []const u8 }{ + .{ &.{part("file", "%PDF-1.7\n...")}, lp.no_pdf }, + .{ &.{part("file", "")}, "the file part is empty" }, + .{ &.{part("file", "GIF89a....")}, "the file is not a PNG, JPEG or WebP image" }, + .{ &.{ part("file", png), part("file", png) }, "a LiteParse request has exactly one file part" }, + // a files part is refused, never dropped: this server reads only LiteParse's file part + .{ &.{part("files", png)}, route.files_parts }, + .{ &.{ part("file", png), part("files", png) }, route.files_parts }, + }; + for (cases) |c| { + try t.expectError(error.Faulted, lp.decode(a, c[0], &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + try t.expectEqualStrings(c[1], fault.message); + } +} + +test "ocr liteparse: a page without text gives an empty results list, and faults map to 400, 422, 503 and 500" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var enc: lp.Encoder = .{ .geometry = .block }; + const sink = enc.sink(); + var pixels: [3]u8 = .{ 0, 0, 0 }; + var blocks = [_]api.ocr.OcrBlock{.{ .content = "", .quad = rect(0, 0, 1, 1), .kind = .picture }}; + const page: types.OcrPage = .{ .index = 0, .width = 1, .height = 1, .dpi = 72, .blocks = &blocks }; + var budget_ = budget.Encodes.init(1, 1); + var fault: types.Fault = undefined; + try sink.page(sink.ctx, a, &page, .{ .width = 1, .height = 1, .pixels = &pixels }, &budget_, &fault); + try t.expectEqualStrings("{\"results\": []}", try enc.reply(a)); + const want = [_]struct { types.Class, u16 }{ .{ .bad_input, 400 }, .{ .unreadable, 422 }, .{ .capacity, 503 }, .{ .internal, 500 } }; + for (want) |w| try t.expectEqual(w[1], lp.status(w[0])); + try t.expectEqualStrings("{\"error\": \"no \\\"boxes\\\"\"}", try lp.errorBody(a, "no \"boxes\"")); +} + +const boundary = "XyZ"; +const form = "multipart/form-data; boundary=" ++ boundary; + +/// LiteParse's request: one ``file`` part (image.png) and a ``language`` part. +fn liteBody(a: Allocator, file: []const u8) ![]const u8 { + return std.mem.concat(a, u8, &.{ + "--" ++ boundary ++ "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\nContent-Type: image/png\r\n\r\n", + file, + "\r\n--" ++ boundary ++ "\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\neng\r\n--" ++ boundary ++ "--\r\n", + }); +} + +/// A whole POST through the dispatcher; the wire holds the reply. +fn post(a: Allocator, h: *Harness, path: []const u8, ct: []const u8, body: []const u8) !harness.Wire { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, path, ct, body), a); + try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nContent-Type: application/json\r\n") != null); + return wire; +} + +fn serve(h: *Harness, replies: []const harness.Script) !void { + h.* = .{ .replies = replies }; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); +} + +test "ocr liteparse: a whole request gives one result a line in image pixels, bbox only" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: Harness = undefined; + // the frame is 100 x 50 and the page 200 x 100: the reader's boxes scale by 2 + const page_text = "title 10 5 90 10\n# Report\n;;\ntext 10 20 90 40\nline **one**\nline two\n;;\npicture 10 40 50 48\n\n;;\ntext 60 5 65 45\nnarrow"; + try serve(&h, &.{ .{ .text = page_text }, .{ .text = page_text } }); + defer h.stop(); + const body = try liteBody(a, try harness.png(a, 200, 100)); + for ([_][]const u8{ "/ocr", "/ocr?format=liteparse" }) |path| { + const wire = try post(a, &h, path, form, body); + try t.expectEqual(@as(u16, 200), wire.status()); + const results = (try wire.parsed()).get("results").?.array; + const Want = struct { text: []const u8, bbox: [4]f64 }; + const want = [_]Want{ + .{ .text = "Report", .bbox = .{ 20, 10, 180, 20 } }, + .{ .text = "line one", .bbox = .{ 20, 40, 180, 60 } }, + .{ .text = "line two", .bbox = .{ 20, 60, 180, 80 } }, + .{ .text = "narrow", .bbox = .{ 120, 10, 130, 90 } }, + }; + try t.expectEqual(want.len, results.len); + for (results, want) |r, w| { + try t.expectEqualStrings(w.text, r.strField("text").?); + for (r.get("bbox").?.array, w.bbox) |v, x| try t.expectEqual(x, v.float64().?); + try t.expectEqual(@as(f64, 1.0), r.get("confidence").?.float64().?); + try t.expectEqual(@as(usize, 3), r.object.count()); // text, bbox, confidence + } + } +} + +test "ocr liteparse: refusals answer in {\"error\"} with LiteParse's statuses" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: Harness = undefined; + try serve(&h, &.{ .{ .text = "!not the grammar" }, .{ .text = "text 0 0 1 1\nhalf", .reason = .length }, .{ .text = "", .reason = .cancelled } }); + defer h.stop(); + const png = try harness.png(a, 20, 10); + const body = try liteBody(a, png); + const Case = struct { path: []const u8 = "/ocr", ct: []const u8 = form, body: []const u8, status: u16, says: []const u8 }; + const cases = [_]Case{ + .{ .body = body, .status = 422, .says = "page 0: the model's output does not follow its format" }, + .{ .body = body, .status = 422, .says = "page 0: the model's output was cut at the context limit" }, + .{ .body = body, .status = 503, .says = "the engine stopped the page; retry" }, + .{ .body = try liteBody(a, "%PDF-1.4\n%fake"), .status = 400, .says = lp.no_pdf }, + .{ .path = "/ocr?format=liteparse", .ct = "application/json", .body = "{}", .status = 400, .says = "LiteParse sends multipart/form-data with one file part" }, + }; + for (cases) |c| { + const wire = try post(a, &h, c.path, c.ct, c.body); + try t.expectEqual(c.status, wire.status()); + try t.expectEqualStrings(c.says, (try wire.parsed()).strField("error").?); + if (c.status == 503) try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nRetry-After: 1\r\n") != null); + } + // a reader without boxes, then no reader, then no --vision: 400 before any generation + h.srv.info.ocr = .{ .prompt = "Text Recognition:", .geometry = .none, .parse = h.reader.?.parse }; + var wire = try post(a, &h, "/ocr", form, body); + try t.expectEqual(@as(u16, 400), wire.status()); + try t.expectEqualStrings(lp.no_boxes, (try wire.parsed()).strField("error").?); + h.srv.info.ocr = null; + wire = try post(a, &h, "/ocr", form, body); + try t.expectEqualStrings(run.no_reader, (try wire.parsed()).strField("error").?); + h.srv.info.ocr = h.reader; + h.srv.info.vision = null; + wire = try post(a, &h, "/ocr", form, body); + try t.expectEqual(@as(u16, 400), wire.status()); + try t.expectEqualStrings(run.no_vision, (try wire.parsed()).strField("error").?); + try t.expectEqual(@as(usize, 3), h.next); // the refusals reached no engine +} + +test "ocr liteparse: a PNG whose text chunk says %PDF- is read as the image, not refused as a PDF" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const png = try harness.pngWithPdfText(a, 200, 100); + var fault: types.Fault = undefined; + try t.expectEqual(.image, (try lp.decode(a, &.{part("file", png)}, &fault)).kind); + var h: Harness = undefined; + try serve(&h, &.{.{ .text = "text 10 5 90 10\nhello" }}); + defer h.stop(); + const wire = try post(a, &h, "/ocr", form, try liteBody(a, png)); + try t.expectEqual(@as(u16, 200), wire.status()); + const results = (try wire.parsed()).get("results").?.array; + try t.expectEqual(@as(usize, 1), results.len); + try t.expectEqualStrings("hello", results[0].strField("text").?); +} + +/// LiteParse 2514f8e's own request for a 48 x 24 PNG page, byte for byte (fixtures/README.md), and its boundary. +const lit_body = @embedFile("fixtures/lit-2514f8e-ocr.multipart"); +const lit_form = "multipart/form-data; boundary=58d2094fd455366b-9209308a2fdfd403-4cb870f78f225bb5-840e3d54fef15603"; + +fn isNumber(v: json.Value) bool { + return v == .int or v == .float; +} + +test "ocr liteparse: lit's own request gets the reply LiteParse's OCR API spec defines" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: Harness = undefined; + try serve(&h, &.{.{ .text = "text 4 4 50 20\nHello\n;;\ntext 4 25 96 40\nWorld" }}); + defer h.stop(); + const wire = try post(a, &h, "/ocr", lit_form, lit_body); + try t.expectEqual(@as(u16, 200), wire.status()); + const r = try wire.parsed(); + // OCR_API_SPEC.md (LiteParse 2514f8e): {"results": [{"text", "bbox": [x1, y1, x2, y2], "confidence", "polygon"?}]} + try t.expectEqual(@as(usize, 1), r.object.count()); + const results = r.get("results").?.array; + try t.expectEqual(@as(usize, 2), results.len); + for (results, [_][]const u8{ "Hello", "World" }) |item, text| { + for (item.object.keys()) |k| try t.expect(std.mem.eql(u8, k, "text") or std.mem.eql(u8, k, "bbox") or std.mem.eql(u8, k, "confidence")); + try t.expectEqualStrings(text, item.strField("text").?); + const bbox = item.get("bbox").?.array; + try t.expectEqual(@as(usize, 4), bbox.len); + for (bbox) |v| try t.expect(isNumber(v)); + try t.expect(isNumber(item.get("confidence").?)); + // the spec's bbox: x1 < x2 and y1 < y2 + try t.expect(bbox[0].float64().? < bbox[2].float64().? and bbox[1].float64().? < bbox[3].float64().?); + } + // boxes are in pixels of the 48 x 24 page LiteParse sent (the harness frame is 100 x 50) + try t.expect(results[1].get("bbox").?.array[2].float64().? <= 48); +} diff --git a/zig/src/server/ocr/route.zig b/zig/src/server/ocr/route.zig index 39bb19016d3..083aa66912a 100644 --- a/zig/src/server/ocr/route.zig +++ b/zig/src/server/ocr/route.zig @@ -1,21 +1,102 @@ -//! POST /v1/ocr: the body read once, then Mistral's handler (docs/api.md OCR). -const Allocator = @import("std").mem.Allocator; +//! POST /v1/ocr and POST /ocr: the body read once, the /ocr dialect chosen (docs/api.md OCR), then its handler. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const errors = @import("../errors.zig"); const http_body = @import("../http_body.zig"); +const multipart = @import("../multipart.zig"); +const query = @import("../query.zig"); const openai = @import("../openai.zig"); +const routes = @import("../routes.zig"); const Conn = @import("../http_conn.zig").Conn; const Server = @import("../server.zig").Server; const mistral = @import("mistral.zig"); const mistral_reply = @import("mistral_reply.zig"); +const liteparse = @import("liteparse.zig"); +const run = @import("run.zig"); -/// The handler for POST /v1/ocr. -pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { +/// The client contracts POST /ocr answers in. +pub const Dialect = enum { liteparse }; + +/// A chosen dialect, with the multipart parts when choosing it parsed them. +pub const Selected = struct { dialect: Dialect, parts: ?[]const multipart.Part = null }; + +/// A request no dialect takes: its status and message, sent in the OpenAI error shape. +pub const Refusal = struct { status: u16, message: []const u8 }; + +pub const Selection = union(enum) { ok: Selected, refused: Refusal }; + +/// The handler for both OCR paths; ``route`` is the path as the dispatcher reads it (no query, no trailing slash). +pub fn post(srv: *Server, conn: *Conn, a: Allocator, route: []const u8) void { + const is_mistral = std.mem.eql(u8, route, "/v1/ocr"); const body = switch (http_body.read(conn, a, http_body.limit) catch { conn.close = true; - return mistral_reply.sendFault(conn, a, .{ .class = .internal, .message = "out of memory" }); + if (is_mistral) return mistral_reply.sendFault(conn, a, .{ .class = .internal, .message = "out of memory" }); + return sendOpenAi(conn, a, 500, .server, "out of memory"); }) { .ok => |b| b, - .refused => |message| return mistral.refuseBody(conn, a, message), + .refused => |message| return if (is_mistral) mistral.refuseBody(conn, a, message) else sendOpenAi(conn, a, 400, .request, message), }; const gone: openai.Gone = .{ .conn = conn }; - mistral.post(srv, conn, a, body, gone); + if (is_mistral) return mistral.post(srv, conn, a, body, gone); + const sel = select(a, conn.path, conn.header("Content-Type"), body) catch return sendOpenAi(conn, a, 500, .server, "out of memory"); + switch (sel) { + // a model that cannot read pages says so first, whatever the body: the same refusal as every dialect's gate + .refused => |r| if (run.gateRefusal(srv)) |m| sendOpenAi(conn, a, 400, .request, m) else sendOpenAi(conn, a, r.status, .request, r.message), + .ok => |s| dialect(srv, conn, a, s, body, gone), + } +} + +/// Runs the chosen dialect, which gates the request and answers in its own error shape. +fn dialect(srv: *Server, conn: *Conn, a: Allocator, s: Selected, body: []const u8, gone: openai.Gone) void { + switch (s.dialect) { + .liteparse => liteparse.post(srv, conn, a, s.parts, conn.header("Content-Type"), body, gone), + } +} + +/// The /ocr dialect: ``?format=`` first, then the media type, then the multipart part names (docs/api.md OCR). +pub fn select(a: Allocator, raw_path: []const u8, content_type: ?[]const u8, body: []const u8) Allocator.Error!Selection { + const format = query.get(a, raw_path, "format") catch |e| switch (e) { + error.OutOfMemory => return error.OutOfMemory, + error.Malformed => return refuse(400, "the format query parameter is malformed"), + error.Repeated => return refuse(400, "the format query parameter is repeated; send it once"), + }; + if (format) |f| { + const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be liteparse"); + return .{ .ok = .{ .dialect = d } }; + } + const ct = std.mem.trim(u8, content_type orelse "", " \t"); + if (ct.len == 0) return refuse(415, "the request has no Content-Type; send multipart/form-data (LiteParse)"); + const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t"); + if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) + return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send multipart/form-data (LiteParse)", .{media})); + const bound = multipart.boundary(ct) orelse return refuse(400, "multipart/form-data needs a boundary parameter"); + const parts = multipart.parse(a, body, bound) catch |e| switch (e) { + error.OutOfMemory => return error.OutOfMemory, + error.Malformed => return refuse(400, "the multipart body is malformed"), + }; + if (hasFiles(parts)) return refuse(400, files_parts); + var file: usize = 0; + for (parts) |p| file += @intFromBool(std.mem.eql(u8, p.name, "file")); + if (file == 1) return .{ .ok = .{ .dialect = .liteparse, .parts = parts } }; + return refuse(400, "a multipart OCR request needs exactly one file part (LiteParse)"); +} + +/// The refusal for ``files`` parts: on /ocr this server reads only LiteParse's one ``file`` part, and drops nothing. +pub const files_parts = "a multipart OCR request has files parts, which this server does not read; LiteParse sends one file part"; + +/// Whether ``parts`` hold a ``files`` part; refused on every path, ``?format=`` included. +pub fn hasFiles(parts: []const multipart.Part) bool { + for (parts) |p| if (std.mem.eql(u8, p.name, "files")) return true; + return false; +} + +fn refuse(status: u16, message: []const u8) Selection { + return .{ .refused = .{ .status = status, .message = message } }; +} + +/// ``{"error": {"message", "type"}}`` with ``status``: the shape of refusals made before a dialect is known. +pub fn sendOpenAi(conn: *Conn, a: Allocator, status: u16, kind: errors.Kind, message: []const u8) void { + const cx: errors.Cx = .{ .a = a, .kind = kind, .message = message }; + const body = openai.errorBody(a, &cx, null) catch return conn.sendJson(500, "{\"error\": {\"message\": \"out of memory\"}}"); + routes.sendValue(conn, a, status, openai.wrapError(a, body) catch return conn.sendJson(500, "{\"error\": {\"message\": \"out of memory\"}}")); } diff --git a/zig/src/server/ocr/route_test.zig b/zig/src/server/ocr/route_test.zig new file mode 100644 index 00000000000..95a10896b41 --- /dev/null +++ b/zig/src/server/ocr/route_test.zig @@ -0,0 +1,137 @@ +//! The /ocr dialect choice (docs/api.md OCR) and the refusals sent before a dialect is known. +const std = @import("std"); +const route = @import("route.zig"); +const routes = @import("../routes.zig"); +const auth_scope = @import("../auth_scope.zig"); +const harness = @import("harness_test.zig"); +const run = @import("run.zig"); +const t = std.testing; + +const form = "multipart/form-data; boundary=XyZ"; + +fn parts(a: std.mem.Allocator, names: []const []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (names) |n| try out.print(a, "--XyZ\r\nContent-Disposition: form-data; name=\"{s}\"; filename=\"p.png\"\r\nContent-Type: image/png\r\n\r\nbytes\r\n", .{n}); + try out.appendSlice(a, "--XyZ--\r\n"); + return out.items; +} + +test "ocr route: the format query, then the media type, then the part names choose the dialect" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { path: []const u8 = "/ocr", ct: ?[]const u8, body: []const u8 = "", want: ?route.Dialect, status: u16 = 0 }; + const cases = [_]Case{ + .{ .path = "/ocr?format=liteparse", .ct = "application/json", .want = .liteparse }, + .{ .path = "/ocr?x=1&format=liteparse", .ct = null, .want = .liteparse }, + .{ .path = "/ocr?format=doctr", .ct = form, .want = null, .status = 400 }, + .{ .path = "/ocr?format=tesseract", .ct = "application/json", .want = null, .status = 400 }, + .{ .path = "/ocr?format=%zz", .ct = "application/json", .want = null, .status = 400 }, + .{ .path = "/ocr?format=liteparse&format=liteparse", .ct = form, .want = null, .status = 400 }, + .{ .ct = "application/json", .want = null, .status = 415 }, + .{ .ct = null, .body = " {\"file\": \"x\"}", .want = null, .status = 415 }, + .{ .ct = null, .body = "file=x", .want = null, .status = 415 }, + .{ .ct = "text/plain", .want = null, .status = 415 }, + .{ .ct = form, .body = try parts(a, &.{ "files", "files" }), .want = null, .status = 400 }, + .{ .ct = form, .body = try parts(a, &.{ "file", "files" }), .want = null, .status = 400 }, + .{ .ct = form, .body = try parts(a, &.{"file"}), .want = .liteparse }, + .{ .ct = form, .body = try parts(a, &.{ "file", "file" }), .want = null, .status = 400 }, + .{ .ct = form, .body = try parts(a, &.{"image"}), .want = null, .status = 400 }, + .{ .ct = "multipart/form-data", .body = try parts(a, &.{"file"}), .want = null, .status = 400 }, + .{ .ct = form, .body = "not multipart", .want = null, .status = 400 }, + }; + for (cases) |c| switch (try route.select(a, c.path, c.ct, c.body)) { + .ok => |s| { + try t.expectEqual(c.want, s.dialect); + if (c.status == 0 and c.body.len > 0) try t.expect(s.parts != null); + }, + .refused => |r| { + try t.expectEqual(@as(?route.Dialect, null), c.want); + try t.expectEqual(c.status, r.status); + }, + }; +} + +test "ocr route: files parts are refused on every path, the format query included" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const both = try parts(a, &.{ "files", "file" }); + switch (try route.select(a, "/ocr", form, both)) { + .ok => return error.TestUnexpectedResult, + .refused => |r| { + try t.expectEqual(@as(u16, 400), r.status); + try t.expectEqualStrings(route.files_parts, r.message); + }, + } + // the format query picks LiteParse, which refuses the same body in its own envelope rather than drop the parts + var h: harness.Harness = .{}; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); + defer h.stop(); + const cases = [_]struct { []const u8, []const u8 }{ .{ "/ocr", "error" }, .{ "/ocr?format=liteparse", "error" } }; + for (cases) |c| { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, c[0], form, both), a); + try t.expectEqual(@as(u16, 400), wire.status()); + const got = (try wire.parsed()).get(c[1]).?; + try t.expectEqualStrings(route.files_parts, if (got == .string) got.string else got.strField("message").?); + } + try t.expectEqual(@as(usize, 0), h.next); +} + +test "ocr route: /ocr answers in the OpenAI shape until a dialect is chosen; both paths need the inference scope" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = .{}; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); + defer h.stop(); + const cases = [_]struct { path: []const u8, ct: ?[]const u8, status: u16, says: []const u8 }{ + .{ .path = "/ocr", .ct = "text/csv", .status = 415, .says = "unsupported Content-Type text/csv" }, + .{ .path = "/ocr/", .ct = form, .status = 400, .says = "multipart body is malformed" }, + }; + for (cases) |c| { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, c.path, c.ct, "{}"), a); + try t.expectEqual(c.status, wire.status()); + const message = (try wire.parsed()).get("error").?.strField("message").?; + try t.expect(std.mem.indexOf(u8, message, c.says) != null); + } + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, "/ocr?format=liteparse&format=x", form, "{}"), a); + try t.expectEqual(@as(u16, 400), wire.status()); + try t.expectEqualStrings("the format query parameter is repeated; send it once", (try wire.parsed()).get("error").?.strField("message").?); + const infer: auth_scope.Scopes = .{ .inference = true }; + const read: auth_scope.Scopes = .{ .read = true }; + for ([_][]const u8{ "/ocr", "/ocr/", "/v1/ocr", "/ocr?format=liteparse" }) |p| { + try t.expect(auth_scope.allows(infer, "POST", p)); + try t.expect(!auth_scope.allows(read, "POST", p)); + } +} + +/// Every request below reaches no dialect; each must get ``says`` as a 400 in the OpenAI shape. +fn expectGated(a: std.mem.Allocator, h: *harness.Harness, says: []const u8) !void { + const cases = [_]struct { []const u8, ?[]const u8 }{ .{ "/ocr", "text/csv" }, .{ "/ocr", null }, .{ "/ocr?format=x", form } }; + for (cases) |c| { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, c[0], c[1], "{}"), a); + try t.expectEqual(@as(u16, 400), wire.status()); + try t.expectEqualStrings(says, (try wire.parsed()).get("error").?.strField("message").?); + } +} + +test "ocr route: without a reader or --vision, a request no dialect takes gets the gate's refusal, not 415" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = .{}; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); + defer h.stop(); + const reader = h.srv.info.ocr; + h.srv.info.ocr = null; + try expectGated(a, &h, run.no_reader); + h.srv.info.ocr = reader; + h.srv.info.vision = null; + try expectGated(a, &h, run.no_vision); + try t.expectEqual(@as(usize, 0), h.next); +} diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig index aa25d0f12b1..b881c6576e5 100644 --- a/zig/src/server/ocr/run.zig +++ b/zig/src/server/ocr/run.zig @@ -40,10 +40,16 @@ pub const no_vision = "OCR needs image input; start the server with --vision"; /// The decoded-pixel limit of one page: GLM-OCR's processor input limit, the larger of the two reader families'. pub const max_page_pixels = 32 << 20; +/// The gate's message when the engine has no OCR reader or the server reads no images, else null. +pub fn gateRefusal(srv: *const Server) ?[]const u8 { + if (srv.info.ocr == null) return no_reader; + if (srv.info.vision == null) return no_vision; + return null; +} + /// Refuses as bad input unless the engine has an OCR reader and the server reads images. pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void { - if (srv.info.ocr == null) return fault.fail(a, .bad_input, "{s}", .{no_reader}); - if (srv.info.vision == null) return fault.fail(a, .bad_input, "{s}", .{no_vision}); + if (gateRefusal(srv)) |m| return fault.fail(a, .bad_input, "{s}", .{m}); } /// Where a page's encoded image comes from: an image source's bytes, or a measured PDF page rendered just before use. diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 5ed7959aeb2..aee28f56e7d 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -382,7 +382,9 @@ test { _ = @import("ocr/mistral_sdk_test.zig"); _ = @import("ocr/run_test.zig"); _ = @import("ocr/run_pdf_test.zig"); + _ = @import("ocr/route_test.zig"); _ = @import("ocr/size_test.zig"); + _ = @import("ocr/liteparse_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); _ = @import("open_connections_route_test.zig"); diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index 0d677a46b54..e07e65b0033 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -155,7 +155,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { const imprint_op: ?api.ImprintOp = if (std.mem.eql(u8, route, "/v1/imprint/resume")) .where else if (std.mem.eql(u8, route, "/v1/imprint/load")) .load else null; const is_chat = std.mem.endsWith(u8, route, "/chat/completions"); const is_rerank = @import("score_routes.zig").route(route); - const is_ocr = std.mem.eql(u8, route, "/v1/ocr"); + const is_ocr = std.mem.eql(u8, route, "/ocr") or std.mem.eql(u8, route, "/v1/ocr"); const is_ollama_chat = std.mem.eql(u8, route, "/api/chat"); const is_ollama_generate = std.mem.eql(u8, route, "/api/generate"); const is_ollama_embed = std.mem.eql(u8, route, "/api/embed"); @@ -187,7 +187,7 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { if (is_systemone) return systemone.post(srv, conn, a); if (is_anthropic) return anthropic.post(srv, conn, a); if (is_responses) return responses.postGated(srv, conn, a, &entered.held); - if (is_ocr) return @import("ocr/route.zig").post(srv, conn, a); + if (is_ocr) return @import("ocr/route.zig").post(srv, conn, a, route); openai.post(srv, conn, a, is_chat); } From d49bb25606a4fadcc9cdd842ee6b8575b98d8804 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:47:42 +0000 Subject: [PATCH 051/361] docs(ocr): document POST /ocr in LiteParse's contract The API guide gains the /ocr route: how it picks its contract and which refusals use the OpenAI envelope, the gate's refusal on every path, the refusal of a repeated query name, LiteParse's failure column, the estimated lines and scores, and the LiteParse section on its published OCR spec with the refusal of readers without boxes; the inference scope lists /ocr. --- docs/api.md | 66 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/docs/api.md b/docs/api.md index 9140250a706..c0c1c2f8b94 100644 --- a/docs/api.md +++ b/docs/api.md @@ -45,7 +45,7 @@ different scopes, or scopes a key the flags or environment already give, is refu | Scope | Routes | | --- | --- | -| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | +| `inference` | POST `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/tokenize`, `/v1/detokenize`, `/v1/apply-template`, `/v1/audio/speech`, `/v1/images/generations`, `/v1/embeddings`, `/v1/decisions`, `/v1/systemone`, `/score`, `/v1/score`, `/v2/rerank`, `/v1/rerank` (also by PUT), `/v1/ocr`, `/ocr`, and the same paths without `/v1` where the server has them; GET `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices`; a WebSocket upgrade on GET `/v1/responses` or `/responses` | | `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/execution/witness`, `/v1/models`, `/models`, `/v1/models/{id}`, `/models/{id}`, `/v1/voices` | A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights, @@ -275,12 +275,13 @@ context-window check still applies. Cohere-style requests retain the reranker's ## OCR -The native HIP engine reads pages through Mistral's OCR contract when it serves a model with an OCR reader -and `--vision`. +The native HIP engine reads pages through two OCR contracts when it serves a model with an OCR reader and +`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers LiteParse's. | Route | Contract | Request | Reply | Written for | | --- | --- | --- | --- | --- | | `POST /v1/ocr` | Mistral OCR | JSON `{"model", "document", ...}` | `{"pages", "model", "document_annotation", "usage_info"}` | the `mistralai` Python and `@mistralai/mistralai` TypeScript SDKs, with `server_url` set to the server root | +| `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` | Two families have a reader. A reader gives Markdown blocks in pixels of the page the client sent (after EXIF orientation), never in the model's resized frame. @@ -290,10 +291,23 @@ orientation), never in the model's resized frame. | dots.mocr | one block a layout region (title, text, table, formula, picture, header, footer, ...), tables as pipe tables or, when cells span, HTML | a box a block | | GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none | -Any other model answers the route with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions", +Any other model answers both routes with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions", and a server started without `--vision` answers "OCR needs image input; start the server with --vision". -Embedding, reranker and readout engines refuse the OCR route as they refuse chat. The route takes the `inference` -key scope. +Embedding, reranker and readout engines refuse the OCR routes as they refuse chat. The routes take the +`inference` key scope. + +`POST /ocr` picks its contract in this order: + +1. `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is repeated; send + it once"), because servers differ on which copy wins. +2. `multipart/form-data`: exactly one part named `file` is LiteParse; any other set of parts is HTTP 400, and so + is a body with any `files` part ("a multipart OCR request has files parts, which this server does not read; + LiteParse sends one file part"), even when `?format=` names the contract. +3. Any other content type, or none, is HTTP 415. + +Refusals made before the contract is known (415, those 400s, a drain's 503 and an admission 429 with +`Retry-After`) use the server's `{"error": {"message", "type"}}` envelope. On a model without a reader, or a +server without `--vision`, a request no contract takes gets the 400 above instead of its 415 or 400. ### Reader Markdown @@ -304,7 +318,7 @@ Both readers write block text in one Markdown flavour, the one Mistral's page Ma block holds exactly one table. - Display math as `$$…$$` and inline math as `$…$`, the LaTeX kept as the model wrote it. - Lists with `-` or `1.` markers, and code in fenced blocks. -- No images: a picture block has empty text, and its caption, if any, is its own block. The contract writes its +- No images: a picture block has empty text, and its caption, if any, is its own block. Each contract writes its own image references. - GLM-OCR's single block holds the whole page's Markdown, headings, tables and math included. @@ -335,19 +349,29 @@ stops on its end token and the reader can parse it. ### Failures -| Failure | Mistral | -| --- | --- | -| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | -| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | -| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | -| Engine fault, out of memory, PDF renderer crash or deadline | 500 | -| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | +| Failure | Mistral | LiteParse | +| --- | --- | --- | +| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 400 | +| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | 422 | +| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | +| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | +| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"error": "..."}` | A failed page fails the whole request: no reply returns some pages and drops others. An unreadable page's message names its index, and the model's raw text goes to the server log, never to the client. 422 means the same request fails the same way again under greedy decoding; a 503 carries `Retry-After`. A client that disconnects stops the request before its next page or PDF render. +### Estimates + +dots.mocr gives one box a block and GLM-OCR none, so LiteParse's lines estimate what the models do not give: + +- **Lines.** A block's plain-text lines (Markdown markup removed, a table one line a row with tab-separated + cells, math without its `$`) divide the block's box into equal bands along its left and right edges, first + line at the top. A paragraph written without line breaks stays one line covering the block. +- **Scores.** Every score is `1.0`: LiteParse `confidence`. Mistral replies leave `confidence_scores` out. +- **No geometry.** With GLM-OCR, Mistral returns `blocks: []` and LiteParse is refused. + ### Mistral: `POST /v1/ocr` | Field | Meaning | @@ -370,6 +394,20 @@ stops the request before its next page or PDF render. `content`, its own Markdown with its tables in the `table_format` form; image blocks add `image_id` and table blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size. +### LiteParse: `POST /ocr` + +The contract is LiteParse's published +[OCR API specification](https://github.com/run-llama/liteparse/blob/main/OCR_API_SPEC.md). One `file` part holds a PNG, +JPEG or WebP page image; `language` and other parts are ignored, but a `files` part is HTTP 400 (above). A PDF is +HTTP 400: the specification sends an image. +Each line is one result `{"text", "bbox", "confidence"}`: `bbox` is the line's axis-aligned `[x1, y1, x2, y2]` in +pixels of the image received, and `confidence` is `1.0`, the value the specification asks for when the engine gives +none. The specification's optional `polygon` is not sent: it gives the point order, but not how LiteParse turns a +polygon into a text rotation, so a rotated line is sent as its axis-aligned box. GLM-OCR gives no boxes, so +LiteParse requests to it are HTTP 400 "this model gives no text boxes; LiteParse needs them". With dots.mocr a +paragraph written without line breaks is one result covering its block. Errors use the specification's +`{"error": "..."}` body. + ### GLM-OCR context GLM-OCR's default 8192-token window leaves about 2000 tokens for the reply after a full image budget (6144 From d16f4d241e7a4f9abc7d2399fa69dcf7c5c13586 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:20:45 +0000 Subject: [PATCH 052/361] fix(server): close multipart only on a well-formed close line A body line `--XyZ--junk`, with boundary XyZ, was taken as the close delimiter, so the parser stopped there and ignored any later parts. RFC 2046 lets only transport padding and a line break, or the end of the body, follow `--boundary--`, so the close now needs exactly that, and a line with more text stays in the part body like any other boundary-like text; a regression test reads a later part past such a line and checks the accepted close forms. --- zig/src/server/multipart.zig | 13 +++++++------ zig/src/server/multipart_test.zig | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/zig/src/server/multipart.zig b/zig/src/server/multipart.zig index b3eedd8092a..e92cc43e976 100644 --- a/zig/src/server/multipart.zig +++ b/zig/src/server/multipart.zig @@ -63,19 +63,20 @@ const Delimiter = struct { close: bool, }; -/// The first `--boundary` at a line start that `--`, or blanks and a CRLF or LF, follows; other such text is body. +/// The first `--boundary` line start, `--` if it closes, then blanks and a CRLF, LF or (to close) the end; else body. fn delimiter(body: []const u8, from: usize, bound: []const u8) ?Delimiter { var pos = from + 2; while (std.mem.indexOfPos(u8, body, pos, bound)) |at| : (pos = at + 1) { const line = at - 2; if (!std.mem.eql(u8, body[line..at], "--")) continue; if (line != 0 and body[line - 1] != '\n') continue; - const end = at + bound.len; - if (std.mem.startsWith(u8, body[end..], "--")) return .{ .line = line, .next = end + 2, .close = true }; - var i = end; + var i = at + bound.len; + const close = std.mem.startsWith(u8, body[i..], "--"); + if (close) i += 2; while (i < body.len and (body[i] == ' ' or body[i] == '\t')) i += 1; - if (std.mem.startsWith(u8, body[i..], "\r\n")) return .{ .line = line, .next = i + 2, .close = false }; - if (std.mem.startsWith(u8, body[i..], "\n")) return .{ .line = line, .next = i + 1, .close = false }; + if (close and i == body.len) return .{ .line = line, .next = i, .close = true }; + if (std.mem.startsWith(u8, body[i..], "\r\n")) return .{ .line = line, .next = i + 2, .close = close }; + if (std.mem.startsWith(u8, body[i..], "\n")) return .{ .line = line, .next = i + 1, .close = close }; } return null; } diff --git a/zig/src/server/multipart_test.zig b/zig/src/server/multipart_test.zig index e385a609321..e37c5a9cc9a 100644 --- a/zig/src/server/multipart_test.zig +++ b/zig/src/server/multipart_test.zig @@ -86,6 +86,25 @@ test "ocr multipart: boundary-like text inside a body stays in the body" { try t.expectEqualStrings(inner, parts[0].body); } +test "ocr multipart: the close delimiter takes only blanks and a line break or the end after it" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const head = "--XyZ\r\nContent-Disposition: form-data; name=a\r\n\r\n"; + const b = "--XyZ\r\nContent-Disposition: form-data; name=b\r\n\r\nB\r\n"; + // a `--XyZ--` line with more text is body, so a later part is still read + const parts = try parse(&arena, head ++ "A\r\n--XyZ--junk\r\n" ++ b ++ "--XyZ--"); + try t.expectEqual(@as(usize, 2), parts.len); + try t.expectEqualStrings("A\r\n--XyZ--junk", parts[0].body); + try t.expectEqualStrings("B", parts[1].body); + try t.expectError(error.Malformed, parse(&arena, head ++ "A\r\n--XyZ--junk")); + try t.expectError(error.Malformed, parse(&arena, head ++ "A\r\n--XyZ-- x\r\n")); + inline for ([_][]const u8{ "--XyZ--", "--XyZ-- \t", "--XyZ--\r\n", "--XyZ--\t\n", "--XyZ--\r\nepilogue" }) |close| { + const got = try parse(&arena, head ++ "A\r\n" ++ close); + try t.expectEqual(@as(usize, 1), got.len); + try t.expectEqualStrings("A", got[0].body); + } +} + test "ocr multipart: missing delimiters are malformed" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); From d90ff02e3cc35557ca8a2a612c95ad7cebb5bed8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:37:06 +0000 Subject: [PATCH 053/361] test(server): the cache-salt OCR case passes its route to the four-argument post main's cache-salt isolation test called ocr/route.zig's post with three arguments; this branch gives post the route it dispatches on. The test sends a /v1/ocr request, so it now passes "/v1/ocr". Nothing else changes. --- zig/src/server/cache_salt_test.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/server/cache_salt_test.zig b/zig/src/server/cache_salt_test.zig index 63292e20974..e80b2fdd820 100644 --- a/zig/src/server/cache_salt_test.zig +++ b/zig/src/server/cache_salt_test.zig @@ -514,7 +514,7 @@ test "cache salt isolation: two keys OCR pages never resume each other and each var wire: harness.Wire = .{ .a = a }; const conn = try harness.request(a, &wire, "/v1/ocr", "application/json", body); conn.key_digest = @as([32]u8, @splat(key)); - @import("ocr/route.zig").post(srv, conn, a); + @import("ocr/route.zig").post(srv, conn, a, "/v1/ocr"); try std.testing.expectEqual(@as(u16, 200), wire.status()); try isolated(&cache, from, 1, resumed); const reply = try wire.parsed(); From 83f4a6b4952d6700f9463c31f1a6a3f5d312f9ac Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:39:34 +0000 Subject: [PATCH 054/361] changelog: #2573 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ba6b06e142..69af41b3d30 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 +- 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. + - 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. From 8a6879f4ba6eb5a92f11e0e6e03a902c146c7632 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:39:34 +0000 Subject: [PATCH 055/361] changelog: #2573 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69af41b3d30..99e693443a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ 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. + + - 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. From 49dcd0ab4feeb292ddb63070fb48c880e089bb13 Mon Sep 17 00:00:00 2001 From: yguanrong <41421888+yguanrong@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:09:30 +0800 Subject: [PATCH 056/361] CUDA: add the scoped sm_110 product target --- RUNBOOK.md | 3 +- docs/kernel-contract.md | 6 ++-- docs/recipes/qwen3.8-27b.md | 6 ++-- zig/build/product.zig | 4 +-- zig/src/cuda/driver.zig | 2 ++ zig/src/cuda/gpu_builds.zig | 2 +- zig/src/families/qwen3_5/cuda_geometry.zig | 20 +++++++++++ zig/src/families/qwen3_5/cuda_sm110_modes.zig | 1 + zig/src/families/qwen3_5/cuda_sm110_open.zig | 2 ++ .../families/qwen3_5/cuda_sm110_open_test.zig | 33 +++++++++++++++++++ zig/src/native/cuda.zig | 1 + zig/src/native/cuda_refusal.zig | 25 ++++++++++++++ 12 files changed, 96 insertions(+), 9 deletions(-) diff --git a/RUNBOOK.md b/RUNBOOK.md index 452b9a795c5..e27411b244c 100644 --- a/RUNBOOK.md +++ b/RUNBOOK.md @@ -262,7 +262,8 @@ zig build -Dgpu=spark -Dnvcc=/usr/local/cuda/bin/nvcc # zig-out/nativ zig build -Dgpu=gfx1201 -Dhipcc=/opt/rocm/core/bin/hipcc # zig-out/native-hip/bin/tensorfold-native ``` -- `-Dgpu`: `sm_80`, `sm_86`, `sm_89`, `sm_120`, `sm_121`, `spark` (GB10, sm_121), or an exact HIP architecture from `zig/src/hip/caps.zig`. It replaces `-Dsm`, `-Dhip` and `-Dhip-arch`. +- `-Dgpu`: `sm_80`, `sm_86`, `sm_89`, `sm_110`, `sm_120`, `sm_121`, `spark` (GB10, sm_121), or an exact HIP architecture from `zig/src/hip/caps.zig`. It replaces `-Dsm`, `-Dhip` and `-Dhip-arch`. +- `sm_110` serves Qwen3.8-27B text on one Thor GPU with BF16 KV and DFlash2. Its checkpoint formats are MLX affine 4-bit/group-64 and the NVIDIA ModelOpt NVFP4 export. - `sm_89` builds, but the release set (sm_80, 86, 120, 121) holds no image qualified on it. - The server refuses a GPU of another architecture at startup and names the `-Dgpu` that fits it (HIP already refuses one at device open). - CUDA needs `-Dnvcc`, or `-Dfatbins` with prebuilt images; each prebuilt image must hold exactly the one SASS profile its kernel needs on that GPU. `-Dstrip=false` keeps debug info. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 4841b24f5be..bd756c25362 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -90,11 +90,11 @@ On a CUDA machine, build with `-Dnvcc` (the controls are compiled only then), an -Dsm=80,86,89,120,121`, then `tf-cuda-test kernel-contract-limits zig-out/fatbin`. Its `RECORD` lines are the values `registry.zig` holds for that build's nvcc (see [CUDA records per nvcc release](#cuda-records-per-nvcc-release)). -For a development sm_110 build, use `-Dsm=110` in the fatbin build and run the same limits command on that set. +For the sm_110 image set, use `-Dsm=110` in the fatbin build and run the same limits command on that set. The `DIR` must contain `norms.fatbin` and every registered image; the runner reads `norms.fatbin` first to select the release or sm_110 audit mode. It reads sm_110 registers, static shared bytes and bounds from each cubin and -checks its device limits; the five release SMs retain their pinned `RECORD` entries. This does not enable -`-Dgpu=sm_110`. On sm_110, some 48 KiB dynamic shared-memory kernels carry another 1 KiB of static shared memory. +checks its device limits; the five release SMs retain their pinned `RECORD` entries. +On sm_110, some 48 KiB dynamic shared-memory kernels carry another 1 KiB of static shared memory. Only their sm_110 audit uses the opt-in limit already raised by their loaders (`allowDynamicShared`). For a mixed release and sm_110 set, each planted control must go red on each target separately. diff --git a/docs/recipes/qwen3.8-27b.md b/docs/recipes/qwen3.8-27b.md index a389c3fa0a7..3bac80cfdba 100644 --- a/docs/recipes/qwen3.8-27b.md +++ b/docs/recipes/qwen3.8-27b.md @@ -266,9 +266,11 @@ This section is the Python engine's (0.6.6). The native CUDA engine reads the ML NVFP4 and FP8 exports, and turboderp's EXL3 packs through the shared EXL3 module of #832; its own measurements are not the ones below. -### Native engine on sm_110 (development build) +### Native engine on sm_110 -On NVIDIA Thor (sm_110), build the native CUDA engine with `-Dsm=110`. This is a development target; `-Dgpu=sm_110` is not a product target yet. The measured path uses the MLX affine 4-bit/group-64 checkpoint, one GPU, BF16 KV and prompt activations, and the DFlash2 drafter. Text and PNG image requests were checked against `"draft": false` with greedy and seeded sampling, solo and concurrent streams, cancelled requests and resumed prompts. The device receipt belongs to the commit and checkpoint hashes recorded with the test run; it does not qualify other checkpoints or image decoders. +Use `-Dgpu=sm_110` for the Thor product server. It serves Qwen3.8-27B text on one GPU with BF16 KV and DFlash2, +using the MLX affine 4-bit/group-64 or NVIDIA ModelOpt NVFP4 checkpoint. The device receipt pins the revisions. +Use `-Dsm=110` for developmental validation, where MLX text and PNG requests have been exercised. The SM110 Qwen loader refuses `--slide`, DSpine `--drafter`, `TF_DSPINE_WINDOW`, `--kv-cache fp8`, `--prompt-precision int8`, `--rope-yarn`, `TF_QWEN_KV_PAGES`, `TF_QWEN_KV_PAGES_ALL=1`, `TF_QWEN_KV_SHARE`, `TF_QWEN_REQUEST_STARTS=1`, `TF_QWEN_KV_PAGE_TEST`, `TF_QWEN_KEEP_LATE=1`, `TF_NO_TREES` and `TF_DRAFT_NODES` when they would change the default serving path. Their other-GPU behavior is unchanged. Unset or explicit off values for the `TF_QWEN_*` switches keep the default path; `TF_NO_TREES` and `TF_DRAFT_NODES` must be unset. diff --git a/zig/build/product.zig b/zig/build/product.zig index 29031dd1e1e..cf1407de0e8 100644 --- a/zig/build/product.zig +++ b/zig/build/product.zig @@ -6,7 +6,7 @@ const gpu_builds = @import("../src/cuda/gpu_builds.zig"); /// The `-Dgpu` name, or null for the development build. pub fn requested(b: *std.Build) ?[]const u8 { - return b.option([]const u8, "gpu", "Build one server for one GPU: sm_80, sm_86, sm_89, sm_120, sm_121, spark, or a HIP arch (gfx1201 ...)"); + return b.option([]const u8, "gpu", "Build one server for one GPU: sm_80, sm_86, sm_89, sm_110, sm_120, sm_121, spark, or a HIP arch (gfx1201 ...)"); } /// A CUDA SM as `-Dsm` spells it, or an exact HIP architecture. @@ -73,7 +73,7 @@ fn undeclared(b: *std.Build) ?[]const u8 { /// Why `-Dgpu=name` with these options builds nothing, or null when it builds. fn refusal(b: *std.Build, name: []const u8, gpu: ?Gpu, o: Options) ?[]const u8 { - const g = gpu orelse return b.fmt("-Dgpu={s}: not a GPU this build knows; use sm_80, sm_86, sm_89, sm_120, sm_121, spark, or an exact HIP arch from zig/src/hip/caps.zig", .{name}); + const g = gpu orelse return b.fmt("-Dgpu={s}: not a GPU this build knows; use sm_80, sm_86, sm_89, sm_110, sm_120, sm_121, spark, or an exact HIP arch from zig/src/hip/caps.zig", .{name}); if (o.sm) return "-Dsm: -Dgpu sets the architecture"; if (o.hip) return b.fmt("-Dhip: -Dgpu={s} chooses the backend", .{name}); if (o.hip_options.hip_arch != null) return "-Dhip-arch: -Dgpu sets the architecture"; diff --git a/zig/src/cuda/driver.zig b/zig/src/cuda/driver.zig index 2ee2d530d7c..18d071cd7f2 100644 --- a/zig/src/cuda/driver.zig +++ b/zig/src/cuda/driver.zig @@ -211,6 +211,8 @@ pub fn gpuRefusal(built: ?u32, capability: u32, ordinal: c_int, buf: []u8) ?[]co test "a -Dgpu server: a GPU of another SM is refused naming both SMs, and a -Dgpu only when it builds one" { var buf: [256]u8 = undefined; try std.testing.expectEqualStrings("this server was built for sm_120 (-Dgpu=sm_120), and CUDA device 0 is sm_121: build it with -Dgpu=sm_121, or use the release server", gpuRefusal(120, 121, 0, &buf).?); + try std.testing.expectEqualStrings("this server was built for sm_110 (-Dgpu=sm_110), and CUDA device 0 is sm_121: build it with -Dgpu=sm_121, or use the release server", gpuRefusal(110, 121, 0, &buf).?); + try std.testing.expect(gpuRefusal(110, 110, 0, &buf) == null); try std.testing.expectEqualStrings("this server was built for sm_121 (-Dgpu=sm_121), and CUDA device 2 is sm_86: build it with -Dgpu=sm_86, or use the release server", gpuRefusal(121, 86, 2, &buf).?); try std.testing.expectEqualStrings("this server was built for sm_120 (-Dgpu=sm_120), and CUDA device 0 is sm_90, which -Dgpu does not build a server for", gpuRefusal(120, 90, 0, &buf).?); try std.testing.expect(gpuRefusal(120, 120, 0, &buf) == null); diff --git a/zig/src/cuda/gpu_builds.zig b/zig/src/cuda/gpu_builds.zig index e993ae446c0..3f585b4c3ee 100644 --- a/zig/src/cuda/gpu_builds.zig +++ b/zig/src/cuda/gpu_builds.zig @@ -1,4 +1,4 @@ //! The CUDA SMs `zig build -Dgpu` builds a server for (zig/build/product.zig); a refusal names only these. /// 10 * major + minor, as `Context.capability` reports it. -pub const sms = [_]u32{ 80, 86, 89, 120, 121 }; +pub const sms = [_]u32{ 80, 86, 89, 110, 120, 121 }; diff --git a/zig/src/families/qwen3_5/cuda_geometry.zig b/zig/src/families/qwen3_5/cuda_geometry.zig index 1e952aa517a..f5ad526b70c 100644 --- a/zig/src/families/qwen3_5/cuda_geometry.zig +++ b/zig/src/families/qwen3_5/cuda_geometry.zig @@ -115,6 +115,26 @@ pub const Geometry = struct { return g; } + /// The dense 27B geometry and weight recipes qualified for the Thor product. + pub fn sm110Product(g: Geometry) bool { + if (g.hidden != 5120 or g.layers != 64 or g.intermediate != 17408 or g.vocab != 248320 or + g.q_heads != 24 or g.kv_heads != 4 or g.moe() or g.pocket != 0 or g.rope != .plain) + return false; + if (g.exl3 or g.bf16 or g.kinds.ct) return false; + if (!g.kinds.modelopt) return !g.bits.mixed(g.layers); + if (g.kinds.head != .nvfp4) return false; + for (0..g.layers) |i| { + for ([_]Slot{ .gate, .up, .down }) |slot| if (g.kinds.of(i, slot) != .nvfp4) return false; + if (g.linear[i]) { + for ([_]Slot{ .qkv, .z, .out }) |slot| if (g.kinds.of(i, slot) != .fp8) return false; + for ([_]Slot{ .a, .b }) |slot| if (g.kinds.of(i, slot) != .bf16) return false; + } else { + for ([_]Slot{ .q, .k, .v, .o }) |slot| if (g.kinds.of(i, slot) != .fp8) return false; + } + } + return true; + } + /// Whether the MLPs are routed experts, whose width is `intermediate` (the shared expert's too). pub fn moe(g: Geometry) bool { return g.experts != 0; diff --git a/zig/src/families/qwen3_5/cuda_sm110_modes.zig b/zig/src/families/qwen3_5/cuda_sm110_modes.zig index ff88c918e63..a02961dd96a 100644 --- a/zig/src/families/qwen3_5/cuda_sm110_modes.zig +++ b/zig/src/families/qwen3_5/cuda_sm110_modes.zig @@ -78,6 +78,7 @@ fn needsDevice(modes: Modes) bool { pub fn explain(err: anyerror) ?[]const u8 { return switch (err) { + error.Sm110ProductDrafter => "sm_110 product: --drafter must point to a DFlash2 checkpoint", error.QwenSm110SlideUnqualified => "--slide is not qualified for Qwen on sm_110; omit it", error.QwenSm110DspineUnqualified => "DSpine --drafter is not qualified for Qwen on sm_110; use DFlash2", error.QwenSm110DspineWindowUnqualified => "TF_DSPINE_WINDOW is not qualified for Qwen on sm_110; unset it", diff --git a/zig/src/families/qwen3_5/cuda_sm110_open.zig b/zig/src/families/qwen3_5/cuda_sm110_open.zig index b4c5f0d065a..afdd3ec6a42 100644 --- a/zig/src/families/qwen3_5/cuda_sm110_open.zig +++ b/zig/src/families/qwen3_5/cuda_sm110_open.zig @@ -17,4 +17,6 @@ pub fn check(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, o: na const doc = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}); defer doc.deinit(); try modes.check(110, .{ .dspine = @import("core").dspine.declared(doc.value) }); + if (cuda.kernels.built_sm == 110 and (doc.value != .object or !doc.value.object.contains("dflash_config"))) + return error.Sm110ProductDrafter; } diff --git a/zig/src/families/qwen3_5/cuda_sm110_open_test.zig b/zig/src/families/qwen3_5/cuda_sm110_open_test.zig index a2927eb8f27..25297cccb3b 100644 --- a/zig/src/families/qwen3_5/cuda_sm110_open_test.zig +++ b/zig/src/families/qwen3_5/cuda_sm110_open_test.zig @@ -42,3 +42,36 @@ test "SM110 startup refuses slide and DSpine while admitting the DFlash2 declara defer _ = env.unsetenv("TF_DSPINE_WINDOW"); try t.expectError(error.QwenSm110DspineWindowUnqualified, guard.check(t.allocator, t.io, &ctx, o)); } +test "SM110 product admits the two dense 27B formats and refuses other geometry or weight recipes" { + const geometry = @import("cuda_geometry.zig"); + var g: geometry.Geometry = .{ + .hidden = 5120, + .intermediate = 17408, + .layers = 64, + .vocab = 248320, + .q_heads = 24, + .kv_heads = 4, + .k_heads = 16, + .v_heads = 48, + .eps = 1e-6, + .tied = false, + .context = 8192, + .linear = @splat(false), + }; + for (0..g.layers) |i| g.linear[i] = i % 4 != 3; + try std.testing.expect(g.sm110Product()); + g.bits.head = 8; + try std.testing.expect(!g.sm110Product()); + g.kinds = .{ .modelopt = true, .head = .nvfp4 }; + for (0..g.layers) |i| { + for ([_]geometry.Slot{ .gate, .up, .down }) |slot| g.kinds.proj[i][@backingInt(slot)] = .nvfp4; + for ([_]geometry.Slot{ .qkv, .z, .out, .q, .k, .v, .o }) |slot| g.kinds.proj[i][@backingInt(slot)] = .fp8; + for ([_]geometry.Slot{ .a, .b }) |slot| g.kinds.proj[i][@backingInt(slot)] = .bf16; + } + try std.testing.expect(g.sm110Product()); + g.kinds.proj[0][@backingInt(geometry.Slot.down)] = .bf16; + try std.testing.expect(!g.sm110Product()); + g.kinds.proj[0][@backingInt(geometry.Slot.down)] = .nvfp4; + g.hidden = 4096; + try std.testing.expect(!g.sm110Product()); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index a116b5ba740..192500d08df 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -162,6 +162,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c defer report.deinit(); if (try refusals.startup(a, o, problem)) return null; if (@import("save_admission.zig").refused(io, o.dir, problem)) return null; + if (cuda.kernels.built_sm == 110 and try refusals.sm110Product(a, io, o, problem)) return null; // a checkpoint that serves pictures rather than tokens: its model_index.json decides, before any family's flags if (@import("moss_image_spec.zig").recognize(a, io, o.dir)) return @import("moss_image_host.zig").open(a, gpa, io, o, problem); if (refusals.backend(o)) |why| { diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index af2bd320fc7..69cce410009 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -6,6 +6,31 @@ const qwen35 = @import("qwen35"); pub const deepseek_release_message = "DeepSeek-V4.1 is not served by this release's CUDA server; its whole-model gate is #827"; const glm_model_type = "glm5_next"; // GLM-5.3-Flash's (glm.cuda_native.model_type): its Options take mtp_confidence +/// The first Thor product serves Qwen3.8-27B text with DFlash2 on one GPU. +pub fn sm110Product(a: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !bool { + if (!std.mem.eql(u8, o.model_type, qwen35.native.model_type)) { + problem.* = try std.fmt.allocPrint(a, "sm_110 product: {s} is not qualified; serve Qwen3.8-27B", .{o.model_type}); + return true; + } + problem.* = if (o.tp != 1 or o.rank != 0) + "sm_110 product: --tp and --rank must select one GPU" + else if (o.vision != null) + "sm_110 product: --vision is not qualified; serve text without --vision" + else if (o.precision == .full) + "sm_110 product: --precision full is not qualified; use checkpoint precision" + else if (o.mtp_drafts != null) + "sm_110 product: --mtp-drafts is not qualified; use the DFlash2 drafter" + else if (!o.drafts or o.drafter == null) + "sm_110 product: use --drafter with a DFlash2 checkpoint and omit --no-drafts" + else if (o.drafter_bits != 4) + "sm_110 product: --drafter-bits must be 4 for the qualified DFlash2 path" + else if (!(try qwen35.geometry.Geometry.read(a, io, o.dir)).sm110Product()) + "sm_110 product: use the Qwen3.8-27B MLX affine 4-bit/group-64 or NVIDIA ModelOpt NVFP4 checkpoint" + else + return false; + return true; +} + /// Flags refused whatever the family; null when `o` may open. pub fn backend(o: api.Open) ?[]const u8 { if (std.mem.eql(u8, o.model_type, "deepseek_v4") or std.mem.eql(u8, o.model_type, "deepseek_v41")) From 6ef3149199df9e216f17712d2515e5349f23c7a0 Mon Sep 17 00:00:00 2001 From: yguanrong <41421888+yguanrong@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:55:40 +0800 Subject: [PATCH 057/361] CUDA: account for Thor fused BF16 launch opt-in --- zig/tests/cuda/contract_limits.zig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 98e4ba9cce5..8a929670786 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -137,6 +137,7 @@ fn auditLaunch(launch: limits.CudaLaunch, sm: u32) limits.CudaLaunch { "qmmf FP8 64-row tile, cluster of 8", // zig/src/cuda/qmmf.zig:147 "qmmf BF16 32-row tile", // zig/src/cuda/qmmf.zig:147 "qmmf BF16 32-row tile, cluster of 8", // zig/src/cuda/qmmf.zig:147 + "qmmf BF16 32-row tile, fused slices", // zig/src/cuda/qmmf.zig:225 "qmmf shared down 32 stride", // zig/src/cuda/qmmf.zig:189 "prompt16 FP8", // zig/src/cuda/nvfp4.zig:122 "qmmf FP8 fp32 out 64-row tile", // zig/src/cuda/qmmf.zig:147 @@ -144,6 +145,7 @@ fn auditLaunch(launch: limits.CudaLaunch, sm: u32) limits.CudaLaunch { "qmmf FP8 fp32 out 64-row tile, fused slices", // zig/src/cuda/qmmf.zig:151 "qmmf BF16 fp32 out 32-row tile", // zig/src/cuda/qmmf.zig:147 "qmmf BF16 fp32 out 32-row tile, cluster of 8", // zig/src/cuda/qmmf.zig:147 + "qmmf BF16 fp32 out 32-row tile, fused slices", // zig/src/cuda/qmmf.zig:225 "h3 h3_attention", // zig/src/families/h3/cuda.zig:97 }; for (raised) |name| if (std.mem.eql(u8, launch.name, name)) { From 1df3f1174d539d7817be8b75dcf5f8bcb6848c68 Mon Sep 17 00:00:00 2001 From: yguanrong <41421888+yguanrong@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:38:02 +0800 Subject: [PATCH 058/361] CUDA: name MOSS-Image in the Thor product refusal --- zig/build/release_cuda_refusal.zig | 4 ++-- zig/cuda_release_refusal_tests.zig | 8 ++++++++ zig/src/native/cuda.zig | 5 +++-- zig/src/native/cuda_refusal.zig | 7 ++++--- 4 files changed, 17 insertions(+), 7 deletions(-) diff --git a/zig/build/release_cuda_refusal.zig b/zig/build/release_cuda_refusal.zig index 94b55e6e1b5..7c31e200a40 100644 --- a/zig/build/release_cuda_refusal.zig +++ b/zig/build/release_cuda_refusal.zig @@ -4,7 +4,7 @@ pub fn tests(b: *std.Build, all: *std.Build.Step, api: *std.Build.Module, nemotr const env = b.createModule(.{ .root_source_file = b.path("zig/cuda_release_refusal_env.zig"), .target = b.graph.host }); const refusal = b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda_refusal.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "nemotron", .module = nemotron }, .{ .name = "qwen35", .module = qwen35 }, .{ .name = "sys", .module = env } } }); const root = b.createModule(.{ .root_source_file = b.path("zig/cuda_release_refusal_tests.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "release_refusal", .module = refusal }, .{ .name = "policy_env", .module = env } } }); - const run = b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"DeepSeek release:"} })); - b.step("test-release-cuda-refusal-host", "Release DeepSeek refusal across controlled opt-in values without device work").dependOn(&run.step); + const run = b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{ "DeepSeek release:", "SM110 product:" } })); + b.step("test-release-cuda-refusal-host", "CUDA release and SM110 product refusals without device work").dependOn(&run.step); all.dependOn(&run.step); } diff --git a/zig/cuda_release_refusal_tests.zig b/zig/cuda_release_refusal_tests.zig index 112c3844493..f71d22eeed9 100644 --- a/zig/cuda_release_refusal_tests.zig +++ b/zig/cuda_release_refusal_tests.zig @@ -25,3 +25,11 @@ test "DeepSeek release: other CUDA admission stays available" { defer env.value = null; try std.testing.expect(gate.backend(.{ .dir = "not-opened", .model_type = "nemotron_h" }) == null); } + +test "SM110 product: a recognized MOSS-Image pipeline is refused by name" { + const a = std.testing.allocator; + var problem: []const u8 = ""; + try std.testing.expect(try gate.sm110Product(a, std.testing.io, .{ .dir = "not-opened", .model_type = "unknown" }, true, &problem)); + defer a.free(problem); + try std.testing.expectEqualStrings("sm_110 product: MOSS-Image is not qualified; serve Qwen3.8-27B", problem); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 192500d08df..6ebb985c796 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -162,9 +162,10 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c defer report.deinit(); if (try refusals.startup(a, o, problem)) return null; if (@import("save_admission.zig").refused(io, o.dir, problem)) return null; - if (cuda.kernels.built_sm == 110 and try refusals.sm110Product(a, io, o, problem)) return null; // a checkpoint that serves pictures rather than tokens: its model_index.json decides, before any family's flags - if (@import("moss_image_spec.zig").recognize(a, io, o.dir)) return @import("moss_image_host.zig").open(a, gpa, io, o, problem); + const moss_image = @import("moss_image_spec.zig").recognize(a, io, o.dir); + if (cuda.kernels.built_sm == 110 and try refusals.sm110Product(a, io, o, moss_image, problem)) return null; + if (moss_image) return @import("moss_image_host.zig").open(a, gpa, io, o, problem); if (refusals.backend(o)) |why| { problem.* = why; return null; diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index 69cce410009..f3061e54e35 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -7,9 +7,10 @@ pub const deepseek_release_message = "DeepSeek-V4.1 is not served by this releas const glm_model_type = "glm5_next"; // GLM-5.3-Flash's (glm.cuda_native.model_type): its Options take mtp_confidence /// The first Thor product serves Qwen3.8-27B text with DFlash2 on one GPU. -pub fn sm110Product(a: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !bool { - if (!std.mem.eql(u8, o.model_type, qwen35.native.model_type)) { - problem.* = try std.fmt.allocPrint(a, "sm_110 product: {s} is not qualified; serve Qwen3.8-27B", .{o.model_type}); +pub fn sm110Product(a: std.mem.Allocator, io: std.Io, o: api.Open, moss_image: bool, problem: *[]const u8) !bool { + const model = if (moss_image) "MOSS-Image" else o.model_type; + if (!std.mem.eql(u8, model, qwen35.native.model_type)) { + problem.* = try std.fmt.allocPrint(a, "sm_110 product: {s} is not qualified; serve Qwen3.8-27B", .{model}); return true; } problem.* = if (o.tp != 1 or o.rank != 0) From 8a1a295e977d5f432f7c1ba59ed3e29d6f806652 Mon Sep 17 00:00:00 2001 From: yguanrong <41421888+yguanrong@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:03:49 +0800 Subject: [PATCH 059/361] CUDA: require the complete 27B geometry on Thor Reject unqualified recurrent heads, epsilon, tied weights, and layer schedules for the SM110 product. Keep the MLX and ModelOpt weight checks and exercise each refusal on the host. Move the SM110 driver assertions out of the byte-pinned serving source so the serving identity check still covers the original driver bytes. --- zig/build/cuda_family_host.zig | 7 ++++ zig/src/cuda/driver.zig | 2 - zig/src/cuda/driver_sm110_host_test.zig | 11 ++++++ zig/src/families/qwen3_5/cuda_geometry.zig | 5 ++- .../families/qwen3_5/cuda_sm110_open_test.zig | 38 ++++++++++++++++++- 5 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 zig/src/cuda/driver_sm110_host_test.zig diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index fac6adb107b..8cc3905a63d 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -6,6 +6,13 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B const sm110 = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"SM110"} })); b.step("test-qwen35-sm110-host", "SM110 startup refusals without device or weight loading").dependOn(&sm110.step); step.dependOn(&sm110.step); + const sm110_driver = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/cuda/driver_sm110_host_test.zig"), + .target = host, + .link_libc = true, + }), .filters = &.{"SM110 CUDA driver:"} })); + b.step("test-cuda-driver-sm110-host", "SM110 CUDA device matching without loading a driver").dependOn(&sm110_driver.step); + step.dependOn(&sm110_driver.step); @import("prefill_widths_cuda.zig").tests(b, cuda, mods, step); const metal_scope = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/config.zig"), .target = host }), .filters = &.{ "Metal 2B format scope:", "admit the affine 2B", "admit untied heads" } })); b.step("test-qwen35-metal-scope-host", "Metal 2B format admission without device or Metal compiler").dependOn(&metal_scope.step); diff --git a/zig/src/cuda/driver.zig b/zig/src/cuda/driver.zig index 18d071cd7f2..2ee2d530d7c 100644 --- a/zig/src/cuda/driver.zig +++ b/zig/src/cuda/driver.zig @@ -211,8 +211,6 @@ pub fn gpuRefusal(built: ?u32, capability: u32, ordinal: c_int, buf: []u8) ?[]co test "a -Dgpu server: a GPU of another SM is refused naming both SMs, and a -Dgpu only when it builds one" { var buf: [256]u8 = undefined; try std.testing.expectEqualStrings("this server was built for sm_120 (-Dgpu=sm_120), and CUDA device 0 is sm_121: build it with -Dgpu=sm_121, or use the release server", gpuRefusal(120, 121, 0, &buf).?); - try std.testing.expectEqualStrings("this server was built for sm_110 (-Dgpu=sm_110), and CUDA device 0 is sm_121: build it with -Dgpu=sm_121, or use the release server", gpuRefusal(110, 121, 0, &buf).?); - try std.testing.expect(gpuRefusal(110, 110, 0, &buf) == null); try std.testing.expectEqualStrings("this server was built for sm_121 (-Dgpu=sm_121), and CUDA device 2 is sm_86: build it with -Dgpu=sm_86, or use the release server", gpuRefusal(121, 86, 2, &buf).?); try std.testing.expectEqualStrings("this server was built for sm_120 (-Dgpu=sm_120), and CUDA device 0 is sm_90, which -Dgpu does not build a server for", gpuRefusal(120, 90, 0, &buf).?); try std.testing.expect(gpuRefusal(120, 120, 0, &buf) == null); diff --git a/zig/src/cuda/driver_sm110_host_test.zig b/zig/src/cuda/driver_sm110_host_test.zig new file mode 100644 index 00000000000..5a40964ef7a --- /dev/null +++ b/zig/src/cuda/driver_sm110_host_test.zig @@ -0,0 +1,11 @@ +//! Device matching for the SM110 product without opening the CUDA driver. +const std = @import("std"); +const gpuRefusal = @import("driver.zig").gpuRefusal; + +test "SM110 CUDA driver: a mismatched SM names both targets, while SM110 is admitted" { + var buf: [256]u8 = undefined; + const expected = "this server was built for sm_110 (-Dgpu=sm_110), and CUDA device 0 is sm_121: " ++ + "build it with -Dgpu=sm_121, or use the release server"; + try std.testing.expectEqualStrings(expected, gpuRefusal(110, 121, 0, &buf).?); + try std.testing.expect(gpuRefusal(110, 110, 0, &buf) == null); +} diff --git a/zig/src/families/qwen3_5/cuda_geometry.zig b/zig/src/families/qwen3_5/cuda_geometry.zig index f5ad526b70c..2dcf5c45602 100644 --- a/zig/src/families/qwen3_5/cuda_geometry.zig +++ b/zig/src/families/qwen3_5/cuda_geometry.zig @@ -118,8 +118,11 @@ pub const Geometry = struct { /// The dense 27B geometry and weight recipes qualified for the Thor product. pub fn sm110Product(g: Geometry) bool { if (g.hidden != 5120 or g.layers != 64 or g.intermediate != 17408 or g.vocab != 248320 or - g.q_heads != 24 or g.kv_heads != 4 or g.moe() or g.pocket != 0 or g.rope != .plain) + g.q_heads != 24 or g.kv_heads != 4 or g.k_heads != 16 or g.v_heads != 48 or + g.eps != 1e-6 or g.tied or g.moe() or g.pocket != 0 or g.rope != .plain) return false; + for (g.linear[0..g.layers], 0..) |linear, i| + if (linear != !layer_pattern.every(layer_pattern.default_interval, i)) return false; if (g.exl3 or g.bf16 or g.kinds.ct) return false; if (!g.kinds.modelopt) return !g.bits.mixed(g.layers); if (g.kinds.head != .nvfp4) return false; diff --git a/zig/src/families/qwen3_5/cuda_sm110_open_test.zig b/zig/src/families/qwen3_5/cuda_sm110_open_test.zig index 25297cccb3b..3f9f06b164d 100644 --- a/zig/src/families/qwen3_5/cuda_sm110_open_test.zig +++ b/zig/src/families/qwen3_5/cuda_sm110_open_test.zig @@ -42,7 +42,7 @@ test "SM110 startup refuses slide and DSpine while admitting the DFlash2 declara defer _ = env.unsetenv("TF_DSPINE_WINDOW"); try t.expectError(error.QwenSm110DspineWindowUnqualified, guard.check(t.allocator, t.io, &ctx, o)); } -test "SM110 product admits the two dense 27B formats and refuses other geometry or weight recipes" { +fn dense27B() @import("cuda_geometry.zig").Geometry { const geometry = @import("cuda_geometry.zig"); var g: geometry.Geometry = .{ .hidden = 5120, @@ -59,6 +59,12 @@ test "SM110 product admits the two dense 27B formats and refuses other geometry .linear = @splat(false), }; for (0..g.layers) |i| g.linear[i] = i % 4 != 3; + return g; +} + +test "SM110 product admits the two dense 27B formats and refuses other geometry or weight recipes" { + const geometry = @import("cuda_geometry.zig"); + var g = dense27B(); try std.testing.expect(g.sm110Product()); g.bits.head = 8; try std.testing.expect(!g.sm110Product()); @@ -75,3 +81,33 @@ test "SM110 product admits the two dense 27B formats and refuses other geometry g.hidden = 4096; try std.testing.expect(!g.sm110Product()); } + +test "SM110 product refuses a different recurrent key head count" { + var g = dense27B(); + g.k_heads = 8; + try t.expect(!g.sm110Product()); +} + +test "SM110 product refuses a different recurrent value head count" { + var g = dense27B(); + g.v_heads = 32; + try t.expect(!g.sm110Product()); +} + +test "SM110 product refuses a different normalization epsilon" { + var g = dense27B(); + g.eps = 1e-5; + try t.expect(!g.sm110Product()); +} + +test "SM110 product refuses tied embedding and output weights" { + var g = dense27B(); + g.tied = true; + try t.expect(!g.sm110Product()); +} + +test "SM110 product refuses a different attention layer schedule" { + var g = dense27B(); + g.linear[g.layers - 1] = true; + try t.expect(!g.sm110Product()); +} From a0f809ea09d1656b51ba0b49d62192aab2f44230 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:39:36 +0000 Subject: [PATCH 060/361] changelog: #4796 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 99e693443a8..2668d5648ce 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 +- 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. From 77f3d3b76fee621852415069eebd1dde7fd9208b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:53:44 -0800 Subject: [PATCH 061/361] Use pre-M5 solo prompt frame rows with bounded decode plans --- docs/optimization-ledger.md | 2 +- docs/recipes/qwen3.8-27b.md | 3 ++ zig/qwen27_bank_boundary_host.zig | 43 ++++++++++++++++++++ zig/src/families/qwen27/attention.zig | 13 ++++-- zig/src/families/qwen27/attention_memory.zig | 9 ++-- zig/src/families/qwen27/attention_plan.zig | 15 ++++--- zig/src/families/qwen27/decode_round.zig | 9 +++- zig/src/native/qwen27_prompt_rows.zig | 8 +++- zig/src/native/qwen27_slots.zig | 6 +-- zig/src/qwen27_memory_test.zig | 3 +- zig/src/qwen27_rows_test.zig | 38 ++++++++++++++++- zig/src/qwen27_speed_test.zig | 19 +++++++++ zig/tests/qwen27/run.zig | 4 +- 13 files changed, 151 insertions(+), 21 deletions(-) diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index ba21f2e1051..68174124472 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -200,7 +200,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 17. DSpark | yes | no (scores) | yes | yes | | 18. Copy drafts | done¹ | no (scores) | done M¹ | done M¹ | | 19. Shared drafts | done [#578] | no (scores) | no (no head) | yes | -| 20. Solo chunks | yes | no (scores) | yes | yes | +| 20. Solo chunks | M5 yes; pre-M5 open [#2907] | no (scores) | yes | yes | | 21. Read-ahead | no (Metal) | yes | no (Metal) | no (Metal) | | 22. Direct load | yes | yes | yes | yes | | 23. Page drop | done M[#1885] | done [#1884] | done M[#1885] | done M[#1885] | diff --git a/docs/recipes/qwen3.8-27b.md b/docs/recipes/qwen3.8-27b.md index 3bac80cfdba..9969984dfa8 100644 --- a/docs/recipes/qwen3.8-27b.md +++ b/docs/recipes/qwen3.8-27b.md @@ -83,6 +83,9 @@ Larger or unbounded cuts keep the general draw. Sampling time has its own pass-p On Metal, M5 prompt passes request 2,048 rows when no other request is decoding. The dense 27B and 9B default frame follows the attention geometry at model load and serving. The qualified shared-prefix path keeps the 512-row default before M5; `TF_QWEN27_SHARED_PREFIX=0` on those chips uses a 128-row frame for its 128-row passes. +M1-M4 solo prompt chains take that frame's rows when the prompt attention kernels build, otherwise they keep +128-row passes. Decoded spans, trees and verifies keep their 128-row limit before M5; a live decoder caps the +next prompt chunk at 128 rows before M5, or 512 with tensor units. Valid `TF_PROMPT_ROWS` values and a caller's explicit row count remain unchanged, as do M5 and routed defaults. Less unused scratch on the unshared path may let a tight startup fit or admit more streams. The larger frame must fit the configured context and all streams beside loaded weights and the 8 GiB diff --git a/zig/qwen27_bank_boundary_host.zig b/zig/qwen27_bank_boundary_host.zig index cb3e51740a0..5cd77aa6ef2 100644 --- a/zig/qwen27_bank_boundary_host.zig +++ b/zig/qwen27_bank_boundary_host.zig @@ -78,3 +78,46 @@ test "qwen27 bank boundary: snapshot drain preserves the picked bonus while rese try g.settle(); try std.testing.expectEqual(@as(?u32, null), g.pending); } + +test "qwen27 bank boundary: decode rows retain the pre-M5 limit while solo prompt rows follow the frame" { + var model: q.model.Model = undefined; + var runner: q.decode_round.Runner = undefined; + runner.model = &model; + for ([_]u32{ 128, 512, 2048 }) |capacity| { + model.frame.capacity = capacity; + runner.geometry = .{ .shared_prefix = false, .solo_prompt = true }; + try std.testing.expectEqual(@as(u32, 128), runner.decodeRows()); + try std.testing.expectEqual(capacity, runner.promptRows(2048)); + runner.geometry.solo_prompt = false; + try std.testing.expectEqual(@as(u32, 128), runner.promptRows(2048)); + runner.geometry.shared_prefix = true; + try std.testing.expectEqual(capacity, runner.decodeRows()); + } +} + +test "qwen27 bank boundary: prompt partial scratch fits packed rows and rejects one tile past its bytes" { + const planning = q.attention.planning; + var parents: [2048]i32 = undefined; + for (&parents, 0..) |*p, i| p.* = @as(i32, @intCast(i)) - 1; + for ([_]u32{ 128, 512, 1024, 2048 }) |rows| { + const limits = q.attention.Limits{ .rows = rows, .streams = 1, .keys = 65536, .shared_prefix = false, .geometry = .{ .shared_prefix = false, .solo_prompt = true } }; + const layout = q.attention.Layout.init(limits); + const rp = @as(usize, layout.tiles) * 16; + const want = @max(@as(usize, @min(rows, planning.max_rows)) * 16, rp); + try std.testing.expectEqual(want, layout.chunk_rows); + try std.testing.expectEqual(@as(usize, 4) * layout.tail_chunks * want * 256 * 4, layout.sizes[10]); + try std.testing.expectEqual(@as(usize, 4) * @min(rows, planning.max_rows) * 16 * 256 * 2, layout.sizes[6]); + var scratch: q.attention.Scratch = undefined; + scratch.limits = limits; + scratch.tiles = layout.tiles; + scratch.chunks = layout.chunks; + scratch.tail_chunks = layout.tail_chunks; + scratch.chunk_rows = layout.chunk_rows; + var plan = try planning.Plan.init(std.testing.allocator, &.{.{ .parents = parents[0..rows], .start = 16384, .capacity = 65536 }}, limits.geometry); + defer plan.deinit(); + const chunks: u32 = @intCast(@divFloor(16384 + rows + planning.chunk - 1, planning.chunk)); + try scratch.checkPrompt(chunks, plan.tiles, false); + scratch.tiles = @intCast(layout.chunk_rows / 16 + 1); + try std.testing.expectError(error.AttentionLimits, scratch.checkPrompt(layout.tail_chunks, scratch.tiles, false)); + } +} diff --git a/zig/src/families/qwen27/attention.zig b/zig/src/families/qwen27/attention.zig index a3250c2cc28..c9e8ee8f4cd 100644 --- a/zig/src/families/qwen27/attention.zig +++ b/zig/src/families/qwen27/attention.zig @@ -6,6 +6,7 @@ const Ref = @import("projection.zig").Ref; const glue = @import("glue.zig"); pub const planning = @import("attention_plan.zig"); pub const Plan = planning.Plan; +pub const Layout = @import("attention_memory.zig").Layout; pub const Cache = struct { keys: Ref, values: Ref, @@ -150,10 +151,11 @@ pub const Scratch = struct { tiles: u32, chunks: u32, tail_chunks: u32, + chunk_rows: usize, uploaded: ?[32]u8 = null, pub fn init(device: mtl.Device, limits: Limits) !Scratch { try validLimits(limits); - const layout = @import("attention_memory.zig").Layout.init(limits); + const layout = Layout.init(limits); const sizes = layout.sizes; comptime std.debug.assert(sizes.len == std.enums.values(Field).len); var buffers: [sizes.len]mtl.Buffer = undefined; @@ -164,7 +166,11 @@ pub const Scratch = struct { made += 1; } @memset(buffers[@backingInt(Field.pick)].slice(u32, 12), 0); // the pick clears the flag after each read - return .{ .buffers = buffers, .limits = limits, .tiles = layout.tiles, .chunks = layout.chunks, .tail_chunks = layout.tail_chunks }; + return .{ .buffers = buffers, .limits = limits, .tiles = layout.tiles, .chunks = layout.chunks, .tail_chunks = layout.tail_chunks, .chunk_rows = layout.chunk_rows }; + } + pub fn checkPrompt(s: *const Scratch, chunks: u32, tiles: u32, shared: bool) !void { + if (chunks > s.chunks or tiles > s.tiles) return error.AttentionLimits; + if (!shared and @as(usize, chunks) * tiles * 16 > @as(usize, s.tail_chunks) * s.chunk_rows) return error.AttentionLimits; } pub fn deinit(s: *Scratch) void { for (s.buffers) |buffer| buffer.deinit(); @@ -470,10 +476,9 @@ pub const Attention = struct { const start: i32 = plan.meta[planning.global_words + 4]; for (plan.positions, 0..) |position, i| if (position != start + @as(i32, @intCast(i))) return error.PromptRowsNotChain; // the kernel places row i at start + i const chunks: u32 = @intCast(@divFloor(start + @as(i32, @intCast(plan.rows)) + planning.chunk - 1, planning.chunk)); - if (chunks > scratch.chunks or plan.tiles > scratch.tiles) return error.AttentionLimits; // before M5 (no shared prefix) the partials take the tail's buffers, which hold every chunk's packed rows const parts = if (g.shared_prefix) [3]Field{ .poa, .pma, .pla } else [3]Field{ .pob, .pmb, .plb }; - if (!g.shared_prefix and @as(usize, chunks) * plan.tiles * 16 > @as(usize, scratch.tail_chunks) * scratch.limits.rows * 16) return error.AttentionLimits; + try scratch.checkPrompt(chunks, plan.tiles, g.shared_prefix); const args = PromptArgs{ .start = start, .rows = @intCast(plan.rows), .chunks = @intCast(chunks), .rp = @intCast(plan.tiles * 16), .key_stride = @intCast(binding.strides[0][0]), .value_stride = @intCast(binding.strides[0][1]), .scale2 = 0.0625 * std.math.log2e, .kv_heads = @intCast(g.kv_heads) }; const pairs = prompt_threads / 64; // simdgroup pairs, each halving the head dim of one 16-row tile const pick = scratch.get(.pick).buffer; diff --git a/zig/src/families/qwen27/attention_memory.zig b/zig/src/families/qwen27/attention_memory.zig index 1b8b364f13c..138a0865c22 100644 --- a/zig/src/families/qwen27/attention_memory.zig +++ b/zig/src/families/qwen27/attention_memory.zig @@ -4,6 +4,7 @@ pub const Layout = struct { tiles: u32, chunks: u32, tail_chunks: u32, + chunk_rows: usize, sizes: [17]usize, pub fn init(limits: anytype) Layout { const hk: usize = limits.geometry.kv_heads; @@ -13,8 +14,10 @@ pub const Layout = struct { const rp: usize = tiles * 16; const a: usize = if (limits.shared_prefix) hk * @as(usize, chunks) * rp else 0; const tail_chunks = if (limits.shared_prefix) 3 else chunks; // a tail of up to 191 keys over 128-key chunks - const b: usize = hk * @as(usize, tail_chunks) * @as(usize, limits.rows) * 16; - const sizes = [_]usize{ tiles * 4, rp * 4, limits.rows * planning.node_words * 4, limits.rows * planning.path_width * 4, limits.rows * 4, hk * rp * dim * 2, hk * @as(usize, limits.rows) * 16 * dim * 2, a * dim * 4, a * 4, a * 4, b * dim * 4, b * 4, b * 4, limits.rows * hk * dim * 2, limits.rows * hk * dim * 2, 48, limits.rows * 3 * 4 }; // pick: the scan's flag, then two indirect grids - return .{ .tiles = tiles, .chunks = chunks, .tail_chunks = tail_chunks, .sizes = sizes }; + const tree_rows = if (limits.shared_prefix) limits.rows else @min(limits.rows, planning.max_rows); + const chunk_rows = if (limits.shared_prefix) @as(usize, tree_rows) * 16 else @max(@as(usize, tree_rows) * 16, rp); + const b: usize = hk * @as(usize, tail_chunks) * chunk_rows; + const sizes = [_]usize{ tiles * 4, rp * 4, limits.rows * planning.node_words * 4, limits.rows * planning.path_width * 4, limits.rows * 4, hk * rp * dim * 2, hk * @as(usize, tree_rows) * 16 * dim * 2, a * dim * 4, a * 4, a * 4, b * dim * 4, b * 4, b * 4, limits.rows * hk * dim * 2, limits.rows * hk * dim * 2, 48, limits.rows * 3 * 4 }; // pick: the scan's flag, then two indirect grids + return .{ .tiles = tiles, .chunks = chunks, .tail_chunks = tail_chunks, .chunk_rows = chunk_rows, .sizes = sizes }; } }; diff --git a/zig/src/families/qwen27/attention_plan.zig b/zig/src/families/qwen27/attention_plan.zig index a7f1b39451e..ecf7fd1058c 100644 --- a/zig/src/families/qwen27/attention_plan.zig +++ b/zig/src/families/qwen27/attention_plan.zig @@ -30,6 +30,8 @@ pub const Geometry = struct { shared_prefix: bool = true, /// Chains of rows take the prefix kernel to their last key; a test turns this off to compare with the tail kernel. fuse_chain: bool = true, + /// One chain of prompt rows may use the simdgroup prompt kernel beyond a tree round's row bound. + solo_prompt: bool = false, /// Read the target's attention geometry; the current kernel qualification still applies. pub fn fromConfig(c: @import("config.zig").Config, shared_prefix: bool) !Geometry { const g = Geometry{ @@ -54,7 +56,7 @@ pub const Geometry = struct { if (g.heads / g.kv_heads != 6 and !one_mac) return error.TargetAttentionShape; } pub fn promptRows(g: Geometry, requested: u32) u32 { - return @min(requested, @as(u32, if (g.shared_prefix and g.fuse_chain) chain_rows else max_rows)); + return @min(requested, @as(u32, if ((g.shared_prefix and g.fuse_chain) or g.solo_prompt) chain_rows else max_rows)); } pub fn group(g: Geometry) u32 { @@ -88,12 +90,15 @@ pub const Plan = struct { var tile_count: u32 = 0; var ca_max: u32 = 0; var cb_max: u32 = 0; - var fused = geometry.shared_prefix and geometry.fuse_chain; + var chain = true; for (windows) |w| for (w.parents, 0..) |p, r| if (r > 0 and p != @as(i32, @intCast(r)) - 1) { - fused = false; + chain = false; }; + const fused = geometry.shared_prefix and geometry.fuse_chain and chain; + const solo = geometry.solo_prompt and windows.len == 1 and chain; + const row_limit: usize = if (fused or solo) chain_rows else max_rows; for (windows, 0..) |w, st| { - if (w.parents.len == 0 or w.parents.len > @as(usize, if (fused) chain_rows else max_rows) or w.start > w.capacity or @as(u64, w.start) + w.parents.len > w.capacity or w.capacity > std.math.maxInt(i32) / geometry.dim) return error.AttentionCapacity; + if (w.parents.len == 0 or w.parents.len > row_limit or w.start > w.capacity or @as(u64, w.start) + w.parents.len > w.capacity or w.capacity > std.math.maxInt(i32) / geometry.dim) return error.AttentionCapacity; if (w.parents[0] != -1) return error.AttentionParents; var depths: [chain_rows]u32 = undefined; for (w.parents, 0..) |p, r| { @@ -129,7 +134,7 @@ pub const Plan = struct { ca_max = @max(ca_max, ca); cb_max = @max(cb_max, cb); } - if (row_count > @as(u32, if (fused) chain_rows else max_rows)) return error.AttentionRows; + if (row_count > row_limit) return error.AttentionRows; meta[0] = @intCast(windows.len); meta[1] = @intCast(ca_max); meta[2] = @intCast(tile_count); diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 741bd733429..5a05f6e8c92 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -151,6 +151,7 @@ pub const Runner = struct { }; defer library.deinit(); var attention = try attn.Attention.init(m.device, library); + geometry.solo_prompt = !units and attention.prompt != null; errdefer attention.deinit(); attention.join = try @import("attention_join.zig").build(a, m.device, units, geometry.group(), geometry.kv_heads, paged); pipelines.end(); @@ -527,11 +528,17 @@ pub const Runner = struct { return r.geometry.promptRows(@min(requested, r.model.frame.capacity)); } + pub fn decodeRows(r: *const Runner) u32 { + return if (r.geometry.shared_prefix) r.model.frame.capacity else attn.planning.max_rows; + } + pub fn attentionPlan(r: *Runner, round: *const Round) !attn.Plan { var windows: [attn.planning.max_streams]attn.planning.Window = undefined; if (round.windows.len > windows.len) return error.AttentionStreams; for (round.windows, round.slots, 0..) |window, slot, i| windows[i] = .{ .parents = window.parents, .start = window.start, .capacity = if (r.kv_step != null) r.heldRows(slot) else r.capacity }; - var plan = try attn.Plan.init(r.allocator, windows[0..round.windows.len], r.geometry); + var geometry = r.geometry; + geometry.solo_prompt = geometry.solo_prompt and r.model.kernels.prompt; + var plan = try attn.Plan.init(r.allocator, windows[0..round.windows.len], geometry); if (r.attention.join != null) plan.pair(&.{}); // a stream's rows in pairs over the keys below its window return plan; } diff --git a/zig/src/native/qwen27_prompt_rows.zig b/zig/src/native/qwen27_prompt_rows.zig index 893c77e99de..854847e7999 100644 --- a/zig/src/native/qwen27_prompt_rows.zig +++ b/zig/src/native/qwen27_prompt_rows.zig @@ -2,11 +2,17 @@ pub fn choose(b: anytype, current: anytype, at: usize) usize { const width = for (b.owners[0..b.runner.slots]) |owner| { const stream = owner orelse continue; - if (stream != current and !stream.finished and !stream.paused and !b.fills.contains(stream)) break @min(b.chunk, 512); + if (stream != current and !stream.finished and !stream.paused and !b.fills.contains(stream)) break @min(b.chunk, @as(usize, if (b.runner.model.device.tensorUnits()) 512 else 128)); } else b.chunk; return if (current.yield_check != null) @min(width, deep(b.chunk, at)) else width; } +/// Decoded spans keep the runner's decode bound even when a solo prompt can take its whole frame. +pub fn chunk(b: anytype, current: anytype, at: usize, decoded: bool) usize { + const rows = choose(b, current, at); + return if (decoded) @min(rows, @as(usize, b.runner.decodeRows())) else rows; +} + /// A background chunk's width at offset `at`: narrower with depth, each about as long (256 at least). pub fn deep(chunk: usize, at: usize) usize { const scaled = @min(chunk, chunk * 16384 / @max(at, 16384)); diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index f12947f6c93..27d2dcd3702 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -96,11 +96,11 @@ pub fn chunk(b: *Metal, s: *lanes.Stream, f: *Fill, _: u32) !bool { return error.Yielded; } const at = f.at; - var end = resume_rules.chunkEnd(at, @import("qwen27_prompt_rows.zig").choose(b, s, at), ids.len, s.chunks, s.decode_spans); - if (f.checkpoint > at and f.checkpoint < end) end = f.checkpoint; - end = resume_rules.rewindEnd(at, end, f.rewind); var decoded = false; for (s.decode_spans) |span| decoded = decoded or (at >= span[0] and at < span[1]); + var end = resume_rules.chunkEnd(at, @import("qwen27_prompt_rows.zig").chunk(b, s, at, decoded), ids.len, s.chunks, s.decode_spans); + if (f.checkpoint > at and f.checkpoint < end) end = f.checkpoint; + end = resume_rules.rewindEnd(at, end, f.rewind); var mark_bank: ?q.gdn_pool_gpu.PromptMarks = null; defer { if (mark_bank) |*m| { diff --git a/zig/src/qwen27_memory_test.zig b/zig/src/qwen27_memory_test.zig index 799e765d8bd..c0e0b605cfc 100644 --- a/zig/src/qwen27_memory_test.zig +++ b/zig/src/qwen27_memory_test.zig @@ -76,7 +76,8 @@ test "qwen27 memory: startup counts shared scratch once and each slot's state, K f.context = 32768; try std.testing.expect(try f.cost(2048, 2) < wide); f.shared = false; - try std.testing.expect(try f.cost(512, 2) > old); + const kv_and_slots = @as(usize, f.slots) * (@as(usize, f.context) * 16 * 2 * 1024 * 2 + (256 << 20)); + try std.testing.expect(try f.cost(512, 2) > kv_and_slots); } test "qwen27 memory: the development working-set cap cannot raise real capacity" { diff --git a/zig/src/qwen27_rows_test.zig b/zig/src/qwen27_rows_test.zig index c8abd5c3abc..7002b4b03ac 100644 --- a/zig/src/qwen27_rows_test.zig +++ b/zig/src/qwen27_rows_test.zig @@ -56,8 +56,21 @@ test "qwen27 rows: valid overrides stay exact and invalid ones use the chip defa } } +const Device = struct { + units: bool = true, + pub fn tensorUnits(d: Device) bool { + return d.units; + } +}; const Backend = struct { - runner: struct { slots: usize = 3 } = .{}, + runner: struct { + slots: usize = 3, + model: struct { device: Device = .{} } = .{}, + decode_rows: u32 = 2048, + pub fn decodeRows(r: *const @This()) u32 { + return r.decode_rows; + } + } = .{}, chunk: usize = 2048, owners: [3]?*Stream = @splat(null), fills: std.AutoHashMapUnmanaged(*Stream, bool) = .empty, @@ -188,3 +201,26 @@ test "qwen27 rows: empty or whitespace-only settings are unset and reach the loa try std.testing.expectEqual(@as(usize, 3), loader.calls); try std.testing.expectEqualStrings("unchanged", why); } + +test "qwen27 rows: pre-M5 decoded spans and a live decoder keep the 128-row bound" { + var prompt = try Stream.init(a, .{ .id = "prompt", .prompt = &.{ 1, 2 }, .max_new = 4, .drafts = false }); + defer prompt.deinit(a); + var decoder = try Stream.init(a, .{ .id = "decoder", .prompt = &.{ 1, 2 }, .max_new = 4, .drafts = false }); + defer decoder.deinit(a); + var b: Backend = .{ .owners = .{ &prompt, null, null } }; + defer b.fills.deinit(a); + try b.fills.put(a, &prompt, true); + for ([_]bool{ false, true }) |units| { + b.runner.model.device.units = units; + b.runner.decode_rows = if (units) 2048 else 128; + b.owners[1] = null; + try std.testing.expectEqual(@as(usize, 2048), policy.chunk(&b, &prompt, false)); + try std.testing.expectEqual(@as(usize, b.runner.decode_rows), policy.chunk(&b, &prompt, true)); + b.owners[1] = &decoder; + try std.testing.expectEqual(@as(usize, if (units) 512 else 128), policy.choose(&b, &prompt)); + try std.testing.expectEqual(@as(usize, if (units) 512 else 128), policy.chunk(&b, &prompt, true)); + decoder.paused = true; + try std.testing.expectEqual(@as(usize, 2048), policy.choose(&b, &prompt)); + decoder.paused = false; + } +} diff --git a/zig/src/qwen27_speed_test.zig b/zig/src/qwen27_speed_test.zig index dd9c9ffccfa..baeaa3c700d 100644 --- a/zig/src/qwen27_speed_test.zig +++ b/zig/src/qwen27_speed_test.zig @@ -117,3 +117,22 @@ test "qwen27 speed: every cache buffer failure frees the complete CPU allocation try std.testing.expectEqual(a.allocated, a.freed); } } + +test "qwen27 speed: only solo prompt chains may exceed the unfused tree row bound" { + var parents: [2048]i32 = undefined; + for (&parents, 0..) |*p, i| p.* = @as(i32, @intCast(i)) - 1; + const g = planning.Geometry{ .shared_prefix = false, .solo_prompt = true }; + for ([_]u32{ 512, 2048 }) |n| { + try std.testing.expectEqual(n, g.promptRows(n)); + var plan = try planning.Plan.init(std.testing.allocator, &.{.{ .parents = parents[0..n], .start = 8192, .capacity = 32768 }}, g); + defer plan.deinit(); + try std.testing.expectEqual(n, plan.rows); + try std.testing.expect(!plan.fused); + try std.testing.expectEqual(@as(i32, @intCast(8192 + n - 1)), plan.positions[n - 1]); + } + parents[128] = 0; + try std.testing.expectError(error.AttentionCapacity, planning.Plan.init(std.testing.allocator, &.{.{ .parents = parents[0..129], .start = 0, .capacity = 4096 }}, g)); + parents[128] = 127; + try std.testing.expectError(error.AttentionCapacity, planning.Plan.init(std.testing.allocator, &.{.{ .parents = parents[0..129], .start = 0, .capacity = 4096 }}, .{ .shared_prefix = false })); + try std.testing.expectError(error.AttentionRows, planning.Plan.init(std.testing.allocator, &.{ .{ .parents = parents[0..64], .start = 0, .capacity = 4096 }, .{ .parents = parents[0..65], .start = 0, .capacity = 4096 } }, g)); +} diff --git a/zig/tests/qwen27/run.zig b/zig/tests/qwen27/run.zig index a1be85fe5b6..9537e173757 100644 --- a/zig/tests/qwen27/run.zig +++ b/zig/tests/qwen27/run.zig @@ -38,6 +38,8 @@ fn write(a: std.mem.Allocator, io: std.Io, dir: []const u8, name: []const u8, te fn emit(a: std.mem.Allocator, io: std.Io, dir: []const u8) !void { try write(a, io, dir, "glue.metal", sources.glue ++ sources.copy); try write(a, io, dir, "attention.metal", sources.glue ++ sources.attention_mpp ++ sources.attention_io); + try write(a, io, dir, "attention-tensor.metal", try q.simd_attention.grouped(a, true, true, 6, 4, false)); + try write(a, io, dir, "attention-simd.metal", try q.simd_attention.grouped(a, false, true, 6, 4, false)); try write(a, io, dir, "gdn.metal", gdn_source.text); const helpers = [_]q.quant_gpu.Kind{ .input_norm, .norm, .mlp, .xsum }; const names = [_][]const u8{ "norm_input", "norm_xs", "mlp_xs", "xsum" }; @@ -260,7 +262,7 @@ pub fn main(init: std.process.Init) !void { .prompt_ns = prompt_ns, .decode_ns = decode_ns, .prompt_tok_s = @as(f64, @floatFromInt(ids.len)) * 1e9 / @as(f64, @floatFromInt(@max(prompt_ns, 1))), - .physical_prompt_rows = 128, + .physical_prompt_rows = runner.promptRows(@intCast(chunk)), .projection_rows = 16, .prompt_sha256 = @as([]const u8, &digest_hex), }, .{}); From 6e63991daf7e7e09ce7d373bdfea5462994838a0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:34:31 +0000 Subject: [PATCH 062/361] qwen27: deep() names its width parameter so it no longer shadows the new chunk() --- zig/src/native/qwen27_prompt_rows.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/native/qwen27_prompt_rows.zig b/zig/src/native/qwen27_prompt_rows.zig index 854847e7999..25033ef48b7 100644 --- a/zig/src/native/qwen27_prompt_rows.zig +++ b/zig/src/native/qwen27_prompt_rows.zig @@ -14,7 +14,7 @@ pub fn chunk(b: anytype, current: anytype, at: usize, decoded: bool) usize { } /// A background chunk's width at offset `at`: narrower with depth, each about as long (256 at least). -pub fn deep(chunk: usize, at: usize) usize { - const scaled = @min(chunk, chunk * 16384 / @max(at, 16384)); +pub fn deep(width: usize, at: usize) usize { + const scaled = @min(width, width * 16384 / @max(at, 16384)); return @max(256, scaled / 128 * 128); } From 8d65ac62cd9ba97d78d458303f73d3cb991b8d6a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:55:16 +0000 Subject: [PATCH 063/361] qwen27: pin rebased prompt sources and adapt host row tests Keep the current depth argument in the imported row regressions. Pin every changed serving source by its raw SHA-256 and describe the prompt-frame change under Unreleased. --- zig/src/qwen27_rows_test.zig | 10 +++++----- zig/tests/fixtures/gradient-serving.tsv | 6 ++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/zig/src/qwen27_rows_test.zig b/zig/src/qwen27_rows_test.zig index 7002b4b03ac..5c6f88bf6d3 100644 --- a/zig/src/qwen27_rows_test.zig +++ b/zig/src/qwen27_rows_test.zig @@ -214,13 +214,13 @@ test "qwen27 rows: pre-M5 decoded spans and a live decoder keep the 128-row boun b.runner.model.device.units = units; b.runner.decode_rows = if (units) 2048 else 128; b.owners[1] = null; - try std.testing.expectEqual(@as(usize, 2048), policy.chunk(&b, &prompt, false)); - try std.testing.expectEqual(@as(usize, b.runner.decode_rows), policy.chunk(&b, &prompt, true)); + try std.testing.expectEqual(@as(usize, 2048), policy.chunk(&b, &prompt, 0, false)); + try std.testing.expectEqual(@as(usize, b.runner.decode_rows), policy.chunk(&b, &prompt, 0, true)); b.owners[1] = &decoder; - try std.testing.expectEqual(@as(usize, if (units) 512 else 128), policy.choose(&b, &prompt)); - try std.testing.expectEqual(@as(usize, if (units) 512 else 128), policy.chunk(&b, &prompt, true)); + try std.testing.expectEqual(@as(usize, if (units) 512 else 128), policy.choose(&b, &prompt, 0)); + try std.testing.expectEqual(@as(usize, if (units) 512 else 128), policy.chunk(&b, &prompt, 0, true)); decoder.paused = true; - try std.testing.expectEqual(@as(usize, 2048), policy.choose(&b, &prompt)); + try std.testing.expectEqual(@as(usize, 2048), policy.choose(&b, &prompt, 0)); decoder.paused = false; } } diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 94054526225..881359631b9 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -167,3 +167,9 @@ zig/src/families/flashnext/cuda_round_graph.zig 7fa3a54e93c81de36cf3962d0a68eb72 zig/src/families/flashnext/cuda_rows.zig 735fc8915036e47d09f533f4e5948e5fc4b61556172ebe2c6bfdaad3e0373216 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_select_main.zig 5c012c2d59fa6dd573424fce7b6d8b162a06cb9f6103530a0fc0b03dbdb17bd3 raw zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e7240c7da7f0bd8504080a6b56 raw main 4f6017ced (prompt cache marks kept inside the pass), #1953: the prompt cache ladder's values +zig/src/families/qwen27/attention.zig 2fce3087ee3079ac2f06e43c7b6a6fc148ee05bf89b0cfc30ab2120f8d42ab3f raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention_memory.zig 0602a104408a18917c6407feaef3b67bed741739e4762a3d5e972bb874d5865e raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention_plan.zig b905bedc98a5864c7ff3ac98b17d44a5b98170ec5c6b7b5954480415fa0f133c raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/decode_round.zig 43f5826f6913e4964a4158184392a1b9567a27e2cb11b40cf48f11c0b16633de raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig 40984d6b608f156add25400ad52ae86aa25c1eacca828972794909fef096cd7f raw #2916 (solo prompt frames; decode and shared limits retained) From b47f9a0d51b3fabb36be7c4dce1c35536887cf28 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:34:00 +0000 Subject: [PATCH 064/361] qwen27: refresh rebased serving pins and pending device ledger --- docs/optimization-ledger.md | 2 +- zig/src/families/qwen27/decode_round.zig | 1 - zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 68174124472..f87341fe5c5 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -200,7 +200,7 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 17. DSpark | yes | no (scores) | yes | yes | | 18. Copy drafts | done¹ | no (scores) | done M¹ | done M¹ | | 19. Shared drafts | done [#578] | no (scores) | no (no head) | yes | -| 20. Solo chunks | M5 yes; pre-M5 open [#2907] | no (scores) | yes | yes | +| 20. Solo chunks | M5 yes; pre-M5 implemented M[#2916], device gate pending | no (scores) | yes | yes | | 21. Read-ahead | no (Metal) | yes | no (Metal) | no (Metal) | | 22. Direct load | yes | yes | yes | yes | | 23. Page drop | done M[#1885] | done [#1884] | done M[#1885] | done M[#1885] | diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 5a05f6e8c92..75a3ea5f0da 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -138,7 +138,6 @@ pub const Runner = struct { const units = m.device.tensorUnits(); // before M5 the tail attention reads its tensor-op results in the simdgroup-matrix layout (simd_attention.zig) if (!units) try @import("simd_attention.zig").check(m.device, m.queue); - // both builds take the kernels' KV group as the defines attention_mpp.metal reads const text = try @import("simd_attention.zig").grouped(a, units, true, geometry.group(), geometry.kv_heads, paged); defer a.free(text); // before M5 the prompt kernels are optional: a chip that cannot build them keeps the decode path for prompts diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 881359631b9..e765b4f1df3 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -170,6 +170,6 @@ zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e zig/src/families/qwen27/attention.zig 2fce3087ee3079ac2f06e43c7b6a6fc148ee05bf89b0cfc30ab2120f8d42ab3f raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_memory.zig 0602a104408a18917c6407feaef3b67bed741739e4762a3d5e972bb874d5865e raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_plan.zig b905bedc98a5864c7ff3ac98b17d44a5b98170ec5c6b7b5954480415fa0f133c raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/decode_round.zig 43f5826f6913e4964a4158184392a1b9567a27e2cb11b40cf48f11c0b16633de raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/decode_round.zig 4f45741b0fd3c61886ad1412984790ffa806a7b7c29c0ac19ac757e8166990b6 raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/native/qwen27_slots.zig 40984d6b608f156add25400ad52ae86aa25c1eacca828972794909fef096cd7f raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig 531b66b372afeed00e8ae41ed8d4b5ef5897243275b7cbca2787585de86cba3e raw #2916 (solo prompt frames; decode and shared limits retained) From 15b6dfdc4de046e9adc53a468c940b78d97371d9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:57:17 +0000 Subject: [PATCH 065/361] fix: keep attention and decode_round under 600 lines after the solo prompt rows Main had blank separators the rebased PR did not; with the solo prompt fields each file reached 602 and 605 lines. Five and two blank separators were dropped so both files are 600 lines, with every statement unchanged. --- zig/src/families/qwen27/attention.zig | 5 ----- 1 file changed, 5 deletions(-) diff --git a/zig/src/families/qwen27/attention.zig b/zig/src/families/qwen27/attention.zig index c9e8ee8f4cd..05e31e4854c 100644 --- a/zig/src/families/qwen27/attention.zig +++ b/zig/src/families/qwen27/attention.zig @@ -320,7 +320,6 @@ pub const Attention = struct { var timing = profile.begin(a.profiler, input_encoder, .attention_prepare); errdefer timing.cancel(); const e = timing.encoder; - if (p.rows == 0 or p.rows > @import("gpu_frame.zig").max_rows or !std.math.isFinite(p.eps) or p.eps <= 0 or !std.math.isFinite(p.theta) or p.theta <= 0) return error.TargetAttentionShape; try span(p.qg, 2 * q_bytes); try span(p.key, kv_bytes); @@ -416,7 +415,6 @@ pub const Attention = struct { var timing = profile.begin(a.profiler, input_encoder, .attention); errdefer timing.cancel(); const e = timing.encoder; - try scratch.check(plan); try binding.check(plan, caches); try spanAligned(q, q_bytes, 16); @@ -578,7 +576,6 @@ test "cache and pack descriptors match native pointer and six-word ABI" { try std.testing.expectEqual(@as(usize, 24), @sizeOf(PackArgs)); try std.testing.expectEqual(@as(usize, 16), @sizeOf(planning.KeepRow)); } - test "plan fingerprint changes for an ancestor mutation rather than only counts" { var plan = try Plan.init(std.testing.allocator, &.{.{ .parents = &.{ -1, 0, 0 }, .start = 63, .capacity = 512 }}, .{}); defer plan.deinit(); @@ -586,7 +583,6 @@ test "plan fingerprint changes for an ancestor mutation rather than only counts" plan.paths[2 * planning.path_width + 1] = 1; try std.testing.expect(!std.mem.eql(u8, &before, &fingerprint(plan))); } - test "cache span includes padded head strides but no unused trailing padding" { const cache = Cache{ .keys = undefined, .values = undefined, .capacity = 8, .key_stride = 4096, .value_stride = 8192 }; try std.testing.expectEqual(@as(usize, 28672), cacheBytes(cache, true, .{})); @@ -594,7 +590,6 @@ test "cache span includes padded head strides but no unused trailing padding" { const contiguous = Cache{ .keys = undefined, .values = undefined, .capacity = 8 }; try std.testing.expectEqual(@as(usize, 16384), cacheBytes(contiguous, true, .{})); } - test "descriptor identity includes numeric geometry and limits still refuse new shaders" { var plan = try Plan.init(std.testing.allocator, &.{.{ .parents = &.{-1}, .start = 0, .capacity = 8 }}, .{}); defer plan.deinit(); From 5a596921598a9dde20a334b8dd34387fa0c9d1d8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:57:17 +0000 Subject: [PATCH 066/361] tests: re-pin four qwen27 serving sources on main af9777b494 attention, attention_memory, attention_plan and decode_round carry main's extra mates field and prompt-plan pair, so their raw hashes changed; the six #2916 pins now match the rebased files. --- zig/tests/fixtures/gradient-serving.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index e765b4f1df3..db96a368b17 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -167,9 +167,9 @@ zig/src/families/flashnext/cuda_round_graph.zig 7fa3a54e93c81de36cf3962d0a68eb72 zig/src/families/flashnext/cuda_rows.zig 735fc8915036e47d09f533f4e5948e5fc4b61556172ebe2c6bfdaad3e0373216 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_select_main.zig 5c012c2d59fa6dd573424fce7b6d8b162a06cb9f6103530a0fc0b03dbdb17bd3 raw zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e7240c7da7f0bd8504080a6b56 raw main 4f6017ced (prompt cache marks kept inside the pass), #1953: the prompt cache ladder's values -zig/src/families/qwen27/attention.zig 2fce3087ee3079ac2f06e43c7b6a6fc148ee05bf89b0cfc30ab2120f8d42ab3f raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/attention_memory.zig 0602a104408a18917c6407feaef3b67bed741739e4762a3d5e972bb874d5865e raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/attention_plan.zig b905bedc98a5864c7ff3ac98b17d44a5b98170ec5c6b7b5954480415fa0f133c raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/decode_round.zig 4f45741b0fd3c61886ad1412984790ffa806a7b7c29c0ac19ac757e8166990b6 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention.zig 7026b7176edee7a5b019bbd59efceb099ca47f3231fbc7c1e9031d53f2ea5c22 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention_memory.zig 49b9a2643b1499d26cd3d41066ab77351eb6a0258fae87eb880503ccd5c5ecec raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention_plan.zig c5293b8ee88faa995ee3bdb46f5c7d0b8a020f8614ded8559dcab0cc028e9e66 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/decode_round.zig b4907a73ea1d1be640ed4a1eddbd35529b819ad24018faa41c7493fb167d2d2a raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_slots.zig 531b66b372afeed00e8ae41ed8d4b5ef5897243275b7cbca2787585de86cba3e raw #2916 (solo prompt frames; decode and shared limits retained) From 0bb5a196a93aea5de1fa0f8fe57466b489d442b4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:31:36 +0000 Subject: [PATCH 067/361] qwen27: fold comments to keep decode_round at 600 lines (#2916) --- zig/src/families/qwen27/decode_round.zig | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 75a3ea5f0da..381a185d722 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -136,12 +136,10 @@ pub const Runner = struct { errdefer pool.deinit(); const pipelines = @import("core").startup_receipt.span(.runtime_pipelines); const units = m.device.tensorUnits(); - // before M5 the tail attention reads its tensor-op results in the simdgroup-matrix layout (simd_attention.zig) - if (!units) try @import("simd_attention.zig").check(m.device, m.queue); + if (!units) try @import("simd_attention.zig").check(m.device, m.queue); // before M5 the tail reads simdgroup-matrix results const text = try @import("simd_attention.zig").grouped(a, units, true, geometry.group(), geometry.kv_heads, paged); defer a.free(text); - // before M5 the prompt kernels are optional: a chip that cannot build them keeps the decode path for prompts - const library = mtl.Library.fromSource(m.device, text, mtl.CompileOptions.mlx()) catch |err| blk: { + const library = mtl.Library.fromSource(m.device, text, mtl.CompileOptions.mlx()) catch |err| blk: { // before M5 prompt kernels are optional; a chip that cannot build them keeps decode prompts if (units) return err; std.log.info("qwen27: the prompt attention kernels do not build here ({t}); prompt rows take the decode path", .{err}); const base = try @import("simd_attention.zig").grouped(a, units, false, geometry.group(), geometry.kv_heads, paged); @@ -194,14 +192,12 @@ pub const Runner = struct { pub const release = slot_pages.release; pub const reset = slot_pages.reset; - /// Slot `slot`'s pages past its committed rows go back to its promise; no GPU work in flight reads them. - fn trimSlot(r: *Runner, slot: u32) void { + fn trimSlot(r: *Runner, slot: u32) void { // pages past committed rows go back to the promise; no GPU work reads them const k = r.kv orelse return; k.pages.trim(slot, r.offsets[slot]); } - /// Slot `slot`'s first `at` rows of each attention layer's keys then values, head by head, page by page. - pub fn kvSpans(r: *const Runner, a: std.mem.Allocator, slot: u32, at: u32, list: *std.ArrayList(KvSpan)) !void { + pub fn kvSpans(r: *const Runner, a: std.mem.Allocator, slot: u32, at: u32, list: *std.ArrayList(KvSpan)) !void { // first `at` rows of K then V, head by head, page by page return kv_pages.spans(r, a, slot, at, list); } From 362833ef0680105446e96e42c4cf4c2d2e50d5bc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:45:59 +0000 Subject: [PATCH 068/361] tests: re-pin qwen27 serving sources after rebase onto main (#2916) --- zig/tests/fixtures/gradient-serving.tsv | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index db96a368b17..2c93672e2ea 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -167,9 +167,9 @@ zig/src/families/flashnext/cuda_round_graph.zig 7fa3a54e93c81de36cf3962d0a68eb72 zig/src/families/flashnext/cuda_rows.zig 735fc8915036e47d09f533f4e5948e5fc4b61556172ebe2c6bfdaad3e0373216 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_select_main.zig 5c012c2d59fa6dd573424fce7b6d8b162a06cb9f6103530a0fc0b03dbdb17bd3 raw zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e7240c7da7f0bd8504080a6b56 raw main 4f6017ced (prompt cache marks kept inside the pass), #1953: the prompt cache ladder's values -zig/src/families/qwen27/attention.zig 7026b7176edee7a5b019bbd59efceb099ca47f3231fbc7c1e9031d53f2ea5c22 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention.zig ef533e2d07f0b38bd035cc79f282a621ae2b8604ef0f2d0436935b85e45fb55b raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_memory.zig 49b9a2643b1499d26cd3d41066ab77351eb6a0258fae87eb880503ccd5c5ecec raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_plan.zig c5293b8ee88faa995ee3bdb46f5c7d0b8a020f8614ded8559dcab0cc028e9e66 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/decode_round.zig b4907a73ea1d1be640ed4a1eddbd35529b819ad24018faa41c7493fb167d2d2a raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/decode_round.zig 4562446da00af59fbbede2d5b3c0ebdb76ab3d8e640083d87e5f8fcb641bf244 raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/native/qwen27_slots.zig 531b66b372afeed00e8ae41ed8d4b5ef5897243275b7cbca2787585de86cba3e raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig 23994de2663e0300d9ebb7275ebfd74964323f90b672dfbc4a9a03c6cfb6d6ab raw #2916 (solo prompt frames; decode and shared limits retained) From 1e09804319bc9543d317cf73d939e47c523ed52a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:05:17 +0000 Subject: [PATCH 069/361] qwen27: geometry stays mutable for the solo prompt flag after main's fromConfig The rebase kept main's `const geometry` from Geometry.fromConfig; #2916 sets geometry.solo_prompt once the prompt kernels build, so it is a var again. --- zig/src/families/qwen27/decode_round.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 381a185d722..5c3cac9c78e 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -109,7 +109,7 @@ pub const Runner = struct { fn build(a: std.mem.Allocator, m: *Model, slots: u32, capacity: u32, ready: u32, paged: bool, kv_step: ?u32) !Runner { if (slots == 0 or slots > attn.planning.max_streams or capacity == 0 or m.frame.capacity % 16 != 0 or ready == 0 or ready > slots) return error.BadRoundCapacity; - const geometry = try attn.planning.Geometry.fromConfig(m.config, try @import("simd_attention.zig").sharedPrefix(m.device.tensorUnits())); + var geometry = try attn.planning.Geometry.fromConfig(m.config, try @import("simd_attention.zig").sharedPrefix(m.device.tensorUnits())); const linear_index = try a.alloc(u32, m.config.layers); errdefer a.free(linear_index); // with the MTP head loaded, its block is one more attention layer past the last (forward.layerAt) From 9a18bf566dd114f516d9a75b8b01fd9b70a4409c Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:11:53 +0000 Subject: [PATCH 070/361] qwen27: compact row helpers for the 600-line cap --- zig/src/families/qwen27/decode_round.zig | 2 -- 1 file changed, 2 deletions(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 5c3cac9c78e..10455b8e35b 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -522,11 +522,9 @@ pub const Runner = struct { pub fn promptRows(r: *const Runner, requested: u32) u32 { return r.geometry.promptRows(@min(requested, r.model.frame.capacity)); } - pub fn decodeRows(r: *const Runner) u32 { return if (r.geometry.shared_prefix) r.model.frame.capacity else attn.planning.max_rows; } - pub fn attentionPlan(r: *Runner, round: *const Round) !attn.Plan { var windows: [attn.planning.max_streams]attn.planning.Window = undefined; if (round.windows.len > windows.len) return error.AttentionStreams; From d2cb5ff2162500627cd0f23bbed4e4626c28bc71 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:12:17 +0000 Subject: [PATCH 071/361] qwen27: re-pin the rebased solo prompt decoder --- zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 2c93672e2ea..0f85664d017 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -170,6 +170,6 @@ zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e zig/src/families/qwen27/attention.zig ef533e2d07f0b38bd035cc79f282a621ae2b8604ef0f2d0436935b85e45fb55b raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_memory.zig 49b9a2643b1499d26cd3d41066ab77351eb6a0258fae87eb880503ccd5c5ecec raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_plan.zig c5293b8ee88faa995ee3bdb46f5c7d0b8a020f8614ded8559dcab0cc028e9e66 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/decode_round.zig 4562446da00af59fbbede2d5b3c0ebdb76ab3d8e640083d87e5f8fcb641bf244 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/decode_round.zig 933b1971399c1ba0cc2299e398eb7d8bfaf3a4b6a5eff1a9d0b6570de2a07ccc raw main 1eed88bb09 (public attentionPlan and lane-core Drafter/tail state retained), #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/native/qwen27_slots.zig 23994de2663e0300d9ebb7275ebfd74964323f90b672dfbc4a9a03c6cfb6d6ab raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig ac6b8f6f3b570187da624960d887368ed8a2d678e8f3f98e96b4d40ed0628343 raw #2916 (solo prompt frames; decode and shared limits retained) From c6abe6348305439f9dcae182baaae90b6e03c800 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:51:43 +0000 Subject: [PATCH 072/361] tests: re-pin three qwen27 serving sources after the rebase onto main ea37382cb1 attention_plan.zig, decode_round.zig and qwen27_slots.zig now hold main's per-slot window capacity beside this change's solo prompt rows, so their pins move to the rebased bytes. No source changes. --- zig/tests/fixtures/gradient-serving.tsv | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 0f85664d017..aa0c37b2a87 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -169,7 +169,7 @@ zig/src/families/flashnext/cuda_select_main.zig 5c012c2d59fa6dd573424fce7b6d8b16 zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e7240c7da7f0bd8504080a6b56 raw main 4f6017ced (prompt cache marks kept inside the pass), #1953: the prompt cache ladder's values zig/src/families/qwen27/attention.zig ef533e2d07f0b38bd035cc79f282a621ae2b8604ef0f2d0436935b85e45fb55b raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/attention_memory.zig 49b9a2643b1499d26cd3d41066ab77351eb6a0258fae87eb880503ccd5c5ecec raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/attention_plan.zig c5293b8ee88faa995ee3bdb46f5c7d0b8a020f8614ded8559dcab0cc028e9e66 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/decode_round.zig 933b1971399c1ba0cc2299e398eb7d8bfaf3a4b6a5eff1a9d0b6570de2a07ccc raw main 1eed88bb09 (public attentionPlan and lane-core Drafter/tail state retained), #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention_plan.zig 898964a99410620766416c5d5a350ab96061e9d2883354875f7da9e431a9ddc4 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/decode_round.zig 67ef8d3358e5239943ae80fc67bc431bf40d119206df1cc6ab9fe0505e064cde raw main 1eed88bb09 (public attentionPlan and lane-core Drafter/tail state retained), #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/native/qwen27_slots.zig ac6b8f6f3b570187da624960d887368ed8a2d678e8f3f98e96b4d40ed0628343 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig c98070c752614213466f8e5a5c431b25ba1db7f2b4dfb686569206005342c247 raw #2916 (solo prompt frames; decode and shared limits retained) From 510a8d51c37635a9acddab4c2753fd01f9f5703b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:25 +0000 Subject: [PATCH 073/361] changelog: #2916 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2668d5648ce..24c8bde7d51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.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. From 06f23eaf7c5566c0933e21a38fe56b88c3452d15 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:25 +0000 Subject: [PATCH 074/361] changelog: #2916 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24c8bde7d51..c62b43a35b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ 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. From a5a8c914b0bdc18b58fedadac72d158100147035 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:35:49 +0000 Subject: [PATCH 075/361] cli: start a fitting checkpoint with consent and a reply check --- docs/run-guide.md | 13 ++ zig/build/cuda.zig | 12 +- zig/build/cuda_server_host.zig | 16 +++ zig/build/server.zig | 10 ++ zig/src/cli/cli.zig | 9 +- zig/src/cli/cuda_main.zig | 2 + zig/src/cli/models.zig | 74 ++++++++++ zig/src/cli/start.zig | 10 ++ zig/src/server/main.zig | 2 + zig/src/server/start_cli.zig | 222 ++++++++++++++++++++++++++++++ zig/src/server/start_cli_test.zig | 203 +++++++++++++++++++++++++++ 11 files changed, 567 insertions(+), 6 deletions(-) create mode 100644 zig/src/cli/start.zig create mode 100644 zig/src/server/start_cli.zig create mode 100644 zig/src/server/start_cli_test.zig diff --git a/docs/run-guide.md b/docs/run-guide.md index 3b270539ddc..ff4054c1aff 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -19,6 +19,19 @@ a container and the tests that need no GPU. The archive's binary is `tensorfold-native`; the quick start defines a `tensorfold` shell function that calls it. - **Windows with an NVIDIA GPU:** follow [the native Windows build guide](WINDOWS.md). +## Select, download and prove a model + +After installation, `tensorfold start` uses the same machine probe and registry as `tensorfold models`, picks the largest +fully pinned checkpoint that fits and `tensorfold pull` can install, shows its download size, and asks before downloading. +`--yes` gives that consent explicitly. Without `--yes`, a non-interactive run stops before any download; an interactive +run accepts only `y` or `yes`. A cached model and its drafter need no prompt or download. + +The command starts a loopback server and sends one deterministic request. `--check` stops that server after a nonempty +reply and exits 0; without `--check`, the checked server stays in the foreground and Ctrl-C stops it. A failed first reply +is fatal and the started server is stopped. The request key is not printed. No existing `serve` default or flag changes. + +Windows refuses managed server startup: use `tensorfold serve` in one console and `tensorfold chat --url` in another. + ## Send a request Leave the server running. In another terminal, on either platform: diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 0d068dd3e96..9956b346939 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -94,7 +94,9 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const native = engines(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision); for ([_]struct { []const u8, *std.Build.Module }{ .{ "cuda", cuda }, .{ "core", mods.core }, .{ "lanes", mods.lanes }, .{ "nemotron", mods.nemotron }, .{ "dory", native.engines.import_table.get("dory").? }, .{ "cluster", @import("cluster_cuda.zig").module(b, target, optimize, mods.lanes, mods.core, native.canon, native.verbs) }, .{ "ricursive_cuda", native.engines.import_table.get("ricursive_cuda").? } }) |m| cli.addImport(m[0], m[1]); cli.addOptions("build_options", build_options); - cli.addImport("checkpoint_cli", checkpointCli(b, target, optimize, strip, native.engines, mods.core)); + const checkpoint_cli = checkpointCli(b, target, optimize, strip, native.engines, mods.core); + cli.addImport("checkpoint_cli", checkpoint_cli); + cli.addImport("server_start", @import("server.zig").startModule(b, target, optimize, checkpoint_cli, native.api, mods.core, @import("server.zig").json(b, target, optimize))); const cli_exe = b.addExecutable(.{ .name = "tensorfold", .root_module = cli }); b.installArtifact(cli_exe); b.step("compile-cuda-cli", "Compile the CUDA tensorfold CLI without executing a GPU").dependOn(&cli_exe.step); @@ -457,12 +459,16 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st cli.addImport("lanes", mods.lanes); cli.addImport("nemotron", mods.nemotron); cli.addOptions("build_options", build_options); - cli.addImport("checkpoint_cli", checkpointCli(b, host, .debug, false, native_modules.engines, mods.core)); + const checkpoint_cli = checkpointCli(b, host, .debug, false, native_modules.engines, mods.core); + cli.addImport("checkpoint_cli", checkpoint_cli); + cli.addImport("server_start", @import("server.zig").startModule(b, host, .debug, checkpoint_cli, native_modules.api, mods.core, @import("server.zig").json(b, host, .debug))); const memory_cli = checkpointCli(b, host, .debug, false, native_modules.engines, mods.core); memory_cli.root_source_file = b.path("zig/src/cli/tests.zig"); b.step("test-cli-memory-host", "Actual checkpoint info memory tests without device or shader producers").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = memory_cli, .filters = &.{ "info prints family", "issue 934:", "plan" } })).step); b.step("test-info-config", "Info shares the checkpoint config reader and diagnostics").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = memory_cli, .filters = &.{"issue 934:"} })).step); - step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cli })).step); + const cli_run = b.addRunArtifact(b.addTest(.{ .root_module = cli })); + b.step("test-cli-host", "Checkpoint CLI parsing and CUDA start dispatch without devices").dependOn(&cli_run.step); + step.dependOn(&cli_run.step); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = memory_cli, .filters = &.{"plan"} })).step); // plan's verdict tests in the plain `zig build test` gate } diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 849e678015b..62809e5ea31 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -96,6 +96,22 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod b.step("test-benchmark-routing-host", "Benchmark command routing from explicit model capabilities").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"benchmark routing:"} })).step); b.step("test-benchmark-cancel-host", "A cancelled local benchmark saves its receipt, exits 130 and never publishes").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"a cancelled local run"} })).step); b.step("test-chat-cli-host", "tensorfold chat's flags, stream, history, Ctrl-C and serve child against a fake server").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"chat CLI:"} })).step); + const start_tests = b.createModule(.{ + .root_source_file = b.path("zig/src/server/start_cli_test.zig"), + .target = host, + .optimize = .debug, + .link_libc = true, + .imports = &.{ + .{ .name = "engine_api", .module = native_modules.api }, + .{ .name = "core", .module = mods.core }, + .{ .name = "json", .module = server_json }, + .{ .name = "checkpoint_cli", .module = @import("cuda.zig").checkpointCli(b, host, .debug, false, native_modules.engines, mods.core) }, + }, + }); + const start_run = b.addRunArtifact(b.addTest(.{ .root_module = start_tests, .filters = &.{"start CLI:"} })); + start_run.has_side_effects = true; + b.step("test-start-cli-host", "Automatic model choice, download consent, first reply and serve-child cleanup without devices").dependOn(&start_run.step); + step.dependOn(&start_run.step); const server_step = b.step( "test-server-cpu", "The HTTP server's unit tests (routes, templates, tool parsing) without a GPU", diff --git a/zig/build/server.zig b/zig/build/server.zig index c8f7e67d5a3..c6886be2bfb 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -53,6 +53,16 @@ pub fn json(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.built }); } +pub fn startModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, checkpoint: *std.Build.Module, api: *std.Build.Module, core: *std.Build.Module, j: *std.Build.Module) *std.Build.Module { + return b.createModule(.{ + .root_source_file = b.path("zig/src/server/start_cli.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "checkpoint_cli", .module = checkpoint }, .{ .name = "engine_api", .module = api }, .{ .name = "core", .module = core }, .{ .name = "json", .module = j } }, + }); +} + /// Attach a server's shared JSON module (tests run apart), and Living Weights' families where the build gave none. pub fn addTo( b: *std.Build, diff --git a/zig/src/cli/cli.zig b/zig/src/cli/cli.zig index 3afcf3e3cf8..4995d2ea663 100644 --- a/zig/src/cli/cli.zig +++ b/zig/src/cli/cli.zig @@ -10,9 +10,12 @@ const journal_log = @import("journal_log.zig"); const lora_merge = @import("core").lora_merge; /// The checkpoints `models` lists, sized, for `tensorfold device`. pub const onDisk = models.onDisk; +/// `tensorfold start`'s view of the existing registry, fit selector and pull implementation. +pub const start = @import("start.zig"); const usage = \\usage: tensorfold models [--all] [--json] + \\ tensorfold start [--yes] [--check] [--startup-timeout SECONDS] \\ tensorfold info MODEL [--context N] [--parallel N|auto] \\ tensorfold rm REPO[@REVISION] [--yes] [--dry-run] \\ tensorfold pull REPO[@REVISION] @@ -106,12 +109,12 @@ pub fn main(init: std.process.Init, argv: []const [:0]const u8) !u8 { }; return lora_merge.run(init.gpa, init.io, &out.interface, &err.interface, m.dense, m.adapter, m.dest, m.shipped); } - const start = if (args.len >= 2) info.parseStart(args[2..]) else null; - if (start == null) { + const info_start = if (args.len >= 2) info.parseStart(args[2..]) else null; + if (info_start == null) { try err.interface.writeAll(usage); return 2; } - return info.runStart(a, init.io, &out.interface, env, null, args[1], start.?); + return info.runStart(a, init.io, &out.interface, env, null, args[1], info_start.?); } test "wants only the checkpoint subcommands" { diff --git a/zig/src/cli/cuda_main.zig b/zig/src/cli/cuda_main.zig index ae4ee3b3b08..1e725ea934d 100644 --- a/zig/src/cli/cuda_main.zig +++ b/zig/src/cli/cuda_main.zig @@ -11,6 +11,7 @@ const precision = @import("cuda_precision.zig"); const kl = @import("cuda_kl.zig"); const shared_checks = @import("cuda_shared_checks.zig"); const checkpoint_cli = @import("checkpoint_cli"); +const server_start = @import("server_start"); const cluster = @import("cluster"); const lanes_cli = @import("cuda_lanes.zig"); const segments_cli = @import("cuda_segments.zig"); @@ -77,6 +78,7 @@ pub fn main(init: std.process.Init) !u8 { if (args.len >= 2 and cluster.cli.wants(@ptrCast(args[1..]))) return cluster.cli.main(init, args[1..]); if (args.len >= 2 and cluster.validate.wants(@ptrCast(args[1..]))) return cluster.validate.main(init, args[1..]); // The checkpoint commands must work without a model, driver or GPU too. + if (args.len >= 2 and std.mem.eql(u8, args[1], "start")) return server_start.main(init, args[2..]); if (args.len >= 2 and checkpoint_cli.wants(@ptrCast(args[1..]))) return checkpoint_cli.main(init, args[1..]); // A leading flag is not a command: the usage covers it, without touching the GPU. if (args.len >= 2 and std.mem.startsWith(u8, args[1], "--")) { diff --git a/zig/src/cli/models.zig b/zig/src/cli/models.zig index 4c20c26e530..97d05e8b9a4 100644 --- a/zig/src/cli/models.zig +++ b/zig/src/cli/models.zig @@ -42,6 +42,53 @@ pub fn fitOf(e: *const Entry, mc: *const Machine) Fit { return if (n + room <= mc.gpu_limit) .fits else .tight; } +/// The one checkpoint `start` selects, with pinned pull specs and the snapshot directories serve must use. +pub const StartChoice = struct { + entry: *const Entry, + model: []const u8, + drafter: ?[]const u8, + model_dir: []const u8, + drafter_dir: ?[]const u8, + download_bytes: u64, + cached: bool, +}; + +fn pinned(repo: []const u8, revision: []const u8, a: Allocator) ![]const u8 { + return std.fmt.allocPrint(a, "{s}@{s}", .{ repo, revision }); +} + +/// The exact snapshot a fully pinned entry names, whether it is cached yet or a successful pull will create it. +fn startSnapshot(a: Allocator, io: std.Io, root: []const u8, repo: []const u8, revision: []const u8) !struct { []const u8, bool } { + const dir = try std.fs.path.join(a, &.{ root, try hub.repoDirName(a, repo), "snapshots", revision }); + return .{ dir, hub.isDir(io, dir) and @import("checkpoint_config").optional(a, io, dir) != null }; +} + +/// Largest comfortably fitting fully pinned `models` row that `tensorfold pull` can install; ties keep registry order. +pub fn chooseForStart(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, override: ?[]const u8, entries: []const Entry, mc: *const Machine) !?StartChoice { + var best: ?*const Entry = null; + for (entries) |*e| { + if (e.hf_dir != null) continue; + const revision = e.revision orelse continue; + if (!hub.hexSha(revision)) continue; + if (e.drafter != null and (e.drafter_revision == null or !hub.hexSha(e.drafter_revision.?))) continue; + if (fitOf(e, mc) != .fits) continue; + if (best == null or need(e) > need(best.?)) best = e; + } + const e = best orelse return null; + const root = try hub.cacheDir(a, env, override); + const main = try startSnapshot(a, io, root, e.repo, e.revision.?); + const draft = if (e.drafter) |d| try startSnapshot(a, io, root, d, e.drafter_revision.?) else .{ @as([]const u8, ""), true }; + return .{ + .entry = e, + .model = try pinned(e.repo, e.revision.?, a), + .drafter = if (e.drafter) |d| try pinned(d, e.drafter_revision.?, a) else null, + .model_dir = main[0], + .drafter_dir = if (e.drafter != null) draft[0] else null, + .download_bytes = e.download, + .cached = main[1] and draft[1], + }; +} + /// A measurement on this chip, else the nearest on this backend (same chip generation first) scaled by bandwidth. pub fn estimate(e: *const Entry, mc: *const Machine) ?Estimate { if (mc.backend == .none) return null; @@ -466,6 +513,33 @@ test "onDisk sizes the checkpoints models lists, and an absent cache has none" { try std.testing.expectEqual(@as(usize, 0), (try onDisk(a, io, null, try std.fs.path.join(a, &.{ root, "missing" }))).len); } +test "start CLI: a fake registry picks the largest pullable fit and refuses a machine that fits nothing" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + const missing = try std.fmt.allocPrint(a, ".tf-start-none-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + const entries = [_]Entry{ + .{ .title = "Small", .format = "4-bit", .repo = "Org/Small", .revision = "1111111111111111111111111111111111111111", .download = 2 * gib, .metal = true, .recipe = "small" }, + .{ .title = "Large", .format = "4-bit", .repo = "Org/Large", .revision = "2222222222222222222222222222222222222222", .drafter = "Org/Draft", .drafter_revision = "3333333333333333333333333333333333333333", .download = 9 * gib, .metal = true, .recipe = "large" }, + .{ .title = "Unpinned", .format = "4-bit", .repo = "Org/Unpinned", .download = 20 * gib, .metal = true, .recipe = "unpinned" }, + .{ .title = "Tight", .format = "8-bit", .repo = "Org/Tight", .revision = "4444444444444444444444444444444444444444", .download = 61 * gib, .metal = true, .recipe = "tight" }, + .{ .title = "External installer", .format = "4-bit", .repo = "Org/External", .download = 12 * gib, .metal = true, .hf_dir = "External", .recipe = "external" }, + .{ .title = "Too big", .format = "8-bit", .repo = "Org/TooBig", .download = 100 * gib, .metal = true, .recipe = "too-big" }, + }; + var mc: Machine = .{ .backend = .metal, .memory = 96 * gib, .gpu_limit = 64 * gib }; + const picked = (try chooseForStart(a, io, null, missing, &entries, &mc)).?; + try std.testing.expectEqualStrings("Org/Large", picked.entry.repo); + try std.testing.expectEqualStrings("Org/Large@2222222222222222222222222222222222222222", picked.model); + try std.testing.expectEqualStrings("Org/Draft@3333333333333333333333333333333333333333", picked.drafter.?); + try std.testing.expectEqual(@as(u64, 9 * gib), picked.download_bytes); + try std.testing.expect(!picked.cached); + mc.gpu_limit = gib; + try std.testing.expect((try chooseForStart(a, io, null, missing, &entries, &mc)) == null); + mc = .{}; + try std.testing.expect((try chooseForStart(a, io, null, missing, &entries, &mc)) == null); +} + fn has(text: []const u8, needle: []const u8) bool { if (std.mem.indexOf(u8, text, needle) != null) return true; std.debug.print("missing \"{s}\" in:\n{s}\n", .{ needle, text }); diff --git a/zig/src/cli/start.zig b/zig/src/cli/start.zig new file mode 100644 index 00000000000..e84a400e575 --- /dev/null +++ b/zig/src/cli/start.zig @@ -0,0 +1,10 @@ +//! The checkpoint registry and pull entry points shared by `tensorfold start`. +pub const Entry = @import("catalog.zig").Entry; +pub const entries = @import("catalog.zig").entries; +pub const Choice = @import("models.zig").StartChoice; +pub const choose = @import("models.zig").chooseForStart; +pub const pull = @import("pull.zig"); + +test { + _ = @import("models.zig"); +} diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index e1e0d5e0a9f..833cce6bec1 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -17,6 +17,7 @@ const api = @import("engine_api"); const recall_open = @import("recall_open.zig"); const benchmark = @import("benchmark.zig"); const checkpoint_cli = @import("checkpoint_cli"); +const server_start = @import("start_cli.zig"); const pdf_worker = @import("pdf_worker.zig"); const web_cli = @import("web_cli.zig"); const chat_cli = @import("chat_cli.zig"); @@ -94,6 +95,7 @@ pub fn main(init: std.process.Init) !u8 { }; } // the checkpoint commands need no model, GPU or driver either + if (argv.len >= 2 and std.mem.eql(u8, argv[1], "start")) return server_start.main(init, argv[2..]); if (argv.len >= 2 and checkpoint_cli.wants(@ptrCast(argv[1..]))) return checkpoint_cli.main(init, argv[1..]); if (argv.len >= 2 and std.mem.eql(u8, argv[1], "slide")) return slide_cli.main(init, argv[2..]); log.init(io, false); diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig new file mode 100644 index 00000000000..308c718a655 --- /dev/null +++ b/zig/src/server/start_cli.zig @@ -0,0 +1,222 @@ +//! `tensorfold start`: pick a fitting checkpoint, consent to its pull, serve it and prove one reply. +const std = @import("std"); +const builtin = @import("builtin"); +const registry = @import("checkpoint_cli").start; +const machine = @import("sys").machine; +const child = @import("chat_cli_child.zig"); +const turn = @import("chat_cli_turn.zig"); +const history = @import("chat_cli_history.zig"); +const stream = @import("benchmark_stream.zig"); +const stop = @import("benchmark_stop.zig"); +const Allocator = std.mem.Allocator; + +const windows = builtin.os.tag == .windows; +const Child = if (windows) void else child.Child; +pub const usage = "usage: tensorfold start [--yes] [--check] [--startup-timeout SECONDS]\n"; + +/// Everything the command touches; tests supply a machine, registry, cache, child executable and pull stand-in. +pub const Context = struct { + a: Allocator, + io: std.Io, + environ: *const std.process.Environ.Map, + out: *std.Io.Writer, + err: *std.Io.Writer, + input: *std.Io.Reader, + interactive: bool, + self_exe: ?[]const u8 = null, + signals: bool = false, + given: ?machine.Machine = null, + registry: ?[]const registry.Entry = null, + override: ?[]const u8 = null, + pull: ?Pull = null, +}; + +/// A pull effect for tests; production calls the existing checkpoint command directly. +pub const Pull = struct { + ctx: *anyopaque, + run: *const fn (*anyopaque, []const u8) anyerror!u8, +}; + +const Args = struct { yes: bool = false, check: bool = false, startup_timeout: ?f64 = null, help: bool = false }; + +fn parse(args: []const []const u8) ?Args { + var out: Args = .{}; + var i: usize = 0; + while (i < args.len) : (i += 1) { + const arg = args[i]; + if (std.mem.eql(u8, arg, "--yes")) { + out.yes = true; + } else if (std.mem.eql(u8, arg, "--check")) { + out.check = true; + } else if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { + out.help = true; + } else if (std.mem.eql(u8, arg, "--startup-timeout")) { + i += 1; + if (i == args.len) return null; + const seconds = std.fmt.parseFloat(f64, args[i]) catch return null; + if (!(seconds > 0 and seconds <= 3600)) return null; + out.startup_timeout = seconds; + } else return null; + } + return out; +} + +pub fn main(init: std.process.Init, argv: []const []const u8) !u8 { + const io = init.io; + var out_buf: [16 << 10]u8 = undefined; + var err_buf: [4 << 10]u8 = undefined; + var in_buf: [4 << 10]u8 = undefined; + var out = std.Io.File.stdout().writerStreaming(io, &out_buf); + var err = std.Io.File.stderr().writerStreaming(io, &err_buf); + var in = std.Io.File.stdin().readerStreaming(io, &in_buf); + defer out.interface.flush() catch {}; + defer err.interface.flush() catch {}; + const ctx: Context = .{ + .a = init.arena.allocator(), + .io = io, + .environ = init.environ_map, + .out = &out.interface, + .err = &err.interface, + .input = &in.interface, + .interactive = std.Io.File.stdin().isTty(io) catch false, + .signals = true, + }; + return command(&ctx, argv); +} + +pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { + const args = parse(argv) orelse { + try ctx.err.writeAll(usage); + try ctx.err.flush(); + return 2; + }; + if (args.help) { + try ctx.out.writeAll(usage ++ + "Pick the largest catalog model that fits this machine, ask before any download, serve on loopback, and send one reply.\n" ++ + "--yes consents to the registered download; without it a non-interactive run downloads nothing.\n" ++ + "--check stops the server after a successful first reply; otherwise Ctrl-C stops it.\n"); + try ctx.out.flush(); + return 0; + } + if (comptime windows) return fail(ctx, 2, "starting a server is not supported on Windows yet: use tensorfold serve MODEL in one console and tensorfold chat --url URL MODEL in another") else return run(ctx, args); +} + +fn run(ctx: *const Context, args: Args) !u8 { + if (comptime !windows) if (ctx.signals) stop.install(); + defer if (comptime !windows) if (ctx.signals) stop.restore(); + const mc = ctx.given orelse machine.detect(ctx.a, ctx.io); + const choice = (try registry.choose(ctx.a, ctx.io, ctx.environ, ctx.override, ctx.registry orelse ®istry.entries, &mc)) orelse + return fail(ctx, 1, "no catalog model that this machine can start automatically; tensorfold models --all shows the reasons and manual recipes", .{}); + const e = choice.entry; + try say(ctx.out, "Selected {s}, {s}: {s}", .{ e.title, e.format, e.repo }); + if (choice.cached) { + try say(ctx.out, "Checkpoint and any drafter are already cached; no download is needed", .{}); + } else { + try say(ctx.out, "Download {s}: {d:.1} GiB ({d} bytes) of model weights, including any drafter", .{ choice.model, gibs(choice.download_bytes), choice.download_bytes }); + if (choice.drafter) |d| try say(ctx.out, "Drafter download: {s}", .{d}); + if (!args.yes) { + if (!ctx.interactive) return fail(ctx, 2, "stdin is not a terminal to ask on; pass --yes to consent in a non-interactive run; nothing was downloaded", .{}); + try ctx.err.writeAll("Download these model weights? [y/N] "); + try ctx.err.flush(); + const answer = std.mem.trim(u8, (ctx.input.takeDelimiter('\n') catch null) orelse "", " \t\r"); + if (!std.ascii.eqlIgnoreCase(answer, "y") and !std.ascii.eqlIgnoreCase(answer, "yes")) { + try say(ctx.out, "download declined; nothing was downloaded", .{}); + return 1; + } + } + if (try pull(ctx, choice.model) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{choice.model}); + if (choice.drafter) |d| if (try pull(ctx, d) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{d}); + } + return serve(ctx, args, choice); +} + +fn pull(ctx: *const Context, spec: []const u8) !u8 { + try say(ctx.out, "Pulling {s}", .{spec}); + if (ctx.pull) |p| return p.run(p.ctx, spec); + return registry.pull.run(ctx.a, ctx.io, ctx.out, ctx.err, ctx.environ, ctx.override, spec); +} + +fn serve(ctx: *const Context, args: Args, choice: registry.Choice) !u8 { + var problem: []const u8 = ""; + var tail: []const []const u8 = &.{}; + const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = ctx.self_exe, .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; + var extra: std.ArrayList([]const u8) = .empty; + try extra.appendSlice(ctx.a, &.{ "--name", std.fs.path.basename(choice.entry.repo) }); + if (choice.drafter_dir) |d| try extra.appendSlice(ctx.a, &.{ "--drafter", d }); + const plan = try child.plan(setup, choice.model_dir, extra.items, args.startup_timeout, &problem) orelse return fail(ctx, 1, "{s}", .{problem}); + try say(ctx.err, "Loading {s}; Ctrl-C cancels", .{choice.entry.repo}); + var own = try child.start(setup, plan, &tail, &problem) orelse { + if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); + const code = try fail(ctx, 1, "{s}", .{problem}); + try lastLines(ctx, tail); + return code; + }; + errdefer _ = own.managed.stop(); + const code = try firstReply(ctx, &own); + if (code != 0) { + if (own.managed.stop()) |why| try say(ctx.err, "tensorfold start: {s}", .{why}); + return code; + } + if (args.check) { + if (own.managed.stop()) |why| return fail(ctx, 1, "{s}", .{why}); + try say(ctx.out, "first-reply check passed; server stopped", .{}); + return 0; + } + try say(ctx.out, "Serving {s} at {s}/v1; Ctrl-C stops the server", .{ own.served, own.managed.base() }); + return wait(ctx, &own); +} + +/// One deterministic short request proves answer content, not only a listening socket. +fn firstReply(ctx: *const Context, own: *Child) !u8 { + var problem: []const u8 = ""; + const url = try stream.endpoint(ctx.a, own.managed.base(), true, &problem) orelse return fail(ctx, 1, "{s}", .{problem}); + var h: history.History = .{ .a = ctx.a }; + const request = try turn.body(ctx.a, .{ .model = own.served, .temperature = 0, .max_tokens = 32 }, &h, "Reply with a short confirmation that the server is ready."); + try say(ctx.out, "First reply:", .{}); + switch (try turn.run(ctx.a, ctx.io, url, own.key, request, ctx.out, .{})) { + .finished => |f| { + if (f.content.len == 0) return fail(ctx, 1, "first reply failed: the model returned no answer content", .{}); + return 0; + }, + .stopped => return stop.exitCode(stop.requested() orelse .INT), + .failed => |f| return fail(ctx, 1, "first reply failed: {s}", .{f.reason}), + } +} + +/// Keep the checked server in the foreground until a signal or its own exit. +fn wait(ctx: *const Context, own: *Child) !u8 { + while (true) { + if (stop.requested()) |sig| { + if (own.managed.stop()) |why| try say(ctx.err, "tensorfold start: {s}", .{why}); + return stop.exitCode(sig); + } + if (try own.managed.exitedTail(ctx.a)) |tail| { + const code = try fail(ctx, 1, "the model server exited after its successful first reply", .{}); + try lastLines(ctx, tail); + return code; + } + ctx.io.sleep(.fromMilliseconds(200), .awake) catch {}; + } +} + +fn lastLines(ctx: *const Context, tail: []const []const u8) !void { + if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{tail[0]}); + if (tail.len > 1) try ctx.err.writeAll("Last server log lines:\n"); + if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{line}); + try ctx.err.flush(); +} + +fn gibs(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / @as(f64, @floatFromInt(machine.gib)); +} + +fn say(w: *std.Io.Writer, comptime fmt: []const u8, args: anytype) !void { + try w.print(fmt ++ "\n", args); + try w.flush(); +} + +fn fail(ctx: *const Context, code: u8, comptime fmt: []const u8, args: anytype) !u8 { + try ctx.err.print("tensorfold start: " ++ fmt ++ "\n", args); + try ctx.err.flush(); + return code; +} diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig new file mode 100644 index 00000000000..d66fe15360a --- /dev/null +++ b/zig/src/server/start_cli_test.zig @@ -0,0 +1,203 @@ +//! `tensorfold start` against fake devices, registries, checkpoints and HTTP servers. +const std = @import("std"); +const start = @import("start_cli.zig"); +const registry = @import("checkpoint_cli").start; +const machine_mod = @import("sys").machine; +const fake = @import("benchmark_fake.zig"); +const stop = @import("benchmark_stop.zig"); +const Allocator = std.mem.Allocator; + +const revision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const draft_revision = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const gib = machine_mod.gib; +const entries = [_]registry.Entry{ + .{ .title = "Fixture", .format = "4-bit", .repo = "Org/Model", .revision = revision, .drafter = "Org/Draft", .drafter_revision = draft_revision, .download = 5 * gib, .metal = true, .cuda = true, .recipe = "fixture" }, +}; + +const Run = struct { + a: Allocator, + env: std.process.Environ.Map, + dir: []const u8, + root: []const u8, + out: std.Io.Writer.Allocating, + err: std.Io.Writer.Allocating, + stdin: std.Io.Reader = .fixed(""), + input: []const u8 = "", + interactive: bool = false, + self_exe: ?[]const u8 = null, + machine: machine_mod.Machine = .{ .backend = .metal, .memory = 96 * gib, .gpu_limit = 64 * gib }, + pull_code: u8 = 0, + pulls: std.ArrayList([]const u8) = .empty, + + fn init(a: Allocator, tmp: *std.testing.TmpDir) !Run { + var r: Run = .{ .a = a, .env = .init(a), .dir = try fake.tmpPath(a, tmp), .root = undefined, .out = .init(a), .err = .init(a) }; + r.root = try r.path("hub"); + try r.env.put("PATH", "/usr/bin:/bin"); + try r.env.put("HOME", r.dir); + try r.env.put("TMPDIR", r.dir); + try r.env.put("HF_HUB_CACHE", r.root); + return r; + } + + fn path(r: *const Run, name: []const u8) ![]const u8 { + return std.fs.path.join(r.a, &.{ r.dir, name }); + } + + fn command(r: *Run, argv: []const []const u8) !u8 { + r.out.clearRetainingCapacity(); + r.err.clearRetainingCapacity(); + r.stdin = .fixed(r.input); + const ctx: start.Context = .{ + .a = r.a, + .io = std.testing.io, + .environ = &r.env, + .out = &r.out.writer, + .err = &r.err.writer, + .input = &r.stdin, + .interactive = r.interactive, + .self_exe = r.self_exe, + .given = r.machine, + .registry = &entries, + .override = r.root, + .pull = .{ .ctx = r, .run = fakePull }, + }; + return start.command(&ctx, argv); + } + + fn fakePull(ctx: *anyopaque, spec: []const u8) !u8 { + const r: *Run = @ptrCast(@alignCast(ctx)); + try r.pulls.append(r.a, spec); + return if (r.pull_code != 0 and r.pulls.items.len >= 2) r.pull_code else 0; + } + + fn cache(r: *Run) !void { + const repo = try std.fs.path.join(r.a, &.{ r.root, "models--Org--Model" }); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ repo, "refs" })); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ repo, "snapshots", revision })); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "refs/main" }), .data = "cccccccccccccccccccccccccccccccccccccccc" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "snapshots", revision, "config.json" }), .data = "{\"model_type\": \"qwen4_exp\", \"quantization\": {\"bits\": 6, \"group_size\": 32}}" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "snapshots", revision, "model.safetensors" }), .data = "fixture" }); + const draft = try std.fs.path.join(r.a, &.{ r.root, "models--Org--Draft" }); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ draft, "refs" })); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ draft, "snapshots", draft_revision })); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "refs/main" }), .data = "dddddddddddddddddddddddddddddddddddddddd" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "snapshots", draft_revision, "config.json" }), .data = "{\"model_type\": \"qwen4_exp_draft\"}" }); + } + + fn standIn(r: *Run, port: u16) !void { + const script = try r.path("serve-stand-in"); + const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nexec sleep 30\n", .{ try r.path("pid"), try r.path("args"), try r.path("key"), port }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = script, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); + r.self_exe = script; + } + + fn childGone(r: *Run) bool { + const text = std.Io.Dir.cwd().readFileAlloc(std.testing.io, r.path("pid") catch return false, r.a, .limited(64)) catch return false; + const pid = std.fmt.parseInt(std.posix.pid_t, std.mem.trim(u8, text, " \n"), 10) catch return false; + stop.releaseChild(pid); + std.posix.kill(pid, @fromBackingInt(0)) catch |e| return e == error.ProcessNotFound; + return false; + } +}; + +fn events(a: Allocator, content: []const u8) ![]const []const fake.Write { + const head = try fake.headOf(a, "200 OK", "text/event-stream"); + const body = try fake.event(a, try std.fmt.allocPrint(a, "{{\"choices\": [{{\"index\": 0, \"delta\": {{\"content\": \"{s}\"}}, \"finish_reason\": \"stop\"}}]}}", .{content})); + const writes = try a.dupe(fake.Write, &.{.{ .bytes = try std.mem.concat(a, u8, &.{ head, body, try fake.event(a, "[DONE]") }) }}); + return a.dupe([]const fake.Write, &.{writes}); +} + +fn world(r: *Run, replies: []const []const fake.Write) !*fake.Fake { + return fake.Fake.startKeyed(std.testing.allocator, try r.a.dupe(fake.Route, &.{ + .{ .method = "GET", .path = "/health", .replies = try r.a.dupe([]const fake.Write, &.{try fake.jsonReply(r.a, "200 OK", "{\"status\": \"ok\", \"warming\": false}")}) }, + .{ .method = "GET", .path = "/v1/models", .replies = try r.a.dupe([]const fake.Write, &.{try fake.jsonReply(r.a, "200 OK", "{\"data\": [{\"id\": \"Model\"}]}")}) }, + .{ .method = "POST", .path = "/v1/chat/completions", .replies = replies }, + }), try r.path("key")); +} + +test "start CLI: a missing fit or a refused download never invokes pull or serve" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.machine.gpu_limit = gib; + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "no catalog model that this machine can start automatically") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + + r.machine.gpu_limit = 64 * gib; + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "pass --yes to consent in a non-interactive run; nothing was downloaded") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + r.interactive = true; + r.input = "no\n"; + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{})); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "download declined; nothing was downloaded") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); +} + +test "start CLI: explicit consent shows sizes and pulls both pinned specs before a failed pull stops" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.pull_code = 1; + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{"--yes"})); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "5.0 GiB (5368709120 bytes) of model weights") != null); + try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); + try std.testing.expectEqualStrings("Org/Model@" ++ revision, r.pulls.items[0]); + try std.testing.expectEqualStrings("Org/Draft@" ++ draft_revision, r.pulls.items[1]); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "pull Org/Draft@" ++ draft_revision ++ " failed") != null); + + r.pulls.clearRetainingCapacity(); + r.interactive = true; + r.input = "yes\n"; + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{})); + try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); +} + +test "start CLI: a cached model answers once, prints no key and --check reaps its serve child" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.env.put("TENSORFOLD_API_KEY", "user-key-must-not-leak"); + try r.cache(); + const f = try world(&r, try events(a, "Ready.")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{"--check"})); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "First reply:\nReady.\n") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "first-reply check passed; server stopped") != null); + try std.testing.expect(r.childGone()); + const key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("key"), a, .limited(256)); + try std.testing.expect(key.len == 64 and !std.mem.eql(u8, key, "user-key-must-not-leak")); + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, key) == null); + const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); + const want = try std.fmt.allocPrint(a, "serve\n{s}/models--Org--Model/snapshots/{s}\n--host\n127.0.0.1\n--port\n0\n--name\n{s}\n--name\nModel\n--drafter\n{s}/models--Org--Draft/snapshots/{s}\n", .{ r.root, revision, revision, r.root, draft_revision }); + try std.testing.expect(std.mem.indexOf(u8, args, want) != null); +} + +test "start CLI: a failed first reply is fatal and still reaps its serve child" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.cache(); + const refusal = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "500 Internal Server Error", "{\"error\": {\"message\": \"generation failed\", \"type\": \"server_error\"}}")}); + const f = try world(&r, refusal); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{"--check"})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "first reply failed: HTTP 500: generation failed") != null); + try std.testing.expect(r.childGone()); +} From 753b07850cc7dd76da1148b1335c4f4ec5873aab Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:56:36 +0000 Subject: [PATCH 076/361] cli: repair managed start across supported hosts --- docs/run-guide.md | 16 ++-- zig/build/cuda_server_host.zig | 12 ++- zig/src/cli/cuda_main.zig | 2 +- zig/src/cli/models.zig | 27 +++++- zig/src/server/chat_cli_child.zig | 8 +- zig/src/server/start_cli.zig | 61 ++++++++++++- zig/src/server/start_cli_test.zig | 146 +++++++++++++++++++++++++++++- 7 files changed, 245 insertions(+), 27 deletions(-) diff --git a/docs/run-guide.md b/docs/run-guide.md index ff4054c1aff..6b7f83a9a98 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -24,21 +24,25 @@ a container and the tests that need no GPU. After installation, `tensorfold start` uses the same machine probe and registry as `tensorfold models`, picks the largest fully pinned checkpoint that fits and `tensorfold pull` can install, shows its download size, and asks before downloading. `--yes` gives that consent explicitly. Without `--yes`, a non-interactive run stops before any download; an interactive -run accepts only `y` or `yes`. A cached model and its drafter need no prompt or download. +run accepts only `y` or `yes`. A cached model needs no prompt or download. Rows whose Gemma 4 drafts need M5 tensor units are +served without the drafter on pre-M5 Metal; M5 and CUDA retain it. The command starts a loopback server and sends one deterministic request. `--check` stops that server after a nonempty -reply and exits 0; without `--check`, the checked server stays in the foreground and Ctrl-C stops it. A failed first reply -is fatal and the started server is stopped. The request key is not printed. No existing `serve` default or flag changes. - -Windows refuses managed server startup: use `tensorfold serve` in one console and `tensorfold chat --url` in another. +reply and exits 0; this ephemeral check replaces any caller API key with a private temporary key. Without `--check`, set +`TENSORFOLD_API_KEY` in the environment first: persistent `start` requires that caller credential, reuses it only through +the child environment, and stays in the foreground until Ctrl-C. Send requests with `Authorization: Bearer +$TENSORFOLD_API_KEY`; the key is never printed or placed in the child arguments. A failed first reply is fatal and the +started server is stopped. No existing `serve` default or flag changes. ## Send a request -Leave the server running. In another terminal, on either platform: +Leave the server running. In another terminal, on either platform (the authorization header is the persistent `start` +credential flow; an unauthenticated manual `serve` does not need it): ```sh curl -fsS http://127.0.0.1:8080/v1/chat/completions \ -H 'Content-Type: application/json' \ + -H "Authorization: Bearer ${TENSORFOLD_API_KEY}" \ -d '{"model":"local-model","messages":[{"role":"user","content":"Say hello in one sentence."}],"max_tokens":128,"temperature":0}' ``` diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 62809e5ea31..20be734bb31 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -110,8 +110,18 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod }); const start_run = b.addRunArtifact(b.addTest(.{ .root_module = start_tests, .filters = &.{"start CLI:"} })); start_run.has_side_effects = true; - b.step("test-start-cli-host", "Automatic model choice, download consent, first reply and serve-child cleanup without devices").dependOn(&start_run.step); + const start_step = b.step("test-start-cli-host", "Automatic model choice, download consent, first reply and serve-child cleanup without devices"); + start_step.dependOn(&start_run.step); step.dependOn(&start_run.step); + const windows_target = b.resolveTargetQuery(.{ .cpu_arch = .x86_64, .os_tag = .windows, .abi = .gnu }); + const windows_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = windows_target, .optimize = .debug, .link_libc = true }); + const windows_start = @import("server.zig").plain(b, "zig/src/server/start_cli.zig", windows_target, .debug, windows_lanes); + const windows_api = windows_start.import_table.get("engine_api").?; + const windows_core = windows_start.import_table.get("core").?; + const windows_none = b.createModule(.{ .root_source_file = b.path("zig/src/native/none.zig"), .target = windows_target, .optimize = .debug, .imports = &.{.{ .name = "engine_api", .module = windows_api }} }); + windows_start.addImport("checkpoint_cli", @import("cuda.zig").checkpointCli(b, windows_target, .debug, false, windows_none, windows_core)); + const windows_check = b.addTest(.{ .root_module = windows_start, .filters = &.{"start CLI: Windows refusal"} }); + start_step.dependOn(&windows_check.step); // compile only: a Windows test binary is never executed const server_step = b.step( "test-server-cpu", "The HTTP server's unit tests (routes, templates, tool parsing) without a GPU", diff --git a/zig/src/cli/cuda_main.zig b/zig/src/cli/cuda_main.zig index 1e725ea934d..583d018df2d 100644 --- a/zig/src/cli/cuda_main.zig +++ b/zig/src/cli/cuda_main.zig @@ -78,7 +78,7 @@ pub fn main(init: std.process.Init) !u8 { if (args.len >= 2 and cluster.cli.wants(@ptrCast(args[1..]))) return cluster.cli.main(init, args[1..]); if (args.len >= 2 and cluster.validate.wants(@ptrCast(args[1..]))) return cluster.validate.main(init, args[1..]); // The checkpoint commands must work without a model, driver or GPU too. - if (args.len >= 2 and std.mem.eql(u8, args[1], "start")) return server_start.main(init, args[2..]); + if (args.len >= 2 and std.mem.eql(u8, args[1], "start")) return server_start.mainCuda(init, args[2..]); if (args.len >= 2 and checkpoint_cli.wants(@ptrCast(args[1..]))) return checkpoint_cli.main(init, args[1..]); // A leading flag is not a command: the usage covers it, without touching the GPU. if (args.len >= 2 and std.mem.startsWith(u8, args[1], "--")) { diff --git a/zig/src/cli/models.zig b/zig/src/cli/models.zig index 97d05e8b9a4..d59dbf40e5b 100644 --- a/zig/src/cli/models.zig +++ b/zig/src/cli/models.zig @@ -70,25 +70,32 @@ pub fn chooseForStart(a: Allocator, io: std.Io, env: ?*const std.process.Environ if (e.hf_dir != null) continue; const revision = e.revision orelse continue; if (!hub.hexSha(revision)) continue; - if (e.drafter != null and (e.drafter_revision == null or !hub.hexSha(e.drafter_revision.?))) continue; + const drafting = startUsesDrafter(e, mc); + if (drafting and (e.drafter_revision == null or !hub.hexSha(e.drafter_revision.?))) continue; if (fitOf(e, mc) != .fits) continue; if (best == null or need(e) > need(best.?)) best = e; } const e = best orelse return null; + const drafting = startUsesDrafter(e, mc); const root = try hub.cacheDir(a, env, override); const main = try startSnapshot(a, io, root, e.repo, e.revision.?); - const draft = if (e.drafter) |d| try startSnapshot(a, io, root, d, e.drafter_revision.?) else .{ @as([]const u8, ""), true }; + const draft = if (drafting) try startSnapshot(a, io, root, e.drafter.?, e.drafter_revision.?) else .{ @as([]const u8, ""), true }; return .{ .entry = e, .model = try pinned(e.repo, e.revision.?, a), - .drafter = if (e.drafter) |d| try pinned(d, e.drafter_revision.?, a) else null, + .drafter = if (drafting) try pinned(e.drafter.?, e.drafter_revision.?, a) else null, .model_dir = main[0], - .drafter_dir = if (e.drafter != null) draft[0] else null, + .drafter_dir = if (drafting) draft[0] else null, .download_bytes = e.download, .cached = main[1] and draft[1], }; } +/// `.m5 = .drafts` rows serve plain on pre-M5 Metal; M5 and CUDA keep their pinned drafter. +fn startUsesDrafter(e: *const Entry, mc: *const Machine) bool { + return e.drafter != null and !(mc.backend == .metal and e.m5 == .drafts and !m5(mc.chip())); +} + /// A measurement on this chip, else the nearest on this backend (same chip generation first) scaled by bandwidth. pub fn estimate(e: *const Entry, mc: *const Machine) ?Estimate { if (mc.backend == .none) return null; @@ -521,19 +528,29 @@ test "start CLI: a fake registry picks the largest pullable fit and refuses a ma const missing = try std.fmt.allocPrint(a, ".tf-start-none-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); const entries = [_]Entry{ .{ .title = "Small", .format = "4-bit", .repo = "Org/Small", .revision = "1111111111111111111111111111111111111111", .download = 2 * gib, .metal = true, .recipe = "small" }, - .{ .title = "Large", .format = "4-bit", .repo = "Org/Large", .revision = "2222222222222222222222222222222222222222", .drafter = "Org/Draft", .drafter_revision = "3333333333333333333333333333333333333333", .download = 9 * gib, .metal = true, .recipe = "large" }, + .{ .title = "Large", .format = "4-bit", .repo = "Org/Large", .revision = "2222222222222222222222222222222222222222", .drafter = "Org/Draft", .drafter_revision = "3333333333333333333333333333333333333333", .download = 9 * gib, .metal = true, .cuda = true, .m5 = .drafts, .recipe = "large" }, .{ .title = "Unpinned", .format = "4-bit", .repo = "Org/Unpinned", .download = 20 * gib, .metal = true, .recipe = "unpinned" }, .{ .title = "Tight", .format = "8-bit", .repo = "Org/Tight", .revision = "4444444444444444444444444444444444444444", .download = 61 * gib, .metal = true, .recipe = "tight" }, .{ .title = "External installer", .format = "4-bit", .repo = "Org/External", .download = 12 * gib, .metal = true, .hf_dir = "External", .recipe = "external" }, .{ .title = "Too big", .format = "8-bit", .repo = "Org/TooBig", .download = 100 * gib, .metal = true, .recipe = "too-big" }, }; var mc: Machine = .{ .backend = .metal, .memory = 96 * gib, .gpu_limit = 64 * gib }; + mc.setChip("Apple M5 Max"); const picked = (try chooseForStart(a, io, null, missing, &entries, &mc)).?; try std.testing.expectEqualStrings("Org/Large", picked.entry.repo); try std.testing.expectEqualStrings("Org/Large@2222222222222222222222222222222222222222", picked.model); try std.testing.expectEqualStrings("Org/Draft@3333333333333333333333333333333333333333", picked.drafter.?); + try std.testing.expect(picked.drafter_dir != null); try std.testing.expectEqual(@as(u64, 9 * gib), picked.download_bytes); try std.testing.expect(!picked.cached); + mc.setChip("Apple M4 Max"); + const plain = (try chooseForStart(a, io, null, missing, &entries, &mc)).?; + try std.testing.expectEqualStrings("Org/Large", plain.entry.repo); + try std.testing.expect(plain.drafter == null and plain.drafter_dir == null); + mc = .{ .backend = .cuda, .memory = 96 * gib, .gpu_limit = 64 * gib }; + const cuda = (try chooseForStart(a, io, null, missing, &entries, &mc)).?; + try std.testing.expectEqualStrings("Org/Large", cuda.entry.repo); + try std.testing.expect(cuda.drafter != null and cuda.drafter_dir != null); mc.gpu_limit = gib; try std.testing.expect((try chooseForStart(a, io, null, missing, &entries, &mc)) == null); mc = .{}; diff --git a/zig/src/server/chat_cli_child.zig b/zig/src/server/chat_cli_child.zig index d9b64f379d1..20ac3ae7a6a 100644 --- a/zig/src/server/chat_cli_child.zig +++ b/zig/src/server/chat_cli_child.zig @@ -16,8 +16,8 @@ pub const words: server.Words = .{ .stuck = "Model server did not exit after termination; cleanup is incomplete", }; -/// What a start needs: the environment, this executable unless tests name another, and where the log is made. -pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, log_dir: []const u8 }; +/// What a managed child needs. ``exe`` defaults to this executable; ``key`` defaults to a fresh private key. +pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, key: ?[]const u8 = null, log_dir: []const u8 }; /// The started server, the name it serves and the key every request to it carries. pub const Child = struct { managed: server.Managed, served: []const u8, key: []const u8 }; @@ -65,14 +65,14 @@ pub fn freshKey(a: Allocator, io: std.Io) ![]const u8 { return a.dupe(u8, &std.fmt.bytesToHex(raw, .lower)); } -/// The plan for ``model_arg``: a cached checkpoint and flags serve takes; null with ``problem`` set. +/// The plan for ``model_arg``: a cached checkpoint, serving flags and the caller-supplied or fresh child key. pub fn plan(s: Setup, model_arg: []const u8, extra: []const []const u8, startup_timeout: ?f64, problem: *[]const u8) !?Plan { const dir = try hub.resolve(s.a, s.io, s.environ, model_arg, problem) orelse return null; const exe = s.exe orelse try std.process.executablePathAlloc(s.io, s.a); const child_argv = try argv(s.a, exe, dir, hub.servedName("", model_arg, dir), extra); const served = try check(s.a, child_argv, problem) orelse return null; const timeout_s = startup_timeout orelse server.startupTimeout(model.weightBytes(s.io, dir)); - return .{ .argv = child_argv, .served = served, .timeout_s = timeout_s, .key = try freshKey(s.a, s.io) }; + return .{ .argv = child_argv, .served = served, .timeout_s = timeout_s, .key = s.key orelse try freshKey(s.a, s.io) }; } /// ``p`` started and ready; null with ``problem`` set ("" when stopped) and ``tail`` the child's last log lines. diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 308c718a655..1b46ab0b902 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -14,7 +14,7 @@ const windows = builtin.os.tag == .windows; const Child = if (windows) void else child.Child; pub const usage = "usage: tensorfold start [--yes] [--check] [--startup-timeout SECONDS]\n"; -/// Everything the command touches; tests supply a machine, registry, cache, child executable and pull stand-in. +/// Everything the command touches; tests supply a machine, registry, cache, child executables and inert effects. pub const Context = struct { a: Allocator, io: std.Io, @@ -23,7 +23,10 @@ pub const Context = struct { err: *std.Io.Writer, input: *std.Io.Reader, interactive: bool, + /// The invoking low-level executable, or a test's deliberately different current executable. self_exe: ?[]const u8 = null, + /// The native serving executable, explicitly injected by CUDA's production route. + serve_exe: ?[]const u8 = null, signals: bool = false, given: ?machine.Machine = null, registry: ?[]const registry.Entry = null, @@ -31,7 +34,7 @@ pub const Context = struct { pull: ?Pull = null, }; -/// A pull effect for tests; production calls the existing checkpoint command directly. +/// A pull effect for tests; its output goes through the same privacy sink as production pulls. pub const Pull = struct { ctx: *anyopaque, run: *const fn (*anyopaque, []const u8) anyerror!u8, @@ -62,6 +65,27 @@ fn parse(args: []const []const u8) ?Args { } pub fn main(init: std.process.Init, argv: []const []const u8) !u8 { + return mainWithServeExe(init, argv, null); +} + +/// CUDA's low-level `tensorfold` routes start to its native serving sibling, never back to itself. +pub fn mainCuda(init: std.process.Init, argv: []const []const u8) !u8 { + const current = try std.process.executablePathAlloc(init.io, init.arena.allocator()); + return mainWithServeExe(init, argv, try nativeSibling(init.arena.allocator(), current)); +} + +pub fn nativeSibling(a: Allocator, current: []const u8) ![]const u8 { + const name = std.fs.path.basename(current); + const sibling = if (std.ascii.eqlIgnoreCase(name, "tensorfold")) + "tensorfold-native" + else if (std.ascii.eqlIgnoreCase(name, "tensorfold.exe")) + "tensorfold-native.exe" + else + return current; + return std.fs.path.join(a, &.{ std.fs.path.dirname(current) orelse ".", sibling }); +} + +fn mainWithServeExe(init: std.process.Init, argv: []const []const u8, serve_exe: ?[]const u8) !u8 { const io = init.io; var out_buf: [16 << 10]u8 = undefined; var err_buf: [4 << 10]u8 = undefined; @@ -79,6 +103,7 @@ pub fn main(init: std.process.Init, argv: []const []const u8) !u8 { .err = &err.interface, .input = &in.interface, .interactive = std.Io.File.stdin().isTty(io) catch false, + .serve_exe = serve_exe, .signals = true, }; return command(&ctx, argv); @@ -94,14 +119,20 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { try ctx.out.writeAll(usage ++ "Pick the largest catalog model that fits this machine, ask before any download, serve on loopback, and send one reply.\n" ++ "--yes consents to the registered download; without it a non-interactive run downloads nothing.\n" ++ - "--check stops the server after a successful first reply; otherwise Ctrl-C stops it.\n"); + "--check stops the server after a successful first reply and uses a private temporary key; persistent mode requires TENSORFOLD_API_KEY.\n"); try ctx.out.flush(); return 0; } - if (comptime windows) return fail(ctx, 2, "starting a server is not supported on Windows yet: use tensorfold serve MODEL in one console and tensorfold chat --url URL MODEL in another") else return run(ctx, args); + if (comptime windows) return fail(ctx, 2, "starting a server is not supported on Windows yet: use tensorfold serve MODEL in one console and tensorfold chat --url URL MODEL in another", .{}) else return run(ctx, args); +} + +fn callerKey(ctx: *const Context) ?[]const u8 { + return if (ctx.environ.get("TENSORFOLD_API_KEY")) |key| key else null; } fn run(ctx: *const Context, args: Args) !u8 { + if (!args.check and (callerKey(ctx) == null or callerKey(ctx).?.len == 0)) + return fail(ctx, 2, "persistent start requires TENSORFOLD_API_KEY in the environment; requests send Authorization: Bearer $TENSORFOLD_API_KEY, or use --check for a private temporary key", .{}); if (comptime !windows) if (ctx.signals) stop.install(); defer if (comptime !windows) if (ctx.signals) stop.restore(); const mc = ctx.given orelse machine.detect(ctx.a, ctx.io); @@ -132,6 +163,11 @@ fn run(ctx: *const Context, args: Args) !u8 { fn pull(ctx: *const Context, spec: []const u8) !u8 { try say(ctx.out, "Pulling {s}", .{spec}); + var buffer: [4 << 10]u8 = undefined; + const discard: std.Io.Writer.Discarding = .init(&buffer); + const saved = ctx.out.*; + ctx.out.* = discard.writer; + defer ctx.out.* = saved; if (ctx.pull) |p| return p.run(p.ctx, spec); return registry.pull.run(ctx.a, ctx.io, ctx.out, ctx.err, ctx.environ, ctx.override, spec); } @@ -139,7 +175,8 @@ fn pull(ctx: *const Context, spec: []const u8) !u8 { fn serve(ctx: *const Context, args: Args, choice: registry.Choice) !u8 { var problem: []const u8 = ""; var tail: []const []const u8 = &.{}; - const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = ctx.self_exe, .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; + const serving_exe = ctx.serve_exe orelse if (ctx.self_exe) |current| try nativeSibling(ctx.a, current) else null; + const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = serving_exe, .key = if (args.check) null else callerKey(ctx), .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; var extra: std.ArrayList([]const u8) = .empty; try extra.appendSlice(ctx.a, &.{ "--name", std.fs.path.basename(choice.entry.repo) }); if (choice.drafter_dir) |d| try extra.appendSlice(ctx.a, &.{ "--drafter", d }); @@ -220,3 +257,17 @@ fn fail(ctx: *const Context, code: u8, comptime fmt: []const u8, args: anytype) try ctx.err.flush(); return code; } + +test "start CLI: Windows refusal compiles through the complete command context" { + if (comptime !windows) return; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var env: std.process.Environ.Map = .init(a); + var out: std.Io.Writer.Allocating = .init(a); + var err: std.Io.Writer.Allocating = .init(a); + var input: std.Io.Reader = .fixed(""); + const ctx: Context = .{ .a = a, .io = std.testing.io, .environ = &env, .out = &out.writer, .err = &err.writer, .input = &input, .interactive = false }; + try std.testing.expectEqual(@as(u8, 2), try command(&ctx, &.{})); + try std.testing.expect(std.mem.indexOf(u8, err.written(), "not supported on Windows") != null); +} diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index d66fe15360a..b2ef8f4e289 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -11,7 +11,7 @@ const revision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const draft_revision = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; const gib = machine_mod.gib; const entries = [_]registry.Entry{ - .{ .title = "Fixture", .format = "4-bit", .repo = "Org/Model", .revision = revision, .drafter = "Org/Draft", .drafter_revision = draft_revision, .download = 5 * gib, .metal = true, .cuda = true, .recipe = "fixture" }, + .{ .title = "Fixture", .format = "4-bit", .repo = "Org/Model", .revision = revision, .drafter = "Org/Draft", .drafter_revision = draft_revision, .download = 5 * gib, .metal = true, .cuda = true, .m5 = .drafts, .recipe = "fixture" }, }; const Run = struct { @@ -31,6 +31,7 @@ const Run = struct { fn init(a: Allocator, tmp: *std.testing.TmpDir) !Run { var r: Run = .{ .a = a, .env = .init(a), .dir = try fake.tmpPath(a, tmp), .root = undefined, .out = .init(a), .err = .init(a) }; + r.machine.setChip("Apple M5 Max"); r.root = try r.path("hub"); try r.env.put("PATH", "/usr/bin:/bin"); try r.env.put("HOME", r.dir); @@ -67,6 +68,11 @@ const Run = struct { fn fakePull(ctx: *anyopaque, spec: []const u8) !u8 { const r: *Run = @ptrCast(@alignCast(ctx)); try r.pulls.append(r.a, spec); + try r.out.writer.print("stored {s} at {s}/private-snapshot\n", .{ spec, r.root }); + const model = std.mem.eql(u8, spec, "Org/Model@" ++ revision); + const repo = if (model) "models--Org--Model" else "models--Org--Draft"; + const rev = if (model) revision else draft_revision; + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ r.root, repo, "snapshots", rev })); return if (r.pull_code != 0 and r.pulls.items.len >= 2) r.pull_code else 0; } @@ -85,12 +91,24 @@ const Run = struct { } fn standIn(r: *Run, port: u16) !void { - const script = try r.path("serve-stand-in"); - const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nexec sleep 30\n", .{ try r.path("pid"), try r.path("args"), try r.path("key"), port }); + return standInAt(r, port, "serve-stand-in"); + } + + fn standInAt(r: *Run, port: u16, name: []const u8) !void { + const script = try r.path(name); + const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '%s' \"$START_TEST_UNRELATED\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nif [ \"$START_TEST_SHORT_LIVED\" = 1 ]; then exec sleep 1; else exec sleep 30; fi\n", .{ try r.path("pid"), try r.path("args"), try r.path("child-key"), try r.path("unrelated"), port }); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = script, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); r.self_exe = script; } + fn cudaStandIn(r: *Run, port: u16) !void { + try standInAt(r, port, "tensorfold-native"); + const low_level = try r.path("tensorfold"); + const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\ntouch {s}\nexit 2\n", .{try r.path("low-level-called")}); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = low_level, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); + r.self_exe = low_level; + } + fn childGone(r: *Run) bool { const text = std.Io.Dir.cwd().readFileAlloc(std.testing.io, r.path("pid") catch return false, r.a, .limited(64)) catch return false; const pid = std.fmt.parseInt(std.posix.pid_t, std.mem.trim(u8, text, " \n"), 10) catch return false; @@ -108,11 +126,15 @@ fn events(a: Allocator, content: []const u8) ![]const []const fake.Write { } fn world(r: *Run, replies: []const []const fake.Write) !*fake.Fake { + return worldKeyed(r, replies, try r.path("child-key")); +} + +fn worldKeyed(r: *Run, replies: []const []const fake.Write, key_file: []const u8) !*fake.Fake { return fake.Fake.startKeyed(std.testing.allocator, try r.a.dupe(fake.Route, &.{ .{ .method = "GET", .path = "/health", .replies = try r.a.dupe([]const fake.Write, &.{try fake.jsonReply(r.a, "200 OK", "{\"status\": \"ok\", \"warming\": false}")}) }, .{ .method = "GET", .path = "/v1/models", .replies = try r.a.dupe([]const fake.Write, &.{try fake.jsonReply(r.a, "200 OK", "{\"data\": [{\"id\": \"Model\"}]}")}) }, .{ .method = "POST", .path = "/v1/chat/completions", .replies = replies }, - }), try r.path("key")); + }), key_file); } test "start CLI: a missing fit or a refused download never invokes pull or serve" { @@ -122,6 +144,7 @@ test "start CLI: a missing fit or a refused download never invokes pull or serve var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var r = try Run.init(a, &tmp); + try r.env.put("TENSORFOLD_API_KEY", "fixture-consent-key"); r.machine.gpu_limit = gib; try std.testing.expectEqual(@as(u8, 1), try r.command(&.{})); try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "no catalog model that this machine can start automatically") != null); @@ -145,6 +168,7 @@ test "start CLI: explicit consent shows sizes and pulls both pinned specs before var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var r = try Run.init(a, &tmp); + try r.env.put("TENSORFOLD_API_KEY", "fixture-consent-key"); r.pull_code = 1; try std.testing.expectEqual(@as(u8, 1), try r.command(&.{"--yes"})); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "5.0 GiB (5368709120 bytes) of model weights") != null); @@ -152,6 +176,12 @@ test "start CLI: explicit consent shows sizes and pulls both pinned specs before try std.testing.expectEqualStrings("Org/Model@" ++ revision, r.pulls.items[0]); try std.testing.expectEqualStrings("Org/Draft@" ++ draft_revision, r.pulls.items[1]); try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "pull Org/Draft@" ++ draft_revision ++ " failed") != null); + for ([_][]const u8{ "Org/Model@" ++ revision, "Org/Draft@" ++ draft_revision }) |spec| { + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Pulling") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), spec) != null); + } + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| + try std.testing.expect(std.mem.indexOf(u8, text, r.root) == null); r.pulls.clearRetainingCapacity(); r.interactive = true; @@ -177,12 +207,14 @@ test "start CLI: a cached model answers once, prints no key and --check reaps it try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "First reply:\nReady.\n") != null); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "first-reply check passed; server stopped") != null); try std.testing.expect(r.childGone()); - const key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("key"), a, .limited(256)); + const key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("child-key"), a, .limited(256)); try std.testing.expect(key.len == 64 and !std.mem.eql(u8, key, "user-key-must-not-leak")); for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, key) == null); const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); const want = try std.fmt.allocPrint(a, "serve\n{s}/models--Org--Model/snapshots/{s}\n--host\n127.0.0.1\n--port\n0\n--name\n{s}\n--name\nModel\n--drafter\n{s}/models--Org--Draft/snapshots/{s}\n", .{ r.root, revision, revision, r.root, draft_revision }); try std.testing.expect(std.mem.indexOf(u8, args, want) != null); + for ([_][]const u8{ key, "user-key-must-not-leak" }) |secret| + for ([_][]const u8{ r.out.written(), r.err.written(), args }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } test "start CLI: a failed first reply is fatal and still reaps its serve child" { @@ -201,3 +233,107 @@ test "start CLI: a failed first reply is fatal and still reaps its serve child" try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "first reply failed: HTTP 500: generation failed") != null); try std.testing.expect(r.childGone()); } + +test "start CLI: CUDA spawns its native sibling instead of the unsupported low-level serve child" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.cache(); + const f = try world(&r, try events(a, "Ready.")); + defer f.stop(); + try r.cudaStandIn(f.port); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{"--check"})); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "first-reply check passed") != null); + try std.testing.expect(r.childGone()); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(std.testing.io, try r.path("low-level-called"), .{})); +} + +test "start CLI: pre-M5 Metal starts Gemma-style rows without resolving pulling or passing a drafter" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.machine.setChip("Apple M4 Max"); + const f = try world(&r, try events(a, "Ready.")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--yes", "--check" })); + try std.testing.expectEqual(@as(usize, 1), r.pulls.items.len); + try std.testing.expectEqualStrings("Org/Model@" ++ revision, r.pulls.items[0]); + const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); + try std.testing.expect(std.mem.indexOf(u8, args, "--drafter") == null); + try std.testing.expect(std.mem.indexOf(u8, args, "Org/Draft") == null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Drafter download") == null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Pulling Org/Model@" ++ revision) != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), r.root) == null); +} + +test "start CLI: CUDA still resolves pulls and passes the selected drafter" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.machine.backend = .cuda; + r.machine.setChip("NVIDIA RTX 4090"); + const f = try world(&r, try events(a, "Ready.")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--yes", "--check" })); + try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); + const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); + const drafter = try std.fs.path.join(a, &.{ r.root, "models--Org--Draft", "snapshots", draft_revision }); + const want_drafter = try std.fmt.allocPrint(a, "--drafter\n{s}", .{drafter}); + try std.testing.expect(std.mem.indexOf(u8, args, want_drafter) != null); +} + +test "start CLI: persistent mode requires an environment credential before model work" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.machine.gpu_limit = gib; + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "requires TENSORFOLD_API_KEY in the environment") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); +} + +test "start CLI: persistent caller credential reaches child env and HTTP without leaking" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const caller_key = "fixture-persistent-caller-key"; + try r.env.put("TENSORFOLD_API_KEY", caller_key); + try r.env.put("START_TEST_UNRELATED", "caller-value-retained"); + try r.env.put("START_TEST_SHORT_LIVED", "1"); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = caller_key }); + const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--startup-timeout", "2" })); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "the model server exited after its successful first reply") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Serving Model at") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + try std.testing.expect(r.childGone()); + const child_key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("child-key"), a, .limited(256)); + try std.testing.expect(std.mem.eql(u8, child_key, caller_key)); + const unrelated = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("unrelated"), a, .limited(256)); + try std.testing.expect(std.mem.eql(u8, unrelated, "caller-value-retained")); + const bearer = try std.fmt.allocPrint(a, "Bearer {s}", .{caller_key}); + try std.testing.expect(f.count() > 0 and std.mem.eql(u8, f.header(f.count() - 1, "authorization") orelse "", bearer)); + try std.testing.expectEqual(@as(usize, 0), f.refusals()); + const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); + for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, caller_key) == null); +} From 9c56d28e14e94e63fead5852598729317966616b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:45:38 +0000 Subject: [PATCH 077/361] cli: parse managed caller credentials --- docs/run-guide.md | 9 +++++---- zig/src/server/benchmark_server.zig | 6 ++++-- zig/src/server/chat_cli.zig | 4 ++-- zig/src/server/chat_cli_child.zig | 6 +++--- zig/src/server/start_cli.zig | 15 +++++++-------- zig/src/server/start_cli_test.zig | 21 ++++++++++++++++----- 6 files changed, 37 insertions(+), 24 deletions(-) diff --git a/docs/run-guide.md b/docs/run-guide.md index 6b7f83a9a98..a0d7845ab33 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -29,10 +29,11 @@ served without the drafter on pre-M5 Metal; M5 and CUDA retain it. The command starts a loopback server and sends one deterministic request. `--check` stops that server after a nonempty reply and exits 0; this ephemeral check replaces any caller API key with a private temporary key. Without `--check`, set -`TENSORFOLD_API_KEY` in the environment first: persistent `start` requires that caller credential, reuses it only through -the child environment, and stays in the foreground until Ctrl-C. Send requests with `Authorization: Bearer -$TENSORFOLD_API_KEY`; the key is never printed or placed in the child arguments. A failed first reply is fatal and the -started server is stopped. No existing `serve` default or flag changes. +`TENSORFOLD_API_KEY` in the environment first: persistent `start` requires that caller credential, passes a comma-separated +list to the child unchanged, and uses its first nonempty trimmed entry for the managed checks. The server accepts each +registered entry. Send external requests with `Authorization: Bearer KEY`, replacing `KEY` with one accepted entry. Keys +are never printed or placed in the child arguments. A failed first reply is fatal and the started server is stopped. +No existing `serve` default or flag changes. ## Send a request diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 95593bdc462..f244caf4c15 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -37,8 +37,10 @@ pub const Options = struct { lock: bool = true, /// The child in a process group of its own, so a terminal's Ctrl-C reaches only this process. own_group: bool = false, - /// The child's only API key: TENSORFOLD_API_KEY in its environment and the probes' bearer (none for a benchmark). + /// The probes' bearer; normally also the child's only API key (none for a benchmark). key: ?[]const u8 = null, + /// The complete caller credential list for the child environment when it differs from ``key``. + environment_key: ?[]const u8 = null, words: Words = .{}, }; @@ -155,7 +157,7 @@ pub const Managed = struct { io.random(&rand); const log_path = try std.fmt.allocPrint(a, "{s}/.serve-{s}.log", .{ o.bench_dir, std.fmt.bytesToHex(rand, .lower) }); var child_env = try environ(a, env); - if (o.key) |k| try child_env.put("TENSORFOLD_API_KEY", k); + if (o.environment_key orelse o.key) |k| try child_env.put("TENSORFOLD_API_KEY", k); const lock = if (o.lock) lockRun(io, o.bench_dir, problem) orelse return null else null; const cwd = std.Io.Dir.cwd(); const log = cwd.createFile(io, log_path, .{ .exclusive = true, .read = true, .permissions = .fromMode(0o600) }) catch { diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 53fdc2c101d..83aaa8815d4 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -94,10 +94,10 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { if (comptime windows) return fail(ctx, windows_child) else return served(ctx, args, message); } -const bad_key = "TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each"; +pub const bad_key = "TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each"; /// The key ``--url`` sends: TENSORFOLD_API_KEY's first, as serve splits the variable; null when it names none. -fn envKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u8 { +pub fn envKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u8 { const text = (environment.path("TENSORFOLD_API_KEY", environ.get("TENSORFOLD_API_KEY")) catch return error.Refused) orelse return null; var keys = std.mem.splitScalar(u8, text, ','); while (keys.next()) |raw| { diff --git a/zig/src/server/chat_cli_child.zig b/zig/src/server/chat_cli_child.zig index 20ac3ae7a6a..351c4ec9a73 100644 --- a/zig/src/server/chat_cli_child.zig +++ b/zig/src/server/chat_cli_child.zig @@ -16,8 +16,8 @@ pub const words: server.Words = .{ .stuck = "Model server did not exit after termination; cleanup is incomplete", }; -/// What a managed child needs. ``exe`` defaults to this executable; ``key`` defaults to a fresh private key. -pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, key: ?[]const u8 = null, log_dir: []const u8 }; +/// A managed child's needs. ``key`` defaults to a fresh private key; ``environment_key`` can preserve a caller list for the child. +pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, key: ?[]const u8 = null, environment_key: ?[]const u8 = null, log_dir: []const u8 }; /// The started server, the name it serves and the key every request to it carries. pub const Child = struct { managed: server.Managed, served: []const u8, key: []const u8 }; @@ -77,7 +77,7 @@ pub fn plan(s: Setup, model_arg: []const u8, extra: []const []const u8, startup_ /// ``p`` started and ready; null with ``problem`` set ("" when stopped) and ``tail`` the child's last log lines. pub fn start(s: Setup, p: Plan, tail: *[]const []const u8, problem: *[]const u8) !?Child { - const o: server.Options = .{ .startup_timeout_s = p.timeout_s, .bench_dir = s.log_dir, .tail = tail, .served = p.served, .lock = false, .own_group = true, .key = p.key, .words = words }; + const o: server.Options = .{ .startup_timeout_s = p.timeout_s, .bench_dir = s.log_dir, .tail = tail, .served = p.served, .lock = false, .own_group = true, .key = p.key, .environment_key = s.environment_key, .words = words }; const m = try server.Managed.spawn(s.a, s.io, s.environ, p.argv, o, problem) orelse return null; return .{ .managed = m, .served = p.served, .key = p.key }; } diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 1b46ab0b902..f8eff9d2f60 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -8,6 +8,7 @@ const turn = @import("chat_cli_turn.zig"); const history = @import("chat_cli_history.zig"); const stream = @import("benchmark_stream.zig"); const stop = @import("benchmark_stop.zig"); +const chat = @import("chat_cli.zig"); const Allocator = std.mem.Allocator; const windows = builtin.os.tag == .windows; @@ -126,12 +127,10 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { if (comptime windows) return fail(ctx, 2, "starting a server is not supported on Windows yet: use tensorfold serve MODEL in one console and tensorfold chat --url URL MODEL in another", .{}) else return run(ctx, args); } -fn callerKey(ctx: *const Context) ?[]const u8 { - return if (ctx.environ.get("TENSORFOLD_API_KEY")) |key| key else null; -} - fn run(ctx: *const Context, args: Args) !u8 { - if (!args.check and (callerKey(ctx) == null or callerKey(ctx).?.len == 0)) + const caller_key = if (args.check) null else chat.envKey(ctx.environ) catch return fail(ctx, 2, chat.bad_key, .{}); + const raw_key = ctx.environ.get("TENSORFOLD_API_KEY"); + if (!args.check and (raw_key == null or raw_key.?.len == 0)) return fail(ctx, 2, "persistent start requires TENSORFOLD_API_KEY in the environment; requests send Authorization: Bearer $TENSORFOLD_API_KEY, or use --check for a private temporary key", .{}); if (comptime !windows) if (ctx.signals) stop.install(); defer if (comptime !windows) if (ctx.signals) stop.restore(); @@ -158,7 +157,7 @@ fn run(ctx: *const Context, args: Args) !u8 { if (try pull(ctx, choice.model) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{choice.model}); if (choice.drafter) |d| if (try pull(ctx, d) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{d}); } - return serve(ctx, args, choice); + return serve(ctx, args, choice, caller_key); } fn pull(ctx: *const Context, spec: []const u8) !u8 { @@ -172,11 +171,11 @@ fn pull(ctx: *const Context, spec: []const u8) !u8 { return registry.pull.run(ctx.a, ctx.io, ctx.out, ctx.err, ctx.environ, ctx.override, spec); } -fn serve(ctx: *const Context, args: Args, choice: registry.Choice) !u8 { +fn serve(ctx: *const Context, args: Args, choice: registry.Choice, caller_key: ?[]const u8) !u8 { var problem: []const u8 = ""; var tail: []const []const u8 = &.{}; const serving_exe = ctx.serve_exe orelse if (ctx.self_exe) |current| try nativeSibling(ctx.a, current) else null; - const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = serving_exe, .key = if (args.check) null else callerKey(ctx), .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; + const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = serving_exe, .key = caller_key, .environment_key = if (args.check) null else ctx.environ.get("TENSORFOLD_API_KEY"), .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; var extra: std.ArrayList([]const u8) = .empty; try extra.appendSlice(ctx.a, &.{ "--name", std.fs.path.basename(choice.entry.repo) }); if (choice.drafter_dir) |d| try extra.appendSlice(ctx.a, &.{ "--drafter", d }); diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index b2ef8f4e289..c74f623186e 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -5,6 +5,7 @@ const registry = @import("checkpoint_cli").start; const machine_mod = @import("sys").machine; const fake = @import("benchmark_fake.zig"); const stop = @import("benchmark_stop.zig"); +const stream = @import("benchmark_stream.zig"); const Allocator = std.mem.Allocator; const revision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; @@ -306,7 +307,7 @@ test "start CLI: persistent mode requires an environment credential before model try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); } -test "start CLI: persistent caller credential reaches child env and HTTP without leaking" { +test "start CLI: persistent caller keys preserve the child list and send only the first key" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -314,7 +315,9 @@ test "start CLI: persistent caller credential reaches child env and HTTP without defer tmp.cleanup(); var r = try Run.init(a, &tmp); const caller_key = "fixture-persistent-caller-key"; - try r.env.put("TENSORFOLD_API_KEY", caller_key); + const second_key = "fixture-second-caller-key"; + const key_list = " , " ++ caller_key ++ "," ++ second_key; + try r.env.put("TENSORFOLD_API_KEY", key_list); try r.env.put("START_TEST_UNRELATED", "caller-value-retained"); try r.env.put("START_TEST_SHORT_LIVED", "1"); try r.cache(); @@ -322,18 +325,26 @@ test "start CLI: persistent caller credential reaches child env and HTTP without const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); defer f.stop(); try r.standIn(f.port); + + var client: std.http.Client = .{ .allocator = a, .io = std.testing.io }; + defer client.deinit(); + const unauthenticated = stream.fetch(a, std.testing.io, &client, .{ .url = try f.url(a, "/v1/models"), .limit = 4096, .timeout_s = 1, .token = null }); + try std.testing.expectEqual(.none, unauthenticated.failed); + try std.testing.expectEqual(@as(u16, 401), unauthenticated.status); + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--startup-timeout", "2" })); try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "the model server exited after its successful first reply") != null); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Serving Model at") != null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(r.childGone()); const child_key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("child-key"), a, .limited(256)); - try std.testing.expect(std.mem.eql(u8, child_key, caller_key)); + try std.testing.expectEqualStrings(key_list, child_key); const unrelated = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("unrelated"), a, .limited(256)); try std.testing.expect(std.mem.eql(u8, unrelated, "caller-value-retained")); const bearer = try std.fmt.allocPrint(a, "Bearer {s}", .{caller_key}); try std.testing.expect(f.count() > 0 and std.mem.eql(u8, f.header(f.count() - 1, "authorization") orelse "", bearer)); - try std.testing.expectEqual(@as(usize, 0), f.refusals()); + try std.testing.expectEqual(@as(usize, 1), f.refusals()); const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); - for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, caller_key) == null); + for ([_][]const u8{ caller_key, second_key, key_list }) |secret| + for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } From 5e9b37b98ac378441d8c8be662d9f627c3256aa6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:47:05 +0000 Subject: [PATCH 078/361] cli: reject empty managed credential lists --- docs/run-guide.md | 14 +++++++------- zig/src/server/chat_cli_child.zig | 2 +- zig/src/server/start_cli.zig | 5 ++--- zig/src/server/start_cli_test.zig | 11 +++++++++-- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/run-guide.md b/docs/run-guide.md index a0d7845ab33..84fd21f3ad0 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -29,16 +29,16 @@ served without the drafter on pre-M5 Metal; M5 and CUDA retain it. The command starts a loopback server and sends one deterministic request. `--check` stops that server after a nonempty reply and exits 0; this ephemeral check replaces any caller API key with a private temporary key. Without `--check`, set -`TENSORFOLD_API_KEY` in the environment first: persistent `start` requires that caller credential, passes a comma-separated -list to the child unchanged, and uses its first nonempty trimmed entry for the managed checks. The server accepts each -registered entry. Send external requests with `Authorization: Bearer KEY`, replacing `KEY` with one accepted entry. Keys -are never printed or placed in the child arguments. A failed first reply is fatal and the started server is stopped. +`TENSORFOLD_API_KEY` in the environment first: persistent `start` requires at least one nonempty, valid entry, passes a +comma-separated list to the child unchanged, and uses its first nonempty trimmed entry for the managed checks. The server +accepts each registered entry. Send external requests with `Authorization: Bearer KEY`, replacing `KEY` with one accepted entry. +Keys are never printed or placed in the child arguments. A failed first reply is fatal and the started server is stopped. No existing `serve` default or flag changes. ## Send a request - -Leave the server running. In another terminal, on either platform (the authorization header is the persistent `start` -credential flow; an unauthenticated manual `serve` does not need it): +Leave the server running. In another terminal, on either platform, send the persistent credential below. For a +comma-separated `TENSORFOLD_API_KEY`, substitute one accepted entry for the whole value in the Authorization header. +An unauthenticated manual `serve` does not need a key: ```sh curl -fsS http://127.0.0.1:8080/v1/chat/completions \ diff --git a/zig/src/server/chat_cli_child.zig b/zig/src/server/chat_cli_child.zig index 351c4ec9a73..25339f2f6ce 100644 --- a/zig/src/server/chat_cli_child.zig +++ b/zig/src/server/chat_cli_child.zig @@ -16,7 +16,7 @@ pub const words: server.Words = .{ .stuck = "Model server did not exit after termination; cleanup is incomplete", }; -/// A managed child's needs. ``key`` defaults to a fresh private key; ``environment_key`` can preserve a caller list for the child. +/// Managed child setup: request ``key`` (fresh by default), and optional full-list ``environment_key`` for the child. pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, key: ?[]const u8 = null, environment_key: ?[]const u8 = null, log_dir: []const u8 }; /// The started server, the name it serves and the key every request to it carries. diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index f8eff9d2f60..b570bc0cc46 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -129,9 +129,8 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { fn run(ctx: *const Context, args: Args) !u8 { const caller_key = if (args.check) null else chat.envKey(ctx.environ) catch return fail(ctx, 2, chat.bad_key, .{}); - const raw_key = ctx.environ.get("TENSORFOLD_API_KEY"); - if (!args.check and (raw_key == null or raw_key.?.len == 0)) - return fail(ctx, 2, "persistent start requires TENSORFOLD_API_KEY in the environment; requests send Authorization: Bearer $TENSORFOLD_API_KEY, or use --check for a private temporary key", .{}); + if (!args.check and caller_key == null) + return fail(ctx, 2, "persistent start requires a nonempty TENSORFOLD_API_KEY entry in the environment, or use --check for a private temporary key", .{}); if (comptime !windows) if (ctx.signals) stop.install(); defer if (comptime !windows) if (ctx.signals) stop.restore(); const mc = ctx.given orelse machine.detect(ctx.a, ctx.io); diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index c74f623186e..ae95b63b5b8 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -294,7 +294,7 @@ test "start CLI: CUDA still resolves pulls and passes the selected drafter" { try std.testing.expect(std.mem.indexOf(u8, args, want_drafter) != null); } -test "start CLI: persistent mode requires an environment credential before model work" { +test "start CLI: persistent mode requires a valid environment credential before model work" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -303,8 +303,15 @@ test "start CLI: persistent mode requires an environment credential before model var r = try Run.init(a, &tmp); r.machine.gpu_limit = gib; try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); - try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "requires TENSORFOLD_API_KEY in the environment") != null); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "persistent start requires") != null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + for ([_][]const u8{ " ", ",", " , ", "\t,\r\n", "" }) |key| { + try r.env.put("TENSORFOLD_API_KEY", key); + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "persistent start requires a nonempty TENSORFOLD_API_KEY entry") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); + } } test "start CLI: persistent caller keys preserve the child list and send only the first key" { From 32d19e2219491032b029b8abaae1b9296deacf2c Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:24:21 +0000 Subject: [PATCH 079/361] cli: validate every managed credential entry --- docs/run-guide.md | 7 ++++--- zig/src/server/auth.zig | 16 +++++++++++----- zig/src/server/chat_cli.zig | 11 ++++++----- zig/src/server/start_cli_test.zig | 7 +++++++ 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/run-guide.md b/docs/run-guide.md index 84fd21f3ad0..0f610805242 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -30,9 +30,10 @@ served without the drafter on pre-M5 Metal; M5 and CUDA retain it. The command starts a loopback server and sends one deterministic request. `--check` stops that server after a nonempty reply and exits 0; this ephemeral check replaces any caller API key with a private temporary key. Without `--check`, set `TENSORFOLD_API_KEY` in the environment first: persistent `start` requires at least one nonempty, valid entry, passes a -comma-separated list to the child unchanged, and uses its first nonempty trimmed entry for the managed checks. The server -accepts each registered entry. Send external requests with `Authorization: Bearer KEY`, replacing `KEY` with one accepted entry. -Keys are never printed or placed in the child arguments. A failed first reply is fatal and the started server is stopped. +comma-separated list to the child unchanged, and uses its first nonempty trimmed entry for the managed checks. Every entry +must be UTF-8, at most 256 bytes, and contain no whitespace or control characters. The server accepts each registered entry. +Send external requests with `Authorization: Bearer KEY`, replacing `KEY` with one accepted entry. Keys are never printed or +placed in the child arguments. A failed first reply is fatal and the started server is stopped. No existing `serve` default or flag changes. ## Send a request diff --git a/zig/src/server/auth.zig b/zig/src/server/auth.zig index 981188e9daa..59ae43e4539 100644 --- a/zig/src/server/auth.zig +++ b/zig/src/server/auth.zig @@ -251,12 +251,18 @@ fn emptyDigest() [32]u8 { return out; } -/// SHA-256 of a key, or null for empty text or text with whitespace or control characters. -fn digest(key: []const u8) ?[32]u8 { - if (key.len == 0) return null; - var view = std.unicode.Utf8View.init(key) catch return null; +/// An API key is 1-256 bytes of UTF-8 without whitespace or control characters. +pub fn validKey(key: []const u8) bool { + if (key.len == 0 or key.len > 256) return false; + var view = std.unicode.Utf8View.init(key) catch return false; var it = view.iterator(); - while (it.nextCodepoint()) |cp| if (cp < 32 or isSpace(cp)) return null; + while (it.nextCodepoint()) |cp| if (cp < 32 or cp == 0x7f or isSpace(cp)) return false; + return true; +} + +/// SHA-256 of a key, or null when ``validKey`` rejects it. +fn digest(key: []const u8) ?[32]u8 { + if (!validKey(key)) return null; var out: [32]u8 = undefined; Sha256.hash(key, &out, .{}); return out; diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 83aaa8815d4..f2e2b08183e 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -2,6 +2,7 @@ const std = @import("std"); const builtin = @import("builtin"); const json = @import("json"); +const auth = @import("auth.zig"); const args_mod = @import("chat_cli_args.zig"); const history = @import("chat_cli_history.zig"); const turn = @import("chat_cli_turn.zig"); @@ -96,18 +97,18 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { pub const bad_key = "TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each"; -/// The key ``--url`` sends: TENSORFOLD_API_KEY's first, as serve splits the variable; null when it names none. +/// The first nonempty valid entry for ``--url``; null when all are empty. Every entry is checked first. pub fn envKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u8 { const text = (environment.path("TENSORFOLD_API_KEY", environ.get("TENSORFOLD_API_KEY")) catch return error.Refused) orelse return null; var keys = std.mem.splitScalar(u8, text, ','); + var selected: ?[]const u8 = null; while (keys.next()) |raw| { const key = std.mem.trim(u8, raw, " \t\r\n\x0b\x0c"); if (key.len == 0) continue; - if (key.len > 256) return error.Refused; - for (key) |ch| if (ch < 0x21 or ch == 0x7f) return error.Refused; - return key; + if (!auth.validKey(key)) return error.Refused; + if (selected == null) selected = key; } - return null; + return selected; } /// What a running server's 401 adds: whether TENSORFOLD_API_KEY gave the key it refused. diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index ae95b63b5b8..9110f10b8ec 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -312,6 +312,13 @@ test "start CLI: persistent mode requires a valid environment credential before try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); } + for ([_][]const u8{ "\xc2\xa0", "good-key,bad key", "good-key,\xc2\xa0" }) |key| { + try r.env.put("TENSORFOLD_API_KEY", key); + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "expected keys without spaces or control characters") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); + } } test "start CLI: persistent caller keys preserve the child list and send only the first key" { From 8a5a5c80ea7f2a785ab85572aa46b1867fbc23fa Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:28:30 +0000 Subject: [PATCH 080/361] cli: launch the installed CUDA native server --- zig/src/server/start_cli.zig | 7 ++++++- zig/src/server/start_cli_test.zig | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index b570bc0cc46..833cee3990a 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -83,7 +83,12 @@ pub fn nativeSibling(a: Allocator, current: []const u8) ![]const u8 { "tensorfold-native.exe" else return current; - return std.fs.path.join(a, &.{ std.fs.path.dirname(current) orelse ".", sibling }); + const directory = std.fs.path.dirname(current) orelse "."; + if (std.ascii.eqlIgnoreCase(std.fs.path.basename(directory), "bin")) { + const prefix = std.fs.path.dirname(directory) orelse "."; + return std.fs.path.join(a, &.{ prefix, "native", "bin", sibling }); + } + return std.fs.path.join(a, &.{ directory, sibling }); } fn mainWithServeExe(init: std.process.Init, argv: []const []const u8, serve_exe: ?[]const u8) !u8 { diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 9110f10b8ec..f41da77aacb 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -103,8 +103,10 @@ const Run = struct { } fn cudaStandIn(r: *Run, port: u16) !void { - try standInAt(r, port, "tensorfold-native"); - const low_level = try r.path("tensorfold"); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try r.path("bin")); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try r.path("native/bin")); + try standInAt(r, port, "native/bin/tensorfold-native"); + const low_level = try r.path("bin/tensorfold"); const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\ntouch {s}\nexit 2\n", .{try r.path("low-level-called")}); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = low_level, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); r.self_exe = low_level; From 9f287809e707d5e1c0d7382624800aeaef177027 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:09:12 +0000 Subject: [PATCH 081/361] cli: require published snapshots for start --- zig/src/cli/models.zig | 8 ++++++-- zig/src/server/start_cli_test.zig | 22 ++++++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/zig/src/cli/models.zig b/zig/src/cli/models.zig index d59dbf40e5b..3c2c23de8a1 100644 --- a/zig/src/cli/models.zig +++ b/zig/src/cli/models.zig @@ -57,9 +57,13 @@ fn pinned(repo: []const u8, revision: []const u8, a: Allocator) ![]const u8 { return std.fmt.allocPrint(a, "{s}@{s}", .{ repo, revision }); } -/// The exact snapshot a fully pinned entry names, whether it is cached yet or a successful pull will create it. +/// A pinned entry is cached only after pull publishes its exact revision through refs/main. fn startSnapshot(a: Allocator, io: std.Io, root: []const u8, repo: []const u8, revision: []const u8) !struct { []const u8, bool } { - const dir = try std.fs.path.join(a, &.{ root, try hub.repoDirName(a, repo), "snapshots", revision }); + const repo_dir = try std.fs.path.join(a, &.{ root, try hub.repoDirName(a, repo) }); + const dir = try std.fs.path.join(a, &.{ repo_dir, "snapshots", revision }); + var ref_buf: [128]u8 = undefined; + const ref = std.Io.Dir.cwd().readFile(io, try std.fs.path.join(a, &.{ repo_dir, "refs", "main" }), &ref_buf) catch return .{ dir, false }; + if (!std.mem.eql(u8, std.mem.trim(u8, ref, " \r\n"), revision)) return .{ dir, false }; return .{ dir, hub.isDir(io, dir) and @import("checkpoint_config").optional(a, io, dir) != null }; } diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index f41da77aacb..7cd6d98e487 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -81,13 +81,13 @@ const Run = struct { const repo = try std.fs.path.join(r.a, &.{ r.root, "models--Org--Model" }); try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ repo, "refs" })); try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ repo, "snapshots", revision })); - try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "refs/main" }), .data = "cccccccccccccccccccccccccccccccccccccccc" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "refs/main" }), .data = revision }); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "snapshots", revision, "config.json" }), .data = "{\"model_type\": \"qwen4_exp\", \"quantization\": {\"bits\": 6, \"group_size\": 32}}" }); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "snapshots", revision, "model.safetensors" }), .data = "fixture" }); const draft = try std.fs.path.join(r.a, &.{ r.root, "models--Org--Draft" }); try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ draft, "refs" })); try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ draft, "snapshots", draft_revision })); - try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "refs/main" }), .data = "dddddddddddddddddddddddddddddddddddddddd" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "refs/main" }), .data = draft_revision }); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "snapshots", draft_revision, "config.json" }), .data = "{\"model_type\": \"qwen4_exp_draft\"}" }); } @@ -193,6 +193,24 @@ test "start CLI: explicit consent shows sizes and pulls both pinned specs before try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); } +test "start CLI: an unpublished snapshot is not complete and cannot skip its pull" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.cache(); + const repo = try std.fs.path.join(a, &.{ r.root, "models--Org--Model" }); + try std.Io.Dir.cwd().deleteFile(std.testing.io, try std.fs.path.join(a, &.{ repo, "refs/main" })); + const f = try world(&r, try events(a, "Ready.")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{"--check"})); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "nothing was downloaded") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); +} + test "start CLI: a cached model answers once, prints no key and --check reaps its serve child" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); From 550426578acb5bdbc68c915b32de72434553b4a1 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:10:57 +0000 Subject: [PATCH 082/361] cli: stop cancelled deferred downloads --- zig/src/server/start_cli.zig | 2 ++ zig/src/server/start_cli_test.zig | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 833cee3990a..6548dae4bf6 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -159,7 +159,9 @@ fn run(ctx: *const Context, args: Args) !u8 { } } if (try pull(ctx, choice.model) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{choice.model}); + if (stop.requested()) |sig| return stop.exitCode(sig); if (choice.drafter) |d| if (try pull(ctx, d) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{d}); + if (stop.requested()) |sig| return stop.exitCode(sig); } return serve(ctx, args, choice, caller_key); } diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 7cd6d98e487..fcf67763446 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -28,6 +28,7 @@ const Run = struct { self_exe: ?[]const u8 = null, machine: machine_mod.Machine = .{ .backend = .metal, .memory = 96 * gib, .gpu_limit = 64 * gib }, pull_code: u8 = 0, + cancel_in_pull: bool = false, pulls: std.ArrayList([]const u8) = .empty, fn init(a: Allocator, tmp: *std.testing.TmpDir) !Run { @@ -58,6 +59,7 @@ const Run = struct { .input = &r.stdin, .interactive = r.interactive, .self_exe = r.self_exe, + .signals = r.cancel_in_pull, .given = r.machine, .registry = &entries, .override = r.root, @@ -68,6 +70,12 @@ const Run = struct { fn fakePull(ctx: *anyopaque, spec: []const u8) !u8 { const r: *Run = @ptrCast(@alignCast(ctx)); + if (r.cancel_in_pull) { + var action: std.posix.Sigaction = undefined; + std.posix.sigaction(.INT, null, &action); + if (action.handler.handler == std.posix.SIG.DFL) return error.DownloadSignalNotInstalled; + stop.request(.INT); + } try r.pulls.append(r.a, spec); try r.out.writer.print("stored {s} at {s}/private-snapshot\n", .{ spec, r.root }); const model = std.mem.eql(u8, spec, "Org/Model@" ++ revision); @@ -193,6 +201,21 @@ test "start CLI: explicit consent shows sizes and pulls both pinned specs before try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); } +test "start CLI: Ctrl-C during a deferred download stops before a drafter or server" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.cancel_in_pull = true; + stop.reset(); + defer stop.reset(); + try std.testing.expectEqual(@as(u8, 130), try r.command(&.{ "--yes", "--check" })); + try std.testing.expectEqual(@as(usize, 1), r.pulls.items.len); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(std.testing.io, try r.path("pid"), .{})); +} + test "start CLI: an unpublished snapshot is not complete and cannot skip its pull" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); From 6a8cc8cb6113fc819e09b071e6feff07cb461877 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:11:34 +0000 Subject: [PATCH 083/361] server: encode bearer headers as latin-1 --- zig/src/server/benchmark_stream.zig | 18 +++++++++++++++++- zig/src/server/benchmark_stream_test.zig | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index 3664f00a8df..32d65ead827 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -330,6 +330,22 @@ pub const Fetched = struct { failed: enum { none, network, too_large, stopped, deadline } = .none, }; +/// Python's raw Authorization header: Unicode scalar values encoded as Latin-1, never raw UTF-8. +fn rawHeader(buf: []u8, token: []const u8) ?[]const u8 { + const prefix = "Bearer "; + if (prefix.len + token.len > buf.len) return null; + @memcpy(buf[0..prefix.len], prefix); + var view = std.unicode.Utf8View.init(token) catch return null; + var it = view.iterator(); + var n = prefix.len; + while (it.nextCodepoint()) |cp| { + if (cp > 0xff or cp < 0x20 or cp == 0x7f) return null; + buf[n] = @intCast(cp); + n += 1; + } + return buf[0..n]; +} + const FetchTask = struct { a: Allocator, client: *std.http.Client, @@ -341,7 +357,7 @@ const FetchTask = struct { x.out.failed = .network; const uri = std.Uri.parse(x.f.url) catch return; var auth_buf: [300]u8 = undefined; - const auth: std.http.Client.Request.Headers.Value = if (x.f.token) |tok| .{ .override = std.fmt.bufPrint(&auth_buf, "Bearer {s}", .{tok}) catch return } else .omit; + const auth: std.http.Client.Request.Headers.Value = if (x.f.token) |tok| .{ .override = rawHeader(&auth_buf, tok) orelse return } else .omit; var req = x.client.request(x.f.method, uri, .{ .keep_alive = false, .redirect_behavior = .unhandled, diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index e11e926d99d..be0432d9563 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -267,6 +267,24 @@ test "a reply of exactly the limit is read, and one byte more is too large" { try std.testing.expect(at.failed == .none and std.mem.eql(u8, at.body, "[1234]")); try std.testing.expect(stream.fetch(a, std.testing.io, &client, .{ .url = try f.url(a, "/x"), .limit = 6, .timeout_s = 5 }).failed == .too_large); } +test "chat CLI: a Latin-1 bearer uses the server's header bytes without exposing UTF-8" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const f = try fake.Fake.start(std.testing.allocator, &.{.{ .method = "GET", .path = "/v1/models", .replies = &.{try fake.jsonReply(a, "200 OK", "{\"data\": []}")} }}); + defer f.stop(); + var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = std.testing.io }; + defer client.deinit(); + const token = "fixture-caf\u{e9}"; + const got = stream.fetch(a, std.testing.io, &client, .{ .url = try f.url(a, "/v1/models"), .limit = 64, .timeout_s = 5, .token = token }); + try std.testing.expectEqual(.none, got.failed); + try std.testing.expectEqual(@as(u16, 200), got.status); + try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(0, "authorization").?); + try std.testing.expect(std.mem.indexOf(u8, f.request(0).head, token) == null); + const refused = stream.fetch(a, std.testing.io, &client, .{ .url = try f.url(a, "/v1/models"), .limit = 64, .timeout_s = 5, .token = "fixture-\u{20ac}" }); + try std.testing.expectEqual(.network, refused.failed); + try std.testing.expectEqual(@as(usize, 1), f.count()); +} test "an https exchange is never sent through a proxy that refuses to tunnel" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); From 44a863b8dbc6fd39dfbfb3161805fc8b3d318534 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:12:18 +0000 Subject: [PATCH 084/361] build: skip POSIX start tests on Windows hosts --- zig/build/cuda_server_host.zig | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 20be734bb31..8c6570c0f73 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -111,8 +111,10 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod const start_run = b.addRunArtifact(b.addTest(.{ .root_module = start_tests, .filters = &.{"start CLI:"} })); start_run.has_side_effects = true; const start_step = b.step("test-start-cli-host", "Automatic model choice, download consent, first reply and serve-child cleanup without devices"); - start_step.dependOn(&start_run.step); - step.dependOn(&start_run.step); + if (host.result.os.tag != .windows) { + start_step.dependOn(&start_run.step); + step.dependOn(&start_run.step); + } const windows_target = b.resolveTargetQuery(.{ .cpu_arch = .x86_64, .os_tag = .windows, .abi = .gnu }); const windows_lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = windows_target, .optimize = .debug, .link_libc = true }); const windows_start = @import("server.zig").plain(b, "zig/src/server/start_cli.zig", windows_target, .debug, windows_lanes); From b698ba3efdcd92ee895af3b42b3f9a806afb6479 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:14:39 +0000 Subject: [PATCH 085/361] cli: restore process cancellation during downloads --- zig/src/server/start_cli.zig | 6 ++--- zig/src/server/start_cli_test.zig | 44 ++++++++++++++++++++++--------- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 6548dae4bf6..5a35ca62cd1 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -136,8 +136,6 @@ fn run(ctx: *const Context, args: Args) !u8 { const caller_key = if (args.check) null else chat.envKey(ctx.environ) catch return fail(ctx, 2, chat.bad_key, .{}); if (!args.check and caller_key == null) return fail(ctx, 2, "persistent start requires a nonempty TENSORFOLD_API_KEY entry in the environment, or use --check for a private temporary key", .{}); - if (comptime !windows) if (ctx.signals) stop.install(); - defer if (comptime !windows) if (ctx.signals) stop.restore(); const mc = ctx.given orelse machine.detect(ctx.a, ctx.io); const choice = (try registry.choose(ctx.a, ctx.io, ctx.environ, ctx.override, ctx.registry orelse ®istry.entries, &mc)) orelse return fail(ctx, 1, "no catalog model that this machine can start automatically; tensorfold models --all shows the reasons and manual recipes", .{}); @@ -159,10 +157,10 @@ fn run(ctx: *const Context, args: Args) !u8 { } } if (try pull(ctx, choice.model) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{choice.model}); - if (stop.requested()) |sig| return stop.exitCode(sig); if (choice.drafter) |d| if (try pull(ctx, d) != 0) return fail(ctx, 1, "pull {s} failed; fix the reported error and run start again", .{d}); - if (stop.requested()) |sig| return stop.exitCode(sig); } + if (comptime !windows) if (ctx.signals) stop.install(); + defer if (comptime !windows) if (ctx.signals) stop.restore(); return serve(ctx, args, choice, caller_key); } diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index fcf67763446..180bad7db65 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -1,5 +1,7 @@ //! `tensorfold start` against fake devices, registries, checkpoints and HTTP servers. const std = @import("std"); +const builtin = @import("builtin"); +const platform = @import("sys"); const start = @import("start_cli.zig"); const registry = @import("checkpoint_cli").start; const machine_mod = @import("sys").machine; @@ -70,12 +72,7 @@ const Run = struct { fn fakePull(ctx: *anyopaque, spec: []const u8) !u8 { const r: *Run = @ptrCast(@alignCast(ctx)); - if (r.cancel_in_pull) { - var action: std.posix.Sigaction = undefined; - std.posix.sigaction(.INT, null, &action); - if (action.handler.handler == std.posix.SIG.DFL) return error.DownloadSignalNotInstalled; - stop.request(.INT); - } + if (r.cancel_in_pull) _ = platform.c.raise(.INT); try r.pulls.append(r.a, spec); try r.out.writer.print("stored {s} at {s}/private-snapshot\n", .{ spec, r.root }); const model = std.mem.eql(u8, spec, "Org/Model@" ++ revision); @@ -201,7 +198,31 @@ test "start CLI: explicit consent shows sizes and pulls both pinned specs before try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); } -test "start CLI: Ctrl-C during a deferred download stops before a drafter or server" { +const DownloadInterrupt = struct { + var run: *Run = undefined; + + fn body() u8 { + return run.command(&.{ "--yes", "--check" }) catch 99; + } +}; + +fn forkedDownload() !?u32 { + const pid = platform.c.fork(); + if (pid < 0) return error.SkipZigTest; + if (pid == 0) platform.c._exit(DownloadInterrupt.body()); + var status: c_int = 0; + var waited: u32 = 0; + while (waited < 5000) : (waited += 10) { + if (platform.c.waitpid(pid, &status, platform.c.W.NOHANG) == pid) return @bitCast(status); + fake.nap(10); + } + _ = platform.c.kill(pid, .KILL); + _ = platform.c.waitpid(pid, &status, 0); + return null; +} + +test "start CLI: Ctrl-C during a deferred download has its normal process effect" { + if (builtin.os.tag != .macos and builtin.os.tag != .linux) return error.SkipZigTest; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -209,11 +230,10 @@ test "start CLI: Ctrl-C during a deferred download stops before a drafter or ser defer tmp.cleanup(); var r = try Run.init(a, &tmp); r.cancel_in_pull = true; - stop.reset(); - defer stop.reset(); - try std.testing.expectEqual(@as(u8, 130), try r.command(&.{ "--yes", "--check" })); - try std.testing.expectEqual(@as(usize, 1), r.pulls.items.len); - try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(std.testing.io, try r.path("pid"), .{})); + DownloadInterrupt.run = &r; + const status = (try forkedDownload()) orelse return error.TestUnexpectedResult; + try std.testing.expect(platform.c.W.IFSIGNALED(status)); + try std.testing.expect(platform.c.W.TERMSIG(status) == std.posix.SIG.INT); } test "start CLI: an unpublished snapshot is not complete and cannot skip its pull" { From b339070e2201f26fee5ce67df4bc3402b7de91d6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:38:01 +0000 Subject: [PATCH 086/361] cli: revoke completion during snapshot repair --- zig/build/pull_tests.zig | 4 +-- zig/src/cli/pull.zig | 6 ++++ zig/src/cli/pull_host_test.zig | 5 ++++ zig/src/cli/pull_repair_test.zig | 47 ++++++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 zig/src/cli/pull_host_test.zig create mode 100644 zig/src/cli/pull_repair_test.zig diff --git a/zig/build/pull_tests.zig b/zig/build/pull_tests.zig index 082de40f7ff..2282185f0d2 100644 --- a/zig/build/pull_tests.zig +++ b/zig/build/pull_tests.zig @@ -21,7 +21,7 @@ pub fn add(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti test_step.dependOn(&journal_log.step); } const mod = b.createModule(.{ - .root_source_file = b.path("zig/src/cli/pull_test.zig"), + .root_source_file = b.path("zig/src/cli/pull_host_test.zig"), .target = target, .optimize = optimize, .link_libc = true, @@ -51,7 +51,7 @@ pub fn compile(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *std. const mods = cuda.family(b, target, .debug, runtime, draft_ids); const native = @import("cuda_engines.zig").engines(b, target, .debug, runtime, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision); const tests = b.addTest(.{ .name = "tf-pull-host-tests", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/src/cli/pull_test.zig"), + .root_source_file = b.path("zig/src/cli/pull_host_test.zig"), .target = target, .optimize = .debug, .link_libc = true, diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index 304002c8c36..3498b8f4211 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -113,6 +113,12 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W const snapshot_dir = try std.fs.path.join(a, &.{ repo_dir, "snapshots", sha }); const refs_dir = try std.fs.path.join(a, &.{ repo_dir, "refs" }); for ([_][]const u8{ blobs_dir, snapshot_dir, refs_dir }) |d| try w.createDirPath(io, d); + // A failed same-revision repair must not leave its old completion marker behind. + const ref_path = try std.fs.path.join(a, &.{ refs_dir, "main" }); + var ref_buf: [128]u8 = undefined; + const published: ?[]const u8 = w.readFile(io, ref_path, &ref_buf) catch null; + if (published) |text| if (std.mem.eql(u8, std.mem.trim(u8, text, " \r\n"), sha)) + try w.deleteFile(io, ref_path); var big: std.ArrayList(Big) = .empty; for (entries) |e| { diff --git a/zig/src/cli/pull_host_test.zig b/zig/src/cli/pull_host_test.zig new file mode 100644 index 00000000000..965efc4c903 --- /dev/null +++ b/zig/src/cli/pull_host_test.zig @@ -0,0 +1,5 @@ +//! Pull-host integration tests and same-revision repair coverage. +test { + _ = @import("pull_test.zig"); + _ = @import("pull_repair_test.zig"); +} diff --git a/zig/src/cli/pull_repair_test.zig b/zig/src/cli/pull_repair_test.zig new file mode 100644 index 00000000000..f33f4673f0f --- /dev/null +++ b/zig/src/cli/pull_repair_test.zig @@ -0,0 +1,47 @@ +//! Published snapshots lose completion evidence when a same-revision repair fails. +const std = @import("std"); +const pull = @import("pull.zig"); +const FakeHub = @import("pull_test.zig").FakeHub; +const TestClient = @import("pull_test_client.zig").Client; + +fn refuseWeight(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + if (!std.mem.startsWith(u8, head, "GET ") or std.mem.indexOf(u8, head, FakeHub.weights_path) == null) return null; + fake.sendAll(conn, "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + return false; +} + +test "pull revokes completion before a failed repair of a published snapshot" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-repair-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + var env: std.process.Environ.Map = .{ .array_hash_map = .empty, .allocator = a }; + try env.put("HF_ENDPOINT", try fake.endpoint(a)); + var out: std.Io.Writer.Allocating = .init(a); + var err: std.Io.Writer.Allocating = .init(a); + const sizes: pull.Sizes = .{ .threshold = 1 << 20 }; + const spec = "Org/Flash"; + try std.testing.expectEqual(@as(u8, 0), try pull.runWith(a, io, &out.writer, &err.writer, &env, root, spec, sizes)); + + const repo = try std.fs.path.join(a, &.{ root, "models--Org--Flash" }); + const ref_path = try std.fs.path.join(a, &.{ repo, "refs/main" }); + const snapshot = try std.fs.path.join(a, &.{ repo, "snapshots/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1" }); + try std.Io.Dir.cwd().deleteFile(io, try std.fs.path.join(a, &.{ repo, "blobs", fake.weights_sha_hex })); + fake.route = refuseWeight; + try std.testing.expectEqual(@as(u8, 1), try pull.runWith(a, io, &out.writer, &err.writer, &env, root, spec, sizes)); + try std.Io.Dir.cwd().access(io, try std.fs.path.join(a, &.{ snapshot, "config.json" }), .{}); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, ref_path, .{})); + + fake.route = null; + try std.testing.expectEqual(@as(u8, 0), try pull.runWith(a, io, &out.writer, &err.writer, &env, root, spec, sizes)); + const ref = try std.Io.Dir.cwd().readFileAlloc(io, ref_path, a, .limited(64)); + try std.testing.expectEqualStrings("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1", ref); +} From 793634a65c9dab1038a1b843f1edad7f1d5de5f6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:40:57 +0000 Subject: [PATCH 087/361] server: encode reply bearer headers as latin-1 --- zig/src/server/benchmark_stream.zig | 2 +- zig/src/server/benchmark_stream_test.zig | 34 ++++++++++++++++++++++++ zig/src/server/chat_cli_turn.zig | 5 +++- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index 32d65ead827..7574f23ef85 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -331,7 +331,7 @@ pub const Fetched = struct { }; /// Python's raw Authorization header: Unicode scalar values encoded as Latin-1, never raw UTF-8. -fn rawHeader(buf: []u8, token: []const u8) ?[]const u8 { +pub fn rawHeader(buf: []u8, token: []const u8) ?[]const u8 { const prefix = "Bearer "; if (prefix.len + token.len > buf.len) return null; @memcpy(buf[0..prefix.len], prefix); diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index be0432d9563..e1e0580cac6 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -4,6 +4,8 @@ const suite = @import("benchmark_suite.zig"); const stream = @import("benchmark_stream.zig"); const stop = @import("benchmark_stop.zig"); const fake = @import("benchmark_fake.zig"); +const history = @import("chat_cli_history.zig"); +const turn = @import("chat_cli_turn.zig"); const Write = fake.Write; const golden_chat = "{\"model\": \".tensorfold-benchmark\", \"max_tokens\": 256, \"temperature\": 1.0, \"seed\": 1234, \"stream\": true, \"stream_options\": {\"include_usage\": true}, \"presence_penalty\": 0.0, \"frequency_penalty\": 0.0, \"top_k\": 20, \"top_p\": 0.95, \"draft\": false, \"messages\": [{\"role\": \"user\", \"content\": \"Explain how matrix multiplication uses a GPU in plain English, then give a small numerical example.\"}], \"chat_template_kwargs\": {\"enable_thinking\": false}}"; @@ -286,6 +288,38 @@ test "chat CLI: a Latin-1 bearer uses the server's header bytes without exposing try std.testing.expectEqual(@as(usize, 1), f.count()); } +test "chat CLI: a streamed reply uses Latin-1 bearer bytes and refuses unsupported keys" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const replies = [_]Write{ + .{ .bytes = try fake.headOf(a, "200 OK", "text/event-stream") }, + .{ .bytes = try fake.event(a, "{\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Ready.\"},\"finish_reason\":\"stop\"}]}") }, + .{ .bytes = try fake.event(a, "[DONE]") }, + }; + const responses = [_][]const Write{&replies}; + const f = try fake.Fake.start(a, &.{.{ .method = "POST", .path = "/v1/chat/completions", .replies = &responses }}); + defer f.stop(); + var h: history.History = .{ .a = a }; + var out: std.Io.Writer.Allocating = .init(a); + const token = "fixture-caf\u{e9}"; + const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, + try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + switch (ended) { + .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), + else => return error.TestUnexpectedResult, + } + try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(0, "authorization").?); + try std.testing.expect(std.mem.indexOf(u8, f.request(0).head, token) == null); + const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", + try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + switch (refused) { + .failed => |why| try std.testing.expect(std.mem.indexOf(u8, why.reason, "fixture") == null), + else => return error.TestUnexpectedResult, + } + try std.testing.expectEqual(@as(usize, 1), f.count()); +} + test "an https exchange is never sent through a proxy that refuses to tunnel" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index e39f533b04c..b93068edb89 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -53,7 +53,10 @@ pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, request: defer client.deinit(); var printer: Printer = .{ .io = io, .out = out, .show = show }; var r: reply.Reply = .{ .a = a, .sink = printer.sink() }; - const bearer = if (key) |k| try std.fmt.allocPrint(a, "Bearer {s}", .{k}) else null; + var auth_buf: [300]u8 = undefined; + const bearer = if (key) |k| stream.rawHeader(&auth_buf, k) orelse return .{ .failed = .{ + .reason = "API key cannot be encoded as Latin-1 header text", + } } else null; var x: Exchange = .{ .a = a, .io = io, .client = &client, .uri = try std.Uri.parse(url), .bearer = bearer, .body = request, .reply = &r }; const ended = stream.bounded(io, null, Exchange.run, &x); printer.end(); From 39b55c8ff77d3e72a9f8e9e1852fa6349985c936 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:43:16 +0000 Subject: [PATCH 088/361] server: reject non-latin-1 keys before model work --- zig/src/server/auth.zig | 4 ++-- zig/src/server/benchmark_stream_test.zig | 6 ++---- zig/src/server/chat_cli.zig | 2 +- zig/src/server/chat_cli_test.zig | 2 +- zig/src/server/start_cli_test.zig | 19 ++++++++++++++++++- 5 files changed, 24 insertions(+), 9 deletions(-) diff --git a/zig/src/server/auth.zig b/zig/src/server/auth.zig index 59ae43e4539..81034038583 100644 --- a/zig/src/server/auth.zig +++ b/zig/src/server/auth.zig @@ -251,12 +251,12 @@ fn emptyDigest() [32]u8 { return out; } -/// An API key is 1-256 bytes of UTF-8 without whitespace or control characters. +/// An API key is 1-256 bytes of UTF-8 whose scalars fit Latin-1 and exclude whitespace or controls. pub fn validKey(key: []const u8) bool { if (key.len == 0 or key.len > 256) return false; var view = std.unicode.Utf8View.init(key) catch return false; var it = view.iterator(); - while (it.nextCodepoint()) |cp| if (cp < 32 or cp == 0x7f or isSpace(cp)) return false; + while (it.nextCodepoint()) |cp| if (cp > 0xff or cp < 32 or cp == 0x7f or isSpace(cp)) return false; return true; } diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index e1e0580cac6..20e6af0b117 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -303,16 +303,14 @@ test "chat CLI: a streamed reply uses Latin-1 bearer bytes and refuses unsupport var h: history.History = .{ .a = a }; var out: std.Io.Writer.Allocating = .init(a); const token = "fixture-caf\u{e9}"; - const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, - try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (ended) { .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), else => return error.TestUnexpectedResult, } try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(0, "authorization").?); try std.testing.expect(std.mem.indexOf(u8, f.request(0).head, token) == null); - const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", - try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (refused) { .failed => |why| try std.testing.expect(std.mem.indexOf(u8, why.reason, "fixture") == null), else => return error.TestUnexpectedResult, diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index f2e2b08183e..b1ae7560a8b 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -95,7 +95,7 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { if (comptime windows) return fail(ctx, windows_child) else return served(ctx, args, message); } -pub const bad_key = "TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each"; +pub const bad_key = "TENSORFOLD_API_KEY: expected Latin-1 keys without spaces or control characters, at most 256 bytes each"; /// The first nonempty valid entry for ``--url``; null when all are empty. Every entry is checked first. pub fn envKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u8 { diff --git a/zig/src/server/chat_cli_test.zig b/zig/src/server/chat_cli_test.zig index 3e55db2d0d3..9ff7ccece0a 100644 --- a/zig/src/server/chat_cli_test.zig +++ b/zig/src/server/chat_cli_test.zig @@ -195,7 +195,7 @@ test "chat CLI: --url sends TENSORFOLD_API_KEY's first key as the bearer, and a for (0..f.count()) |i| try std.testing.expectEqualStrings("Bearer example-key-1", f.header(i, "authorization").?); try r.env.put("TENSORFOLD_API_KEY", "two words"); try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", url })); - try std.testing.expectEqualStrings("tensorfold chat: TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each\n", r.err.written()); + try std.testing.expectEqualStrings("tensorfold chat: TENSORFOLD_API_KEY: expected Latin-1 keys without spaces or control characters, at most 256 bytes each\n", r.err.written()); try std.testing.expect(f.refusals() == 5 and f.count() == 2); } diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 180bad7db65..17ed0423cc8 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -169,6 +169,23 @@ test "start CLI: a missing fit or a refused download never invokes pull or serve try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); } +test "start CLI: an above-Latin-1 key is refused before model selection or pulls" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const token = "fixture-\u{20ac}"; + try r.env.put("TENSORFOLD_API_KEY", token); + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{"--yes"})); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected") == null); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "Latin-1") != null); + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| + try std.testing.expect(std.mem.indexOf(u8, text, token) == null); +} + test "start CLI: explicit consent shows sizes and pulls both pinned specs before a failed pull stops" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -378,7 +395,7 @@ test "start CLI: persistent mode requires a valid environment credential before for ([_][]const u8{ "\xc2\xa0", "good-key,bad key", "good-key,\xc2\xa0" }) |key| { try r.env.put("TENSORFOLD_API_KEY", key); try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); - try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "expected keys without spaces or control characters") != null); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "expected Latin-1 keys without spaces or control characters") != null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); } From 961cd8a6e9f05711e63b10d1162ced8201f4b3c5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:10:26 +0000 Subject: [PATCH 089/361] cli: propagate ref reads and authenticate Latin-1 test replies --- zig/src/cli/pull.zig | 5 ++- zig/src/cli/pull_repair_test.zig | 34 +++++++++++++++++++++ zig/src/server/benchmark_fake.zig | 32 ++++++++++++++----- zig/src/server/benchmark_stream_test.zig | 13 ++++++-- zig/src/server/start_cli_test.zig | 39 ++++++++++++++++++++++++ 5 files changed, 111 insertions(+), 12 deletions(-) diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index 3498b8f4211..74365115401 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -116,7 +116,10 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W // A failed same-revision repair must not leave its old completion marker behind. const ref_path = try std.fs.path.join(a, &.{ refs_dir, "main" }); var ref_buf: [128]u8 = undefined; - const published: ?[]const u8 = w.readFile(io, ref_path, &ref_buf) catch null; + const published: ?[]const u8 = w.readFile(io, ref_path, &ref_buf) catch |err| switch (err) { + error.FileNotFound => null, + else => return err, + }; if (published) |text| if (std.mem.eql(u8, std.mem.trim(u8, text, " \r\n"), sha)) try w.deleteFile(io, ref_path); diff --git a/zig/src/cli/pull_repair_test.zig b/zig/src/cli/pull_repair_test.zig index f33f4673f0f..7d9cca7b348 100644 --- a/zig/src/cli/pull_repair_test.zig +++ b/zig/src/cli/pull_repair_test.zig @@ -45,3 +45,37 @@ test "pull revokes completion before a failed repair of a published snapshot" { const ref = try std.Io.Dir.cwd().readFileAlloc(io, ref_path, a, .limited(64)); try std.testing.expectEqualStrings("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1", ref); } + +test "pull leaves a published snapshot untouched when its ref cannot be read" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-ref-read-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + var env: std.process.Environ.Map = .{ .array_hash_map = .empty, .allocator = a }; + try env.put("HF_ENDPOINT", try fake.endpoint(a)); + var out: std.Io.Writer.Allocating = .init(a); + var err: std.Io.Writer.Allocating = .init(a); + const sizes: pull.Sizes = .{ .threshold = 1 << 20 }; + try std.testing.expectEqual(@as(u8, 0), try pull.runWith(a, io, &out.writer, &err.writer, &env, root, "Org/Flash", sizes)); + + const repo = try std.fs.path.join(a, &.{ root, "models--Org--Flash" }); + const ref_path = try std.fs.path.join(a, &.{ repo, "refs/main" }); + const snapshot = try std.fs.path.join(a, &.{ repo, "snapshots/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1" }); + const blob = try std.fs.path.join(a, &.{ repo, "blobs", fake.weights_sha_hex }); + try std.Io.Dir.cwd().deleteFile(io, blob); + try std.Io.Dir.cwd().deleteFile(io, ref_path); + try std.Io.Dir.cwd().createDirPath(io, ref_path); + fake.route = refuseWeight; + try std.testing.expectError(error.IsDir, pull.runWith(a, io, &out.writer, &err.writer, &env, root, "Org/Flash", sizes)); + try std.Io.Dir.cwd().access(io, try std.fs.path.join(a, &.{ snapshot, "config.json" }), .{}); + try std.Io.Dir.cwd().access(io, ref_path, .{}); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, blob, .{})); +} diff --git a/zig/src/server/benchmark_fake.zig b/zig/src/server/benchmark_fake.zig index bf2d30630fb..5c64c601bb5 100644 --- a/zig/src/server/benchmark_fake.zig +++ b/zig/src/server/benchmark_fake.zig @@ -2,6 +2,7 @@ const std = @import("std"); const platform = @import("sys"); const posix = std.posix; +const auth = @import("auth.zig"); const Allocator = std.mem.Allocator; /// Write bytes, then wait on ``after`` (caller releases before cleanup) and pause. @@ -89,18 +90,33 @@ pub const Fake = struct { return f.refused; } - /// True unless the fake is keyed and the request, not GET /health, lacks the file's key. + /// Match the request with the server's Latin-1 header digest conversion. fn authorized(f: *Fake, method: []const u8, path: []const u8, head: []const u8) bool { const file = f.key_file orelse return true; if (std.mem.eql(u8, method, "GET") and std.mem.eql(u8, path, "/health")) return true; var buf: [512]u8 = undefined; - const key = std.mem.trim(u8, std.Io.Dir.cwd().readFile(std.testing.io, file, &buf) catch "", " \r\n"); - const sent = headerIn(head, "authorization") orelse ""; - if (key.len > 0 and std.mem.startsWith(u8, sent, "Bearer ") and std.mem.eql(u8, sent["Bearer ".len..], key)) return true; - f.mutex.lockUncancelable(std.testing.io); - defer f.mutex.unlock(std.testing.io); - f.refused += 1; - return false; + var allow = false; + if (std.Io.Dir.cwd().readFile(std.testing.io, file, &buf)) |raw| { + const key = std.mem.trim(u8, raw, " \r\n"); + var arena: std.heap.ArenaAllocator = .init(f.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var problem: []const u8 = ""; + var store = auth.Store.init(a, &.{key}, "", null, false, &problem) catch { + f.mutex.lockUncancelable(std.testing.io); + defer f.mutex.unlock(std.testing.io); + f.refused += 1; + return false; + }; + defer store.deinit(); + allow = store.match(a, headerIn(head, "authorization"), null) != null; + } else |_| {} + if (!allow) { + f.mutex.lockUncancelable(std.testing.io); + defer f.mutex.unlock(std.testing.io); + f.refused += 1; + } + return allow; } fn accept(f: *Fake) void { diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index 20e6af0b117..18a2400d8cd 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -288,21 +288,25 @@ test "chat CLI: a Latin-1 bearer uses the server's header bytes without exposing try std.testing.expectEqual(@as(usize, 1), f.count()); } -test "chat CLI: a streamed reply uses Latin-1 bearer bytes and refuses unsupported keys" { +test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses unsupported keys" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const token = "fixture-caf\u{e9}"; + const key_file = try std.fs.path.join(a, &.{ try fake.tmpPath(a, &tmp), "caller-key" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = key_file, .data = token }); const replies = [_]Write{ .{ .bytes = try fake.headOf(a, "200 OK", "text/event-stream") }, .{ .bytes = try fake.event(a, "{\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Ready.\"},\"finish_reason\":\"stop\"}]}") }, .{ .bytes = try fake.event(a, "[DONE]") }, }; const responses = [_][]const Write{&replies}; - const f = try fake.Fake.start(a, &.{.{ .method = "POST", .path = "/v1/chat/completions", .replies = &responses }}); + const f = try fake.Fake.startKeyed(a, &.{.{ .method = "POST", .path = "/v1/chat/completions", .replies = &responses }}, key_file); defer f.stop(); var h: history.History = .{ .a = a }; var out: std.Io.Writer.Allocating = .init(a); - const token = "fixture-caf\u{e9}"; const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (ended) { .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), @@ -316,6 +320,9 @@ test "chat CLI: a streamed reply uses Latin-1 bearer bytes and refuses unsupport else => return error.TestUnexpectedResult, } try std.testing.expectEqual(@as(usize, 1), f.count()); + try std.testing.expectEqual(@as(usize, 0), f.refusals()); + try std.testing.expect(std.mem.indexOf(u8, f.request(0).path, token) == null); + try std.testing.expect(std.mem.indexOf(u8, out.written(), token) == null); } test "an https exchange is never sent through a proxy that refuses to tunnel" { diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 17ed0423cc8..fda34ec647b 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -442,3 +442,42 @@ test "start CLI: persistent caller keys preserve the child list and send only th for ([_][]const u8{ caller_key, second_key, key_list }) |secret| for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } + +test "start CLI: a managed first reply authenticates a Latin-1 caller key" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const caller_key = "fixture-caf\u{e9}"; + const second_key = "fixture-second-caller-key"; + const key_list = " , " ++ caller_key ++ "," ++ second_key; + try r.env.put("TENSORFOLD_API_KEY", key_list); + try r.env.put("START_TEST_SHORT_LIVED", "1"); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = caller_key }); + const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); + defer f.stop(); + try r.standIn(f.port); + + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--startup-timeout", "2" })); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Serving Model at") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Ready.") != null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + try std.testing.expect(r.childGone()); + const child_key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("child-key"), a, .limited(256)); + try std.testing.expectEqualStrings(key_list, child_key); + try std.testing.expect(f.count() > 0); + try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(f.count() - 1, "authorization") orelse ""); + try std.testing.expectEqual(@as(usize, 0), f.refusals()); + const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); + for ([_][]const u8{ caller_key, second_key, key_list }) |secret| { + for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| + try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); + for (0..f.count()) |i| { + try std.testing.expect(std.mem.indexOf(u8, f.request(i).path, secret) == null); + try std.testing.expect(std.mem.indexOf(u8, f.request(i).head, secret) == null); + } + } +} From 9f623ea4b98990fab365c468252c0d5e59a8acd3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:43:04 +0000 Subject: [PATCH 090/361] cli: guard cache setup and count selected Gemma bytes --- zig/src/cli/catalog.zig | 4 +++- zig/src/cli/models.zig | 2 +- zig/src/cli/pull.zig | 4 ++-- zig/src/cli/pull_repair_test.zig | 33 ++++++++++++++++++++++++++++ zig/src/server/start_cli_test.zig | 36 ++++++++++++++++++++++++++++++- 5 files changed, 74 insertions(+), 5 deletions(-) diff --git a/zig/src/cli/catalog.zig b/zig/src/cli/catalog.zig index 1a8e992ffb2..5631bb9f52c 100644 --- a/zig/src/cli/catalog.zig +++ b/zig/src/cli/catalog.zig @@ -22,6 +22,8 @@ pub const Entry = struct { hf_dir: ?[]const u8 = null, /// Safetensors bytes on the Hub, drafter included. download: u64, + /// Main-model bytes for a pre-M5 recipe that omits the drafter, when different from the combined total. + download_main: ?u64 = null, /// What the engine keeps resident, where the model guide documents a figure other than the download. resident: ?u64 = null, metal: bool = false, @@ -101,7 +103,7 @@ pub const entries = [_]Entry{ .{ .title = "Qwen3.6-35B-A3B", .format = "NVFP4 + MTP", .repo = "nvidia/Qwen3.6-35B-A3B-NVFP4", .revision = "1355db6a052410cfd62085d94b58866fd0f2c3c5", .download = 23_424_338_320, .resident = tenthsGib(209), .cuda = true, .recipe = "docs/recipes/qwen3.6-moe.md", .speeds = &.{ .{ .backend = c, .chip = "GB10", .tok_s = 111.8, .src = "docs/recipes/qwen3.6-moe.md" }, } }, - .{ .title = "Gemma 4 31B", .format = "MLX 4-bit + DFlash", .repo = "mlx-community/gemma-4-31B-it-4bit", .revision = "696d436c404745a59f30e4939a658162b0a9e57f", .drafter = "z-lab/gemma-4-31B-it-DFlash", .drafter_revision = "eabd648301ce28583cc14757912e5e0f84e152e1", .download = 18_412_016_676 + 3_071_941_240, .metal = true, .cuda = true, .m5 = .drafts, .recipe = "docs/recipes/gemma-4-native.md", .speeds = &.{ + .{ .title = "Gemma 4 31B", .format = "MLX 4-bit + DFlash", .repo = "mlx-community/gemma-4-31B-it-4bit", .revision = "696d436c404745a59f30e4939a658162b0a9e57f", .drafter = "z-lab/gemma-4-31B-it-DFlash", .drafter_revision = "eabd648301ce28583cc14757912e5e0f84e152e1", .download = 18_412_016_676 + 3_071_941_240, .download_main = 18_412_016_676, .metal = true, .cuda = true, .m5 = .drafts, .recipe = "docs/recipes/gemma-4-native.md", .speeds = &.{ .{ .backend = m, .chip = "M5 Ultra", .tok_s = 150, .src = "docs/recipes/gemma-4-native.md" }, .{ .backend = m, .chip = "M5 Ultra", .tok_s = 51, .plain = true, .src = "docs/recipes/gemma-4-native.md" }, .{ .backend = c, .chip = "GB10", .tok_s = 29.9, .src = "CHANGELOG 1.1.4" }, diff --git a/zig/src/cli/models.zig b/zig/src/cli/models.zig index 3c2c23de8a1..08ffd3e6cad 100644 --- a/zig/src/cli/models.zig +++ b/zig/src/cli/models.zig @@ -90,7 +90,7 @@ pub fn chooseForStart(a: Allocator, io: std.Io, env: ?*const std.process.Environ .drafter = if (drafting) try pinned(e.drafter.?, e.drafter_revision.?, a) else null, .model_dir = main[0], .drafter_dir = if (drafting) draft[0] else null, - .download_bytes = e.download, + .download_bytes = if (drafting) e.download else e.download_main orelse e.download, .cached = main[1] and draft[1], }; } diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index 74365115401..b5213c4d791 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -112,8 +112,7 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W const blobs_dir = try std.fs.path.join(a, &.{ repo_dir, "blobs" }); const snapshot_dir = try std.fs.path.join(a, &.{ repo_dir, "snapshots", sha }); const refs_dir = try std.fs.path.join(a, &.{ repo_dir, "refs" }); - for ([_][]const u8{ blobs_dir, snapshot_dir, refs_dir }) |d| try w.createDirPath(io, d); - // A failed same-revision repair must not leave its old completion marker behind. + // A failed same-revision repair must not create directories or leave its old completion marker behind. const ref_path = try std.fs.path.join(a, &.{ refs_dir, "main" }); var ref_buf: [128]u8 = undefined; const published: ?[]const u8 = w.readFile(io, ref_path, &ref_buf) catch |err| switch (err) { @@ -122,6 +121,7 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W }; if (published) |text| if (std.mem.eql(u8, std.mem.trim(u8, text, " \r\n"), sha)) try w.deleteFile(io, ref_path); + for ([_][]const u8{ blobs_dir, snapshot_dir, refs_dir }) |d| try w.createDirPath(io, d); var big: std.ArrayList(Big) = .empty; for (entries) |e| { diff --git a/zig/src/cli/pull_repair_test.zig b/zig/src/cli/pull_repair_test.zig index 7d9cca7b348..f4726dbeca3 100644 --- a/zig/src/cli/pull_repair_test.zig +++ b/zig/src/cli/pull_repair_test.zig @@ -79,3 +79,36 @@ test "pull leaves a published snapshot untouched when its ref cannot be read" { try std.Io.Dir.cwd().access(io, ref_path, .{}); try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, blob, .{})); } + +test "pull reads the ref before creating absent blob or snapshot directories" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-ref-directories-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + var env: std.process.Environ.Map = .{ .array_hash_map = .empty, .allocator = a }; + try env.put("HF_ENDPOINT", try fake.endpoint(a)); + var out: std.Io.Writer.Allocating = .init(a); + var err: std.Io.Writer.Allocating = .init(a); + const sizes: pull.Sizes = .{ .threshold = 1 << 20 }; + try std.testing.expectEqual(@as(u8, 0), try pull.runWith(a, io, &out.writer, &err.writer, &env, root, "Org/Flash", sizes)); + + const repo = try std.fs.path.join(a, &.{ root, "models--Org--Flash" }); + const blobs = try std.fs.path.join(a, &.{ repo, "blobs" }); + const snapshots = try std.fs.path.join(a, &.{ repo, "snapshots" }); + const ref_path = try std.fs.path.join(a, &.{ repo, "refs/main" }); + try std.Io.Dir.cwd().deleteTree(io, blobs); + try std.Io.Dir.cwd().deleteTree(io, snapshots); + try std.Io.Dir.cwd().deleteFile(io, ref_path); + try std.Io.Dir.cwd().createDirPath(io, ref_path); + try std.testing.expectError(error.IsDir, pull.runWith(a, io, &out.writer, &err.writer, &env, root, "Org/Flash", sizes)); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, blobs, .{})); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, snapshots, .{})); +} diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index fda34ec647b..0bdfeb540a1 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -30,6 +30,7 @@ const Run = struct { self_exe: ?[]const u8 = null, machine: machine_mod.Machine = .{ .backend = .metal, .memory = 96 * gib, .gpu_limit = 64 * gib }, pull_code: u8 = 0, + catalog: []const registry.Entry = &entries, cancel_in_pull: bool = false, pulls: std.ArrayList([]const u8) = .empty, @@ -63,7 +64,7 @@ const Run = struct { .self_exe = r.self_exe, .signals = r.cancel_in_pull, .given = r.machine, - .registry = &entries, + .registry = r.catalog, .override = r.root, .pull = .{ .ctx = r, .run = fakePull }, }; @@ -354,6 +355,39 @@ test "start CLI: pre-M5 Metal starts Gemma-style rows without resolving pulling try std.testing.expect(std.mem.indexOf(u8, r.out.written(), r.root) == null); } +test "start CLI: pre-M5 Gemma consent counts only the selected model bytes" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + r.machine.setChip("Apple M4 Max"); + const gemma = for (registry.entries) |entry| { + if (std.mem.eql(u8, entry.title, "Gemma 4 31B")) break entry; + } else return error.TestUnexpectedResult; + const selected = [_]registry.Entry{gemma}; + r.catalog = &selected; + try std.testing.expectEqual(@as(u8, 2), try r.command(&.{"--check"})); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "18412016676 bytes") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "17.1 GiB") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "21483957916 bytes") == null); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + + const plain = (try registry.choose(a, std.testing.io, &r.env, r.root, &selected, &r.machine)).?; + try std.testing.expect(plain.drafter == null); + try std.testing.expectEqual(@as(u64, 18_412_016_676), plain.download_bytes); + r.machine.setChip("Apple M5 Max"); + const m5 = (try registry.choose(a, std.testing.io, &r.env, r.root, &selected, &r.machine)).?; + try std.testing.expect(m5.drafter != null); + try std.testing.expectEqual(@as(u64, 21_483_957_916), m5.download_bytes); + r.machine = .{ .backend = .cuda, .memory = 96 * gib, .gpu_limit = 64 * gib }; + r.machine.setChip("NVIDIA GB10"); + const cuda = (try registry.choose(a, std.testing.io, &r.env, r.root, &selected, &r.machine)).?; + try std.testing.expect(cuda.drafter != null); + try std.testing.expectEqual(@as(u64, 21_483_957_916), cuda.download_bytes); +} + test "start CLI: CUDA still resolves pulls and passes the selected drafter" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); From 7c6093346bfff4b92779de2b42913efca62862de Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:25:59 +0000 Subject: [PATCH 091/361] cli: contain managed credentials and repair cache probes --- zig/src/cli/models.zig | 6 +- zig/src/cli/pull.zig | 33 +++++- zig/src/cli/pull_auth.zig | 38 +++++++ zig/src/cli/pull_auth_test.zig | 126 +++++++++++++++++++++++ zig/src/server/auth.zig | 2 +- zig/src/server/benchmark_server.zig | 27 +++-- zig/src/server/benchmark_sse.zig | 69 ++++++++++++- zig/src/server/benchmark_stream.zig | 2 +- zig/src/server/benchmark_stream_test.zig | 21 +++- zig/src/server/chat_cli.zig | 44 +++++--- zig/src/server/chat_cli_child.zig | 4 +- zig/src/server/chat_cli_reply.zig | 48 +++++++-- zig/src/server/chat_cli_test.zig | 73 +++++++++++++ zig/src/server/chat_cli_turn.zig | 42 ++++++-- zig/src/server/start_cli.zig | 26 ++--- zig/src/server/start_cli_test.zig | 63 +++++++++++- 16 files changed, 563 insertions(+), 61 deletions(-) diff --git a/zig/src/cli/models.zig b/zig/src/cli/models.zig index 08ffd3e6cad..29073e09269 100644 --- a/zig/src/cli/models.zig +++ b/zig/src/cli/models.zig @@ -64,7 +64,11 @@ fn startSnapshot(a: Allocator, io: std.Io, root: []const u8, repo: []const u8, r var ref_buf: [128]u8 = undefined; const ref = std.Io.Dir.cwd().readFile(io, try std.fs.path.join(a, &.{ repo_dir, "refs", "main" }), &ref_buf) catch return .{ dir, false }; if (!std.mem.eql(u8, std.mem.trim(u8, ref, " \r\n"), revision)) return .{ dir, false }; - return .{ dir, hub.isDir(io, dir) and @import("checkpoint_config").optional(a, io, dir) != null }; + if (!hub.isDir(io, dir)) return .{ dir, false }; + const bytes = @import("checkpoint_config").optional(a, io, dir) orelse return .{ dir, false }; + var parsed = std.json.parseFromSlice(std.json.Value, a, bytes, .{}) catch return .{ dir, false }; + defer parsed.deinit(); + return .{ dir, parsed.value == .object }; } /// Largest comfortably fitting fully pinned `models` row that `tensorfold pull` can install; ties keep registry order. diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index b5213c4d791..f39baee044e 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -36,7 +36,6 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W return 2; } const auth = try Auth.init(a, io, env, err_out) orelse return 1; - const endpoint = auth.endpoint; if (!try routes(a, io, err_out, env)) return 2; const root = try hub.cacheDir(a, env, override); const w = std.Io.Dir.cwd(); @@ -61,7 +60,7 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W return 1; }, else => { - try err_out.print("{s}@{s}: the hub at {s} is unreachable: ", .{ repo, revision, endpoint }); + try err_out.print("{s}@{s}: the hub at the configured HF_ENDPOINT is unreachable: ", .{ repo, revision }); try route.explain(io, err_out, e); try err_out.writeAll("; check the network, HF_ENDPOINT or the proxy settings\n"); return 1; @@ -75,6 +74,10 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W try err_out.print("{s}@{s}: file tree exceeds its decompressed byte cap\n", .{ repo, revision }); return 1; }, + error.HubCredentialPath, error.HubUnsafePath => { + try err_out.print("{s}@{s}: the hub returned an unsafe file path\n", .{ repo, sha }); + return 1; + }, else => { try err_out.print("{s}@{s}: the hub's file tree is unreachable: ", .{ repo, revision }); try route.explain(io, err_out, e); @@ -100,11 +103,11 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W const kind = configKind(a, config_bytes); const model_type = kind.model_type; if (kind.drafter) { - try out.print("{s}: DFlash2 drafter ({s}), for serve --drafter\n", .{ repo, model_type }); + try out.print("{s}: DFlash2 drafter ({s}), for serve --drafter\n", .{ repo, try safeModelType(a, model_type, auth) }); } else if (hub.family(model_type)) |family| { try out.print("{s}: {s} ({s})\n", .{ repo, family.title, family.model_type }); } else { - try err_out.print("{s}: no registered Zig family serves model_type {s}; the 0.6 line may: tensorfold@0.6\n", .{ repo, model_type }); + try err_out.print("{s}: no registered Zig family serves model_type {s}; the 0.6 line may: tensorfold@0.6\n", .{ repo, try safeModelType(a, model_type, auth) }); return 1; } @@ -276,6 +279,8 @@ pub fn listTree(a: Allocator, client: *std.http.Client, auth: Auth, repo: []cons if (kind != .string or !std.mem.eql(u8, kind.string, "file")) continue; const path_v = o.get("path") orelse continue; if (path_v != .string) continue; + if (auth.reflects(path_v.string)) return error.HubCredentialPath; + if (!validEntryText(path_v.string)) return error.HubUnsafePath; const size_v = o.get("size"); const size: u64 = if (size_v != null and size_v.? == .integer and size_v.?.integer >= 0) @intCast(size_v.?.integer) else 0; var sha256: ?[32]u8 = null; @@ -311,6 +316,26 @@ fn configKind(a: Allocator, bytes: []const u8) struct { model_type: []const u8, return .{ .model_type = model_type, .drafter = parsed.value.object.get("dflash_config") != null }; } +/// Server-controlled model text made safe for output, with its hub credential removed. +fn safeModelType(a: Allocator, text: []const u8, auth: Auth) ![]const u8 { + var out = text; + if (auth.bearer) |bearer| { + const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer["Bearer ".len..] else bearer; + if (secret.len > 0 and std.mem.indexOf(u8, out, secret) != null) out = try std.mem.replaceOwned(u8, a, out, secret, "[redacted]"); + } + for (out) |ch| if (ch <= 0x20 or ch >= 0x7f) return "[unprintable model_type]"; + return out; +} + +/// Valid UTF-8 without terminal controls, for a path before it reaches a URL, log or local filename. +fn validEntryText(path: []const u8) bool { + if (path.len == 0) return false; + const view = std.unicode.Utf8View.init(path) catch return false; + var it = view.iterator(); + while (it.nextCodepoint()) |cp| if (cp < 0x20 or (cp >= 0x7f and cp <= 0x9f)) return false; + return true; +} + fn parseHex(comptime n: usize, text: []const u8) ?[n]u8 { if (text.len != 2 * n) return null; var out: [n]u8 = undefined; diff --git a/zig/src/cli/pull_auth.zig b/zig/src/cli/pull_auth.zig index 4f9d40b2753..8a09b1dd5bc 100644 --- a/zig/src/cli/pull_auth.zig +++ b/zig/src/cli/pull_auth.zig @@ -55,6 +55,13 @@ pub const Auth = struct { return if (auth.owns(uri)) .{ .override = bearer } else .default; } + /// Whether server-controlled text contains this hub's bearer, directly or percent-encoded. + pub fn reflects(auth: Auth, text: []const u8) bool { + const bearer = auth.bearer orelse return false; + const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; + return containsCredential(text, secret); + } + /// One bodiless request into `req`, redirects followed here so each hop decides the token anew; see `header`. pub fn send(auth: Auth, client: *http.Client, req: *http.Client.Request, method: http.Method, uri: std.Uri, options: http.Client.RequestOptions, buf: []u8) !http.Client.Response { var o = options; @@ -76,6 +83,7 @@ pub const Auth = struct { const location = response.head.location orelse return error.HttpRedirectLocationMissing; if (location.len > rest.len) return error.HttpRedirectLocationOversize; @memcpy(rest[0..location.len], location); // the head's bytes go when the connection does + if (auth.reflects(location)) return error.HubCredentialRedirect; at = at.resolveInPlace(location.len, &rest) catch return error.HttpRedirectLocationInvalid; left.subtractOne(); req.deinit(); @@ -107,6 +115,36 @@ fn origin(uri: std.Uri, buf: []u8) ?Origin { return .{ .scheme = uri.scheme, .host = host, .port = port }; } +/// Match a credential directly or through percent encoding, without decoding an untrusted whole URL. +fn containsCredential(text: []const u8, secret: []const u8) bool { + if (secret.len == 0) return false; + for (0..text.len) |start| { + var at = start; + var matched: usize = 0; + while (matched < secret.len and at < text.len) { + var byte = text[at]; + if (byte == '%' and at + 2 < text.len) { + const hi = hex(text[at + 1]) orelse break; + const lo = hex(text[at + 2]) orelse break; + byte = hi * 16 + lo; + at += 2; + } + if (byte != secret[matched]) break; + matched += 1; + at += 1; + } + if (matched == secret.len) return true; + } + return false; +} + +fn hex(c: u8) ?u8 { + if (c >= '0' and c <= '9') return c - '0'; + if (c >= 'a' and c <= 'f') return c - 'a' + 10; + if (c >= 'A' and c <= 'F') return c - 'A' + 10; + return null; +} + /// The first non-empty of HF_TOKEN and HUGGING_FACE_HUB_TOKEN, else the one token file the `hf` tools read. pub fn token(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, problem: *[]const u8) !?Token { for ([_][:0]const u8{ "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN" }) |name| { diff --git a/zig/src/cli/pull_auth_test.zig b/zig/src/cli/pull_auth_test.zig index 2b32788d810..901479a2ff9 100644 --- a/zig/src/cli/pull_auth_test.zig +++ b/zig/src/cli/pull_auth_test.zig @@ -71,6 +71,36 @@ fn moved(fake: *FakeHub, conn: std.Io.net.Stream, location: []const u8) bool { return true; } +var redirect_secret_seen = false; +var tree_secret_seen = false; + +fn reflectedRedirect(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + const target = requestTarget(head); + if (std.mem.eql(u8, target, "/reflect")) return moved(fake, conn, "/collect?credential=" ++ token); + if (std.mem.startsWith(u8, target, "/collect")) { + redirect_secret_seen = true; + fake.respond(conn, "{}"); + return true; + } + return null; +} + +fn reflectedTree(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + const target = requestTarget(head); + if (std.mem.eql(u8, target, "/api/models/Org/Flash/tree/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1?recursive=true")) { + var buf: [512]u8 = undefined; + const tree = std.fmt.bufPrint(&buf, "[{{\"type\": \"file\", \"oid\": \"{s}\", \"path\": \"config.json\", \"size\": {d}}}, {{\"type\": \"file\", \"path\": \"{s}\", \"size\": 0}}]", .{ &fake.config_git_hex, fake.config.len, token }) catch return false; + fake.respond(conn, tree); + return true; + } + if (std.mem.indexOf(u8, target, token) != null) { + tree_secret_seen = true; + fake.respond(conn, ""); + return true; + } + return null; +} + /// A refusal with a body the hub might send, on a connection that then closes. fn refuse(fake: *FakeHub, conn: std.Io.net.Stream, status: []const u8) bool { const body = "{\"error\": \"Access to this repo is restricted\"}"; @@ -108,6 +138,12 @@ fn has(text: []const u8, part: []const u8) bool { return std.mem.indexOf(u8, text, part) != null; } +fn requestTarget(head: []const u8) []const u8 { + const start = std.mem.indexOfScalar(u8, head, ' ') orelse return ""; + const rest = head[start + 1 ..]; + return rest[0 .. std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len]; +} + /// No file under `root` holds `secret`: not a blob, a snapshot link's target, a ref nor a partial download. fn expectNoFileHolds(a: Allocator, io: std.Io, root: []const u8, secret: []const u8) !void { var dir = try std.Io.Dir.cwd().openDir(io, root, .{ .iterate = true }); @@ -159,6 +195,74 @@ test "security: a gated repo comes down with HF_TOKEN, sent to the hub's host an try std.testing.expectEqual(@as(u32, 1), seen.cdn.load(.monotonic)); // the weights, from the CDN } +test "security: a hub cannot reflect HF_TOKEN or controls through model_type errors" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-reflected-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const env = try gatedEnv(a, &fake, token); + var shown: std.ArrayList(u8) = .empty; + for ([_][]const u8{ token, token ++ "\\u001b[31m" }) |model_type| { + fake.config = try std.fmt.allocPrint(a, "{{\"model_type\": \"{s}\"}}", .{model_type}); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try shown.appendSlice(a, out.written()); + try shown.appendSlice(a, err_out.written()); + } + try std.testing.expect(!has(shown.items, token)); + try std.testing.expect(!has(shown.items, "\x1b")); + try std.testing.expect(has(shown.items, "[redacted]")); +} + +test "security: a reflected hub token never enters a redirect request target" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedRedirect; + fake.start(); + defer fake.stopServer(); + redirect_secret_seen = false; + const hub: auth.Auth = .{ .endpoint = try fake.endpoint(a), .bearer = "Bearer " ++ token, .source = "HF_TOKEN" }; + var client = @import("pull_http.zig").client(a, std.testing.io); + defer client.deinit(); + var buf: [8 << 10]u8 = undefined; + var req: std.http.Client.Request = undefined; + _ = hub.send(&client, &req, .GET, try std.Uri.parse(try std.fmt.allocPrint(a, "{s}/reflect", .{hub.endpoint})), .{}, &buf) catch |err| { + try std.testing.expectEqual(error.HubCredentialRedirect, err); + try std.testing.expect(!redirect_secret_seen); + return; + }; + req.deinit(); + return error.TestExpectedError; +} + +test "security: a reflected hub token in a tree path is refused before output or URL use" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedTree; + fake.start(); + defer fake.stopServer(); + tree_secret_seen = false; + const root = try std.fmt.allocPrint(a, ".tf-pull-tree-secret-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const env = try gatedEnv(a, &fake, token); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try std.testing.expect(!tree_secret_seen); + try std.testing.expect(!has(out.written(), token) and !has(err_out.written(), token)); +} + test "a gated repo's large file comes down as pieces, each redirected to the CDN without the token" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -316,6 +420,28 @@ test "security: a token pull cannot send is refused by its source, and never sho try std.testing.expect(has(err_out.written(), "in HF_TOKEN has a space") and !has(err_out.written(), "hf_Example")); } +test "security: endpoint userinfo never appears in connection errors" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const user = "fixture-endpoint-user"; + const password = "fixture-endpoint-password"; + var env: Map = .init(a); + try env.put("HF_ENDPOINT", try std.fmt.allocPrint(a, "http://{s}:{s}@127.0.0.1:9", .{ user, password })); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, dir, "Org/Name")); + for ([_][]const u8{ user, password }) |secret| { + try std.testing.expect(!has(out.written(), secret)); + try std.testing.expect(!has(err_out.written(), secret)); + } + try std.testing.expect(has(err_out.written(), "HF_ENDPOINT")); +} + test "security: the token goes only to the endpoint's own scheme, host and port" { const bearer = "Bearer hf_ExampleToken"; const public_hub: auth.Auth = .{ .bearer = bearer, .source = "HF_TOKEN" }; diff --git a/zig/src/server/auth.zig b/zig/src/server/auth.zig index 81034038583..61492d14f0c 100644 --- a/zig/src/server/auth.zig +++ b/zig/src/server/auth.zig @@ -256,7 +256,7 @@ pub fn validKey(key: []const u8) bool { if (key.len == 0 or key.len > 256) return false; var view = std.unicode.Utf8View.init(key) catch return false; var it = view.iterator(); - while (it.nextCodepoint()) |cp| if (cp > 0xff or cp < 32 or cp == 0x7f or isSpace(cp)) return false; + while (it.nextCodepoint()) |cp| if (cp > 0xff or cp < 0x20 or (cp >= 0x7f and cp <= 0x9f) or isSpace(cp)) return false; return true; } diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index f244caf4c15..34f32efd687 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -41,6 +41,8 @@ pub const Options = struct { key: ?[]const u8 = null, /// The complete caller credential list for the child environment when it differs from ``key``. environment_key: ?[]const u8 = null, + /// All configured credential forms to remove before a log line is cleaned or truncated. + secrets: []const []const u8 = &.{}, words: Words = .{}, }; @@ -142,6 +144,7 @@ pub const Managed = struct { served: []const u8 = served_name, stuck: []const u8 = (Words{}).stuck, key: ?[]const u8 = null, + secrets: []const []const u8 = &.{}, base_url: []const u8 = "", reaped: bool = false, closed: bool = false, @@ -175,7 +178,7 @@ pub const Managed = struct { }; stop_flag.guardChild(child.id.?); cwd.deleteFile(io, log_path) catch {}; - var m: Managed = .{ .io = io, .pid = child.id.?, .log = log, .lock = lock, .grace_ms = o.grace_ms, .served = o.served, .stuck = o.words.stuck, .key = o.key }; + var m: Managed = .{ .io = io, .pid = child.id.?, .log = log, .lock = lock, .grace_ms = o.grace_ms, .served = o.served, .stuck = o.words.stuck, .key = o.key, .secrets = o.secrets }; const ok = m.ready(a, o.startup_timeout_s, o.tail, o.words, problem) catch |e| { _ = m.stop(); return e; @@ -199,7 +202,7 @@ pub const Managed = struct { } if (m.exited()) { problem.* = words.exited; - if (tail) |t| t.* = try lastLines(a, m.logEnd(&buf)); + if (tail) |t| t.* = try lastLinesRedacted(a, m.logEnd(&buf), m.secrets); return false; } if (port == null) { @@ -213,10 +216,17 @@ pub const Managed = struct { return false; } - /// The log's last ``buf.len`` bytes. + /// The log's last ``buf.len`` bytes, excluding a first line cut in the middle. fn logEnd(m: *Managed, buf: []u8) []const u8 { const size = if (m.log.stat(m.io)) |st| st.size else |_| 0; - return buf[0 .. m.log.readPositional(m.io, &.{buf}, size -| buf.len) catch 0]; + var bytes = buf[0 .. m.log.readPositional(m.io, &.{buf}, size -| buf.len) catch 0]; + if (size > buf.len) { + const cut = std.mem.indexOfAny(u8, bytes, "\r\n") orelse return bytes[bytes.len..]; + var next = cut + 1; + if (bytes[cut] == '\r' and next < bytes.len and bytes[next] == '\n') next += 1; + bytes = bytes[next..]; + } + return bytes; } /// ``http://127.0.0.1:PORT``. @@ -228,7 +238,7 @@ pub const Managed = struct { pub fn exitedTail(m: *Managed, a: Allocator) !?[]const []const u8 { if (m.closed or !m.exited()) return null; var buf: [64 << 10]u8 = undefined; - return try lastLines(a, m.logEnd(&buf)); + return try lastLinesRedacted(a, m.logEnd(&buf), m.secrets); } /// TERM, a grace period, KILL, another; always closes the log and the lock. Null when reaped. @@ -290,12 +300,17 @@ pub fn ended(pid: posix.pid_t) bool { /// Up to three last ``tensorfold:`` or ``error:`` lines in order (an earlier variable hint first), else the last line. pub fn lastLines(a: Allocator, log: []const u8) ![]const []const u8 { + return lastLinesRedacted(a, log, &.{}); +} + +/// Select managed log lines only after credentials are removed and before their 300-byte terminal cut. +pub fn lastLinesRedacted(a: Allocator, log: []const u8, secrets: []const []const u8) ![]const []const u8 { var picked: std.ArrayList([]const u8) = .empty; // newest first var fallback: []const u8 = ""; var hint: ?[]const u8 = null; var lines = std.mem.splitBackwardsAny(u8, log, "\r\n"); while (lines.next()) |line| { - const text = try sse.clean(a, line, sse.line_limit); + const text = try sse.clean(a, try sse.redact(a, line, secrets), sse.line_limit); if (text.len == 0 or leakNoise(text)) continue; if (fallback.len == 0) fallback = text; if ((std.mem.startsWith(u8, text, "tensorfold:") or std.mem.startsWith(u8, text, "error:")) and picked.items.len < 3) { diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index f5cd6092640..3a38c7323ee 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -219,7 +219,13 @@ pub const line_limit = 300; /// A refused attempt's reason for the terminal, ``HTTP 400: message``; it never reaches a receipt. pub fn refusal(a: Allocator, status: u16, body: []const u8) ![]const u8 { - const text = try clean(a, try errorText(a, body), line_limit); + return refusalRedacted(a, status, body, &.{}); +} + +/// Redact decoded JSON text or a plain body independently, before terminal truncation. +pub fn refusalRedacted(a: Allocator, status: u16, body: []const u8, secrets: []const []const u8) ![]const u8 { + const decoded = try errorText(a, body); + const text = try clean(a, try redact(a, decoded, secrets), line_limit); if (text.len == 0) return std.fmt.allocPrint(a, "HTTP {d}", .{status}); return std.fmt.allocPrint(a, "HTTP {d}: {s}", .{ status, text }); } @@ -263,6 +269,67 @@ pub fn clean(a: Allocator, text: []const u8, limit: usize) ![]const u8 { return std.mem.trim(u8, out.items, " "); } +/// Terminal/error text with every supplied credential replaced, longest first at each byte. +pub fn redact(a: Allocator, text: []const u8, secrets: []const []const u8) ![]const u8 { + var scan: usize = 0; + while (scan < text.len and secretAt(text, scan, secrets).len == 0) scan += 1; + if (scan == text.len) return text; + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < text.len) { + const found = secretAt(text, i, secrets); + if (found.len > 0) { + try out.appendSlice(a, "[redacted]"); + i += found.len; + } else { + try out.append(a, text[i]); + i += 1; + } + } + return out.items; +} + +pub const RedactedPiece = struct { text: []const u8, rest: []const u8 }; + +/// One streamed piece: emit complete safe text and retain only a suffix that may begin a credential. +pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) !RedactedPiece { + var out: std.ArrayList(u8) = .empty; + var changed = false; + var i: usize = 0; + while (i < text.len) { + const found = secretAt(text, i, secrets); + const rest = text[i..]; + var holds = false; + if (found.len == 0) for (secrets) |secret| { + if (secret.len > rest.len and std.mem.startsWith(u8, secret, rest)) { + holds = true; + break; + } + }; + if (found.len > 0 or holds) { + if (!changed) { + try out.appendSlice(a, text[0..i]); + changed = true; + } + if (holds) return .{ .text = out.items, .rest = rest }; + try out.appendSlice(a, "[redacted]"); + i += found.len; + } else { + if (changed) try out.append(a, text[i]); + i += 1; + } + } + return .{ .text = if (changed) out.items else text, .rest = "" }; +} + +fn secretAt(text: []const u8, i: usize, secrets: []const []const u8) []const u8 { + var found: []const u8 = ""; + for (secrets) |secret| { + if (secret.len > found.len and std.mem.startsWith(u8, text[i..], secret)) found = secret; + } + return found; +} + /// The index past the escape sequence at ``i``: a CSI sequence through its final byte, else ESC and one more byte. fn afterEscape(text: []const u8, i: usize) usize { if (i + 1 >= text.len or text[i + 1] != '[') return @min(i + 2, text.len); diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index 7574f23ef85..d9ba3814c6b 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -339,7 +339,7 @@ pub fn rawHeader(buf: []u8, token: []const u8) ?[]const u8 { var it = view.iterator(); var n = prefix.len; while (it.nextCodepoint()) |cp| { - if (cp > 0xff or cp < 0x20 or cp == 0x7f) return null; + if (cp > 0xff or cp < 0x20 or (cp >= 0x7f and cp <= 0x9f)) return null; buf[n] = @intCast(cp); n += 1; } diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index 18a2400d8cd..1df7abf3024 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -288,6 +288,23 @@ test "chat CLI: a Latin-1 bearer uses the server's header bytes without exposing try std.testing.expectEqual(@as(usize, 1), f.count()); } +test "chat CLI: the complete C1 range is refused by key validation and raw headers" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var buf: [300]u8 = undefined; + for (0x7f..0xa0) |cp| { + var encoded: [4]u8 = undefined; + const len = try std.unicode.utf8Encode(@intCast(cp), &encoded); + const token = try std.mem.concat(a, u8, &.{ "fixture-", encoded[0..len] }); + try std.testing.expect(!@import("auth.zig").validKey(token)); + try std.testing.expect(stream.rawHeader(&buf, token) == null); + } + const latin1 = "fixture-caf\u{e9}"; + try std.testing.expect(@import("auth.zig").validKey(latin1)); + try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", stream.rawHeader(&buf, latin1).?); +} + test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses unsupported keys" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -307,14 +324,14 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses defer f.stop(); var h: history.History = .{ .a = a }; var out: std.Io.Writer.Allocating = .init(a); - const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (ended) { .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), else => return error.TestUnexpectedResult, } try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(0, "authorization").?); try std.testing.expect(std.mem.indexOf(u8, f.request(0).head, token) == null); - const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (refused) { .failed => |why| try std.testing.expect(std.mem.indexOf(u8, why.reason, "fixture") == null), else => return error.TestUnexpectedResult, diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index b1ae7560a8b..5ffacc65db7 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -8,6 +8,7 @@ const history = @import("chat_cli_history.zig"); const turn = @import("chat_cli_turn.zig"); const child = @import("chat_cli_child.zig"); const stream = @import("benchmark_stream.zig"); +const sse = @import("benchmark_sse.zig"); const stop = @import("benchmark_stop.zig"); const environment = @import("sys").environment; const Allocator = std.mem.Allocator; @@ -83,6 +84,7 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { if (windows and args.url == null) return fail(ctx, windows_child); // a running server's key comes from TENSORFOLD_API_KEY; the server the chat starts gets a fresh one of its own const key = if (args.url == null) null else envKey(ctx.environ) catch return fail(ctx, bad_key); + const credentials: turn.Credentials = if (args.url != null) try turn.Credentials.init(ctx.a, try callerCredentials(ctx.a, ctx.environ, null)) else .{}; if (comptime !windows) if (ctx.signals) signals.install(); defer if (comptime !windows) if (ctx.signals) signals.restore(); // a piped message is read before any server starts, so an empty one costs no model load @@ -91,7 +93,7 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { .text => |text| message = text, .code => |code| return code, }; - if (args.url) |url| return session(ctx, args, .{ .base = url, .model = args.model, .key = key, .denied = denied(key != null) }, message); + if (args.url) |url| return session(ctx, args, .{ .base = url, .model = args.model, .key = key, .credentials = credentials, .denied = denied(key != null) }, message); if (comptime windows) return fail(ctx, windows_child) else return served(ctx, args, message); } @@ -111,6 +113,19 @@ pub fn envKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u return selected; } +/// Every configured caller credential, including an optional managed server's private key. +pub fn callerCredentials(a: Allocator, environ: *const std.process.Environ.Map, extra: ?[]const u8) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + if (extra) |key| if (key.len > 0) try out.append(a, key); + const raw = environ.get("TENSORFOLD_API_KEY") orelse return out.items; + var keys = std.mem.splitScalar(u8, raw, ','); + while (keys.next()) |entry| { + const key = std.mem.trim(u8, entry, " \t\r\n\x0b\x0c"); + if (key.len > 0) try out.append(a, key); + } + return out.items; +} + /// What a running server's 401 adds: whether TENSORFOLD_API_KEY gave the key it refused. fn denied(sent: bool) []const u8 { return if (sent) "the server refused the key in TENSORFOLD_API_KEY" else "set TENSORFOLD_API_KEY to a key the server accepts"; @@ -120,17 +135,19 @@ fn denied(sent: bool) []const u8 { fn served(ctx: *const Context, args: args_mod.Args, message: ?[]const u8) !u8 { var problem: []const u8 = ""; var tail: []const []const u8 = &.{}; - const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = ctx.self_exe, .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; + var setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = ctx.self_exe, .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; const plan = try child.plan(setup, args.model.?, args.serve, args.startup_timeout, &problem) orelse return fail(ctx, problem); + const credentials = try turn.Credentials.init(ctx.a, try callerCredentials(ctx.a, ctx.environ, plan.key)); + setup.secrets = credentials.forms; try say(ctx.err, "Loading {s}; Ctrl-C cancels.", .{args.model.?}); var own = try child.start(setup, plan, &tail, &problem) orelse { if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); - const code = try fail(ctx, problem); - try lastLines(ctx, tail); + const code = try fail(ctx, try credentials.redact(ctx.a, problem)); + try lastLines(ctx, tail, credentials); return code; }; errdefer _ = own.managed.stop(); - const code = try session(ctx, args, .{ .base = own.managed.base(), .model = own.served, .key = own.key, .own = &own }, message); + const code = try session(ctx, args, .{ .base = own.managed.base(), .model = own.served, .key = own.key, .credentials = credentials, .own = &own }, message); if (own.managed.stop()) |why| { const failed = try fail(ctx, why); return if (code == 0) failed else code; @@ -139,15 +156,15 @@ fn served(ctx: *const Context, args: args_mod.Args, message: ?[]const u8) !u8 { } /// An exited child's last log lines after its failure, as the benchmark prints them. -fn lastLines(ctx: *const Context, tail: []const []const u8) !void { - if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{tail[0]}); +fn lastLines(ctx: *const Context, tail: []const []const u8, credentials: turn.Credentials) !void { + if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{try credentials.redact(ctx.a, tail[0])}); if (tail.len > 1) try ctx.err.writeAll("Last server log lines:\n"); - if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{line}); + if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{try credentials.redact(ctx.a, line)}); try ctx.err.flush(); } /// The server a session talks to: its address, the model to ask for, its key, and what its 401 adds. -const Target = struct { base: []const u8, model: ?[]const u8, key: ?[]const u8 = null, denied: ?[]const u8 = null, own: ?*Child = null }; +const Target = struct { base: []const u8, model: ?[]const u8, key: ?[]const u8 = null, credentials: turn.Credentials = .{}, denied: ?[]const u8 = null, own: ?*Child = null }; const Session = struct { ctx: *const Context, @@ -161,7 +178,7 @@ const Session = struct { /// One message and its streamed reply, in an arena of its own that lives until the turn is kept. fn ask(s: *Session, a: Allocator, message: []const u8) !turn.Ended { const request = try turn.body(a, s.settings, &s.history, message); - return turn.run(a, s.ctx.io, s.url, s.target.key, request, s.ctx.out, s.show); + return turn.run(a, s.ctx.io, s.url, s.target.key, s.target.credentials, request, s.ctx.out, s.show); } /// A finished reply's notes: cut at its token limit, or nothing but reasoning that was hidden. @@ -176,7 +193,7 @@ const Session = struct { _ = try fail(s.ctx, if (hint) |h| try std.fmt.allocPrint(s.ctx.a, "{s}; {s}", .{ f.reason, h }) else f.reason); if (comptime !windows) if (f.connect) if (s.target.own) |own| if (try own.managed.exitedTail(s.ctx.a)) |tail| { try s.ctx.err.writeAll("The model server has exited.\n"); - try lastLines(s.ctx, tail); + try lastLines(s.ctx, tail, s.target.credentials); return 1; }; return if (s.ctx.interactive) null else 1; @@ -297,7 +314,7 @@ fn discover(ctx: *const Context, chat_url: []const u8, target: Target) !Found { .ok => |v| doc = v, .err => {}, }; - const name = target.model orelse first(doc) orelse { + const raw_name = target.model orelse first(doc) orelse { if (got.failed == .none and got.status == 401) if (target.denied) |hint| return .{ .problem = try std.fmt.allocPrint(ctx.a, "no model to chat with: {s} answered HTTP 401; {s}", .{ url, hint }) }; const why = switch (got.failed) { @@ -309,7 +326,8 @@ fn discover(ctx: *const Context, chat_url: []const u8, target: Target) !Found { }; return .{ .problem = try std.fmt.allocPrint(ctx.a, "no model to chat with: {s} {s}; name one after the URL", .{ url, why }) }; }; - return .{ .model = name, .thinking_switch = if (doc) |d| stream.thinkingSwitch(d, name) else null }; + const name = if (target.model == null) try target.credentials.clean(ctx.a, raw_name, sse.line_limit) else raw_name; + return .{ .model = name, .thinking_switch = if (doc) |d| stream.thinkingSwitch(d, raw_name) else null }; } /// The first ``data[].id`` of a ``/v1/models`` document. diff --git a/zig/src/server/chat_cli_child.zig b/zig/src/server/chat_cli_child.zig index 25339f2f6ce..d5aa047421e 100644 --- a/zig/src/server/chat_cli_child.zig +++ b/zig/src/server/chat_cli_child.zig @@ -17,7 +17,7 @@ pub const words: server.Words = .{ }; /// Managed child setup: request ``key`` (fresh by default), and optional full-list ``environment_key`` for the child. -pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, key: ?[]const u8 = null, environment_key: ?[]const u8 = null, log_dir: []const u8 }; +pub const Setup = struct { a: Allocator, io: std.Io, environ: *const std.process.Environ.Map, exe: ?[]const u8 = null, key: ?[]const u8 = null, environment_key: ?[]const u8 = null, log_dir: []const u8, secrets: []const []const u8 = &.{} }; /// The started server, the name it serves and the key every request to it carries. pub const Child = struct { managed: server.Managed, served: []const u8, key: []const u8 }; @@ -77,7 +77,7 @@ pub fn plan(s: Setup, model_arg: []const u8, extra: []const []const u8, startup_ /// ``p`` started and ready; null with ``problem`` set ("" when stopped) and ``tail`` the child's last log lines. pub fn start(s: Setup, p: Plan, tail: *[]const []const u8, problem: *[]const u8) !?Child { - const o: server.Options = .{ .startup_timeout_s = p.timeout_s, .bench_dir = s.log_dir, .tail = tail, .served = p.served, .lock = false, .own_group = true, .key = p.key, .environment_key = s.environment_key, .words = words }; + const o: server.Options = .{ .startup_timeout_s = p.timeout_s, .bench_dir = s.log_dir, .tail = tail, .served = p.served, .lock = false, .own_group = true, .key = p.key, .environment_key = s.environment_key, .secrets = s.secrets, .words = words }; const m = try server.Managed.spawn(s.a, s.io, s.environ, p.argv, o, problem) orelse return null; return .{ .managed = m, .served = p.served, .key = p.key }; } diff --git a/zig/src/server/chat_cli_reply.zig b/zig/src/server/chat_cli_reply.zig index 106f30255de..d4db6cebcac 100644 --- a/zig/src/server/chat_cli_reply.zig +++ b/zig/src/server/chat_cli_reply.zig @@ -17,6 +17,9 @@ const error_limit = 2000; pub const Reply = struct { a: Allocator, sink: Sink, + secrets: []const []const u8 = &.{}, + answer_stream: Stream = .{}, + reason_stream: Stream = .{}, pending: std.ArrayList(u8) = .empty, frames: sse.Frames = .{}, /// The answer so far: what a kept turn holds. @@ -28,6 +31,29 @@ pub const Reply = struct { failure: ?[]const u8 = null, done: bool = false, + /// Release a final non-secret prefix after the stream stops. + pub fn end(r: *Reply) Failure!void { + try r.flush(.reasoning); + try r.flush(.content); + } + + fn redacted(r: *Reply, kind: Kind, text: []const u8) ![]const u8 { + const state = streamFor(r, kind); + const whole = if (state.pending.len > 0) try std.mem.concat(r.a, u8, &.{ state.pending, text }) else text; + const got = try sse.redactPiece(r.a, whole, r.secrets); + state.pending = got.rest; + return got.text; + } + + fn flush(r: *Reply, kind: Kind) Failure!void { + const state = streamFor(r, kind); + if (state.pending.len == 0) return; + const text = state.pending; + state.pending = ""; + if (kind == .content) try r.content.appendSlice(r.a, text); + try r.sink.piece(r.sink.ctx, kind, text); + } + /// Bytes as they were read: whole lines are handled now, a cut line waits for the rest. pub fn feed(r: *Reply, bytes: []const u8) Failure!void { var rest = bytes; @@ -70,7 +96,7 @@ pub const Reply = struct { }; if (chunk != .object) return error.InvalidStream; if (chunk.field("error")) |e| { - r.failure = try errorText(r.a, e); + r.failure = try errorText(r.a, e, r.secrets); return; } const choices = chunk.get("choices") orelse return; // a usage event carries none @@ -80,11 +106,13 @@ pub const Reply = struct { const thought = delta.strField("reasoning_content") orelse delta.strField("reasoning"); if (thought) |t| if (t.len > 0) { r.reasoned = true; - try r.sink.piece(r.sink.ctx, .reasoning, t); + const safe = try r.redacted(.reasoning, t); + if (safe.len > 0) try r.sink.piece(r.sink.ctx, .reasoning, safe); }; if (delta.strField("content")) |c| if (c.len > 0) { - try r.content.appendSlice(r.a, c); - try r.sink.piece(r.sink.ctx, .content, c); + const safe = try r.redacted(.content, c); + try r.content.appendSlice(r.a, safe); + if (safe.len > 0) try r.sink.piece(r.sink.ctx, .content, safe); }; } if (choice.field("finish_reason")) |f| if (f == .string) { @@ -93,10 +121,16 @@ pub const Reply = struct { } }; -/// An error event's ``message`` (or the error itself when it is text), without terminal control sequences. -fn errorText(a: Allocator, e: json.Value) ![]const u8 { +const Stream = struct { pending: []const u8 = "" }; + +fn streamFor(r: *Reply, kind: Kind) *Stream { + return if (kind == .content) &r.answer_stream else &r.reason_stream; +} + +/// An error event's ``message`` with credentials removed before terminal cleaning and truncation. +fn errorText(a: Allocator, e: json.Value, secrets: []const []const u8) ![]const u8 { const text = e.strField("message") orelse e.str() orelse "the server reported an error without a message"; - return sse.clean(a, text, error_limit); + return sse.clean(a, try sse.redact(a, text, secrets), error_limit); } const Seen = struct { diff --git a/zig/src/server/chat_cli_test.zig b/zig/src/server/chat_cli_test.zig index 9ff7ccece0a..d9ed69bc5fc 100644 --- a/zig/src/server/chat_cli_test.zig +++ b/zig/src/server/chat_cli_test.zig @@ -199,6 +199,79 @@ test "chat CLI: --url sends TENSORFOLD_API_KEY's first key as the bearer, and a try std.testing.expect(f.refusals() == 5 and f.count() == 2); } +test "chat CLI: attached responses redact credentials before every output boundary" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const first = "fixture"; + const second = "fixture-secret"; + const third = "fixture-\u{00c3}\u{00a9}"; + const latin1 = "fixture-\xc3\xa9"; + const json_reflection = try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s} and {s}\"}}}}", .{ first, second }); + const event_head = try fake.headOf(a, "200 OK", "text/event-stream"); + const event_error = try fake.event(a, try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{second})); + const event_content = try std.mem.concat(a, u8, &.{ try chunk(a, "{\"content\": \"split-\"}"), try chunk(a, "{\"content\": \"secret\"}") }); + var filler: [299]u8 = undefined; + @memset(&filler, 'x'); + const truncated = try std.mem.concat(a, u8, &.{ &filler, second }); + const quoted = try std.fmt.allocPrint(a, "\"{s}", .{filler[0..255]}); + @memset(filler[0..100], 'y'); + const escaped = try std.mem.concat(a, u8, &.{ "{\"error\":{\"message\":\"", filler[0..100], "\\\"", quoted[1..], "\"}}}" }); + const replies = try a.dupe([]const fake.Write, &.{ + try fake.jsonReply(a, "401 Unauthorized", json_reflection), + try fake.jsonReply(a, "500 Internal Server Error", second), + &.{.{ .bytes = try std.mem.concat(a, u8, &.{ event_head, event_error, try fake.event(a, "[DONE]") }) }}, + try fake.jsonReply(a, "500 Internal Server Error", truncated), + try fake.jsonReply(a, "500 Internal Server Error", escaped), + try fake.jsonReply(a, "500 Internal Server Error", "{\"error\":{\"message\":\"fixture-\\u00c3\\u00a9\"}}"), + &.{.{ .bytes = try std.mem.concat(a, u8, &.{ event_head, event_content, try fake.event(a, "[DONE]") }) }}, + }); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{second}); + const f = try world(a, models, replies); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ first, ",", second, ",", third, ",split-secret", ",", quoted })); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..7) |i| { + try std.testing.expectEqual(@as(u8, if (i < 6) 1 else 0), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + r.interactive = true; + r.input = "/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + for ([_][]const u8{ first, second, third, latin1, "split-secret", quoted, quoted[0..100] }) |secret| + try std.testing.expect(std.mem.indexOf(u8, shown.items, secret) == null); + try std.testing.expect(std.mem.indexOf(u8, shown.items, "[redacted]") != null); +} + +test "chat CLI: C1 controls in any key entry are refused before any request" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const replies = try a.dupe([]const fake.Write, &.{try streamed(a)}); + const f = try world(a, models_doc, replies); + defer f.stop(); + r.input = "hi"; + var ok = true; + for ([_][]const u8{ "fixture-\u{009b}", "good-key,fixture-\u{009b}" }) |key| { + try r.env.put("TENSORFOLD_API_KEY", key); + const code = try r.command(&.{ "--url", try f.url(a, "") }); + ok = ok and code == 1; + ok = ok and f.count() == 0; + ok = ok and std.mem.indexOf(u8, r.err.written(), "expected Latin-1 keys without spaces or control characters") != null; + ok = ok and std.mem.indexOf(u8, r.err.written(), key) == null; + } + try std.testing.expect(ok); +} + test "chat CLI: --no-thinking sends the documented switch, and is refused before any turn when the model has none" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index b93068edb89..a59b0641260 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -17,6 +17,31 @@ pub const Settings = struct { model: []const u8, temperature: ?f64 = null, max_t /// How a reply is shown: reasoning dimmed or hidden, and on a terminal its styles and only printable text. pub const Show = struct { thinking: bool = false, terminal: bool = false }; +/// Every configured secret in its decoded and raw-header forms, shared by all response boundaries. +pub const Credentials = struct { + forms: []const []const u8 = &.{}, + + pub fn init(a: Allocator, secrets: []const []const u8) !Credentials { + var forms: std.ArrayList([]const u8) = .empty; + for (secrets) |secret| { + if (secret.len == 0) continue; + try forms.append(a, secret); + var buf: [300]u8 = undefined; + if (stream.rawHeader(&buf, secret)) |raw| try forms.append(a, try a.dupe(u8, raw[7..])); + } + return .{ .forms = forms.items }; + } + + pub fn redact(c: Credentials, a: Allocator, text: []const u8) ![]const u8 { + return sse.redact(a, text, c.forms); + } + + /// Remove secrets before control cleaning and byte limiting can hide a suffix or split a match. + pub fn clean(c: Credentials, a: Allocator, text: []const u8, limit: usize) ![]const u8 { + return sse.clean(a, try c.redact(a, text), limit); + } +}; + /// A finished reply: its answer, whether it stopped at its token limit, and whether reasoning came. pub const Finished = struct { content: []const u8, cut: bool, reasoned: bool }; @@ -47,25 +72,29 @@ pub fn body(a: Allocator, s: Settings, history: *const History, user: []const u8 } /// One streamed turn to ``url``, the chat route, printed to ``out`` as it arrives; a stop signal ends it ``stopped``. -pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, request: []u8, out: *std.Io.Writer, show: Show) !Ended { +pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credentials: Credentials, request: []u8, out: *std.Io.Writer, show: Show) !Ended { var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = io }; client.connection_pool.free_size = 0; defer client.deinit(); var printer: Printer = .{ .io = io, .out = out, .show = show }; - var r: reply.Reply = .{ .a = a, .sink = printer.sink() }; + var r: reply.Reply = .{ .a = a, .sink = printer.sink(), .secrets = credentials.forms }; var auth_buf: [300]u8 = undefined; const bearer = if (key) |k| stream.rawHeader(&auth_buf, k) orelse return .{ .failed = .{ .reason = "API key cannot be encoded as Latin-1 header text", } } else null; - var x: Exchange = .{ .a = a, .io = io, .client = &client, .uri = try std.Uri.parse(url), .bearer = bearer, .body = request, .reply = &r }; + var x: Exchange = .{ .a = a, .io = io, .client = &client, .uri = try std.Uri.parse(url), .bearer = bearer, .credentials = credentials, .body = request, .reply = &r }; const ended = stream.bounded(io, null, Exchange.run, &x); + try r.end(); printer.end(); switch (ended) { .stopped, .deadline => return .{ .stopped = r.content.items }, .unavailable => return .{ .failed = .{ .reason = "could not start the request" } }, .finished => {}, } - if (x.failure) |f| return .{ .failed = .{ .reason = try x.reason(f, url), .connect = f == .connect, .status = x.status } }; + if (x.failure) |f| { + const reason = try x.reason(f, url); + return .{ .failed = .{ .reason = try credentials.redact(a, reason), .connect = f == .connect, .status = x.status } }; + } if (r.failure) |why| return .{ .failed = .{ .reason = why } }; if (!r.complete()) return .{ .failed = .{ .reason = "the server closed the stream before the reply finished" } }; return .{ .finished = .{ .content = r.content.items, .cut = std.mem.eql(u8, r.finish orelse "", "length"), .reasoned = r.reasoned } }; @@ -83,6 +112,7 @@ const Exchange = struct { bearer: ?[]const u8, body: []u8, reply: *reply.Reply, + credentials: Credentials, status: u16 = 0, refused: []const u8 = "", content_type: []const u8 = "", @@ -145,8 +175,8 @@ const Exchange = struct { return switch (f) { .connect => try std.fmt.allocPrint(x.a, "could not reach the server at {s}", .{url}), .lost => "the connection to the server broke during the reply", - .http => try sse.refusal(x.a, x.status, x.refused), - .not_events => try std.fmt.allocPrint(x.a, "the server answered with {s}, not an event stream", .{try sse.clean(x.a, x.content_type, sse.line_limit)}), + .http => try sse.refusalRedacted(x.a, x.status, x.refused, x.credentials.forms), + .not_events => try std.fmt.allocPrint(x.a, "the server answered with {s}, not an event stream", .{try x.credentials.clean(x.a, x.content_type, sse.line_limit)}), .stream => "the server sent a malformed event stream", .output => "could not write the reply", }; diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 5a35ca62cd1..1db1aebe360 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -179,20 +179,22 @@ fn serve(ctx: *const Context, args: Args, choice: registry.Choice, caller_key: ? var problem: []const u8 = ""; var tail: []const []const u8 = &.{}; const serving_exe = ctx.serve_exe orelse if (ctx.self_exe) |current| try nativeSibling(ctx.a, current) else null; - const setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = serving_exe, .key = caller_key, .environment_key = if (args.check) null else ctx.environ.get("TENSORFOLD_API_KEY"), .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; + var setup: child.Setup = .{ .a = ctx.a, .io = ctx.io, .environ = ctx.environ, .exe = serving_exe, .key = caller_key, .environment_key = if (args.check) null else ctx.environ.get("TENSORFOLD_API_KEY"), .log_dir = ctx.environ.get("TMPDIR") orelse "/tmp" }; var extra: std.ArrayList([]const u8) = .empty; try extra.appendSlice(ctx.a, &.{ "--name", std.fs.path.basename(choice.entry.repo) }); if (choice.drafter_dir) |d| try extra.appendSlice(ctx.a, &.{ "--drafter", d }); const plan = try child.plan(setup, choice.model_dir, extra.items, args.startup_timeout, &problem) orelse return fail(ctx, 1, "{s}", .{problem}); + const credentials = try turn.Credentials.init(ctx.a, try chat.callerCredentials(ctx.a, ctx.environ, plan.key)); + setup.secrets = credentials.forms; try say(ctx.err, "Loading {s}; Ctrl-C cancels", .{choice.entry.repo}); var own = try child.start(setup, plan, &tail, &problem) orelse { if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); - const code = try fail(ctx, 1, "{s}", .{problem}); - try lastLines(ctx, tail); + const code = try fail(ctx, 1, "{s}", .{try credentials.redact(ctx.a, problem)}); + try lastLines(ctx, tail, credentials); return code; }; errdefer _ = own.managed.stop(); - const code = try firstReply(ctx, &own); + const code = try firstReply(ctx, &own, credentials); if (code != 0) { if (own.managed.stop()) |why| try say(ctx.err, "tensorfold start: {s}", .{why}); return code; @@ -203,17 +205,17 @@ fn serve(ctx: *const Context, args: Args, choice: registry.Choice, caller_key: ? return 0; } try say(ctx.out, "Serving {s} at {s}/v1; Ctrl-C stops the server", .{ own.served, own.managed.base() }); - return wait(ctx, &own); + return wait(ctx, &own, credentials); } /// One deterministic short request proves answer content, not only a listening socket. -fn firstReply(ctx: *const Context, own: *Child) !u8 { +fn firstReply(ctx: *const Context, own: *Child, credentials: turn.Credentials) !u8 { var problem: []const u8 = ""; const url = try stream.endpoint(ctx.a, own.managed.base(), true, &problem) orelse return fail(ctx, 1, "{s}", .{problem}); var h: history.History = .{ .a = ctx.a }; const request = try turn.body(ctx.a, .{ .model = own.served, .temperature = 0, .max_tokens = 32 }, &h, "Reply with a short confirmation that the server is ready."); try say(ctx.out, "First reply:", .{}); - switch (try turn.run(ctx.a, ctx.io, url, own.key, request, ctx.out, .{})) { + switch (try turn.run(ctx.a, ctx.io, url, own.key, credentials, request, ctx.out, .{ .terminal = true })) { .finished => |f| { if (f.content.len == 0) return fail(ctx, 1, "first reply failed: the model returned no answer content", .{}); return 0; @@ -224,7 +226,7 @@ fn firstReply(ctx: *const Context, own: *Child) !u8 { } /// Keep the checked server in the foreground until a signal or its own exit. -fn wait(ctx: *const Context, own: *Child) !u8 { +fn wait(ctx: *const Context, own: *Child, credentials: turn.Credentials) !u8 { while (true) { if (stop.requested()) |sig| { if (own.managed.stop()) |why| try say(ctx.err, "tensorfold start: {s}", .{why}); @@ -232,17 +234,17 @@ fn wait(ctx: *const Context, own: *Child) !u8 { } if (try own.managed.exitedTail(ctx.a)) |tail| { const code = try fail(ctx, 1, "the model server exited after its successful first reply", .{}); - try lastLines(ctx, tail); + try lastLines(ctx, tail, credentials); return code; } ctx.io.sleep(.fromMilliseconds(200), .awake) catch {}; } } -fn lastLines(ctx: *const Context, tail: []const []const u8) !void { - if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{tail[0]}); +fn lastLines(ctx: *const Context, tail: []const []const u8, credentials: turn.Credentials) !void { + if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{try credentials.redact(ctx.a, tail[0])}); if (tail.len > 1) try ctx.err.writeAll("Last server log lines:\n"); - if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{line}); + if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{try credentials.redact(ctx.a, line)}); try ctx.err.flush(); } diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 0bdfeb540a1..aaf70cec30e 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -103,7 +103,7 @@ const Run = struct { fn standInAt(r: *Run, port: u16, name: []const u8) !void { const script = try r.path(name); - const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '%s' \"$START_TEST_UNRELATED\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nif [ \"$START_TEST_SHORT_LIVED\" = 1 ]; then exec sleep 1; else exec sleep 30; fi\n", .{ try r.path("pid"), try r.path("args"), try r.path("child-key"), try r.path("unrelated"), port }); + const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '%s' \"$START_TEST_UNRELATED\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nif [ \"$START_TEST_LOG_KEY\" = 1 ]; then printf 'error: %0250d%s\\n' 0 \"$TENSORFOLD_API_KEY\" >&2; fi\nif [ \"$START_TEST_SHORT_LIVED\" = 1 ]; then exec sleep 1; else exec sleep 30; fi\n", .{ try r.path("pid"), try r.path("args"), try r.path("child-key"), try r.path("unrelated"), port }); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = script, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); r.self_exe = script; } @@ -299,6 +299,56 @@ test "start CLI: a cached model answers once, prints no key and --check reaps it for ([_][]const u8{ r.out.written(), r.err.written(), args }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } +test "start CLI: a malformed cached config requires repair while valid caches skip pulls" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.cache(); + const config = try std.fs.path.join(a, &.{ r.root, "models--Org--Model", "snapshots", revision, "config.json" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = config, .data = "{" }); + const f = try world(&r, try events(a, "Ready.")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--yes", "--check" })); + try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); + try std.testing.expectEqualStrings("Org/Model@" ++ revision, r.pulls.items[0]); + try std.testing.expectEqualStrings("Org/Draft@" ++ draft_revision, r.pulls.items[1]); +} + +test "start CLI: managed first-reply failures redact every configured credential" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const first = "fixture-managed-first"; + const second = "fixture-managed-second"; + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ first, ",", second })); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = first }); + const reflected = try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{first}); + const replies = try a.dupe([]const fake.Write, &.{ + try fake.jsonReply(a, "401 Unauthorized", reflected), + try fake.jsonReply(a, "500 Internal Server Error", second), + }); + const f = try worldKeyed(&r, replies, try r.path("credential")); + defer f.stop(); + var errors: std.ArrayList(u8) = .empty; + for (0..2) |_| { + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{})); + try errors.appendSlice(a, r.err.written()); + try std.testing.expect(r.childGone()); + } + for ([_][]const u8{ first, second }) |secret| + try std.testing.expect(std.mem.indexOf(u8, errors.items, secret) == null); + try std.testing.expect(std.mem.indexOf(u8, errors.items, "[redacted]") != null); +} + test "start CLI: a failed first reply is fatal and still reaps its serve child" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -426,7 +476,7 @@ test "start CLI: persistent mode requires a valid environment credential before try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); } - for ([_][]const u8{ "\xc2\xa0", "good-key,bad key", "good-key,\xc2\xa0" }) |key| { + for ([_][]const u8{ "\xc2\xa0", "good-key,bad key", "good-key,\xc2\xa0", "fixture-\u{009b}", "good-key,fixture-\u{009b}" }) |key| { try r.env.put("TENSORFOLD_API_KEY", key); try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "expected Latin-1 keys without spaces or control characters") != null); @@ -448,6 +498,7 @@ test "start CLI: persistent caller keys preserve the child list and send only th try r.env.put("TENSORFOLD_API_KEY", key_list); try r.env.put("START_TEST_UNRELATED", "caller-value-retained"); try r.env.put("START_TEST_SHORT_LIVED", "1"); + try r.env.put("START_TEST_LOG_KEY", "1"); try r.cache(); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = caller_key }); const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); @@ -473,11 +524,11 @@ test "start CLI: persistent caller keys preserve the child list and send only th try std.testing.expect(f.count() > 0 and std.mem.eql(u8, f.header(f.count() - 1, "authorization") orelse "", bearer)); try std.testing.expectEqual(@as(usize, 1), f.refusals()); const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); - for ([_][]const u8{ caller_key, second_key, key_list }) |secret| + for ([_][]const u8{ caller_key, second_key, second_key[0..8], key_list }) |secret| for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } -test "start CLI: a managed first reply authenticates a Latin-1 caller key" { +test "start CLI: a managed first reply authenticates Latin-1 and removes terminal controls" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -491,13 +542,15 @@ test "start CLI: a managed first reply authenticates a Latin-1 caller key" { try r.env.put("START_TEST_SHORT_LIVED", "1"); try r.cache(); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = caller_key }); - const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); + const f = try worldKeyed(&r, try events(a, "Ready.\\u001b[2J\\u009b2J"), try r.path("credential")); defer f.stop(); try r.standIn(f.port); try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--startup-timeout", "2" })); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Serving Model at") != null); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Ready.") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "\x1b") == null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "\u{009b}") == null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(r.childGone()); const child_key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("child-key"), a, .limited(256)); From 095811edd70e79c87bf24dfd50ae5076c32e7aec Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:30:48 +0000 Subject: [PATCH 092/361] security: close credential containment gaps --- zig/src/cli/pull.zig | 6 +- zig/src/cli/pull_auth.zig | 126 +++++++-- zig/src/cli/pull_exlr8.zig | 1 + zig/src/cli/pull_file.zig | 2 +- zig/src/cli/pull_host_test.zig | 1 + zig/src/cli/pull_kp50_test.zig | 371 ++++++++++++++++++++++++++ zig/src/cli/pull_runs.zig | 1 + zig/src/server/benchmark_sse.zig | 123 +++++++-- zig/src/server/benchmark_stream.zig | 21 +- zig/src/server/chat_cli.zig | 4 + zig/src/server/chat_cli_kp50_test.zig | 275 +++++++++++++++++++ zig/src/server/chat_cli_reply.zig | 6 +- zig/src/server/chat_cli_test.zig | 10 +- zig/src/server/start_cli_test.zig | 29 +- 14 files changed, 920 insertions(+), 56 deletions(-) create mode 100644 zig/src/cli/pull_kp50_test.zig create mode 100644 zig/src/server/chat_cli_kp50_test.zig diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index f39baee044e..9453754c5ca 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -318,11 +318,7 @@ fn configKind(a: Allocator, bytes: []const u8) struct { model_type: []const u8, /// Server-controlled model text made safe for output, with its hub credential removed. fn safeModelType(a: Allocator, text: []const u8, auth: Auth) ![]const u8 { - var out = text; - if (auth.bearer) |bearer| { - const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer["Bearer ".len..] else bearer; - if (secret.len > 0 and std.mem.indexOf(u8, out, secret) != null) out = try std.mem.replaceOwned(u8, a, out, secret, "[redacted]"); - } + const out = try auth.redact(a, text); for (out) |ch| if (ch <= 0x20 or ch >= 0x7f) return "[unprintable model_type]"; return out; } diff --git a/zig/src/cli/pull_auth.zig b/zig/src/cli/pull_auth.zig index 8a09b1dd5bc..f997943730b 100644 --- a/zig/src/cli/pull_auth.zig +++ b/zig/src/cli/pull_auth.zig @@ -62,6 +62,26 @@ pub const Auth = struct { return containsCredential(text, secret); } + /// Server-controlled text with each plain or repeatedly percent-encoded credential occurrence replaced. + pub fn redact(auth: Auth, a: Allocator, text: []const u8) ![]const u8 { + const bearer = auth.bearer orelse return text; + const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; + if (secret.len == 0) return text; + var out: std.ArrayList(u8) = .empty; + var rest = text; + var replaced = false; + while (true) { + const span = (try credentialSpan(a, rest, secret)) orelse break; + try out.appendSlice(a, rest[0..span.start]); + try out.appendSlice(a, "[redacted]"); + rest = rest[span.end..]; + replaced = true; + } + if (!replaced) return text; + try out.appendSlice(a, rest); + return out.items; + } + /// One bodiless request into `req`, redirects followed here so each hop decides the token anew; see `header`. pub fn send(auth: Auth, client: *http.Client, req: *http.Client.Request, method: http.Method, uri: std.Uri, options: http.Client.RequestOptions, buf: []u8) !http.Client.Response { var o = options; @@ -115,27 +135,97 @@ fn origin(uri: std.Uri, buf: []u8) ?Origin { return .{ .scheme = uri.scheme, .host = host, .port = port }; } -/// Match a credential directly or through percent encoding, without decoding an untrusted whole URL. -fn containsCredential(text: []const u8, secret: []const u8) bool { - if (secret.len == 0) return false; - for (0..text.len) |start| { - var at = start; - var matched: usize = 0; - while (matched < secret.len and at < text.len) { - var byte = text[at]; - if (byte == '%' and at + 2 < text.len) { - const hi = hex(text[at + 1]) orelse break; - const lo = hex(text[at + 2]) orelse break; - byte = hi * 16 + lo; - at += 2; +/// The original-text span of a credential, including one hidden by any number of percent-encoding layers. +fn credentialSpan(a: Allocator, text: []const u8, secret: []const u8) !?Span { + if (secret.len == 0) return null; + var best: ?Span = if (std.mem.indexOf(u8, text, secret)) |at| .{ .start = at, .end = at + secret.len } else null; + if (std.mem.indexOfScalar(u8, text, '%') == null) return best; + + // One shrinking in-place buffer plus provenance avoids generating exponentially many encoded variants. + const decoded = try a.dupe(u8, text); + defer a.free(decoded); + const starts = try a.alloc(usize, text.len); + defer a.free(starts); + const ends = try a.alloc(usize, text.len); + defer a.free(ends); + for (starts, ends, 0..) |*start, *end, i| { + start.* = i; + end.* = i + 1; + } + const states = try a.alloc(usize, text.len + 1); + defer a.free(states); + const next_states = try a.alloc(usize, text.len + 1); + defer a.free(next_states); + var len = text.len; + if (layerSpan(decoded[0..len], secret, starts, ends, states, next_states)) |span| { + if (best == null or span.start < best.?.start or (span.start == best.?.start and span.end > best.?.end)) best = span; + } + while (true) { + var read: usize = 0; + var write: usize = 0; + var changed = false; + while (read < len) { + if (read + 2 < len and decoded[read] == '%' and hex(decoded[read + 1]) != null and hex(decoded[read + 2]) != null) { + decoded[write] = hex(decoded[read + 1]).? * 16 + hex(decoded[read + 2]).?; + starts[write] = starts[read]; + ends[write] = ends[read + 2]; + read += 3; + changed = true; + } else { + decoded[write] = decoded[read]; + starts[write] = starts[read]; + ends[write] = ends[read]; + read += 1; } - if (byte != secret[matched]) break; - matched += 1; - at += 1; + write += 1; } - if (matched == secret.len) return true; + len = write; + if (layerSpan(decoded[0..len], secret, starts, ends, states, next_states)) |span| { + if (best == null or span.start < best.?.start or (span.start == best.?.start and span.end > best.?.end)) best = span; + } + if (!changed) return best; } - return false; +} + +/// One layer's polynomial-time matcher: each input position retains only its earliest possible match start. +fn layerSpan(text: []const u8, secret: []const u8, starts: []const usize, ends: []const usize, state_buf: []usize, next_buf: []usize) ?Span { + if (std.mem.indexOfScalar(u8, secret, '%') == null) { + const at = std.mem.indexOf(u8, text, secret) orelse return null; + return .{ .start = starts[at], .end = ends[at + secret.len - 1] }; + } + const none = std.math.maxInt(usize); + for (state_buf[0 .. text.len + 1], 0..) |*state, i| state.* = i; + var states = state_buf; + var next = next_buf; + for (secret) |wanted| { + @memset(next[0 .. text.len + 1], none); + for (states[0 .. text.len + 1], 0..) |start, at| { + if (start == none) continue; + // Literal input always remains an alternative, including '%' beginning a valid escape. + if (at < text.len and text[at] == wanted and start < next[at + 1]) next[at + 1] = start; + if (at + 2 < text.len and text[at] == '%' and hex(text[at + 1]) != null and hex(text[at + 2]) != null) { + const byte = hex(text[at + 1]).? * 16 + hex(text[at + 2]).?; + if (byte == wanted and start < next[at + 3]) next[at + 3] = start; + } + } + const swap = states; + states = next; + next = swap; + } + var best: ?Span = null; + for (states[0 .. text.len + 1], 0..) |start, end| { + if (start == none) continue; + const span: Span = .{ .start = starts[start], .end = ends[end - 1] }; + if (best == null or span.start < best.?.start or (span.start == best.?.start and span.end > best.?.end)) best = span; + } + return best; +} + +const Span = struct { start: usize, end: usize }; + +fn containsCredential(text: []const u8, secret: []const u8) bool { + const span = credentialSpan(std.heap.page_allocator, text, secret) catch return true; + return span != null; } fn hex(c: u8) ?u8 { diff --git a/zig/src/cli/pull_exlr8.zig b/zig/src/cli/pull_exlr8.zig index 2eda3691bd3..0198c78686f 100644 --- a/zig/src/cli/pull_exlr8.zig +++ b/zig/src/cli/pull_exlr8.zig @@ -110,6 +110,7 @@ fn gib(n: u64) f64 { /// Every file the node needs whole, each equal to the hub's sha256 (LFS) or git blob sha1; returns how many. pub fn fetchWhole(a: Allocator, io: std.Io, client: *std.http.Client, out: *std.Io.Writer, err_out: *std.Io.Writer, auth: Auth, repo: []const u8, sha: []const u8, dir: []const u8, whole: []const single.Entry) !u32 { + for (whole) |e| if (!single.snapshotPathOk(e.path)) return error.SnapshotPath; const w = std.Io.Dir.cwd(); const tmp = try std.fs.path.join(a, &.{ dir, ".pull" }); try w.createDirPath(io, tmp); diff --git a/zig/src/cli/pull_file.zig b/zig/src/cli/pull_file.zig index a938aedb4f2..b3c72d131e6 100644 --- a/zig/src/cli/pull_file.zig +++ b/zig/src/cli/pull_file.zig @@ -182,7 +182,7 @@ pub fn fileStat(io: std.Io, path: []const u8) !u64 { } /// A snapshot's path a hub tree names: relative, and no traversal segments. -fn snapshotPathOk(path: []const u8) bool { +pub fn snapshotPathOk(path: []const u8) bool { if (path.len == 0 or path[0] == '/') return false; if (std.mem.indexOfAny(u8, path, "\\:\x00") != null) return false; var it = std.mem.splitScalar(u8, path, '/'); diff --git a/zig/src/cli/pull_host_test.zig b/zig/src/cli/pull_host_test.zig index 965efc4c903..47a20de5073 100644 --- a/zig/src/cli/pull_host_test.zig +++ b/zig/src/cli/pull_host_test.zig @@ -2,4 +2,5 @@ test { _ = @import("pull_test.zig"); _ = @import("pull_repair_test.zig"); + _ = @import("pull_kp50_test.zig"); } diff --git a/zig/src/cli/pull_kp50_test.zig b/zig/src/cli/pull_kp50_test.zig new file mode 100644 index 00000000000..55fa2eb43b2 --- /dev/null +++ b/zig/src/cli/pull_kp50_test.zig @@ -0,0 +1,371 @@ +//! KP50 hub regressions: EXLR8 path containment and credential reflection/redaction. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const pull = @import("pull.zig"); +const auth_mod = @import("pull_auth.zig"); +const Auth = auth_mod.Auth; +const exlr8_pull = @import("pull_exlr8.zig"); +const runs = @import("pull_runs.zig"); +const single = @import("pull_file.zig"); +const FakeHub = @import("pull_test.zig").FakeHub; +const Map = std.process.Environ.Map; + +const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1"; +const plain_token = "fixture-token"; +const literal_token = "fixture%2Ftoken"; + +fn target(head: []const u8) []const u8 { + const start = std.mem.indexOfScalar(u8, head, ' ') orelse return ""; + const rest = head[start + 1 ..]; + return rest[0 .. std.mem.indexOfScalar(u8, rest, ' ') orelse rest.len]; +} + +fn method(head: []const u8) []const u8 { + return head[0 .. std.mem.indexOfScalar(u8, head, ' ') orelse return ""]; +} + +fn redirect(fake: *FakeHub, conn: std.Io.net.Stream, location: []const u8) bool { + var buf: [8192]u8 = undefined; + fake.sendAll(conn, std.fmt.bufPrint(&buf, "HTTP/1.1 302 Found\r\nLocation: {s}\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n", .{location}) catch return false); + return true; +} + +fn encoded(a: Allocator, text: []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (text) |c| try out.print(a, "%{X:0>2}", .{c}); + return out.items; +} + +fn envWithToken(a: Allocator, fake: *FakeHub, token: []const u8) !Map { + var env: Map = .{ .array_hash_map = .empty, .allocator = a }; + try env.put("HF_ENDPOINT", try fake.endpoint(a)); + try env.put("HF_TOKEN", token); + return env; +} + +fn expectAbsent(text: []const u8, secret: []const u8) !void { + try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} + +fn expectNoFile(io: std.Io, path: []const u8) !void { + std.Io.Dir.cwd().access(io, path, .{}) catch |err| switch (err) { + error.FileNotFound => return, + else => return err, + }; + return error.UnsafeHubPathCreatedFile; +} + +// Finding 1: even a valid LFS response must not make an unsafe path reachable. +var traversal_requests: std.atomic.Value(u32) = .init(0); + +fn traversalFixture(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + const prefix = "/Org/Flash/resolve/" ++ sha ++ "/"; + if (!std.mem.startsWith(u8, target(head), prefix)) return null; + _ = traversal_requests.fetchAdd(1, .monotonic); + if (std.mem.eql(u8, method(head), "HEAD")) { + fake.sendAll(conn, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n"); + return true; + } + var buf: [256]u8 = undefined; + fake.sendAll(conn, std.fmt.bufPrint(&buf, "HTTP/1.1 206 Partial Content\r\nContent-Length: {d}\r\nContent-Range: bytes 0-{d}/{d}\r\nConnection: keep-alive\r\n\r\n", .{ fake.weights.len, fake.weights.len - 1, fake.weights.len }) catch return false); + fake.sendAll(conn, fake.weights); + return true; +} + +test "security KP50-1: EXLR8 LFS paths obey snapshotPathOk before filesystem or URL use" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = traversalFixture; + fake.start(); + defer fake.stopServer(); + const hub: Auth = .{ .endpoint = try fake.endpoint(a) }; + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + var digest: [32]u8 = undefined; + _ = try std.fmt.hexToBytes(&digest, fake.weights_sha_hex); + + const stamp = std.Io.Clock.awake.now(io).toNanoseconds(); + const sandbox = try std.fmt.allocPrint(a, ".tf-pull-kp50-paths-{d}", .{stamp}); + defer std.Io.Dir.cwd().deleteTree(io, sandbox) catch {}; + const names = [_][]const u8{ + "../outside", "absolute", "a/../b", "..\\outside", + ".tensorfold-save-pending", "nested/.TensorFold-Original/graphs", "weights.tensorfold-rollback", + }; + for (names, 0..) |name, i| { + const case_root = try std.fmt.allocPrint(a, "{s}/case-{d}", .{ sandbox, i }); + const dir = try std.fs.path.join(a, &.{ case_root, "destination" }); + const absolute = try std.fmt.allocPrint(a, "/{s}/case-{d}/absolute-outside", .{ sandbox, i }); + const path = if (std.mem.eql(u8, name, "absolute")) absolute else name; + const entry = single.Entry{ .path = path, .size = fake.weights.len, .sha256 = digest }; + const final = try std.fs.path.join(a, &.{ dir, path }); + traversal_requests.store(0, .monotonic); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + const result = exlr8_pull.fetchWhole(a, io, &client, &out.writer, &err_out.writer, hub, "Org/Flash", sha, dir, &.{entry}); + if (result) |_| { + try expectNoFile(io, final); + if (std.mem.eql(u8, name, "absolute")) try expectNoFile(io, absolute); + try std.testing.expectEqual(@as(u32, 0), traversal_requests.load(.monotonic)); + return error.UnsafeExlr8PathAccepted; + } else |err| { + try std.testing.expectEqual(error.SnapshotPath, err); + } + try expectNoFile(io, final); + if (std.mem.eql(u8, name, "../outside")) { + try expectNoFile(io, try std.fs.path.join(a, &.{ case_root, "outside" })); + } + if (std.mem.eql(u8, name, "absolute")) try expectNoFile(io, absolute); + try std.testing.expectEqual(@as(u32, 0), traversal_requests.load(.monotonic)); + } +} + +// Finding 4: runs.resolve handles this redirect itself rather than in Auth.send. +var head_location: []const u8 = ""; +var requests_after_head: std.atomic.Value(u32) = .init(0); + +fn headRedirectFixture(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + if (std.mem.eql(u8, target(head), "/head") and std.mem.eql(u8, method(head), "HEAD")) { + return redirect(fake, conn, head_location); + } + _ = requests_after_head.fetchAdd(1, .monotonic); + fake.respond(conn, "{}"); + return true; +} + +test "security KP50-4: EXLR8 HEAD redirects refuse credentials in every absolute URI component" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = headRedirectFixture; + fake.start(); + defer fake.stopServer(); + const hub: Auth = .{ .endpoint = try fake.endpoint(a), .bearer = "Bearer " ++ plain_token, .source = "HF_TOKEN" }; + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + const coded = try encoded(a, plain_token); + for ([_][]const u8{ plain_token, coded }) |secret| { + const authority = try std.fmt.allocPrint(a, "127.0.0.1:{d}", .{fake.port}); + const locations = [_][]const u8{ + try std.fmt.allocPrint(a, "http://{s}@{s}/cdn", .{ secret, authority }), + try std.fmt.allocPrint(a, "http://{s}/cdn/{s}", .{ authority, secret }), + try std.fmt.allocPrint(a, "http://{s}/cdn?credential={s}", .{ authority, secret }), + try std.fmt.allocPrint(a, "http://{s}/cdn#{s}", .{ authority, secret }), + }; + for (locations) |location| { + head_location = location; + requests_after_head.store(0, .monotonic); + const result = runs.resolve(a, &client, hub, try std.fmt.allocPrint(a, "{s}/head", .{hub.endpoint})); + var caught: ?anyerror = null; + if (result) |_| {} else |err| caught = err; + try std.testing.expectEqual(@as(u32, 0), requests_after_head.load(.monotonic)); + try std.testing.expect(caught != null); + try std.testing.expectEqual(error.HubCredentialRedirect, caught.?); + } + } +} + +// Finding 5 records raw request targets and all displayed text for each attack. +const Attack = struct { + secret: []const u8, + payload: []const u8, + variants: [4][]const u8, +}; + +var attack_payload: []const u8 = ""; +var attack_requests: std.atomic.Value(u32) = .init(0); +var request_log: [4096]u8 = undefined; +var request_log_len: usize = 0; + +fn noteAttack(head: []const u8) void { + _ = attack_requests.fetchAdd(1, .monotonic); + const text = target(head); + request_log_len = @min(text.len, request_log.len); + @memcpy(request_log[0..request_log_len], text[0..request_log_len]); +} + +fn reflectedRedirectFixture(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + if (std.mem.eql(u8, target(head), "/reflect")) { + return redirect(fake, conn, std.fmt.allocPrint(fake.allocator, "/collect?credential={s}", .{attack_payload}) catch return false); + } + if (std.mem.startsWith(u8, target(head), "/collect")) { + noteAttack(head); + fake.respond(conn, "{}"); + return true; + } + return null; +} + +fn reflectedTreeFixture(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + const at = target(head); + if (std.mem.eql(u8, at, "/api/models/Org/Flash/tree/" ++ sha ++ "?recursive=true")) { + var buf: [4096]u8 = undefined; + const tree = std.fmt.bufPrint(&buf, "[{{\"type\":\"file\",\"oid\":\"{s}\",\"path\":\"config.json\",\"size\":{d}}},{{\"type\":\"file\",\"path\":\"weights-{s}\",\"size\":0}}]", .{ &fake.config_git_hex, fake.config.len, attack_payload }) catch return false; + fake.respond(conn, tree); + return true; + } + if (std.mem.startsWith(u8, at, "/Org/Flash/resolve/" ++ sha ++ "/weights-")) { + noteAttack(head); + fake.respond(conn, ""); + return true; + } + return null; +} + +fn resetAttack(payload: []const u8) void { + attack_payload = payload; + attack_requests.store(0, .monotonic); + request_log_len = 0; +} + +fn expectAttackAbsent(attack: Attack, out: []const u8, err_out: []const u8) !void { + try expectAbsent(request_log[0..request_log_len], attack.payload); + try expectAbsent(out, attack.payload); + try expectAbsent(err_out, attack.payload); + for (attack.variants) |variant| { + try expectAbsent(request_log[0..request_log_len], variant); + try expectAbsent(out, variant); + try expectAbsent(err_out, variant); + } +} + +fn redirectAttack(a: Allocator, client: *std.http.Client, hub: Auth, attack: Attack) !void { + resetAttack(attack.payload); + var buf: [8192]u8 = undefined; + var req: std.http.Client.Request = undefined; + const result = hub.send(client, &req, .GET, try std.Uri.parse(try std.fmt.allocPrint(a, "{s}/reflect", .{hub.endpoint})), .{}, &buf); + var caught: ?anyerror = null; + if (result) |_| req.deinit() else |err| caught = err; + try expectAttackAbsent(attack, request_log[0..request_log_len], ""); + try std.testing.expectEqual(@as(u32, 0), attack_requests.load(.monotonic)); + try std.testing.expect(caught != null); + try std.testing.expectEqual(error.HubCredentialRedirect, caught.?); +} + +fn treeAttack(a: Allocator, io: std.Io, fake: *FakeHub, root: []const u8, attack: Attack) !void { + resetAttack(attack.payload); + const env = try envWithToken(a, fake, attack.secret); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + const status = try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash"); + try expectAttackAbsent(attack, out.written(), err_out.written()); + try std.testing.expectEqual(@as(u32, 0), attack_requests.load(.monotonic)); + try std.testing.expectEqual(@as(u8, 1), status); +} + +test "security KP50-5: literal-percent and nested-encoded tokens are contained in redirects" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedRedirectFixture; + fake.start(); + defer fake.stopServer(); + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + + const plain = [4][]const u8{ + plain_token, try encoded(a, plain_token), + try encoded(a, try encoded(a, plain_token)), try encoded(a, try encoded(a, try encoded(a, plain_token))), + }; + const literal = [4][]const u8{ + literal_token, try encoded(a, literal_token), + try encoded(a, try encoded(a, literal_token)), try encoded(a, try encoded(a, try encoded(a, literal_token))), + }; + const attacks = [_]Attack{ + .{ .secret = plain_token, .payload = plain[0], .variants = plain }, + .{ .secret = plain_token, .payload = "%66ixture-token", .variants = plain }, + .{ .secret = plain_token, .payload = plain[1], .variants = plain }, + .{ .secret = plain_token, .payload = plain[2], .variants = plain }, + .{ .secret = plain_token, .payload = plain[3], .variants = plain }, + .{ .secret = literal_token, .payload = literal[0], .variants = literal }, + .{ .secret = literal_token, .payload = "%66ixture%2Ftoken", .variants = literal }, + .{ .secret = literal_token, .payload = literal[1], .variants = literal }, + .{ .secret = literal_token, .payload = literal[2], .variants = literal }, + .{ .secret = literal_token, .payload = literal[3], .variants = literal }, + }; + for (attacks) |attack| { + const hub: Auth = .{ .endpoint = try fake.endpoint(a), .bearer = try std.fmt.allocPrint(a, "Bearer {s}", .{attack.secret}), .source = "HF_TOKEN" }; + try redirectAttack(a, &client, hub, attack); + } +} + +test "security KP50-5: literal-percent and nested-encoded tokens are contained in tree paths" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedTreeFixture; + fake.start(); + defer fake.stopServer(); + + const plain = [4][]const u8{ + plain_token, try encoded(a, plain_token), + try encoded(a, try encoded(a, plain_token)), try encoded(a, try encoded(a, try encoded(a, plain_token))), + }; + const literal = [4][]const u8{ + literal_token, try encoded(a, literal_token), + try encoded(a, try encoded(a, literal_token)), try encoded(a, try encoded(a, try encoded(a, literal_token))), + }; + const attacks = [_]Attack{ + .{ .secret = plain_token, .payload = plain[0], .variants = plain }, + .{ .secret = plain_token, .payload = "%66ixture-token", .variants = plain }, + .{ .secret = plain_token, .payload = plain[1], .variants = plain }, + .{ .secret = plain_token, .payload = plain[2], .variants = plain }, + .{ .secret = plain_token, .payload = plain[3], .variants = plain }, + .{ .secret = literal_token, .payload = literal[0], .variants = literal }, + .{ .secret = literal_token, .payload = literal[1], .variants = literal }, + .{ .secret = literal_token, .payload = "%66ixture%2Ftoken", .variants = literal }, + .{ .secret = literal_token, .payload = literal[2], .variants = literal }, + .{ .secret = literal_token, .payload = literal[3], .variants = literal }, + }; + for (attacks, 0..) |attack, i| { + const root = try std.fmt.allocPrint(a, ".tf-pull-kp50-tree-{d}-{d}", .{ std.Io.Clock.awake.now(io).toNanoseconds(), i }); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + try treeAttack(a, io, &fake, root, attack); + } +} + +test "security KP50-6: percent-encoded credentials are redacted from model_type" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const once = try encoded(a, plain_token); + const twice = try encoded(a, once); + const thrice = try encoded(a, twice); + const root = try std.fmt.allocPrint(a, ".tf-pull-kp50-model-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const env = try envWithToken(a, &fake, plain_token); + for ([_][]const u8{ once, twice, thrice }) |model_type| { + fake.config = try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\"}}", .{model_type}); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + for ([_][]const u8{ plain_token, once, twice, thrice }) |variant| { + try expectAbsent(out.written(), variant); + try expectAbsent(err_out.written(), variant); + } + try std.testing.expect(std.mem.indexOf(u8, err_out.written(), "[redacted]") != null); + } + const encoded_percent = "%2525"; + fake.config = "{\"model_type\":\"%2525\"}"; + const percent_env = try envWithToken(a, &fake, "%25"); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &percent_env, root, "Org/Flash")); + for ([_][]const u8{ out.written(), err_out.written() }) |text| { + try expectAbsent(text, encoded_percent); + try expectAbsent(text, "[redacted]25"); + } + try std.testing.expect(std.mem.indexOf(u8, err_out.written(), "[redacted]") != null); +} diff --git a/zig/src/cli/pull_runs.zig b/zig/src/cli/pull_runs.zig index 9b35b76a603..d85b94c1d7b 100644 --- a/zig/src/cli/pull_runs.zig +++ b/zig/src/cli/pull_runs.zig @@ -198,6 +198,7 @@ pub fn resolve(a: Allocator, client: *std.http.Client, auth: Auth, url: []const defer req.deinit(); if (response.head.status.class() == .redirect) { const to = response.head.location orelse return error.HttpRedirectLocationMissing; + if (auth.reflects(to)) return error.HubCredentialRedirect; if (!std.mem.startsWith(u8, to, "https://") and !std.mem.startsWith(u8, to, "http://")) return error.RelativeRedirect; return a.dupe(u8, to); } diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index 3a38c7323ee..a7dce626cc1 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -269,18 +269,20 @@ pub fn clean(a: Allocator, text: []const u8, limit: usize) ![]const u8 { return std.mem.trim(u8, out.items, " "); } -/// Terminal/error text with every supplied credential replaced, longest first at each byte. +/// Terminal/error text with credentials replaced, longest first; bytes may be literal or one %XX escape. pub fn redact(a: Allocator, text: []const u8, secrets: []const []const u8) ![]const u8 { + var scratch = try MatchScratch.init(a, text, secrets); + defer scratch.deinit(a); var scan: usize = 0; - while (scan < text.len and secretAt(text, scan, secrets).len == 0) scan += 1; + while (scan < text.len and secretAt(text, scan, secrets, &scratch).consumed == 0) scan += 1; if (scan == text.len) return text; var out: std.ArrayList(u8) = .empty; var i: usize = 0; while (i < text.len) { - const found = secretAt(text, i, secrets); - if (found.len > 0) { + const found = secretAt(text, i, secrets, &scratch); + if (found.consumed > 0) { try out.appendSlice(a, "[redacted]"); - i += found.len; + i += found.consumed; } else { try out.append(a, text[i]); i += 1; @@ -291,29 +293,25 @@ pub fn redact(a: Allocator, text: []const u8, secrets: []const []const u8) ![]co pub const RedactedPiece = struct { text: []const u8, rest: []const u8 }; -/// One streamed piece: emit complete safe text and retain only a suffix that may begin a credential. +/// One streamed piece: emit safe text and retain a suffix that may still become a credential. pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) !RedactedPiece { + var scratch = try MatchScratch.init(a, text, secrets); + defer scratch.deinit(a); var out: std.ArrayList(u8) = .empty; var changed = false; var i: usize = 0; while (i < text.len) { - const found = secretAt(text, i, secrets); + const found = secretAt(text, i, secrets, &scratch); const rest = text[i..]; - var holds = false; - if (found.len == 0) for (secrets) |secret| { - if (secret.len > rest.len and std.mem.startsWith(u8, secret, rest)) { - holds = true; - break; - } - }; - if (found.len > 0 or holds) { + if (found.consumed > 0 or found.hold) { if (!changed) { try out.appendSlice(a, text[0..i]); changed = true; } - if (holds) return .{ .text = out.items, .rest = rest }; + // A complete shorter key stays pending while the whole suffix can still become a longer key. + if (found.hold) return .{ .text = out.items, .rest = rest }; try out.appendSlice(a, "[redacted]"); - i += found.len; + i += found.consumed; } else { if (changed) try out.append(a, text[i]); i += 1; @@ -322,14 +320,99 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) return .{ .text = if (changed) out.items else text, .rest = "" }; } -fn secretAt(text: []const u8, i: usize, secrets: []const []const u8) []const u8 { - var found: []const u8 = ""; +const Match = struct { secret_len: usize = 0, consumed: usize = 0, hold: bool = false }; + +/// The longest complete credential at ``i``; ``hold`` outranks it only for a longer possible credential. +fn secretAt(text: []const u8, i: usize, secrets: []const []const u8, scratch: *MatchScratch) Match { + var found: Match = .{}; + var possible: usize = 0; for (secrets) |secret| { - if (secret.len > found.len and std.mem.startsWith(u8, text[i..], secret)) found = secret; + const m = matchSecret(text[i..], secret, scratch); + if (m.consumed > 0 and m.secret_len > found.secret_len) found = m; + if (m.hold) possible = @max(possible, m.secret_len); } + found.hold = found.hold or possible > found.secret_len; return found; } +const MatchScratch = struct { + states: []bool, + next: []bool, + + fn init(a: Allocator, text: []const u8, secrets: []const []const u8) !MatchScratch { + var longest: usize = 0; + for (secrets) |secret| longest = @max(longest, secret.len); + const has_percent = std.mem.indexOfScalar(u8, text, '%') != null; + const encoded_span = std.math.mul(usize, longest, 3) catch text.len; + const span = if (has_percent) @min(text.len, encoded_span) else 0; + const room = if (has_percent) span + 1 else 0; + const states = try a.alloc(bool, room); + errdefer a.free(states); + return .{ .states = states, .next = try a.alloc(bool, room) }; + } + + fn deinit(s: *MatchScratch, a: Allocator) void { + a.free(s.states); + a.free(s.next); + } +}; + +/// A raw or mixed single-layer percent-encoded match, or a proper prefix ending at ``rest``'s end. +fn matchSecret(rest: []const u8, secret: []const u8, scratch: *MatchScratch) Match { + if (secret.len == 0) return .{}; + if (std.mem.indexOfScalar(u8, rest, '%') == null) { + if (std.mem.startsWith(u8, rest, secret)) return .{ .secret_len = secret.len, .consumed = secret.len }; + if (rest.len < secret.len and std.mem.startsWith(u8, secret, rest)) return .{ .secret_len = secret.len, .hold = true }; + return .{}; + } + var states = scratch.states; + var next = scratch.next; + @memset(states, false); + states[0] = true; + var hold = false; + for (secret) |wanted| { + @memset(next, false); + var any = false; + for (states, 0..) |active, at| { + if (!active) continue; + if (at == rest.len) { + hold = true; + continue; + } + if (rest[at] == '%') { + const left = rest.len - at; + if (left < 3 and (left == 1 or std.ascii.isHex(rest[at + 1]))) hold = true; + if (at + 2 < states.len and left >= 3 and std.ascii.isHex(rest[at + 1]) and std.ascii.isHex(rest[at + 2])) { + const byte = (hex(rest[at + 1]).? << 4) | hex(rest[at + 2]).?; + if (byte == wanted) { + next[at + 3] = true; + any = true; + } + } + } + if (at + 1 < states.len and rest[at] == wanted) { + next[at + 1] = true; + any = true; + } + } + if (!any) return .{ .secret_len = secret.len, .hold = hold }; + const swap = states; + states = next; + next = swap; + } + var consumed: usize = 0; + for (states, 0..) |active, at| { + if (active) consumed = at; + } + return .{ .secret_len = secret.len, .consumed = consumed, .hold = hold }; +} + +fn hex(c: u8) ?u8 { + if (c >= '0' and c <= '9') return c - '0'; + const lower = std.ascii.toLower(c); + return if (lower >= 'a' and lower <= 'f') lower - 'a' + 10 else null; +} + /// The index past the escape sequence at ``i``: a CSI sequence through its final byte, else ESC and one more byte. fn afterEscape(text: []const u8, i: usize) usize { if (i + 1 >= text.len or text[i + 1] != '[') return @min(i + 2, text.len); diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index d9ba3814c6b..7083e44748d 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -215,11 +215,18 @@ const Exchange = struct { } }; -/// A refusal's body, up to 16 KiB, read for at most 100 ms past its head, after its sample's time and code are set. +/// A complete refusal body up to 16 KiB, read for 100 ms; oversized, timed-out and incomplete bodies return none. pub fn errorBody(a: Allocator, io: std.Io, resp: *const std.http.Client.Response) []const u8 { if (resp.head.transfer_encoding != .none) return ""; - var wait: BodyWait = .{ .in = resp.request.reader.in, .want = @min(resp.head.content_length orelse 16 << 10, 16 << 10) }; - if (wait.in.buffered().len < wait.want) _ = bounded(io, deadlineAfter(io, 0.1), BodyWait.run, &wait); + const declared = resp.head.content_length; + if (declared != null and declared.? > 16 << 10) return ""; + var wait: BodyWait = .{ .in = resp.request.reader.in, .want = @min(declared orelse 16 << 10, 16 << 10), .exact = declared != null }; + if (wait.exact and wait.in.buffered().len >= wait.want) { + wait.complete = true; + } else { + _ = bounded(io, deadlineAfter(io, 0.1), BodyWait.run, &wait); + if (!wait.complete) return ""; + } const got = wait.in.buffered(); return a.dupe(u8, got[0..@min(got.len, wait.want)]) catch ""; } @@ -227,10 +234,16 @@ pub fn errorBody(a: Allocator, io: std.Io, resp: *const std.http.Client.Response const BodyWait = struct { in: *std.Io.Reader, want: usize, + exact: bool, + complete: bool = false, done: std.atomic.Value(bool) = .init(false), fn run(w: *BodyWait) void { - while (w.in.buffered().len < w.want) w.in.fillMore() catch return; + while (w.in.buffered().len < w.want) w.in.fillMore() catch |e| { + w.complete = !w.exact and e == error.EndOfStream; + return; + }; + w.complete = w.exact; } }; diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 5ffacc65db7..868226a37eb 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -428,3 +428,7 @@ fn fail(ctx: *const Context, message: []const u8) !u8 { try ctx.err.flush(); return 1; } + +test { + if (comptime !windows) _ = @import("chat_cli_kp50_test.zig"); +} diff --git a/zig/src/server/chat_cli_kp50_test.zig b/zig/src/server/chat_cli_kp50_test.zig new file mode 100644 index 00000000000..08d5b001c87 --- /dev/null +++ b/zig/src/server/chat_cli_kp50_test.zig @@ -0,0 +1,275 @@ +//! KP50 host regressions for truncation, streamed hold-back and encoded credentials. +const std = @import("std"); +const fake = @import("benchmark_fake.zig"); +const fixtures = @import("chat_cli_test.zig"); +const Allocator = std.mem.Allocator; + +const ascii_key = "fixture-ascii/token+part"; +const ascii_encoded = "fixture-ascii%2Ftoken%2Bpart"; +const latin_key = "fixture-caf\u{e9}/ol\u{f1}"; +const latin_encoded = "fixture-caf%E9%2Fol%F1"; + +fn postBody(f: *fake.Fake, wanted: usize) ![]const u8 { + var seen: usize = 0; + for (0..f.count()) |i| if (std.mem.eql(u8, f.request(i).method, "POST")) { + if (seen == wanted) return f.request(i).body; + seen += 1; + }; + return error.TestUnexpectedResult; +} + +fn absent(text: []const u8, secrets: []const []const u8) !void { + for (secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} + +fn stream(a: Allocator, parts: []const []const u8) ![]const fake.Write { + var bytes: std.ArrayList(u8) = .empty; + try bytes.appendSlice(a, try fake.headOf(a, "200 OK", "text/event-stream")); + for (parts) |part| try bytes.appendSlice(a, part); + return a.dupe(fake.Write, &.{.{ .bytes = bytes.items }}); +} + +fn delta(a: Allocator, content: []const u8) ![]const u8 { + return fake.event(a, try std.fmt.allocPrint(a, "{{\"choices\": [{{\"index\": 0, \"delta\": {{\"content\": \"{s}\"}}, \"finish_reason\": null}}]}}", .{content})); +} + +fn successful(a: Allocator, content: []const u8) ![]const fake.Write { + return stream(a, try a.dupe([]const u8, &.{ + try delta(a, content), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); +} + +fn httpError(a: Allocator, message: []const u8) ![]const fake.Write { + return fake.jsonReply(a, "500 Internal Server Error", try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})); +} + +fn sseError(a: Allocator, message: []const u8) ![]const fake.Write { + return stream(a, try a.dupe([]const u8, &.{ + try fake.event(a, try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})), + try fake.event(a, "[DONE]"), + })); +} + +const Bodies = struct { plain: []const u8, json: []const u8 }; +const message_head = "{\"error\":{\"message\":\""; + +fn truncationBodies(a: Allocator, controls: []const u8, key: []const u8) !Bodies { + return .{ + .plain = try std.mem.concat(a, u8, &.{ controls, key }), + .json = try std.mem.concat(a, u8, &.{ message_head, controls, key, "\"}}" }), + }; +} + +/// A declared body whose first write stops short of the 16 KiB capture until after its 100 ms deadline. +fn timedError(a: Allocator, body: []const u8, kept: usize) ![]const fake.Write { + const head = try std.fmt.allocPrint(a, "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{body.len}); + const writes = try a.alloc(fake.Write, 2); + writes[0] = .{ .bytes = try std.mem.concat(a, u8, &.{ head, body[0..kept] }), .pause_ms = 300 }; + writes[1] = .{ .bytes = body[kept..] }; + return writes; +} + +test "chat CLI: KP50 fixed-length plain and JSON-message bodies expose no truncated key prefix" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const key = try a.alloc(u8, 256); + @memset(key, 'K'); + const controls = try a.alloc(u8, 16_129); + @memset(controls, 1); + const bodies = try truncationBodies(a, controls, key); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try fake.jsonReply(a, "500 Internal Server Error", bodies.plain), + try fake.jsonReply(a, "500 Internal Server Error", bodies.json), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", key); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try absent(shown.items, &.{ key[0..255], key[0..128] }); +} + +test "chat CLI: KP50 genuinely timed plain and JSON-message bodies expose no retained key prefix" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const key = try a.alloc(u8, 256); + @memset(key, 'K'); + const plain = key; + const json = try std.mem.concat(a, u8, &.{ message_head, key, "\"}}" }); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try timedError(a, plain, 128), + try timedError(a, json, message_head.len + 128), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", key); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try absent(shown.items, &.{key[0..128]}); +} + +test "chat CLI: KP50 a successful final ambiguous SSE prefix stays out of output and history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const prefix = "fixture-secre"; + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, prefix), + try successful(a, "next"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "fixture-secret"); + r.interactive = true; + r.input = "first\nsecond\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try absent(r.out.written(), &.{prefix}); + try absent(r.err.written(), &.{prefix}); + try absent(try postBody(f, 1), &.{prefix}); +} + +test "chat CLI: KP50 error-event and truncated-EOF replies never flush an ambiguous prefix" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const prefix = "fixture-secre"; + const failing = try stream(a, try a.dupe([]const u8, &.{ + try delta(a, prefix), + try fake.event(a, "{\"error\": {\"message\": \"generation failed\"}}"), + try fake.event(a, "[DONE]"), + })); + const truncated = try stream(a, try a.dupe([]const u8, &.{try delta(a, prefix)})); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ failing, truncated })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "fixture-secret"); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try absent(shown.items, &.{prefix}); +} + +test "chat CLI: KP50 a shorter key never releases a longer key suffix across deltas or history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const split = try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "fixture"), + try delta(a, "-secret"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ split, try successful(a, "next") })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "fixture,fixture-secret"); + r.interactive = true; + r.input = "first\nsecond\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try absent(r.out.written(), &.{ "-secret", "[redacted]-secret" }); + try absent(r.err.written(), &.{ "-secret", "[redacted]-secret" }); + try absent(try postBody(f, 1), &.{ "-secret", "[redacted]-secret" }); +} + +test "chat CLI: KP50 literal-percent keys consume their full encoded span in content and history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ try successful(a, "%2525"), try successful(a, "a%25%62"), try successful(a, "done") })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "%25,a%25b"); + r.interactive = true; + r.input = "first\nsecond\nthird\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try absent(r.out.written(), &.{ "%2525", "a%25%62", "%62", "[redacted]25" }); + try absent(r.err.written(), &.{ "%2525", "a%25%62", "%62", "[redacted]25" }); + try absent(try postBody(f, 1), &.{ "%2525", "[redacted]25" }); + try absent(try postBody(f, 2), &.{ "%2525", "a%25%62", "%62", "[redacted]25" }); +} + +test "chat CLI: KP50 percent-encoded credentials are absent from HTTP and SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try httpError(a, ascii_encoded), + try httpError(a, latin_encoded), + try httpError(a, "%2525"), + try httpError(a, "a%25%62"), + try sseError(a, ascii_encoded), + try sseError(a, latin_encoded), + try sseError(a, "%2525"), + try sseError(a, "a%25%62"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ ascii_key, ",", latin_key, ",%25,a%25b" })); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..8) |_| { + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try absent(shown.items, &.{ ascii_encoded, latin_encoded, "%2525", "a%25%62", "%62", "[redacted]25" }); +} + +test "chat CLI: KP50 discovered encoded IDs leave neither the banner nor the follow-up POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const model = try std.mem.concat(a, u8, &.{ ascii_encoded, "|", latin_encoded, "|%2525|a%25%62" }); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{model}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "ok")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ ascii_key, ",", latin_key, ",%25,a%25b" })); + var shown: std.ArrayList(u8) = .empty; + r.interactive = true; + r.input = "/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + r.interactive = false; + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + try absent(shown.items, &.{ ascii_encoded, latin_encoded, "%2525", "a%25%62", "%62", "[redacted]25" }); + try absent(try postBody(f, 0), &.{ ascii_encoded, latin_encoded, "%2525", "a%25%62", "%62", "[redacted]25" }); +} diff --git a/zig/src/server/chat_cli_reply.zig b/zig/src/server/chat_cli_reply.zig index d4db6cebcac..c8d9c256c7a 100644 --- a/zig/src/server/chat_cli_reply.zig +++ b/zig/src/server/chat_cli_reply.zig @@ -31,7 +31,7 @@ pub const Reply = struct { failure: ?[]const u8 = null, done: bool = false, - /// Release a final non-secret prefix after the stream stops. + /// Redact a final ambiguous credential prefix after the stream stops. pub fn end(r: *Reply) Failure!void { try r.flush(.reasoning); try r.flush(.content); @@ -48,7 +48,7 @@ pub const Reply = struct { fn flush(r: *Reply, kind: Kind) Failure!void { const state = streamFor(r, kind); if (state.pending.len == 0) return; - const text = state.pending; + const text = "[redacted]"; state.pending = ""; if (kind == .content) try r.content.appendSlice(r.a, text); try r.sink.piece(r.sink.ctx, kind, text); @@ -96,6 +96,8 @@ pub const Reply = struct { }; if (chunk != .object) return error.InvalidStream; if (chunk.field("error")) |e| { + try r.flush(.reasoning); + try r.flush(.content); r.failure = try errorText(r.a, e, r.secrets); return; } diff --git a/zig/src/server/chat_cli_test.zig b/zig/src/server/chat_cli_test.zig index d9ed69bc5fc..cf0b35e5772 100644 --- a/zig/src/server/chat_cli_test.zig +++ b/zig/src/server/chat_cli_test.zig @@ -9,7 +9,7 @@ const fake = @import("benchmark_fake.zig"); const stream = @import("benchmark_stream.zig"); const Allocator = std.mem.Allocator; -const Run = struct { +pub const Run = struct { a: Allocator, env: std.process.Environ.Map, dir: []const u8, @@ -22,14 +22,14 @@ const Run = struct { interactive: bool = false, self_exe: ?[]const u8 = null, - fn init(a: Allocator, tmp: *std.testing.TmpDir) !Run { + pub fn init(a: Allocator, tmp: *std.testing.TmpDir) !Run { var r: Run = .{ .a = a, .env = .init(a), .dir = try fake.tmpPath(a, tmp), .out = .init(a), .err = .init(a) }; try r.env.put("PATH", "/usr/bin:/bin"); for ([_][]const u8{ "TMPDIR", "HOME" }) |name| try r.env.put(name, r.dir); return r; } - fn command(r: *Run, argv: []const []const u8) !u8 { + pub fn command(r: *Run, argv: []const []const u8) !u8 { r.out.clearRetainingCapacity(); r.err.clearRetainingCapacity(); r.stdin = .fixed(r.input); @@ -52,7 +52,7 @@ const Run = struct { } }; -const models_doc = "{\"object\": \"list\", \"data\": [{\"id\": \"example-model\", \"capabilities\": {\"thinking_switch\": true}}, {\"id\": \"other-model\"}]}"; +pub const models_doc = "{\"object\": \"list\", \"data\": [{\"id\": \"example-model\", \"capabilities\": {\"thinking_switch\": true}}, {\"id\": \"other-model\"}]}"; fn chunk(a: Allocator, delta: []const u8) ![]const u8 { return fake.event(a, try std.fmt.allocPrint(a, "{{\"choices\": [{{\"index\": 0, \"delta\": {s}, \"finish_reason\": null}}]}}", .{delta})); @@ -70,7 +70,7 @@ fn streamed(a: Allocator) ![]const fake.Write { } /// A server that lists ``models`` and answers the n-th chat request with ``replies[n]`` (the last one after). -fn world(a: Allocator, models: []const u8, replies: []const []const fake.Write) !*fake.Fake { +pub fn world(a: Allocator, models: []const u8, replies: []const []const fake.Write) !*fake.Fake { return worldKeyed(a, models, replies, null); } diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index aaf70cec30e..4cbf13e36a1 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -103,7 +103,7 @@ const Run = struct { fn standInAt(r: *Run, port: u16, name: []const u8) !void { const script = try r.path(name); - const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '%s' \"$START_TEST_UNRELATED\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nif [ \"$START_TEST_LOG_KEY\" = 1 ]; then printf 'error: %0250d%s\\n' 0 \"$TENSORFOLD_API_KEY\" >&2; fi\nif [ \"$START_TEST_SHORT_LIVED\" = 1 ]; then exec sleep 1; else exec sleep 30; fi\n", .{ try r.path("pid"), try r.path("args"), try r.path("child-key"), try r.path("unrelated"), port }); + const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '%s' \"$TENSORFOLD_API_KEY\" > {s}\nprintf '%s' \"$START_TEST_UNRELATED\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nif [ \"$START_TEST_LOG_KEY\" = 1 ]; then printf 'error: %0250d%s\\n' 0 \"$TENSORFOLD_API_KEY\" >&2; fi\nif [ \"$START_TEST_LOG_ENCODED\" ]; then printf 'error: %s\\n' \"$START_TEST_LOG_ENCODED\" >&2; fi\nif [ \"$START_TEST_SHORT_LIVED\" = 1 ]; then exec sleep 1; else exec sleep 30; fi\n", .{ try r.path("pid"), try r.path("args"), try r.path("child-key"), try r.path("unrelated"), port }); try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = script, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); r.self_exe = script; } @@ -568,3 +568,30 @@ test "start CLI: a managed first reply authenticates Latin-1 and removes termina } } } + +test "start CLI: managed logs redact percent-encoded ASCII and Latin-1 credentials" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + const ascii = "fixture-ascii/token+part"; + const latin = "fixture-caf\u{e9}/ol\u{f1}"; + const encoded_ascii = "fixture-ascii%2Ftoken%2Bpart"; + const encoded_latin = "fixture-caf%E9%2Fol%F1"; + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ ascii, ",", latin, ",%25,a%25b" })); + try r.env.put("START_TEST_SHORT_LIVED", "1"); + try r.env.put("START_TEST_LOG_KEY", "1"); + try r.env.put("START_TEST_LOG_ENCODED", try std.mem.concat(a, u8, &.{ encoded_ascii, " ", encoded_latin, " %2525 a%25%62" })); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = ascii }); + const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--startup-timeout", "2" })); + try std.testing.expect(r.childGone()); + for ([_][]const u8{ ascii, latin, encoded_ascii, encoded_latin, "%2525", "a%25%62", "%62", "[redacted]25" }) |secret| + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| + try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} From e3a5e725ae4831598c4afbc5c96eecad1f3dec29 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:43:17 +0000 Subject: [PATCH 093/361] security: match arbitrarily nested credentials Rebase KF45 onto the current CUDA CLI and replace layered percent scans with one memoized decoder. Explicit dependency frames bound call depth on adversarial nesting. Mixed-depth hub attacks, encoded-key overlap and nested streaming credentials failed before this change; all 184 focused host tests now pass. --- zig/src/cli/pull_auth.zig | 116 ++---------- zig/src/cli/pull_host_test.zig | 1 + zig/src/cli/pull_kp50_test.zig | 86 +++++++++ zig/src/platform/credential.zig | 260 ++++++++++++++++++++++++++ zig/src/platform/sys.zig | 2 + zig/src/server/benchmark_sse.zig | 110 +---------- zig/src/server/chat_cli_kp50_test.zig | 135 +++++++++++++ zig/src/server/start_cli_test.zig | 39 ++-- 8 files changed, 525 insertions(+), 224 deletions(-) create mode 100644 zig/src/platform/credential.zig diff --git a/zig/src/cli/pull_auth.zig b/zig/src/cli/pull_auth.zig index f997943730b..b681cf88acc 100644 --- a/zig/src/cli/pull_auth.zig +++ b/zig/src/cli/pull_auth.zig @@ -3,6 +3,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const http = std.http; const hub = @import("hub.zig"); +const credential = @import("sys").credential; const environment = @import("sys").environment; /// The hub pull talks to when HF_ENDPOINT names none. @@ -67,18 +68,19 @@ pub const Auth = struct { const bearer = auth.bearer orelse return text; const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; if (secret.len == 0) return text; + var matcher = credential.Matcher.init(a, text); + defer matcher.deinit(); var out: std.ArrayList(u8) = .empty; - var rest = text; + var at: usize = 0; var replaced = false; - while (true) { - const span = (try credentialSpan(a, rest, secret)) orelse break; - try out.appendSlice(a, rest[0..span.start]); + while (try matcher.spanFrom(at, secret)) |span| { + try out.appendSlice(a, text[at..span.start]); try out.appendSlice(a, "[redacted]"); - rest = rest[span.end..]; + at = span.end; replaced = true; } if (!replaced) return text; - try out.appendSlice(a, rest); + try out.appendSlice(a, text[at..]); return out.items; } @@ -134,107 +136,11 @@ fn origin(uri: std.Uri, buf: []u8) ?Origin { const port: u16 = uri.port orelse if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) 443 else if (std.ascii.eqlIgnoreCase(uri.scheme, "http")) 80 else return null; return .{ .scheme = uri.scheme, .host = host, .port = port }; } - -/// The original-text span of a credential, including one hidden by any number of percent-encoding layers. -fn credentialSpan(a: Allocator, text: []const u8, secret: []const u8) !?Span { - if (secret.len == 0) return null; - var best: ?Span = if (std.mem.indexOf(u8, text, secret)) |at| .{ .start = at, .end = at + secret.len } else null; - if (std.mem.indexOfScalar(u8, text, '%') == null) return best; - - // One shrinking in-place buffer plus provenance avoids generating exponentially many encoded variants. - const decoded = try a.dupe(u8, text); - defer a.free(decoded); - const starts = try a.alloc(usize, text.len); - defer a.free(starts); - const ends = try a.alloc(usize, text.len); - defer a.free(ends); - for (starts, ends, 0..) |*start, *end, i| { - start.* = i; - end.* = i + 1; - } - const states = try a.alloc(usize, text.len + 1); - defer a.free(states); - const next_states = try a.alloc(usize, text.len + 1); - defer a.free(next_states); - var len = text.len; - if (layerSpan(decoded[0..len], secret, starts, ends, states, next_states)) |span| { - if (best == null or span.start < best.?.start or (span.start == best.?.start and span.end > best.?.end)) best = span; - } - while (true) { - var read: usize = 0; - var write: usize = 0; - var changed = false; - while (read < len) { - if (read + 2 < len and decoded[read] == '%' and hex(decoded[read + 1]) != null and hex(decoded[read + 2]) != null) { - decoded[write] = hex(decoded[read + 1]).? * 16 + hex(decoded[read + 2]).?; - starts[write] = starts[read]; - ends[write] = ends[read + 2]; - read += 3; - changed = true; - } else { - decoded[write] = decoded[read]; - starts[write] = starts[read]; - ends[write] = ends[read]; - read += 1; - } - write += 1; - } - len = write; - if (layerSpan(decoded[0..len], secret, starts, ends, states, next_states)) |span| { - if (best == null or span.start < best.?.start or (span.start == best.?.start and span.end > best.?.end)) best = span; - } - if (!changed) return best; - } -} - -/// One layer's polynomial-time matcher: each input position retains only its earliest possible match start. -fn layerSpan(text: []const u8, secret: []const u8, starts: []const usize, ends: []const usize, state_buf: []usize, next_buf: []usize) ?Span { - if (std.mem.indexOfScalar(u8, secret, '%') == null) { - const at = std.mem.indexOf(u8, text, secret) orelse return null; - return .{ .start = starts[at], .end = ends[at + secret.len - 1] }; - } - const none = std.math.maxInt(usize); - for (state_buf[0 .. text.len + 1], 0..) |*state, i| state.* = i; - var states = state_buf; - var next = next_buf; - for (secret) |wanted| { - @memset(next[0 .. text.len + 1], none); - for (states[0 .. text.len + 1], 0..) |start, at| { - if (start == none) continue; - // Literal input always remains an alternative, including '%' beginning a valid escape. - if (at < text.len and text[at] == wanted and start < next[at + 1]) next[at + 1] = start; - if (at + 2 < text.len and text[at] == '%' and hex(text[at + 1]) != null and hex(text[at + 2]) != null) { - const byte = hex(text[at + 1]).? * 16 + hex(text[at + 2]).?; - if (byte == wanted and start < next[at + 3]) next[at + 3] = start; - } - } - const swap = states; - states = next; - next = swap; - } - var best: ?Span = null; - for (states[0 .. text.len + 1], 0..) |start, end| { - if (start == none) continue; - const span: Span = .{ .start = starts[start], .end = ends[end - 1] }; - if (best == null or span.start < best.?.start or (span.start == best.?.start and span.end > best.?.end)) best = span; - } - return best; -} - -const Span = struct { start: usize, end: usize }; - fn containsCredential(text: []const u8, secret: []const u8) bool { - const span = credentialSpan(std.heap.page_allocator, text, secret) catch return true; - return span != null; + var matcher = credential.Matcher.init(std.heap.page_allocator, text); + defer matcher.deinit(); + return (matcher.spanFrom(0, secret) catch return true) != null; } - -fn hex(c: u8) ?u8 { - if (c >= '0' and c <= '9') return c - '0'; - if (c >= 'a' and c <= 'f') return c - 'a' + 10; - if (c >= 'A' and c <= 'F') return c - 'A' + 10; - return null; -} - /// The first non-empty of HF_TOKEN and HUGGING_FACE_HUB_TOKEN, else the one token file the `hf` tools read. pub fn token(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, problem: *[]const u8) !?Token { for ([_][:0]const u8{ "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN" }) |name| { diff --git a/zig/src/cli/pull_host_test.zig b/zig/src/cli/pull_host_test.zig index 47a20de5073..4d64ebfade7 100644 --- a/zig/src/cli/pull_host_test.zig +++ b/zig/src/cli/pull_host_test.zig @@ -3,4 +3,5 @@ test { _ = @import("pull_test.zig"); _ = @import("pull_repair_test.zig"); _ = @import("pull_kp50_test.zig"); + _ = @import("sys").credential; } diff --git a/zig/src/cli/pull_kp50_test.zig b/zig/src/cli/pull_kp50_test.zig index 55fa2eb43b2..0ad296cca5e 100644 --- a/zig/src/cli/pull_kp50_test.zig +++ b/zig/src/cli/pull_kp50_test.zig @@ -176,6 +176,14 @@ const Attack = struct { variants: [4][]const u8, }; +fn mixedDepthAttack() Attack { + return .{ + .secret = literal_token, + .payload = "%2566ixture%2Ftoken", + .variants = .{ "%66ixture/token", "fixture/token", "%66ixture%2Ftoken", "%2566ixture/token" }, + }; +} + var attack_payload: []const u8 = ""; var attack_requests: std.atomic.Value(u32) = .init(0); var request_log: [4096]u8 = undefined; @@ -369,3 +377,81 @@ test "security KP50-6: percent-encoded credentials are redacted from model_type" } try std.testing.expect(std.mem.indexOf(u8, err_out.written(), "[redacted]") != null); } + +// KR66 finding 2: independent character depths must not defeat containment. +test "security KR66-2: mixed-depth hub credentials are refused in automatic redirects" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedRedirectFixture; + fake.start(); + defer fake.stopServer(); + var client = @import("pull_http.zig").client(a, std.testing.io); + defer client.deinit(); + const hub: Auth = .{ .endpoint = try fake.endpoint(a), .bearer = "Bearer " ++ literal_token, .source = "HF_TOKEN" }; + try redirectAttack(a, &client, hub, mixedDepthAttack()); +} + +test "security KR66-2: mixed-depth hub credentials are refused in tree paths" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedTreeFixture; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr66-mixed-tree-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + try treeAttack(a, io, &fake, root, mixedDepthAttack()); +} + +test "security KR66-2: mixed-depth hub credentials are refused in EXLR8 HEAD redirects" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = headRedirectFixture; + fake.start(); + defer fake.stopServer(); + const hub: Auth = .{ .endpoint = try fake.endpoint(a), .bearer = "Bearer " ++ literal_token, .source = "HF_TOKEN" }; + var client = @import("pull_http.zig").client(a, std.testing.io); + defer client.deinit(); + const attack = mixedDepthAttack(); + resetAttack(attack.payload); + const authority = try std.fmt.allocPrint(a, "127.0.0.1:{d}", .{fake.port}); + head_location = try std.fmt.allocPrint(a, "http://{s}/storage?credential={s}", .{ authority, attack.payload }); + requests_after_head.store(0, .monotonic); + const result = runs.resolve(a, &client, hub, try std.fmt.allocPrint(a, "{s}/head", .{hub.endpoint})); + var caught: ?anyerror = null; + if (result) |_| {} else |err| caught = err; + try std.testing.expect(caught != null); + try std.testing.expectEqual(error.HubCredentialRedirect, caught.?); + try std.testing.expectEqual(@as(u32, 0), requests_after_head.load(.monotonic)); + try std.testing.expectEqual(@as(u32, 0), attack_requests.load(.monotonic)); + try expectAttackAbsent(attack, "", ""); +} + +test "security KR66-2: mixed-depth hub credentials are redacted from model_type" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const attack = mixedDepthAttack(); + resetAttack(attack.payload); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr66-mixed-model-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const env = try envWithToken(a, &fake, literal_token); + fake.config = try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\"}}", .{attack.payload}); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try expectAttackAbsent(attack, out.written(), err_out.written()); + try std.testing.expectEqual(@as(u32, 0), attack_requests.load(.monotonic)); + try std.testing.expectEqual(@as(u32, 0), fake.weight_requests.load(.monotonic)); + try std.testing.expect(std.mem.indexOf(u8, err_out.written(), "[redacted]") != null); +} diff --git a/zig/src/platform/credential.zig b/zig/src/platform/credential.zig new file mode 100644 index 00000000000..4106643107e --- /dev/null +++ b/zig/src/platform/credential.zig @@ -0,0 +1,260 @@ +//! Arbitrarily nested percent encoding matched against original spans, for containment and streaming redaction. +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const Match = struct { secret_len: usize = 0, consumed: usize = 0, hold: bool = false }; +pub const Span = struct { start: usize, end: usize }; + +/// A reusable matcher; memo entries retain every endpoint so nested escapes and literal bytes stay alternatives. +pub const Matcher = struct { + a: Allocator, + text: []const u8, + memo: std.AutoHashMap(Key, Result), + states: std.ArrayList(usize) = .empty, + next: std.ArrayList(usize) = .empty, + + const Key = struct { at: usize, byte: u8 }; + const Result = struct { + first: ?usize = null, + rest: []const usize = &.{}, + partial: bool = false, + + fn len(r: Result) usize { + return @as(usize, @intFromBool(r.first != null)) + r.rest.len; + } + + fn at(r: Result, index: usize) usize { + return if (index == 0) r.first.? else r.rest[index - 1]; + } + }; + const Ends = struct { + first: ?usize = null, + rest: std.ArrayList(usize) = .empty, + + fn len(e: Ends) usize { + return @as(usize, @intFromBool(e.first != null)) + e.rest.items.len; + } + + fn at(e: Ends, index: usize) usize { + return if (index == 0) e.first.? else e.rest.items[index - 1]; + } + }; + const Frame = struct { + key: Key, + ends: Ends = .{}, + partial: bool, + state: State, + + const Percent = struct { scan: usize = 0, two_index: usize = 0 }; + const Encoded = struct { pair: usize = 0, percent_index: usize = 0, high_index: usize = 0 }; + const State = union(enum) { percent: Percent, encoded: Encoded, finished: void }; + }; + + pub fn init(a: Allocator, text: []const u8) Matcher { + return .{ .a = a, .text = text, .memo = std.AutoHashMap(Key, Result).init(a) }; + } + + pub fn deinit(m: *Matcher) void { + var values = m.memo.valueIterator(); + while (values.next()) |value| if (value.rest.len > 0) m.a.free(value.rest); + m.memo.deinit(); + m.states.deinit(m.a); + m.next.deinit(m.a); + } + + /// The longest full key match at an original start; an unfinished later encoding holds the suffix. + pub fn secretAt(m: *Matcher, start: usize, secrets: anytype) Allocator.Error!Match { + var found: Match = .{}; + var hold = false; + for (secrets) |secret| { + if (secret.len == 0) continue; + const matched = try m.matchSecret(start, secret); + hold = hold or matched.hold; + // Longest original span, then longest key, regardless of which key completes first. + if (matched.consumed > found.consumed or (matched.consumed == found.consumed and matched.secret_len > found.secret_len)) found = matched; + } + found.hold = found.hold or hold; + return found; + } + + /// The leftmost-longest full occurrence of one secret at or after `start`. + pub fn spanFrom(m: *Matcher, start: usize, secret: []const u8) Allocator.Error!?Span { + if (secret.len == 0) return null; + var at = start; + while (at < m.text.len) : (at += 1) { + const matched = try m.matchSecret(at, secret); + if (matched.consumed > 0) return .{ .start = at, .end = at + matched.consumed }; + } + return null; + } + + fn matchSecret(m: *Matcher, start: usize, secret: []const u8) Allocator.Error!Match { + if (start > m.text.len) return .{}; + m.states.clearRetainingCapacity(); + m.next.clearRetainingCapacity(); + try m.states.append(m.a, start); + var states = &m.states; + var next = &m.next; + var hold = false; + for (secret) |wanted| { + next.clearRetainingCapacity(); + for (states.items) |at| { + if (at == m.text.len) { + hold = true; + continue; + } + if (m.text[at] != '%') { + if (m.text[at] == wanted) try appendUnique(m.a, next, at + 1); + continue; + } + const decoded = try m.decode(at, wanted); + hold = hold or decoded.partial; + for (0..decoded.len()) |index| try appendUnique(m.a, next, decoded.at(index)); + } + if (next.items.len == 0) return .{ .secret_len = secret.len, .hold = hold }; + const swap = states; + states = next; + next = swap; + } + var consumed: usize = 0; + for (states.items) |end| consumed = @max(consumed, end - start); + return .{ .secret_len = secret.len, .consumed = consumed, .hold = hold }; + } + + /// One byte's literal or `%XX` representations; nested dependencies use heap frames, not call recursion. + fn decode(m: *Matcher, at: usize, byte: u8) Allocator.Error!Result { + const wanted: Key = .{ .at = at, .byte = byte }; + if (m.memo.get(wanted)) |cached| return cached; + var work: std.ArrayList(Frame) = .empty; + defer { + for (work.items) |*frame| frame.ends.rest.deinit(m.a); + work.deinit(m.a); + } + try work.append(m.a, newFrame(m.text, wanted)); + frames: while (work.items.len > 0) { + const top = &work.items[work.items.len - 1]; + switch (top.state) { + .percent => |*state| { + // S('%') = literal '%' | S('%') S('2') S('5'); each dependency strictly advances. + while (state.scan < top.ends.len()) { + const two_key: Key = .{ .at = top.ends.at(state.scan), .byte = '2' }; + const two = m.memo.get(two_key) orelse { + try work.append(m.a, newFrame(m.text, two_key)); + continue :frames; + }; + top.partial = top.partial or two.partial; + if (state.two_index == two.len()) { + state.scan += 1; + state.two_index = 0; + continue; + } + const five_key: Key = .{ .at = two.at(state.two_index), .byte = '5' }; + const five = m.memo.get(five_key) orelse { + try work.append(m.a, newFrame(m.text, five_key)); + continue :frames; + }; + top.partial = top.partial or five.partial; + for (0..five.len()) |index| try add(m.a, &top.ends, five.at(index)); + state.two_index += 1; + } + top.state = .finished; + }, + .encoded => |*state| { + const percent_key: Key = .{ .at = top.key.at, .byte = '%' }; + const percent = m.memo.get(percent_key) orelse { + try work.append(m.a, newFrame(m.text, percent_key)); + continue :frames; + }; + top.partial = top.partial or percent.partial; + const digits = "0123456789ABCDEF"; + const high = digits[top.key.byte >> 4]; + const low = digits[top.key.byte & 15]; + while (state.pair < 4) { + if (state.percent_index == percent.len()) { + state.pair += 1; + state.percent_index = 0; + state.high_index = 0; + continue; + } + const hi = if (state.pair & 1 == 0) high else std.ascii.toLower(high); + const lo = if (state.pair & 2 == 0) low else std.ascii.toLower(low); + const high_key: Key = .{ .at = percent.at(state.percent_index), .byte = hi }; + const high_result = m.memo.get(high_key) orelse { + try work.append(m.a, newFrame(m.text, high_key)); + continue :frames; + }; + top.partial = top.partial or high_result.partial; + if (state.high_index == high_result.len()) { + state.percent_index += 1; + state.high_index = 0; + continue; + } + const low_key: Key = .{ .at = high_result.at(state.high_index), .byte = lo }; + const low_result = m.memo.get(low_key) orelse { + try work.append(m.a, newFrame(m.text, low_key)); + continue :frames; + }; + top.partial = top.partial or low_result.partial; + for (0..low_result.len()) |index| try add(m.a, &top.ends, low_result.at(index)); + state.high_index += 1; + } + top.state = .finished; + }, + .finished => { + const rest = if (top.ends.rest.items.len == 0) &.{} else try top.ends.rest.toOwnedSlice(m.a); + const result: Result = .{ .first = top.ends.first, .rest = rest, .partial = top.partial }; + errdefer if (rest.len > 0) m.a.free(rest); + try m.memo.put(top.key, result); + _ = work.pop(); + }, + } + } + return m.memo.get(wanted).?; + } + + fn newFrame(text: []const u8, key: Key) Frame { + var frame: Frame = .{ .key = key, .partial = key.at == text.len, .state = .finished }; + if (key.at < text.len and text[key.at] == key.byte) frame.ends.first = key.at + 1; + if (key.byte == '%') { + frame.state = .{ .percent = .{} }; + } else if (key.at < text.len and text[key.at] == '%') { + frame.state = .{ .encoded = .{} }; + } + return frame; + } +}; + +fn add(a: Allocator, ends: *Matcher.Ends, end: usize) Allocator.Error!void { + if (ends.first == null) { + ends.first = end; + return; + } + if (ends.first.? == end) return; + for (ends.rest.items) |present| if (present == end) return; + try ends.rest.append(a, end); +} + +fn appendUnique(a: Allocator, ends: *std.ArrayList(usize), end: usize) Allocator.Error!void { + for (ends.items) |present| if (present == end) return; + try ends.append(a, end); +} + +test "credential matcher: 1024 nested encodings use bounded call depth" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + var encoded: std.ArrayList(u8) = .empty; + try encoded.appendSlice(a, "a/b"); + for (0..1024) |_| { + var next: std.ArrayList(u8) = .empty; + for (encoded.items) |byte| { + if (byte == '%') try next.appendSlice(a, "%25") else try next.append(a, byte); + } + encoded = next; + } + var matcher = Matcher.init(std.testing.allocator, encoded.items); + defer matcher.deinit(); + const span = (try matcher.spanFrom(0, "a/b")).?; + try std.testing.expectEqual(@as(usize, 0), span.start); + try std.testing.expectEqual(encoded.items.len, span.end); +} diff --git a/zig/src/platform/sys.zig b/zig/src/platform/sys.zig index cb7077f55b7..c0835ecae1e 100644 --- a/zig/src/platform/sys.zig +++ b/zig/src/platform/sys.zig @@ -14,6 +14,8 @@ pub const env = if (windows) @import("win_c.zig") else struct { pub const environment = @import("environment.zig"); pub const atomic_file = @import("atomic_file.zig"); pub const folder_lock = @import("folder_lock.zig"); +/// Original-span matching through arbitrarily nested percent encoding. +pub const credential = @import("credential.zig"); /// std.posix, or its sockets, signals and limits over Winsock and console events. pub const posix = if (windows) @import("win_posix.zig") else std.posix; diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index a7dce626cc1..93ad231a3df 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -2,6 +2,7 @@ const std = @import("std"); const json = @import("json"); const suite = @import("benchmark_suite.zig"); +const credential = @import("sys").credential; const Allocator = std.mem.Allocator; const Value = json.Value; @@ -269,17 +270,17 @@ pub fn clean(a: Allocator, text: []const u8, limit: usize) ![]const u8 { return std.mem.trim(u8, out.items, " "); } -/// Terminal/error text with credentials replaced, longest first; bytes may be literal or one %XX escape. +/// Terminal/error text with credentials replaced, longest original span first at any encoding depth. pub fn redact(a: Allocator, text: []const u8, secrets: []const []const u8) ![]const u8 { - var scratch = try MatchScratch.init(a, text, secrets); - defer scratch.deinit(a); + var matcher = credential.Matcher.init(a, text); + defer matcher.deinit(); var scan: usize = 0; - while (scan < text.len and secretAt(text, scan, secrets, &scratch).consumed == 0) scan += 1; + while (scan < text.len and (try matcher.secretAt(scan, secrets)).consumed == 0) scan += 1; if (scan == text.len) return text; var out: std.ArrayList(u8) = .empty; var i: usize = 0; while (i < text.len) { - const found = secretAt(text, i, secrets, &scratch); + const found = try matcher.secretAt(i, secrets); if (found.consumed > 0) { try out.appendSlice(a, "[redacted]"); i += found.consumed; @@ -295,13 +296,13 @@ pub const RedactedPiece = struct { text: []const u8, rest: []const u8 }; /// One streamed piece: emit safe text and retain a suffix that may still become a credential. pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) !RedactedPiece { - var scratch = try MatchScratch.init(a, text, secrets); - defer scratch.deinit(a); + var matcher = credential.Matcher.init(a, text); + defer matcher.deinit(); var out: std.ArrayList(u8) = .empty; var changed = false; var i: usize = 0; while (i < text.len) { - const found = secretAt(text, i, secrets, &scratch); + const found = try matcher.secretAt(i, secrets); const rest = text[i..]; if (found.consumed > 0 or found.hold) { if (!changed) { @@ -320,99 +321,6 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) return .{ .text = if (changed) out.items else text, .rest = "" }; } -const Match = struct { secret_len: usize = 0, consumed: usize = 0, hold: bool = false }; - -/// The longest complete credential at ``i``; ``hold`` outranks it only for a longer possible credential. -fn secretAt(text: []const u8, i: usize, secrets: []const []const u8, scratch: *MatchScratch) Match { - var found: Match = .{}; - var possible: usize = 0; - for (secrets) |secret| { - const m = matchSecret(text[i..], secret, scratch); - if (m.consumed > 0 and m.secret_len > found.secret_len) found = m; - if (m.hold) possible = @max(possible, m.secret_len); - } - found.hold = found.hold or possible > found.secret_len; - return found; -} - -const MatchScratch = struct { - states: []bool, - next: []bool, - - fn init(a: Allocator, text: []const u8, secrets: []const []const u8) !MatchScratch { - var longest: usize = 0; - for (secrets) |secret| longest = @max(longest, secret.len); - const has_percent = std.mem.indexOfScalar(u8, text, '%') != null; - const encoded_span = std.math.mul(usize, longest, 3) catch text.len; - const span = if (has_percent) @min(text.len, encoded_span) else 0; - const room = if (has_percent) span + 1 else 0; - const states = try a.alloc(bool, room); - errdefer a.free(states); - return .{ .states = states, .next = try a.alloc(bool, room) }; - } - - fn deinit(s: *MatchScratch, a: Allocator) void { - a.free(s.states); - a.free(s.next); - } -}; - -/// A raw or mixed single-layer percent-encoded match, or a proper prefix ending at ``rest``'s end. -fn matchSecret(rest: []const u8, secret: []const u8, scratch: *MatchScratch) Match { - if (secret.len == 0) return .{}; - if (std.mem.indexOfScalar(u8, rest, '%') == null) { - if (std.mem.startsWith(u8, rest, secret)) return .{ .secret_len = secret.len, .consumed = secret.len }; - if (rest.len < secret.len and std.mem.startsWith(u8, secret, rest)) return .{ .secret_len = secret.len, .hold = true }; - return .{}; - } - var states = scratch.states; - var next = scratch.next; - @memset(states, false); - states[0] = true; - var hold = false; - for (secret) |wanted| { - @memset(next, false); - var any = false; - for (states, 0..) |active, at| { - if (!active) continue; - if (at == rest.len) { - hold = true; - continue; - } - if (rest[at] == '%') { - const left = rest.len - at; - if (left < 3 and (left == 1 or std.ascii.isHex(rest[at + 1]))) hold = true; - if (at + 2 < states.len and left >= 3 and std.ascii.isHex(rest[at + 1]) and std.ascii.isHex(rest[at + 2])) { - const byte = (hex(rest[at + 1]).? << 4) | hex(rest[at + 2]).?; - if (byte == wanted) { - next[at + 3] = true; - any = true; - } - } - } - if (at + 1 < states.len and rest[at] == wanted) { - next[at + 1] = true; - any = true; - } - } - if (!any) return .{ .secret_len = secret.len, .hold = hold }; - const swap = states; - states = next; - next = swap; - } - var consumed: usize = 0; - for (states, 0..) |active, at| { - if (active) consumed = at; - } - return .{ .secret_len = secret.len, .consumed = consumed, .hold = hold }; -} - -fn hex(c: u8) ?u8 { - if (c >= '0' and c <= '9') return c - '0'; - const lower = std.ascii.toLower(c); - return if (lower >= 'a' and lower <= 'f') lower - 'a' + 10 else null; -} - /// The index past the escape sequence at ``i``: a CSI sequence through its final byte, else ESC and one more byte. fn afterEscape(text: []const u8, i: usize) usize { if (i + 1 >= text.len or text[i + 1] != '[') return @min(i + 2, text.len); diff --git a/zig/src/server/chat_cli_kp50_test.zig b/zig/src/server/chat_cli_kp50_test.zig index 08d5b001c87..ef5a79a614d 100644 --- a/zig/src/server/chat_cli_kp50_test.zig +++ b/zig/src/server/chat_cli_kp50_test.zig @@ -8,6 +8,14 @@ const ascii_key = "fixture-ascii/token+part"; const ascii_encoded = "fixture-ascii%2Ftoken%2Bpart"; const latin_key = "fixture-caf\u{e9}/ol\u{f1}"; const latin_encoded = "fixture-caf%E9%2Fol%F1"; +const repeated_keys = "a/b,fixture-caf\u{e9}"; +const repeated_whole = "a%252Fb a%25252Fb fixture-caf%25E9 fixture-caf%2525E9 fixture-caf%25C3%25A9 fixture-caf%2525C3%2525A9"; +const repeated_leaks = [_][]const u8{ + "a/b", "a%252Fb", "a%25252Fb", "%252Fb", "%25252Fb", "%2Fb", "2Fb", + "fixture-caf\u{e9}", "fixture-caf\xe9", "fixture-caf%25E9", "fixture-caf%2525E9", "%25E9", "%2525E9", "%E9", + "E9", "fixture-caf%25C3%25A9", "fixture-caf%2525C3%2525A9", "%25C3", "%2525C3", "%25A9", "%2525A9", + "%C3", "%A9", "C3", "A9", +}; fn postBody(f: *fake.Fake, wanted: usize) ![]const u8 { var seen: usize = 0; @@ -273,3 +281,130 @@ test "chat CLI: KP50 discovered encoded IDs leave neither the banner nor the fol try absent(shown.items, &.{ ascii_encoded, latin_encoded, "%2525", "a%25%62", "%62", "[redacted]25" }); try absent(try postBody(f, 0), &.{ ascii_encoded, latin_encoded, "%2525", "a%25%62", "%62", "[redacted]25" }); } + +test "chat CLI: KR66 encoded overlapping keys retain the suffix across deltas and history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const split = try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "%41%42"), + try delta(a, "%43%44"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ split, try successful(a, "next") })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "%41%42,ABCD"); + r.interactive = true; + r.input = "first\nsecond\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + for ([_][]const u8{ r.out.written(), r.err.written(), try postBody(f, 1) }) |text| + try absent(text, &.{ "%43%44", "[redacted]%43%44" }); +} + +test "chat CLI: KR66 encoded overlapping keys retain the suffix in HTTP and SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try httpError(a, "%41%42%43%44"), + try sseError(a, "%41%42%43%44"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "%41%42,ABCD"); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + for ([_][]const u8{ shown.items, try postBody(f, 0), try postBody(f, 1) }) |text| + try absent(text, &.{ "%43%44", "[redacted]%43%44" }); +} + +test "chat CLI: KR66 repeatedly encoded credentials leave neither content nor history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const split_ascii = try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "a%25"), + try delta(a, "2Fb"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); + const split_latin = try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "fixture-caf%25"), + try delta(a, "E9"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, repeated_whole), split_ascii, split_latin, try successful(a, "done"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", repeated_keys); + r.interactive = true; + r.input = "first\nsecond\nthird\nfourth\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + for ([_][]const u8{ r.out.written(), r.err.written(), try postBody(f, 3) }) |text| + try absent(text, &repeated_leaks); +} + +test "chat CLI: KR66 repeatedly encoded credentials are absent from HTTP and SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try httpError(a, repeated_whole), + try sseError(a, repeated_whole), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", repeated_keys); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try absent(shown.items, &repeated_leaks); +} + +test "chat CLI: KR66 repeatedly encoded IDs leave neither banner nor follow-up POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{repeated_whole}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "ok")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", repeated_keys); + var shown: std.ArrayList(u8) = .empty; + r.interactive = true; + r.input = "/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + r.interactive = false; + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + try absent(shown.items, &repeated_leaks); + try absent(try postBody(f, 0), &repeated_leaks); +} diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 4cbf13e36a1..5d095bd9c06 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -145,7 +145,6 @@ fn worldKeyed(r: *Run, replies: []const []const fake.Write, key_file: []const u8 .{ .method = "POST", .path = "/v1/chat/completions", .replies = replies }, }), key_file); } - test "start CLI: a missing fit or a refused download never invokes pull or serve" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -169,7 +168,6 @@ test "start CLI: a missing fit or a refused download never invokes pull or serve try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "download declined; nothing was downloaded") != null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); } - test "start CLI: an above-Latin-1 key is refused before model selection or pulls" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -186,7 +184,6 @@ test "start CLI: an above-Latin-1 key is refused before model selection or pulls for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, token) == null); } - test "start CLI: explicit consent shows sizes and pulls both pinned specs before a failed pull stops" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -215,7 +212,6 @@ test "start CLI: explicit consent shows sizes and pulls both pinned specs before try std.testing.expectEqual(@as(u8, 1), try r.command(&.{})); try std.testing.expectEqual(@as(usize, 2), r.pulls.items.len); } - const DownloadInterrupt = struct { var run: *Run = undefined; @@ -238,7 +234,6 @@ fn forkedDownload() !?u32 { _ = platform.c.waitpid(pid, &status, 0); return null; } - test "start CLI: Ctrl-C during a deferred download has its normal process effect" { if (builtin.os.tag != .macos and builtin.os.tag != .linux) return error.SkipZigTest; var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -253,7 +248,6 @@ test "start CLI: Ctrl-C during a deferred download has its normal process effect try std.testing.expect(platform.c.W.IFSIGNALED(status)); try std.testing.expect(platform.c.W.TERMSIG(status) == std.posix.SIG.INT); } - test "start CLI: an unpublished snapshot is not complete and cannot skip its pull" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -271,7 +265,6 @@ test "start CLI: an unpublished snapshot is not complete and cannot skip its pul try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "nothing was downloaded") != null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); } - test "start CLI: a cached model answers once, prints no key and --check reaps its serve child" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -298,7 +291,6 @@ test "start CLI: a cached model answers once, prints no key and --check reaps it for ([_][]const u8{ key, "user-key-must-not-leak" }) |secret| for ([_][]const u8{ r.out.written(), r.err.written(), args }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } - test "start CLI: a malformed cached config requires repair while valid caches skip pulls" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -317,7 +309,6 @@ test "start CLI: a malformed cached config requires repair while valid caches sk try std.testing.expectEqualStrings("Org/Model@" ++ revision, r.pulls.items[0]); try std.testing.expectEqualStrings("Org/Draft@" ++ draft_revision, r.pulls.items[1]); } - test "start CLI: managed first-reply failures redact every configured credential" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -348,7 +339,6 @@ test "start CLI: managed first-reply failures redact every configured credential try std.testing.expect(std.mem.indexOf(u8, errors.items, secret) == null); try std.testing.expect(std.mem.indexOf(u8, errors.items, "[redacted]") != null); } - test "start CLI: a failed first reply is fatal and still reaps its serve child" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -365,7 +355,6 @@ test "start CLI: a failed first reply is fatal and still reaps its serve child" try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "first reply failed: HTTP 500: generation failed") != null); try std.testing.expect(r.childGone()); } - test "start CLI: CUDA spawns its native sibling instead of the unsupported low-level serve child" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -382,7 +371,6 @@ test "start CLI: CUDA spawns its native sibling instead of the unsupported low-l try std.testing.expect(r.childGone()); try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(std.testing.io, try r.path("low-level-called"), .{})); } - test "start CLI: pre-M5 Metal starts Gemma-style rows without resolving pulling or passing a drafter" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -404,7 +392,6 @@ test "start CLI: pre-M5 Metal starts Gemma-style rows without resolving pulling try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Pulling Org/Model@" ++ revision) != null); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), r.root) == null); } - test "start CLI: pre-M5 Gemma consent counts only the selected model bytes" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -437,7 +424,6 @@ test "start CLI: pre-M5 Gemma consent counts only the selected model bytes" { try std.testing.expect(cuda.drafter != null); try std.testing.expectEqual(@as(u64, 21_483_957_916), cuda.download_bytes); } - test "start CLI: CUDA still resolves pulls and passes the selected drafter" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -457,7 +443,6 @@ test "start CLI: CUDA still resolves pulls and passes the selected drafter" { const want_drafter = try std.fmt.allocPrint(a, "--drafter\n{s}", .{drafter}); try std.testing.expect(std.mem.indexOf(u8, args, want_drafter) != null); } - test "start CLI: persistent mode requires a valid environment credential before model work" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -484,7 +469,6 @@ test "start CLI: persistent mode requires a valid environment credential before try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); } } - test "start CLI: persistent caller keys preserve the child list and send only the first key" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -527,7 +511,6 @@ test "start CLI: persistent caller keys preserve the child list and send only th for ([_][]const u8{ caller_key, second_key, second_key[0..8], key_list }) |secret| for ([_][]const u8{ args, r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } - test "start CLI: a managed first reply authenticates Latin-1 and removes terminal controls" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -568,7 +551,6 @@ test "start CLI: a managed first reply authenticates Latin-1 and removes termina } } } - test "start CLI: managed logs redact percent-encoded ASCII and Latin-1 credentials" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -595,3 +577,24 @@ test "start CLI: managed logs redact percent-encoded ASCII and Latin-1 credentia for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } +test "start CLI: KR66 managed logs redact repeatedly encoded ASCII and Latin-1 credentials" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.env.put("TENSORFOLD_API_KEY", "a/b,fixture-caf\u{e9}"); + try r.env.put("START_TEST_SHORT_LIVED", "1"); + try r.env.put("START_TEST_LOG_ENCODED", "a%252Fb a%25252Fb fixture-caf%25E9 fixture-caf%2525E9 fixture-caf%25C3%25A9 fixture-caf%2525C3%2525A9"); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = "a/b" }); + const f = try worldKeyed(&r, try events(a, "Ready."), try r.path("credential")); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--startup-timeout", "2" })); + try std.testing.expect(r.childGone()); + for ([_][]const u8{ "a/b", "a%252Fb", "a%25252Fb", "%252Fb", "%25252Fb", "%2Fb", "2Fb", "fixture-caf\u{e9}", "fixture-caf\xe9", "fixture-caf%25E9", "fixture-caf%2525E9", "%25E9", "%2525E9", "%E9", "E9", "fixture-caf%25C3%25A9", "fixture-caf%2525C3%2525A9", "%25C3", "%2525C3", "%25A9", "%2525A9", "%C3", "%A9", "C3", "A9" }) |secret| + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| + try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} From 6b271fa20c54372f8be16a43e6d84996d58b77b7 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:01:51 +0000 Subject: [PATCH 094/361] security: contain transformed credential output Sanitize server text before matching, redact before truncation, and validate final candidates. Track transformed streaming holds and drop unresolved suffixes. Control-split keys, 255-byte prefixes, exact replacement markers and marker-synthesized keys failed before this change; all 198 focused host tests now pass. --- zig/src/cli/pull.zig | 11 +- zig/src/cli/pull_kp50_test.zig | 64 +++++ zig/src/platform/credential.zig | 11 + zig/src/server/benchmark_server.zig | 4 +- zig/src/server/benchmark_sse.zig | 103 +++++++- zig/src/server/chat_cli.zig | 19 +- zig/src/server/chat_cli_kr67_test.zig | 336 +++++++++++++++++++++++++ zig/src/server/chat_cli_reply.zig | 34 +-- zig/src/server/chat_cli_turn.zig | 26 +- zig/src/server/root.zig | 2 + zig/src/server/start_cli.zig | 16 +- zig/src/server/start_cli_kr67_test.zig | 165 ++++++++++++ zig/src/server/start_cli_test.zig | 6 +- 13 files changed, 740 insertions(+), 57 deletions(-) create mode 100644 zig/src/server/chat_cli_kr67_test.zig create mode 100644 zig/src/server/start_cli_kr67_test.zig diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index 9453754c5ca..39cb2a8d429 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -316,11 +316,16 @@ fn configKind(a: Allocator, bytes: []const u8) struct { model_type: []const u8, return .{ .model_type = model_type, .drafter = parsed.value.object.get("dflash_config") != null }; } -/// Server-controlled model text made safe for output, with its hub credential removed. +/// Server-controlled model text made safe for output, with final containment after every candidate choice. fn safeModelType(a: Allocator, text: []const u8, auth: Auth) ![]const u8 { const out = try auth.redact(a, text); - for (out) |ch| if (ch <= 0x20 or ch >= 0x7f) return "[unprintable model_type]"; - return out; + var printable = true; + for (out) |ch| if (ch <= 0x20 or ch >= 0x7f) { + printable = false; + break; + }; + const candidate = if (printable) out else "[unprintable model_type]"; + return if (auth.reflects(candidate)) "" else candidate; } /// Valid UTF-8 without terminal controls, for a path before it reaches a URL, log or local filename. diff --git a/zig/src/cli/pull_kp50_test.zig b/zig/src/cli/pull_kp50_test.zig index 0ad296cca5e..498a6d75813 100644 --- a/zig/src/cli/pull_kp50_test.zig +++ b/zig/src/cli/pull_kp50_test.zig @@ -9,6 +9,9 @@ const runs = @import("pull_runs.zig"); const single = @import("pull_file.zig"); const FakeHub = @import("pull_test.zig").FakeHub; const Map = std.process.Environ.Map; +const credential = @import("sys").credential; + +const redaction_marker = "[redacted]"; const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1"; const plain_token = "fixture-token"; @@ -47,6 +50,24 @@ fn expectAbsent(text: []const u8, secret: []const u8) !void { try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } +fn expectFinalContainment(a: Allocator, out: []const u8, err_out: []const u8, secret: []const u8) !void { + for ([_][]const u8{ out, err_out }) |text| { + var matcher = credential.Matcher.init(a, text); + defer matcher.deinit(); + try std.testing.expect((try matcher.spanFrom(0, secret)) == null); + } +} + +// Pull configures one active token, so marker synthesis stays within that one-token API. +fn markerModelType(a: Allocator, io: std.Io, fake: *FakeHub, root: []const u8, secret: []const u8, model_type: []const u8) !void { + const env = try envWithToken(a, fake, secret); + fake.config = try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\"}}", .{model_type}); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try expectFinalContainment(a, out.written(), err_out.written(), secret); +} + fn expectNoFile(io: std.Io, path: []const u8) !void { std.Io.Dir.cwd().access(io, path, .{}) catch |err| switch (err) { error.FileNotFound => return, @@ -455,3 +476,46 @@ test "security KR66-2: mixed-depth hub credentials are redacted from model_type" try std.testing.expectEqual(@as(u32, 0), fake.weight_requests.load(.monotonic)); try std.testing.expect(std.mem.indexOf(u8, err_out.written(), "[redacted]") != null); } + +test "security KR67-2: exact redaction-marker HF_TOKEN cannot survive model_type output" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr67-marker-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + try markerModelType(a, io, &fake, root, redaction_marker, redaction_marker); +} + +test "security KR67-2: redaction-marker substring HF_TOKEN cannot survive model_type output" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr67-substring-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + try markerModelType(a, io, &fake, root, "redacted", redaction_marker); +} + +test "security KR67-2: raw percent and nested-encoded redaction markers are contained in model_type output" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr67-encoded-marker-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const once = try encoded(a, redaction_marker); + const twice = try encoded(a, once); + for ([_][]const u8{ redaction_marker, once, twice }) |model_type| { + try markerModelType(a, io, &fake, root, redaction_marker, model_type); + } +} diff --git a/zig/src/platform/credential.zig b/zig/src/platform/credential.zig index 4106643107e..ea981fee384 100644 --- a/zig/src/platform/credential.zig +++ b/zig/src/platform/credential.zig @@ -239,6 +239,17 @@ fn appendUnique(a: Allocator, ends: *std.ArrayList(usize), end: usize) Allocator try ends.append(a, end); } +/// Whether any configured secret occurs literally or at any percent-encoding depth. +pub fn contains(a: Allocator, text: []const u8, secrets: []const []const u8) Allocator.Error!bool { + var matcher = Matcher.init(a, text); + defer matcher.deinit(); + for (secrets) |secret| { + if (secret.len == 0) continue; + if ((try matcher.spanFrom(0, secret)) != null) return true; + } + return false; +} + test "credential matcher: 1024 nested encodings use bounded call depth" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 34f32efd687..88975640627 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -303,14 +303,14 @@ pub fn lastLines(a: Allocator, log: []const u8) ![]const []const u8 { return lastLinesRedacted(a, log, &.{}); } -/// Select managed log lines only after credentials are removed and before their 300-byte terminal cut. +/// Select managed log lines after sanitization, redaction, limiting and final containment. pub fn lastLinesRedacted(a: Allocator, log: []const u8, secrets: []const []const u8) ![]const []const u8 { var picked: std.ArrayList([]const u8) = .empty; // newest first var fallback: []const u8 = ""; var hint: ?[]const u8 = null; var lines = std.mem.splitBackwardsAny(u8, log, "\r\n"); while (lines.next()) |line| { - const text = try sse.clean(a, try sse.redact(a, line, secrets), sse.line_limit); + const text = (try sse.cleanContained(a, line, secrets, sse.line_limit)) orelse continue; if (text.len == 0 or leakNoise(text)) continue; if (fallback.len == 0) fallback = text; if ((std.mem.startsWith(u8, text, "tensorfold:") or std.mem.startsWith(u8, text, "error:")) and picked.items.len < 3) { diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index 93ad231a3df..9322bc6fdb5 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -226,9 +226,12 @@ pub fn refusal(a: Allocator, status: u16, body: []const u8) ![]const u8 { /// Redact decoded JSON text or a plain body independently, before terminal truncation. pub fn refusalRedacted(a: Allocator, status: u16, body: []const u8, secrets: []const []const u8) ![]const u8 { const decoded = try errorText(a, body); - const text = try clean(a, try redact(a, decoded, secrets), line_limit); - if (text.len == 0) return std.fmt.allocPrint(a, "HTTP {d}", .{status}); - return std.fmt.allocPrint(a, "HTTP {d}: {s}", .{ status, text }); + const text = (try cleanContained(a, decoded, secrets, line_limit)) orelse ""; + const candidate = if (text.len == 0) + try std.fmt.allocPrint(a, "HTTP {d}", .{status}) + else + try std.fmt.allocPrint(a, "HTTP {d}: {s}", .{ status, text }); + return suppress(a, candidate, secrets); } /// ``error.message``, ``error``, ``message`` or ``detail`` of a JSON body, else a plain body's first line; markup: "". @@ -247,29 +250,85 @@ fn errorText(a: Allocator, body: []const u8) ![]const u8 { return text[0 .. std.mem.indexOfAny(u8, text, "\r\n") orelse text.len]; } -/// ``text`` without escape sequences, control characters or broken UTF-8, trimmed and cut to ``limit`` bytes. +/// ``text`` without escape sequences, controls or broken UTF-8, then trimmed and cut to ``limit`` bytes. pub fn clean(a: Allocator, text: []const u8, limit: usize) ![]const u8 { + return limited(a, try sanitizeLine(a, text), limit); +} + +pub const Sanitized = struct { text: []const u8, rest: []const u8 }; + +/// One line of server text without transformations that could reconstruct a credential after matching. +pub fn sanitizeLine(a: Allocator, text: []const u8) ![]const u8 { + return (try sanitizeInternal(a, text, false, false)).text; +} + +/// One streamed delta; an incomplete UTF-8 or escape suffix stays pending in its original bytes. +pub fn sanitizeStream(a: Allocator, text: []const u8) !Sanitized { + return sanitizeInternal(a, text, true, true); +} + +fn sanitizeInternal(a: Allocator, text: []const u8, multiline: bool, streaming: bool) !Sanitized { var out: std.ArrayList(u8) = .empty; var i: usize = 0; while (i < text.len) { if (text[i] == 0x1b) { + if (streaming and escapeIncomplete(text, i)) return .{ .text = out.items, .rest = text[i..] }; i = afterEscape(text, i); continue; } const len = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; + if (streaming and len > 0 and i + len > text.len) return .{ .text = out.items, .rest = text[i..] }; const cp: u21 = if (len > 0 and i + len <= text.len) std.unicode.utf8Decode(text[i .. i + len]) catch 0 else 0; i += if (cp == 0) 1 else len; - if (cp == '\t' or cp == '\n' or cp == '\r') try out.append(a, ' '); + if (cp == '\t' or cp == '\n' or cp == '\r') { + if (multiline) { + if (cp != '\r') try out.appendSlice(a, text[i - len .. i]); + } else try out.append(a, ' '); + continue; + } if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue; + try out.appendSlice(a, text[i - len .. i]); + } + return .{ .text = out.items, .rest = "" }; +} + +/// A byte limit applied only after sanitization and credential removal. +fn limited(a: Allocator, text: []const u8, limit: usize) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < text.len) { + const len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; if (out.items.len + len > limit) { try out.appendSlice(a, "..."); break; } - try out.appendSlice(a, text[i - len .. i]); + try out.appendSlice(a, text[i .. i + len]); + i += len; } return std.mem.trim(u8, out.items, " "); } +/// Sanitize, replace, check before limiting, then limit and check the exact final candidate. +pub fn cleanContained(a: Allocator, text: []const u8, secrets: []const []const u8, limit: usize) !?[]const u8 { + const replaced = try redact(a, try sanitizeLine(a, text), secrets); + if (try credential.contains(a, replaced, secrets)) return null; + const candidate = try limited(a, replaced, limit); + if (try credential.contains(a, candidate, secrets)) return null; + return candidate; +} + +/// Sanitize and redact without truncating; null means consume and suppress the candidate. +pub fn redactContained(a: Allocator, text: []const u8, secrets: []const []const u8) !?[]const u8 { + const candidate = try redact(a, try sanitizeLine(a, text), secrets); + if (try credential.contains(a, candidate, secrets)) return null; + return candidate; +} + +/// A generated candidate only when containment proves it safe; otherwise the empty terminal value. +pub fn suppress(a: Allocator, candidate: []const u8, secrets: []const []const u8) ![]const u8 { + return if (try credential.contains(a, candidate, secrets)) "" else candidate; +} + /// Terminal/error text with credentials replaced, longest original span first at any encoding depth. pub fn redact(a: Allocator, text: []const u8, secrets: []const []const u8) ![]const u8 { var matcher = credential.Matcher.init(a, text); @@ -321,10 +380,36 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) return .{ .text = if (changed) out.items else text, .rest = "" }; } -/// The index past the escape sequence at ``i``: a CSI sequence through its final byte, else ESC and one more byte. +pub const ContainedPiece = struct { emit: ?[]const u8, rest: []const u8 }; + +/// Transformed streamed output: suppress a complete key or hold a suffix that may become one later. +pub fn containedPiece(a: Allocator, text: []const u8, secrets: []const []const u8) !ContainedPiece { + var matcher = credential.Matcher.init(a, text); + defer matcher.deinit(); + var i: usize = 0; + while (i < text.len) : (i += 1) { + const found = try matcher.secretAt(i, secrets); + if (found.consumed > 0) return .{ .emit = null, .rest = "" }; + if (found.hold) return .{ .emit = text[0..i], .rest = text[i..] }; + } + return .{ .emit = text, .rest = "" }; +} + +/// Whether an ESC sequence needs another byte before it can be removed safely. +fn escapeIncomplete(text: []const u8, i: usize) bool { + if (i + 1 >= text.len) return true; + if (text[i + 1] != '[') return false; + var j = i + 2; + while (j < text.len and text[j] < 0x40) j += 1; + return j == text.len; +} + +/// Past the escape at ``i``: CSI through its final byte; otherwise ESC plus one ASCII byte, preserving Unicode. fn afterEscape(text: []const u8, i: usize) usize { - if (i + 1 >= text.len or text[i + 1] != '[') return @min(i + 2, text.len); + if (i + 1 >= text.len) return text.len; + if (text[i + 1] != '[') return if (text[i + 1] < 0x80) i + 2 else i + 1; var j = i + 2; - while (j < text.len and (text[j] < 0x40 or text[j] > 0x7e)) j += 1; + while (j < text.len and text[j] < 0x40) j += 1; + if (j < text.len and text[j] >= 0x80) return j; return @min(j + 1, text.len); } diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 868226a37eb..fbeaf42a591 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -142,8 +142,8 @@ fn served(ctx: *const Context, args: args_mod.Args, message: ?[]const u8) !u8 { try say(ctx.err, "Loading {s}; Ctrl-C cancels.", .{args.model.?}); var own = try child.start(setup, plan, &tail, &problem) orelse { if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); - const code = try fail(ctx, try credentials.redact(ctx.a, problem)); - try lastLines(ctx, tail, credentials); + const code = try fail(ctx, (try credentials.safe(ctx.a, problem)) orelse ""); + try lastLines(ctx, tail); return code; }; errdefer _ = own.managed.stop(); @@ -156,10 +156,10 @@ fn served(ctx: *const Context, args: args_mod.Args, message: ?[]const u8) !u8 { } /// An exited child's last log lines after its failure, as the benchmark prints them. -fn lastLines(ctx: *const Context, tail: []const []const u8, credentials: turn.Credentials) !void { - if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{try credentials.redact(ctx.a, tail[0])}); +fn lastLines(ctx: *const Context, tail: []const []const u8) !void { + if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{tail[0]}); if (tail.len > 1) try ctx.err.writeAll("Last server log lines:\n"); - if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{try credentials.redact(ctx.a, line)}); + if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{line}); try ctx.err.flush(); } @@ -190,10 +190,11 @@ const Session = struct { /// A failed turn said; a conversation goes on (null) unless the server it started has exited. fn failed(s: *Session, f: turn.Failure) !?u8 { const hint = if (f.status == 401) s.target.denied else null; - _ = try fail(s.ctx, if (hint) |h| try std.fmt.allocPrint(s.ctx.a, "{s}; {s}", .{ f.reason, h }) else f.reason); + const reason = if (hint) |h| try std.fmt.allocPrint(s.ctx.a, "{s}; {s}", .{ f.reason, h }) else f.reason; + _ = try fail(s.ctx, try s.target.credentials.check(s.ctx.a, reason)); if (comptime !windows) if (f.connect) if (s.target.own) |own| if (try own.managed.exitedTail(s.ctx.a)) |tail| { try s.ctx.err.writeAll("The model server has exited.\n"); - try lastLines(s.ctx, tail, s.target.credentials); + try lastLines(s.ctx, tail); return 1; }; return if (s.ctx.interactive) null else 1; @@ -326,8 +327,8 @@ fn discover(ctx: *const Context, chat_url: []const u8, target: Target) !Found { }; return .{ .problem = try std.fmt.allocPrint(ctx.a, "no model to chat with: {s} {s}; name one after the URL", .{ url, why }) }; }; - const name = if (target.model == null) try target.credentials.clean(ctx.a, raw_name, sse.line_limit) else raw_name; - return .{ .model = name, .thinking_switch = if (doc) |d| stream.thinkingSwitch(d, raw_name) else null }; + const name: ?[]const u8 = if (target.model == null) try target.credentials.clean(ctx.a, raw_name, sse.line_limit) else raw_name; + return .{ .model = name orelse return .{ .problem = try target.credentials.check(ctx.a, "the server supplied an unsafe model name") }, .thinking_switch = if (doc) |d| stream.thinkingSwitch(d, raw_name) else null }; } /// The first ``data[].id`` of a ``/v1/models`` document. diff --git a/zig/src/server/chat_cli_kr67_test.zig b/zig/src/server/chat_cli_kr67_test.zig new file mode 100644 index 00000000000..81509d408ae --- /dev/null +++ b/zig/src/server/chat_cli_kr67_test.zig @@ -0,0 +1,336 @@ +//! KR67 regressions for post-redaction cleaning and credential-valued replacement text. +const std = @import("std"); +const chat = @import("chat_cli.zig"); +const fake = @import("benchmark_fake.zig"); +const fixtures = @import("chat_cli_test.zig"); +const Allocator = std.mem.Allocator; + +const marker = "[redacted]"; +const marker_encoded = "%5Bredacted%5D"; +const marker_nested = "%255Bredacted%255D"; +const substring_encoded = "%72%65%64%61%63%74%65%64"; +const substring_nested = "%2572%2565%2564%2561%2563%2574%2565%2564"; +const marker_input = marker ++ " " ++ marker_encoded ++ " " ++ marker_nested ++ " redacted " ++ substring_encoded ++ " " ++ substring_nested; +const marker_secrets = [_][]const u8{ marker, "redacted", marker_encoded, marker_nested, substring_encoded, substring_nested }; +const synthesized = "prefix-[redacted]-suffix"; +const two_key_input = "prefix-token-suffix"; + +fn absent(text: []const u8, secrets: []const []const u8) !void { + for (secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} + +fn terminalCommand(r: *fixtures.Run, argv: []const []const u8) !u8 { + r.out.clearRetainingCapacity(); + r.err.clearRetainingCapacity(); + r.stdin = .fixed(r.input); + const ctx: chat.Context = .{ + .a = r.a, + .io = std.testing.io, + .environ = &r.env, + .out = &r.out.writer, + .err = &r.err.writer, + .input = r.reader orelse &r.stdin, + .interactive = r.interactive, + .terminal = true, + .self_exe = r.self_exe, + }; + return chat.command(&ctx, argv); +} + +fn postBody(f: *fake.Fake, wanted: usize) ![]const u8 { + var seen: usize = 0; + for (0..f.count()) |i| if (std.mem.eql(u8, f.request(i).method, "POST")) { + if (seen == wanted) return f.request(i).body; + seen += 1; + }; + return error.TestUnexpectedResult; +} + +fn postCount(f: *fake.Fake) usize { + var count: usize = 0; + for (0..f.count()) |i| count += @intFromBool(std.mem.eql(u8, f.request(i).method, "POST")); + return count; +} + +fn stream(a: Allocator, parts: []const []const u8) ![]const fake.Write { + var bytes: std.ArrayList(u8) = .empty; + try bytes.appendSlice(a, try fake.headOf(a, "200 OK", "text/event-stream")); + for (parts) |part| try bytes.appendSlice(a, part); + return a.dupe(fake.Write, &.{.{ .bytes = bytes.items }}); +} + +fn delta(a: Allocator, content: []const u8) ![]const u8 { + return fake.event(a, try std.fmt.allocPrint(a, "{{\"choices\": [{{\"index\": 0, \"delta\": {{\"content\": \"{s}\"}}, \"finish_reason\": null}}]}}", .{content})); +} + +fn successful(a: Allocator, content: []const u8) ![]const fake.Write { + return stream(a, try a.dupe([]const u8, &.{ + try delta(a, content), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); +} + +fn httpError(a: Allocator, message: []const u8) ![]const fake.Write { + return fake.jsonReply(a, "500 Internal Server Error", try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})); +} + +fn httpError401(a: Allocator, message: []const u8) ![]const fake.Write { + return fake.jsonReply(a, "401 Unauthorized", try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})); +} +fn sseError(a: Allocator, message: []const u8) ![]const fake.Write { + return stream(a, try a.dupe([]const u8, &.{ + try fake.event(a, try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})), + try fake.event(a, "[DONE]"), + })); +} + +fn controlMaterials(a: Allocator) !struct { key: []u8, split: []const u8, raw: []const u8 } { + const key = try a.alloc(u8, 256); + for (key, 0..) |*c, i| c.* = 'a' + @as(u8, @intCast(i % 26)); + const printable = "123456789012345678901234567890123456789012345"; + const split = try std.mem.concat(a, u8, &.{ printable, key[0..128], "\\u0001", key[128..] }); + const raw = try std.mem.concat(a, u8, &.{ printable, key[0..128], "\x01", key[128..] }); + return .{ .key = key, .split = split, .raw = raw }; +} + +fn expectClean(texts: []const []const u8, secrets: []const []const u8) !void { + for (texts) |text| try absent(text, secrets); +} + +test "chat CLI: KR67 ESC sanitization preserves adjacent Unicode in terminal and history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, "whole\\u001bé bracket\\u001b[é"), + try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "split\\u001b"), + try delta(a, "é csi\\u001b["), + try delta(a, "é"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })), + try successful(a, "done"), + })); + defer f.stop(); + r.interactive = true; + r.input = "whole\nsplit\nthird\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "wholeé bracketé") != null); + try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "splité csié") != null); + try std.testing.expect(std.mem.indexOf(u8, try postBody(f, 1), "whole\\u00e9 bracket\\u00e9") != null); + try std.testing.expect(std.mem.indexOf(u8, try postBody(f, 2), "split\\u00e9 csi\\u00e9") != null); +} + +test "chat CLI: KR67 control-split keys leave neither terminal streams, history nor HTTP and SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const control = try controlMaterials(a); + const errors = try std.mem.concat(a, u8, &.{ "A\\u0001B ", control.split }); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, "A\\u0001B"), + try successful(a, control.split), + try successful(a, "done"), + try httpError(a, errors), + try sseError(a, errors), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ "AB,", control.key })); + r.interactive = true; + r.input = "first\nsecond\nthird\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + var shown: std.ArrayList(u8) = .empty; + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + const secrets = [_][]const u8{ "AB", control.key, control.key[0..255] }; + try expectClean(&.{ shown.items, try postBody(f, 0), try postBody(f, 1), try postBody(f, 2) }, &secrets); + r.interactive = false; + r.input = "hi"; + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try expectClean(&.{ shown.items, try postBody(f, 3), try postBody(f, 4) }, &secrets); +} + +fn discoveryRun(a: Allocator, tmp: *std.testing.TmpDir, keys: []const u8, model: []const u8, secrets: []const []const u8) !void { + var r = try fixtures.Run.init(a, tmp); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{model}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "done")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", keys); + r.interactive = true; + r.input = "/bye\n"; + _ = try terminalCommand(&r, &.{ "--url", try f.url(a, "") }); + var shown: std.ArrayList(u8) = .empty; + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + r.interactive = false; + r.input = "hi"; + _ = try terminalCommand(&r, &.{ "--url", try f.url(a, "") }); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + try expectClean(&.{ shown.items, try postBody(f, 0) }, secrets); +} + +test "chat CLI: KR67 discovered control-split AB leaves neither its banner nor follow-up POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try discoveryRun(a, &tmp, "AB", "A\\u0001B", &.{"AB"}); +} + +test "chat CLI: KR67 discovery truncation exposes neither a split 256-byte key nor its 255-byte prefix" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const control = try controlMaterials(a); + try discoveryRun(a, &tmp, control.key, control.split, &.{ control.key, control.key[0..255] }); +} + +test "chat CLI: KR67 exact marker and substring keys vanish from raw and encoded streams and history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, marker_input), + try successful(a, marker_input), + try successful(a, "done"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "[redacted],redacted"); + r.interactive = true; + r.input = "first\nsecond\nthird\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try expectClean(&.{ r.out.written(), r.err.written(), try postBody(f, 0), try postBody(f, 1), try postBody(f, 2) }, &marker_secrets); +} + +test "chat CLI: KR67 exact marker and substring discovery suppresses the unsafe model before any POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{marker_input}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "unused")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "[redacted],redacted"); + r.interactive = true; + r.input = "/bye\n"; + _ = try terminalCommand(&r, &.{ "--url", try f.url(a, "") }); + try expectClean(&.{ r.out.written(), r.err.written() }, &marker_secrets); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); +} + +test "chat CLI: KR67 exact marker and substring keys vanish from HTTP and SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ try httpError(a, marker_input), try sseError(a, marker_input) })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "[redacted],redacted"); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + const url = try f.url(a, ""); + for (0..2) |_| { + _ = try terminalCommand(&r, &.{ "--url", url, "safe-model" }); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try expectClean(&.{ shown.items, try postBody(f, 0), try postBody(f, 1) }, &marker_secrets); +} + +test "chat CLI: KR67 containment runs after composing the HTTP 401 credential hint" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{try httpError401(a, "prefix")})); + defer f.stop(); + const synthesized_hint = "TENSORFOLD_API_KEY"; + try r.env.put("TENSORFOLD_API_KEY", synthesized_hint); + r.input = "hi"; + _ = try terminalCommand(&r, &.{ "--url", try f.url(a, ""), "safe-model" }); + try expectClean(&.{ r.out.written(), r.err.written(), try postBody(f, 0) }, &.{synthesized_hint}); +} + +test "chat CLI: KR67 token replacement cannot synthesize another key in streams or history" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, two_key_input), + try successful(a, two_key_input), + try successful(a, "done"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "token," ++ synthesized); + r.interactive = true; + r.input = "first\nsecond\nthird\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try expectClean(&.{ r.out.written(), r.err.written(), try postBody(f, 0), try postBody(f, 1), try postBody(f, 2) }, &.{ "token", synthesized }); +} + +test "chat CLI: KR67 synthesized-key discovery suppresses the unsafe model before any POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{two_key_input}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "unused")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "token," ++ synthesized); + r.interactive = true; + r.input = "/bye\n"; + _ = try terminalCommand(&r, &.{ "--url", try f.url(a, "") }); + try expectClean(&.{ r.out.written(), r.err.written() }, &.{ "token", synthesized }); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); +} + +test "chat CLI: KR67 token replacement cannot synthesize another key in HTTP or SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ try httpError(a, two_key_input), try sseError(a, two_key_input) })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "token," ++ synthesized); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + const url = try f.url(a, ""); + for (0..2) |_| { + _ = try terminalCommand(&r, &.{ "--url", url, "safe-model" }); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try expectClean(&.{ shown.items, try postBody(f, 0), try postBody(f, 1) }, &.{ "token", synthesized }); +} diff --git a/zig/src/server/chat_cli_reply.zig b/zig/src/server/chat_cli_reply.zig index c8d9c256c7a..838a723cc4a 100644 --- a/zig/src/server/chat_cli_reply.zig +++ b/zig/src/server/chat_cli_reply.zig @@ -37,21 +37,23 @@ pub const Reply = struct { try r.flush(.content); } - fn redacted(r: *Reply, kind: Kind, text: []const u8) ![]const u8 { + fn redacted(r: *Reply, kind: Kind, text: []const u8) !?[]const u8 { const state = streamFor(r, kind); const whole = if (state.pending.len > 0) try std.mem.concat(r.a, u8, &.{ state.pending, text }) else text; - const got = try sse.redactPiece(r.a, whole, r.secrets); - state.pending = got.rest; - return got.text; + const cleaned = try sse.sanitizeStream(r.a, whole); + const got = try sse.redactPiece(r.a, cleaned.text, r.secrets); + state.pending = if (got.rest.len == 0 and cleaned.rest.len == 0) "" else try std.mem.concat(r.a, u8, &.{ got.rest, cleaned.rest }); + const candidate = if (state.transformed.len > 0) try std.mem.concat(r.a, u8, &.{ state.transformed, got.text }) else got.text; + const checked = try sse.containedPiece(r.a, candidate, r.secrets); + state.transformed = checked.rest; + return checked.emit; } fn flush(r: *Reply, kind: Kind) Failure!void { const state = streamFor(r, kind); - if (state.pending.len == 0) return; - const text = "[redacted]"; + // Unresolved source or transformed suffixes are consumed, never replaced by an unchecked marker. state.pending = ""; - if (kind == .content) try r.content.appendSlice(r.a, text); - try r.sink.piece(r.sink.ctx, kind, text); + state.transformed = ""; } /// Bytes as they were read: whole lines are handled now, a cut line waits for the rest. @@ -108,13 +110,13 @@ pub const Reply = struct { const thought = delta.strField("reasoning_content") orelse delta.strField("reasoning"); if (thought) |t| if (t.len > 0) { r.reasoned = true; - const safe = try r.redacted(.reasoning, t); - if (safe.len > 0) try r.sink.piece(r.sink.ctx, .reasoning, safe); + if (try r.redacted(.reasoning, t)) |safe| if (safe.len > 0) try r.sink.piece(r.sink.ctx, .reasoning, safe); }; if (delta.strField("content")) |c| if (c.len > 0) { - const safe = try r.redacted(.content, c); - try r.content.appendSlice(r.a, safe); - if (safe.len > 0) try r.sink.piece(r.sink.ctx, .content, safe); + if (try r.redacted(.content, c)) |safe| { + try r.content.appendSlice(r.a, safe); + if (safe.len > 0) try r.sink.piece(r.sink.ctx, .content, safe); + } }; } if (choice.field("finish_reason")) |f| if (f == .string) { @@ -123,16 +125,16 @@ pub const Reply = struct { } }; -const Stream = struct { pending: []const u8 = "" }; +const Stream = struct { pending: []const u8 = "", transformed: []const u8 = "" }; fn streamFor(r: *Reply, kind: Kind) *Stream { return if (kind == .content) &r.answer_stream else &r.reason_stream; } -/// An error event's ``message`` with credentials removed before terminal cleaning and truncation. +/// An error event's ``message`` sanitized before matching and contained after every transformation. fn errorText(a: Allocator, e: json.Value, secrets: []const []const u8) ![]const u8 { const text = e.strField("message") orelse e.str() orelse "the server reported an error without a message"; - return sse.clean(a, try sse.redact(a, text, secrets), error_limit); + return (try sse.cleanContained(a, text, secrets, error_limit)) orelse ""; } const Seen = struct { diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index a59b0641260..e4abb91df94 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -32,13 +32,19 @@ pub const Credentials = struct { return .{ .forms = forms.items }; } - pub fn redact(c: Credentials, a: Allocator, text: []const u8) ![]const u8 { - return sse.redact(a, text, c.forms); + /// Sanitize and redact without truncating; null means consume and suppress. + pub fn safe(c: Credentials, a: Allocator, text: []const u8) !?[]const u8 { + return sse.redactContained(a, text, c.forms); } - /// Remove secrets before control cleaning and byte limiting can hide a suffix or split a match. - pub fn clean(c: Credentials, a: Allocator, text: []const u8, limit: usize) ![]const u8 { - return sse.clean(a, try c.redact(a, text), limit); + /// Sanitize before matching, redact before limiting, and contain the final candidate. + pub fn clean(c: Credentials, a: Allocator, text: []const u8, limit: usize) !?[]const u8 { + return sse.cleanContained(a, text, c.forms, limit); + } + + /// Containment-only validation for a composed or already-safe candidate. + pub fn check(c: Credentials, a: Allocator, text: []const u8) ![]const u8 { + return sse.suppress(a, text, c.forms); } }; @@ -93,7 +99,7 @@ pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credenti } if (x.failure) |f| { const reason = try x.reason(f, url); - return .{ .failed = .{ .reason = try credentials.redact(a, reason), .connect = f == .connect, .status = x.status } }; + return .{ .failed = .{ .reason = try credentials.check(a, reason), .connect = f == .connect, .status = x.status } }; } if (r.failure) |why| return .{ .failed = .{ .reason = why } }; if (!r.complete()) return .{ .failed = .{ .reason = "the server closed the stream before the reply finished" } }; @@ -176,7 +182,13 @@ const Exchange = struct { .connect => try std.fmt.allocPrint(x.a, "could not reach the server at {s}", .{url}), .lost => "the connection to the server broke during the reply", .http => try sse.refusalRedacted(x.a, x.status, x.refused, x.credentials.forms), - .not_events => try std.fmt.allocPrint(x.a, "the server answered with {s}, not an event stream", .{try x.credentials.clean(x.a, x.content_type, sse.line_limit)}), + .not_events => blk: { + const text = (try x.credentials.clean(x.a, x.content_type, sse.line_limit)) orelse ""; + break :blk if (text.len == 0) + "the server did not answer with an event stream" + else + try std.fmt.allocPrint(x.a, "the server answered with {s}, not an event stream", .{text}); + }, .stream => "the server sent a malformed event stream", .output => "could not write the reply", }; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index aee28f56e7d..562f6d9885e 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -318,6 +318,8 @@ test { if (comptime @import("builtin").os.tag != .windows) { _ = @import("chat_cli_child.zig"); _ = @import("chat_cli_test.zig"); + _ = @import("chat_cli_kr67_test.zig"); + _ = @import("start_cli_kr67_test.zig"); } } diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 1db1aebe360..e17211fa820 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -189,8 +189,8 @@ fn serve(ctx: *const Context, args: Args, choice: registry.Choice, caller_key: ? try say(ctx.err, "Loading {s}; Ctrl-C cancels", .{choice.entry.repo}); var own = try child.start(setup, plan, &tail, &problem) orelse { if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); - const code = try fail(ctx, 1, "{s}", .{try credentials.redact(ctx.a, problem)}); - try lastLines(ctx, tail, credentials); + const code = try fail(ctx, 1, "{s}", .{(try credentials.safe(ctx.a, problem)) orelse ""}); + try lastLines(ctx, tail); return code; }; errdefer _ = own.managed.stop(); @@ -205,7 +205,7 @@ fn serve(ctx: *const Context, args: Args, choice: registry.Choice, caller_key: ? return 0; } try say(ctx.out, "Serving {s} at {s}/v1; Ctrl-C stops the server", .{ own.served, own.managed.base() }); - return wait(ctx, &own, credentials); + return wait(ctx, &own); } /// One deterministic short request proves answer content, not only a listening socket. @@ -226,7 +226,7 @@ fn firstReply(ctx: *const Context, own: *Child, credentials: turn.Credentials) ! } /// Keep the checked server in the foreground until a signal or its own exit. -fn wait(ctx: *const Context, own: *Child, credentials: turn.Credentials) !u8 { +fn wait(ctx: *const Context, own: *Child) !u8 { while (true) { if (stop.requested()) |sig| { if (own.managed.stop()) |why| try say(ctx.err, "tensorfold start: {s}", .{why}); @@ -234,17 +234,17 @@ fn wait(ctx: *const Context, own: *Child, credentials: turn.Credentials) !u8 { } if (try own.managed.exitedTail(ctx.a)) |tail| { const code = try fail(ctx, 1, "the model server exited after its successful first reply", .{}); - try lastLines(ctx, tail, credentials); + try lastLines(ctx, tail); return code; } ctx.io.sleep(.fromMilliseconds(200), .awake) catch {}; } } -fn lastLines(ctx: *const Context, tail: []const []const u8, credentials: turn.Credentials) !void { - if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{try credentials.redact(ctx.a, tail[0])}); +fn lastLines(ctx: *const Context, tail: []const []const u8) !void { + if (tail.len == 1) try ctx.err.print("Last server log line: {s}\n", .{tail[0]}); if (tail.len > 1) try ctx.err.writeAll("Last server log lines:\n"); - if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{try credentials.redact(ctx.a, line)}); + if (tail.len > 1) for (tail) |line| try ctx.err.print(" {s}\n", .{line}); try ctx.err.flush(); } diff --git a/zig/src/server/start_cli_kr67_test.zig b/zig/src/server/start_cli_kr67_test.zig new file mode 100644 index 00000000000..6128e45a736 --- /dev/null +++ b/zig/src/server/start_cli_kr67_test.zig @@ -0,0 +1,165 @@ +//! KR67 managed-log containment through the start command's local fake server and child. +const std = @import("std"); +const start = @import("start_cli.zig"); +const registry = @import("checkpoint_cli").start; +const machine_mod = @import("sys").machine; +const fake = @import("benchmark_fake.zig"); +const stop = @import("benchmark_stop.zig"); +const Allocator = std.mem.Allocator; + +const revision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const draft_revision = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const gib = machine_mod.gib; +const entries = [_]registry.Entry{ + .{ .title = "Fixture", .format = "4-bit", .repo = "Org/Model", .revision = revision, .drafter = "Org/Draft", .drafter_revision = draft_revision, .download = 5 * gib, .metal = true, .cuda = true, .m5 = .drafts, .recipe = "fixture" }, +}; +const marker_input = "[redacted] %5Bredacted%5D %255Bredacted%255D redacted %72%65%64%61%63%74%65%64 %2572%2565%2564%2561%2563%2574%2565%2564"; +const marker_secrets = [_][]const u8{ + "[redacted]", + "redacted", + "%5Bredacted%5D", + "%255Bredacted%255D", + "%72%65%64%61%63%74%65%64", + "%2572%2565%2564%2561%2563%2574%2565%2564", +}; + +const Run = struct { + a: Allocator, + env: std.process.Environ.Map, + dir: []const u8, + root: []const u8, + out: std.Io.Writer.Allocating, + err: std.Io.Writer.Allocating, + stdin: std.Io.Reader = .fixed(""), + self_exe: ?[]const u8 = null, + machine: machine_mod.Machine = .{ .backend = .metal, .memory = 96 * gib, .gpu_limit = 64 * gib }, + catalog: []const registry.Entry = &entries, + pulls: std.ArrayList([]const u8) = .empty, + + fn init(a: Allocator, tmp: *std.testing.TmpDir) !Run { + var r: Run = .{ .a = a, .env = .init(a), .dir = try fake.tmpPath(a, tmp), .root = undefined, .out = .init(a), .err = .init(a) }; + r.machine.setChip("Apple M5 Max"); + r.root = try r.path("hub"); + try r.env.put("PATH", "/usr/bin:/bin"); + for ([_][]const u8{ "TMPDIR", "HOME", "HF_HUB_CACHE" }) |name| try r.env.put(name, if (std.mem.eql(u8, name, "HF_HUB_CACHE")) r.root else r.dir); + return r; + } + + fn path(r: *const Run, name: []const u8) ![]const u8 { + return std.fs.path.join(r.a, &.{ r.dir, name }); + } + + fn command(r: *Run) !u8 { + r.out.clearRetainingCapacity(); + r.err.clearRetainingCapacity(); + const ctx: start.Context = .{ + .a = r.a, + .io = std.testing.io, + .environ = &r.env, + .out = &r.out.writer, + .err = &r.err.writer, + .input = &r.stdin, + .interactive = false, + .self_exe = r.self_exe, + .given = r.machine, + .registry = r.catalog, + .override = r.root, + .pull = .{ .ctx = r, .run = fakePull }, + }; + return start.command(&ctx, &.{ "--startup-timeout", "2" }); + } + + fn fakePull(ctx: *anyopaque, spec: []const u8) !u8 { + const r: *Run = @ptrCast(@alignCast(ctx)); + try r.pulls.append(r.a, spec); + return 1; + } + + fn cache(r: *Run) !void { + const repo = try std.fs.path.join(r.a, &.{ r.root, "models--Org--Model" }); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ repo, "refs" })); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ repo, "snapshots", revision })); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "refs/main" }), .data = revision }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "snapshots", revision, "config.json" }), .data = "{\"model_type\": \"qwen4_exp\", \"quantization\": {\"bits\": 6, \"group_size\": 32}}" }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ repo, "snapshots", revision, "model.safetensors" }), .data = "fixture" }); + const draft = try std.fs.path.join(r.a, &.{ r.root, "models--Org--Draft" }); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ draft, "refs" })); + try std.Io.Dir.cwd().createDirPath(std.testing.io, try std.fs.path.join(r.a, &.{ draft, "snapshots", draft_revision })); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "refs/main" }), .data = draft_revision }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fs.path.join(r.a, &.{ draft, "snapshots", draft_revision, "config.json" }), .data = "{\"model_type\": \"qwen4_exp_draft\"}" }); + } + + fn standIn(r: *Run, port: u16) !void { + const script = try r.path("serve-stand-in"); + const text = try std.fmt.allocPrint(r.a, "#!/bin/sh\necho $$ > {s}\nprintf '%s\\n' \"$@\" > {s}\nprintf '[tensorfold] serving Model at http://127.0.0.1:{d}/v1 (x)\\n'\nprintf '%s\\n' \"$START_TEST_LOG_ENCODED\" >&2\nexec sleep 1\n", .{ try r.path("pid"), try r.path("args"), port }); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = script, .data = text, .flags = .{ .permissions = .fromMode(0o755) } }); + r.self_exe = script; + } + + fn childGone(r: *Run) bool { + const text = std.Io.Dir.cwd().readFileAlloc(std.testing.io, r.path("pid") catch return false, r.a, .limited(64)) catch return false; + const pid = std.fmt.parseInt(std.posix.pid_t, std.mem.trim(u8, text, " \n"), 10) catch return false; + stop.releaseChild(pid); + std.posix.kill(pid, @fromBackingInt(0)) catch |e| return e == error.ProcessNotFound; + return false; + } +}; + +fn ready(a: Allocator) ![]const []const fake.Write { + const head = try fake.headOf(a, "200 OK", "text/event-stream"); + const body = try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"Ready.\"}, \"finish_reason\": \"stop\"}]}"); + const writes = try a.dupe(fake.Write, &.{.{ .bytes = try std.mem.concat(a, u8, &.{ head, body, try fake.event(a, "[DONE]") }) }}); + return a.dupe([]const fake.Write, &.{writes}); +} + +fn world(r: *Run) !*fake.Fake { + return fake.Fake.startKeyed(std.testing.allocator, try r.a.dupe(fake.Route, &.{ + .{ .method = "GET", .path = "/health", .replies = try r.a.dupe([]const fake.Write, &.{try fake.jsonReply(r.a, "200 OK", "{\"status\": \"ok\", \"warming\": false}")}) }, + .{ .method = "GET", .path = "/v1/models", .replies = try r.a.dupe([]const fake.Write, &.{try fake.jsonReply(r.a, "200 OK", "{\"data\": [{\"id\": \"Model\"}]}")}) }, + .{ .method = "POST", .path = "/v1/chat/completions", .replies = try ready(r.a) }, + }), try r.path("credential")); +} + +fn managedRun(a: Allocator, tmp: *std.testing.TmpDir, keys: []const u8, first_key: []const u8, log: []const u8, secrets: []const []const u8) !void { + var r = try Run.init(a, tmp); + try r.env.put("TENSORFOLD_API_KEY", keys); + try r.env.put("START_TEST_LOG_ENCODED", log); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = first_key }); + const f = try world(&r); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command()); + try std.testing.expect(r.childGone()); + try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| + for (secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} + +fn controlMaterials(a: Allocator) !struct { key: []u8, raw: []const u8 } { + const key = try a.alloc(u8, 256); + for (key, 0..) |*c, i| c.* = 'a' + @as(u8, @intCast(i % 26)); + const printable = "123456789012345678901234567890123456789012345"; + return .{ .key = key, .raw = try std.mem.concat(a, u8, &.{ printable, key[0..128], "\x01", key[128..] }) }; +} + +test "start CLI: KR67 managed logs contain neither control-split keys nor their 255-byte prefixes" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const control = try controlMaterials(a); + const keys = try std.mem.concat(a, u8, &.{ "AB,", control.key }); + const log = try std.mem.concat(a, u8, &.{ "A\x01B\n", control.raw }); + try managedRun(a, &tmp, keys, "AB", log, &.{ "AB", control.key, control.key[0..255] }); +} + +test "start CLI: KR67 managed logs contain no exact marker, substring or encoded marker credentials" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try managedRun(a, &tmp, "[redacted],redacted", "[redacted]", marker_input, &marker_secrets); +} diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 5d095bd9c06..55371fbfc1a 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -9,14 +9,12 @@ const fake = @import("benchmark_fake.zig"); const stop = @import("benchmark_stop.zig"); const stream = @import("benchmark_stream.zig"); const Allocator = std.mem.Allocator; - const revision = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const draft_revision = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; const gib = machine_mod.gib; const entries = [_]registry.Entry{ .{ .title = "Fixture", .format = "4-bit", .repo = "Org/Model", .revision = revision, .drafter = "Org/Draft", .drafter_revision = draft_revision, .download = 5 * gib, .metal = true, .cuda = true, .m5 = .drafts, .recipe = "fixture" }, }; - const Run = struct { a: Allocator, env: std.process.Environ.Map, @@ -126,7 +124,6 @@ const Run = struct { return false; } }; - fn events(a: Allocator, content: []const u8) ![]const []const fake.Write { const head = try fake.headOf(a, "200 OK", "text/event-stream"); const body = try fake.event(a, try std.fmt.allocPrint(a, "{{\"choices\": [{{\"index\": 0, \"delta\": {{\"content\": \"{s}\"}}, \"finish_reason\": \"stop\"}}]}}", .{content})); @@ -598,3 +595,6 @@ test "start CLI: KR66 managed logs redact repeatedly encoded ASCII and Latin-1 c for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); } +test { + _ = @import("start_cli_kr67_test.zig"); +} From d25ed1a8c51fbd342871060c96ffa1361357b1d2 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:47:47 +0000 Subject: [PATCH 095/361] security: close KR69 containment gaps --- zig/src/cli/pull.zig | 2 +- zig/src/cli/pull_kp50_test.zig | 25 ++ zig/src/server/benchmark_sse.zig | 124 ++++++++- zig/src/server/chat_cli.zig | 6 +- zig/src/server/chat_cli_kr69_test.zig | 339 +++++++++++++++++++++++++ zig/src/server/chat_cli_reply.zig | 72 ++++++ zig/src/server/chat_cli_turn.zig | 65 +++++ zig/src/server/root.zig | 1 + zig/src/server/start_cli_kr67_test.zig | 13 + 9 files changed, 635 insertions(+), 12 deletions(-) create mode 100644 zig/src/server/chat_cli_kr69_test.zig diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index 39cb2a8d429..af20d9703bb 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -105,7 +105,7 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W if (kind.drafter) { try out.print("{s}: DFlash2 drafter ({s}), for serve --drafter\n", .{ repo, try safeModelType(a, model_type, auth) }); } else if (hub.family(model_type)) |family| { - try out.print("{s}: {s} ({s})\n", .{ repo, family.title, family.model_type }); + try out.print("{s}: {s} ({s})\n", .{ repo, family.title, try safeModelType(a, family.model_type, auth) }); } else { try err_out.print("{s}: no registered Zig family serves model_type {s}; the 0.6 line may: tensorfold@0.6\n", .{ repo, try safeModelType(a, model_type, auth) }); return 1; diff --git a/zig/src/cli/pull_kp50_test.zig b/zig/src/cli/pull_kp50_test.zig index 498a6d75813..70ecdb3bb6e 100644 --- a/zig/src/cli/pull_kp50_test.zig +++ b/zig/src/cli/pull_kp50_test.zig @@ -519,3 +519,28 @@ test "security KR67-2: raw percent and nested-encoded redaction markers are cont try markerModelType(a, io, &fake, root, redaction_marker, model_type); } } + +test "security KR69-4: a registered family and raw or nested model types contain the HF token" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr69-family-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + const secret = "qwen4_exp"; + const env = try envWithToken(a, &fake, secret); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 0), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try expectFinalContainment(a, out.written(), err_out.written(), secret); + try std.testing.expect(std.mem.indexOf(u8, out.written(), "Qwen3.8 Flash Next ([redacted])") != null); + + const once = try encoded(a, secret); + const twice = try encoded(a, once); + for ([_][]const u8{ once, twice }) |model_type| { + try markerModelType(a, io, &fake, root, secret, model_type); + } +} diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index 9322bc6fdb5..c3ad25ab66a 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -311,22 +311,22 @@ fn limited(a: Allocator, text: []const u8, limit: usize) ![]const u8 { /// Sanitize, replace, check before limiting, then limit and check the exact final candidate. pub fn cleanContained(a: Allocator, text: []const u8, secrets: []const []const u8, limit: usize) !?[]const u8 { const replaced = try redact(a, try sanitizeLine(a, text), secrets); - if (try credential.contains(a, replaced, secrets)) return null; + if (try containsSensitive(a, replaced, secrets)) return null; const candidate = try limited(a, replaced, limit); - if (try credential.contains(a, candidate, secrets)) return null; + if (try containsSensitive(a, candidate, secrets)) return null; return candidate; } /// Sanitize and redact without truncating; null means consume and suppress the candidate. pub fn redactContained(a: Allocator, text: []const u8, secrets: []const []const u8) !?[]const u8 { const candidate = try redact(a, try sanitizeLine(a, text), secrets); - if (try credential.contains(a, candidate, secrets)) return null; + if (try containsSensitive(a, candidate, secrets)) return null; return candidate; } /// A generated candidate only when containment proves it safe; otherwise the empty terminal value. pub fn suppress(a: Allocator, candidate: []const u8, secrets: []const []const u8) ![]const u8 { - return if (try credential.contains(a, candidate, secrets)) "" else candidate; + return if (try containsSensitive(a, candidate, secrets)) "" else candidate; } /// Terminal/error text with credentials replaced, longest original span first at any encoding depth. @@ -372,6 +372,15 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) if (found.hold) return .{ .text = out.items, .rest = rest }; try out.appendSlice(a, "[redacted]"); i += found.consumed; + continue; + } + const prefix = try sensitivePrefix(a, rest, secrets); + if (prefix > 0) { + if (!changed) { + try out.appendSlice(a, text[0..i]); + changed = true; + } + i += prefix; } else { if (changed) try out.append(a, text[i]); i += 1; @@ -380,19 +389,67 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) return .{ .text = if (changed) out.items else text, .rest = "" }; } +/// A possible first matcher byte; percent can begin any literal or nested encoding. +fn prefixStart(text: []const u8, secrets: []const []const u8) bool { + if (text.len == 0) return false; + if (text[0] == '%') return secrets.len > 0; + for (secrets) |secret| if (secret.len > 0 and secret[0] == text[0]) return true; + return false; +} + +/// The longest matched fragment exceeding two thirds of a credential before it is ruled out. +fn sensitivePrefix(a: Allocator, text: []const u8, secrets: []const []const u8) !usize { + if (!prefixStart(text, secrets)) return 0; + var sensitive: usize = 0; + for (1..text.len + 1) |end| { + var matcher = credential.Matcher.init(a, text[0..end]); + defer matcher.deinit(); + if (!(try matcher.secretAt(0, secrets)).hold) break; + sensitive = end; + } + for (secrets) |secret| if (secret.len > 1 and sensitive > (secret.len * 2) / 3) return sensitive; + return 0; +} + +/// Whether any complete credential or a disambiguated or unfinished credential prefix occurs. +fn containsSensitive(a: Allocator, text: []const u8, secrets: []const []const u8) !bool { + var matcher = credential.Matcher.init(a, text); + defer matcher.deinit(); + var i: usize = 0; + while (i < text.len) : (i += 1) { + const found = try matcher.secretAt(i, secrets); + if (found.consumed > 0) return true; + if (try sensitivePrefix(a, text[i..], secrets) > 0) return true; + } + return false; +} + pub const ContainedPiece = struct { emit: ?[]const u8, rest: []const u8 }; -/// Transformed streamed output: suppress a complete key or hold a suffix that may become one later. +/// Transformed streamed output: suppress complete keys and truncated prefixes, or hold a possible suffix. pub fn containedPiece(a: Allocator, text: []const u8, secrets: []const []const u8) !ContainedPiece { var matcher = credential.Matcher.init(a, text); defer matcher.deinit(); + var out: std.ArrayList(u8) = .empty; + var changed = false; var i: usize = 0; - while (i < text.len) : (i += 1) { + while (i < text.len) { const found = try matcher.secretAt(i, secrets); if (found.consumed > 0) return .{ .emit = null, .rest = "" }; - if (found.hold) return .{ .emit = text[0..i], .rest = text[i..] }; + if (found.hold) return .{ .emit = if (changed) out.items else text[0..i], .rest = text[i..] }; + const prefix = try sensitivePrefix(a, text[i..], secrets); + if (prefix > 0) { + if (!changed) { + try out.appendSlice(a, text[0..i]); + changed = true; + } + i += prefix; + } else { + if (changed) try out.append(a, text[i]); + i += 1; + } } - return .{ .emit = text, .rest = "" }; + return .{ .emit = if (changed) out.items else text, .rest = "" }; } /// Whether an ESC sequence needs another byte before it can be removed safely. @@ -413,3 +470,54 @@ fn afterEscape(text: []const u8, i: usize) usize { if (j < text.len and text[j] >= 0x80) return j; return @min(j + 1, text.len); } + +test "chat CLI: KR69 streaming suppresses disambiguated raw and nested credential prefixes" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_]struct { input: []const u8, expected: []const u8 }{ + .{ .input = "abcdX", .expected = "X" }, + .{ .input = "abc%64X", .expected = "X" }, + .{ .input = "abc%2564X", .expected = "X" }, + .{ .input = "abc%6X", .expected = "X" }, + .{ .input = "pre abcdX post", .expected = "pre X post" }, + }; + for (cases) |case| { + const got = try redactPiece(a, case.input, &.{"abcde"}); + try std.testing.expectEqualStrings(case.expected, got.text); + try std.testing.expectEqualStrings("", got.rest); + } +} + +test "chat CLI: KR69 transformed credential prefixes are not released by a suffix" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const checked = try containedPiece(a, "prefix-[redacted]X", &.{"prefix-[redacted]-suffix"}); + try std.testing.expectEqualStrings("X", checked.emit.?); + try std.testing.expectEqualStrings("", checked.rest); +} + +test "chat CLI: KR69 whole raw, nested and mid-escape credential prefixes are suppressed" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const secrets = [_][]const u8{"abcde"}; + for ([_][]const u8{ "abcd", "pre abcdX post", "abc%64", "abc%2564X", "abc%6X" }) |text| { + try std.testing.expectEqualStrings("", try suppress(a, text, &secrets)); + try std.testing.expect((try redactContained(a, text, &secrets)) == null); + try std.testing.expect((try cleanContained(a, text, &secrets, 2000)) == null); + } + try std.testing.expectEqualStrings("safe continuation", try suppress(a, "safe continuation", &secrets)); +} + +test "chat CLI: KR69 short coincidental credential openers leave safe text byte-identical" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const secrets = [_][]const u8{"example-key-1"}; + const streamed = try redactPiece(a, "Hello there!", &secrets); + try std.testing.expectEqualStrings("Hello there!", streamed.text); + try std.testing.expectEqualStrings("", streamed.rest); + try std.testing.expectEqualStrings("example-model", try suppress(a, "example-model", &secrets)); +} diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index fbeaf42a591..110942f23e2 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -177,7 +177,7 @@ const Session = struct { /// One message and its streamed reply, in an arena of its own that lives until the turn is kept. fn ask(s: *Session, a: Allocator, message: []const u8) !turn.Ended { - const request = try turn.body(a, s.settings, &s.history, message); + const request = try turn.checkedBody(a, s.settings, &s.history, message, s.target.credentials) orelse return .{ .failed = .{ .reason = "the serialized request contains configured credentials" } }; return turn.run(a, s.ctx.io, s.url, s.target.key, s.target.credentials, request, s.ctx.out, s.show); } @@ -228,9 +228,9 @@ fn session(ctx: *const Context, args: args_mod.Args, target: Target, message: ?[ const url = try stream.endpoint(ctx.a, target.base, true, &problem) orelse return fail(ctx, problem); const found = try discover(ctx, url, target); if (found.stopped) |sig| return stop.exitCode(sig); - const model = found.model orelse return fail(ctx, found.problem); + const model = found.model orelse return fail(ctx, try target.credentials.check(ctx.a, found.problem)); if (args.no_thinking and found.thinking_switch == false) - return fail(ctx, "--no-thinking: this model's chat template cannot turn thinking off (its /v1/models thinking_switch is false)"); + return fail(ctx, try target.credentials.check(ctx.a, "--no-thinking: this model's chat template cannot turn thinking off (its /v1/models thinking_switch is false)")); var s: Session = .{ .ctx = ctx, .url = url, diff --git a/zig/src/server/chat_cli_kr69_test.zig b/zig/src/server/chat_cli_kr69_test.zig new file mode 100644 index 00000000000..ccaaff68ee9 --- /dev/null +++ b/zig/src/server/chat_cli_kr69_test.zig @@ -0,0 +1,339 @@ +//! KR69 regressions at terminal, discovery, retained-history and serialized-POST boundaries. +const std = @import("std"); +const chat = @import("chat_cli.zig"); +const fake = @import("benchmark_fake.zig"); +const fixtures = @import("chat_cli_test.zig"); +const stop = @import("benchmark_stop.zig"); +const platform = @import("sys"); +const Allocator = std.mem.Allocator; + +fn terminalCommand(r: *fixtures.Run, argv: []const []const u8) !u8 { + r.out.clearRetainingCapacity(); + r.err.clearRetainingCapacity(); + r.stdin = .fixed(r.input); + const ctx: chat.Context = .{ + .a = r.a, + .io = std.testing.io, + .environ = &r.env, + .out = &r.out.writer, + .err = &r.err.writer, + .input = r.reader orelse &r.stdin, + .interactive = r.interactive, + .terminal = true, + .self_exe = r.self_exe, + }; + return chat.command(&ctx, argv); +} + +fn absent(text: []const u8, secrets: []const []const u8) !void { + for (secrets) |secret| try std.testing.expect(std.mem.indexOf(u8, text, secret) == null); +} + +fn postCount(f: *fake.Fake) usize { + var count: usize = 0; + for (0..f.count()) |i| count += @intFromBool(std.mem.eql(u8, f.request(i).method, "POST")); + return count; +} + +fn stream(a: Allocator, parts: []const []const u8) ![]const fake.Write { + var bytes: std.ArrayList(u8) = .empty; + try bytes.appendSlice(a, try fake.headOf(a, "200 OK", "text/event-stream")); + for (parts) |part| try bytes.appendSlice(a, part); + return a.dupe(fake.Write, &.{.{ .bytes = bytes.items }}); +} + +fn delta(a: Allocator, content: []const u8) ![]const u8 { + return fake.event(a, try std.fmt.allocPrint(a, "{{\"choices\": [{{\"index\": 0, \"delta\": {{\"content\": \"{s}\"}}, \"finish_reason\": null}}]}}", .{content})); +} + +fn successful(a: Allocator, content: []const u8) ![]const fake.Write { + return stream(a, try a.dupe([]const u8, &.{ + try delta(a, content), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })); +} + +fn httpError(a: Allocator, message: []const u8) ![]const fake.Write { + return fake.jsonReply(a, "500 Internal Server Error", try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})); +} + +fn sseError(a: Allocator, message: []const u8) ![]const fake.Write { + return stream(a, try a.dupe([]const u8, &.{ + try fake.event(a, try std.fmt.allocPrint(a, "{{\"error\": {{\"message\": \"{s}\"}}}}", .{message})), + try fake.event(a, "[DONE]"), + })); +} + +fn longKey(a: Allocator) ![]u8 { + const key = try a.alloc(u8, 256); + for (key, 0..) |*c, i| c.* = 'a' + @as(u8, @intCast(i % 26)); + return key; +} + +test "chat CLI: KR69 held raw and nested prefixes never reach output or a following POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "fixture-secre"), + try delta(a, "X"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })), + try successful(a, "fixture-secreX"), + try stream(a, try a.dupe([]const u8, &.{ + try delta(a, "%66ixture-secre%"), + try delta(a, "7X"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })), + try successful(a, "done"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "fixture-secret"); + r.interactive = true; + r.input = "one\ntwo\nthree\nlast\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + const attacks = [_][]const u8{ "fixture-secre", "%66ixture-secre" }; + try absent(r.out.written(), &attacks); + try absent(r.err.written(), &attacks); + try std.testing.expectEqual(@as(usize, 4), postCount(f)); + for (0..f.count()) |i| if (std.mem.eql(u8, f.request(i).method, "POST")) try absent(f.request(i).body, &attacks); +} + +test "chat CLI: KR69 already-truncated raw and nested credentials stay out of HTTP and SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const key = try longKey(a); + const raw = key[0..255]; + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try httpError(a, raw), + try sseError(a, "%66ixture-secre"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", try std.mem.concat(a, u8, &.{ key, ",fixture-secret" })); + r.input = "hi"; + var shown: std.ArrayList(u8) = .empty; + const url = try f.url(a, ""); + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", url, "safe-model" })); + try shown.appendSlice(a, r.out.written()); + try shown.appendSlice(a, r.err.written()); + } + try absent(shown.items, &.{ raw, "%66ixture-secre" }); +} + +test "chat CLI: KR69 an already-truncated discovered key suppresses the model before any POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const key = try longKey(a); + const raw = key[0..255]; + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{raw}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "unused")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", key); + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try absent(r.out.written(), &.{raw}); + try absent(r.err.written(), &.{raw}); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); +} + +fn discoveryFailure(a: Allocator, status: []const u8) !*fake.Fake { + return fake.Fake.startKeyed(std.testing.allocator, try a.dupe(fake.Route, &.{ + .{ .method = "GET", .path = "/v1/models", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, status, "{}")}) }, + }), null); +} + +test "chat CLI: KR69 discovery 401 contains its credential-valued hint" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try discoveryFailure(a, "401 Unauthorized"); + defer f.stop(); + const secret = "TENSORFOLD_API_KEY"; + try r.env.put("TENSORFOLD_API_KEY", secret); + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try absent(r.out.written(), &.{secret}); + try absent(r.err.written(), &.{secret}); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); +} + +test "chat CLI: KR69 generic discovery errors contain encoded credential URLs" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try discoveryFailure(a, "500 Internal Server Error"); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "credential-source"); + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, "/credential%2Dsource") })); + try absent(r.out.written(), &.{ "credential-source", "credential%2Dsource" }); + try absent(r.err.written(), &.{ "credential-source", "credential%2Dsource" }); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); +} + +test "chat CLI: KR69 no-thinking guidance passes final discovery containment" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const models = "{\"data\": [{\"id\": \"safe\", \"capabilities\": {\"thinking_switch\": false}}]}"; + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "unused")})); + defer f.stop(); + const secret = "thinking_switch"; + try r.env.put("TENSORFOLD_API_KEY", secret); + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, ""), "--no-thinking" })); + try absent(r.out.written(), &.{secret}); + try absent(r.err.written(), &.{secret}); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); +} + +fn unsafeModel(a: Allocator, secret: []const u8, model_json: []const u8) !void { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{model_json}); + const f = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "unused")})); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", secret); + r.input = "hi"; + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try std.testing.expectEqual(@as(usize, 0), postCount(f)); + try absent(r.out.written(), &.{secret}); + try absent(r.err.written(), &.{secret}); +} + +test "chat CLI: KR69 JSON model serialization cannot synthesize non-ASCII quote or backslash keys" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try unsafeModel(a, "\\u00e9", "\\u00e9"); + try unsafeModel(a, "\"", "\\\""); + try unsafeModel(a, "\\\"", "\\\\"); +} + +test "chat CLI: KR69 a finished Unicode reply cannot synthesize a key in the following history POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try successful(a, "é"), + try successful(a, "unused"), + })); + defer f.stop(); + const secret = "\\u00e9"; + try r.env.put("TENSORFOLD_API_KEY", secret); + r.interactive = true; + r.input = "first\nsecond\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try std.testing.expectEqual(@as(usize, 1), postCount(f)); + try absent(r.out.written(), &.{secret}); + try absent(r.err.written(), &.{secret}); + for (0..f.count()) |i| try absent(f.request(i).body, &.{secret}); +} + +const Pipe = struct { + fds: [2]std.posix.fd_t = .{ -1, -1 }, + buf: [256]u8 = undefined, + file: std.Io.File.Reader = undefined, + + fn open(p: *Pipe) bool { + if (platform.c.pipe(&p.fds) != 0) return false; + p.file = (std.Io.File{ .handle = p.fds[0], .flags = .{ .nonblocking = false } }).readerStreaming(std.testing.io, &p.buf); + return true; + } + + fn close(p: *Pipe) void { + for (p.fds) |fd| _ = platform.c.close(fd); + } + + fn send(p: *const Pipe, text: []const u8) void { + _ = platform.c.write(p.fds[1], text.ptr, text.len); + } +}; + +fn hasPost(f: *fake.Fake) bool { + return postCount(f) > 0; +} + +fn handled(_: void) bool { + return stop.requested() == null; +} + +fn waitFor(comptime ready: anytype, arg: anytype) bool { + var waited: u32 = 0; + while (waited < 5000) : (waited += 5) { + if (ready(arg)) return true; + fake.nap(5); + } + return false; +} + +test "chat CLI: KR69 a stopped Unicode reply cannot synthesize a key in the following history POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + stop.reset(); + defer stop.reset(); + var gate: std.Io.Event = .unset; + const trickle = try a.dupe(fake.Write, &.{ + .{ .bytes = try std.mem.concat(a, u8, &.{ try fake.headOf(a, "200 OK", "text/event-stream"), try delta(a, "é") }), .after = &gate }, + .{ .bytes = try delta(a, "unused") }, + }); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ trickle, try successful(a, "unused") })); + defer { + gate.set(io); + f.stop(); + } + var pipe: Pipe = .{}; + if (!pipe.open()) return error.SkipZigTest; + defer pipe.close(); + r.interactive = true; + r.reader = &pipe.file.interface; + const Typist = struct { + fn run(p: *const Pipe, fk: *fake.Fake, g: *std.Io.Event) void { + p.send("first\n"); + if (waitFor(hasPost, fk)) fake.nap(300); + stop.request(.INT); + if (!waitFor(handled, {})) g.set(std.testing.io); + p.send("second\n/bye\n"); + } + }; + const t = try std.Thread.spawn(.{}, Typist.run, .{ &pipe, f, &gate }); + defer t.join(); + try r.env.put("TENSORFOLD_API_KEY", "\\u00e9"); + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try std.testing.expectEqual(@as(usize, 1), postCount(f)); + for (0..f.count()) |i| try absent(f.request(i).body, &.{"\\u00e9"}); +} diff --git a/zig/src/server/chat_cli_reply.zig b/zig/src/server/chat_cli_reply.zig index 838a723cc4a..987203ff0bb 100644 --- a/zig/src/server/chat_cli_reply.zig +++ b/zig/src/server/chat_cli_reply.zig @@ -221,3 +221,75 @@ test "chat CLI: a stream that ends early, an event that is not JSON and an endle try long.feed("data: "); try std.testing.expectError(error.InvalidStream, long.feed(filler)); } + +fn contentDelta(a: Allocator, content: []const u8) ![]const u8 { + return std.fmt.allocPrint(a, "data: {{\"choices\": [{{\"index\": 0, \"delta\": {{\"content\": \"{s}\"}}, \"finish_reason\": null}}]}}\n\n", .{content}); +} + +const finishing_events = "data: {\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}\n\n" ++ + "data: [DONE]\n\n"; + +test "chat CLI: KR69 source prefixes stay out of terminal and history across SSE events" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_]struct { held: []const u8, continuation: []const u8 }{ + .{ .held = "abcd", .continuation = "X" }, + .{ .held = "abc%64", .continuation = "X" }, + .{ .held = "abc%2564", .continuation = "X" }, + .{ .held = "abc%6", .continuation = "X" }, + }; + for (cases) |case| { + var seen: Seen = .{ .a = a }; + var r: Reply = .{ .a = a, .sink = seen.sink(), .secrets = &.{"abcde"} }; + try r.feed(try contentDelta(a, case.held)); + try std.testing.expectEqualStrings("", seen.text.items); + try std.testing.expectEqualStrings("", r.content.items); + try r.feed(try contentDelta(a, case.continuation)); + try r.feed(finishing_events); + try r.end(); + try std.testing.expectEqualStrings("X", seen.text.items); + try std.testing.expectEqualStrings("X", r.content.items); + try std.testing.expect(r.complete()); + } +} + +test "chat CLI: KR69 transformed prefixes stay out of terminal and history across SSE events" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var seen: Seen = .{ .a = a }; + var r: Reply = .{ .a = a, .sink = seen.sink(), .secrets = &.{ "token", "[redacted]-suffix" } }; + try r.feed(try contentDelta(a, "token")); + try std.testing.expectEqualStrings("", seen.text.items); + try std.testing.expectEqualStrings("", r.content.items); + try r.feed(try contentDelta(a, "X")); + try r.feed(finishing_events); + try r.end(); + try std.testing.expectEqualStrings("X", seen.text.items); + try std.testing.expectEqualStrings("X", r.content.items); + try std.testing.expect(r.complete()); +} + +test "chat CLI: KR69 bytewise JSON reads cannot release a prefix and safe replies commit" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var seen: Seen = .{ .a = a }; + var cut: Reply = .{ .a = a, .sink = seen.sink(), .secrets = &.{"abcde"} }; + const bytes = try std.mem.concat(a, u8, &.{ try contentDelta(a, "abcdX"), finishing_events }); + for (0..bytes.len) |i| try cut.feed(bytes[i .. i + 1]); + try cut.end(); + try std.testing.expectEqualStrings("X", seen.text.items); + try std.testing.expectEqualStrings("X", cut.content.items); + try std.testing.expect(cut.complete()); + + var safe_seen: Seen = .{ .a = a }; + var safe: Reply = .{ .a = a, .sink = safe_seen.sink(), .secrets = &.{"abcde"} }; + try safe.feed(try contentDelta(a, "whole response")); + try safe.feed(finishing_events); + try safe.end(); + try std.testing.expectEqualStrings("whole response", safe_seen.text.items); + try std.testing.expectEqualStrings("whole response", safe.content.items); + try std.testing.expect(safe.complete()); +} diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index e4abb91df94..ccf7032fd83 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -1,5 +1,6 @@ //! One chat turn over HTTP: the request body, the streamed reply printed as it arrives, and how the turn ended. const std = @import("std"); +const credential = @import("sys").credential; const json = @import("json"); const stream = @import("benchmark_stream.zig"); const sse = @import("benchmark_sse.zig"); @@ -77,6 +78,13 @@ pub fn body(a: Allocator, s: Settings, history: *const History, user: []const u8 return json.stringify(a, .{ .object = o }, .{}); } +/// The exact serialized request, or null when credential containment suppresses it; null must never be POSTed. +pub fn checkedBody(a: Allocator, s: Settings, history: *const History, user: []const u8, credentials: Credentials) !?[]u8 { + const request = try body(a, s, history, user); + if (try credential.contains(a, request, credentials.forms)) return null; + return request; +} + /// One streamed turn to ``url``, the chat route, printed to ``out`` as it arrives; a stop signal ends it ``stopped``. pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credentials: Credentials, request: []u8, out: *std.Io.Writer, show: Show) !Ended { var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = io }; @@ -292,6 +300,63 @@ test "chat CLI: the request body sends the history, stream and only the settings "\"stream\": true, \"max_tokens\": 64, \"temperature\": 0.0, \"chat_template_kwargs\": {\"enable_thinking\": false}}", try body(a, .{ .model = "m", .temperature = 0, .max_tokens = 64, .no_thinking = true }, &h, "q")); } +test "chat CLI: final request containment catches JSON escape synthesis in model IDs and retained replies" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cases = [_]struct { secret: []const u8, decoded: []const u8 }{ + .{ .secret = "\\u00e9", .decoded = "\u{e9}" }, + .{ .secret = "\\n", .decoded = "\n" }, + .{ .secret = "\\\"", .decoded = "\"" }, + .{ .secret = "\\\\", .decoded = "\\" }, + }; + for (cases) |case| { + const secrets = [_][]const u8{case.secret}; + const credentials: Credentials = .{ .forms = &secrets }; + var retained: History = .{ .a = a }; + try retained.keep("question", case.decoded); + try std.testing.expect(std.mem.indexOf(u8, case.decoded, case.secret) == null); + const from_history = try body(a, .{ .model = "m" }, &retained, "next"); + try std.testing.expect(std.mem.indexOf(u8, from_history, case.secret) != null); + try std.testing.expect((try checkedBody(a, .{ .model = "m" }, &retained, "next", credentials)) == null); + + var empty: History = .{ .a = a }; + const from_model = try body(a, .{ .model = case.decoded }, &empty, "next"); + try std.testing.expect(std.mem.indexOf(u8, from_model, case.secret) != null); + try std.testing.expect((try checkedBody(a, .{ .model = case.decoded }, &empty, "next", credentials)) == null); + } +} + +test "chat CLI: final request containment catches a key completed by a retained backslash and structural quote" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const secret = [_]u8{ '\\', '"' }; + const escaped_end = [_]u8{ '\\', '\\', '"' }; + const forms = [_][]const u8{&secret}; + var h: History = .{ .a = a }; + try h.keep("question", "safe decoded reply ending in \\"); + try std.testing.expect(std.mem.indexOf(u8, h.turns.items[0].assistant, &secret) == null); + try std.testing.expect((try checkedBody(a, .{ .model = "m" }, &h, "next", .{ .forms = &forms })) == null); + const request = try body(a, .{ .model = "m" }, &h, "next"); + try std.testing.expect(std.mem.indexOf(u8, request, &escaped_end) != null); + try std.testing.expect(std.mem.indexOf(u8, request, &secret) != null); + try std.testing.expect((try checkedBody(a, .{ .model = "m" }, &h, "again", .{ .forms = &forms })) == null); + try std.testing.expectEqual(@as(usize, 1), h.turns.items.len); +} + +test "chat CLI: final request containment preserves an ordinary serialized body byte for byte" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const forms = [_][]const u8{ "\\u00e9", "\\n", "\\\"", "\\\\" }; + var h: History = .{ .a = a }; + try h.keep("one", "1"); + const expected = try body(a, .{ .model = "m" }, &h, "two"); + const checked = (try checkedBody(a, .{ .model = "m" }, &h, "two", .{ .forms = &forms })) orelse return error.TestUnexpectedResult; + try std.testing.expectEqualStrings(expected, checked); +} + test "chat CLI: on a terminal hidden reasoning shows a hint, shown reasoning is dimmed, and control characters are dropped" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 562f6d9885e..d5a03823a54 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -319,6 +319,7 @@ test { _ = @import("chat_cli_child.zig"); _ = @import("chat_cli_test.zig"); _ = @import("chat_cli_kr67_test.zig"); + _ = @import("chat_cli_kr69_test.zig"); _ = @import("start_cli_kr67_test.zig"); } } diff --git a/zig/src/server/start_cli_kr67_test.zig b/zig/src/server/start_cli_kr67_test.zig index 6128e45a736..c6db538dab7 100644 --- a/zig/src/server/start_cli_kr67_test.zig +++ b/zig/src/server/start_cli_kr67_test.zig @@ -163,3 +163,16 @@ test "start CLI: KR67 managed logs contain no exact marker, substring or encoded defer tmp.cleanup(); try managedRun(a, &tmp, "[redacted],redacted", "[redacted]", marker_input, &marker_secrets); } + +test "start CLI: KR69 managed logs contain raw and nested already-truncated credentials" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const key = try a.alloc(u8, 256); + for (key, 0..) |*c, i| c.* = 'a' + @as(u8, @intCast(i % 26)); + const keys = try std.mem.concat(a, u8, &.{ key, ",fixture-secret" }); + const log = try std.mem.concat(a, u8, &.{ key[0..255], "\n%66ixture-secre" }); + try managedRun(a, &tmp, keys, key, log, &.{ key[0..255], "fixture-secre", "%66ixture-secre" }); +} From 70faf0c47cc72d33b58e61a5f14cd78bd5865972 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:27:34 +0000 Subject: [PATCH 096/361] security: unify credential prefix containment --- zig/src/cli/pull.zig | 5 +- zig/src/cli/pull_auth.zig | 13 ++-- zig/src/cli/pull_kp50_test.zig | 54 ++++++++++++++ zig/src/cli/pull_runs.zig | 4 +- zig/src/platform/credential.zig | 62 +++++++++++++--- zig/src/server/benchmark_sse.zig | 99 ++++++++++++++------------ zig/src/server/chat_cli.zig | 8 ++- zig/src/server/chat_cli_kr69_test.zig | 63 ++++++++++++++++ zig/src/server/chat_cli_reply.zig | 3 +- zig/src/server/chat_cli_test.zig | 6 +- zig/src/server/chat_cli_turn.zig | 4 +- zig/src/server/start_cli.zig | 8 ++- zig/src/server/start_cli_kr67_test.zig | 32 +++++++++ zig/src/server/start_cli_test.zig | 4 +- 14 files changed, 286 insertions(+), 79 deletions(-) diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index af20d9703bb..c6d77f60078 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -10,6 +10,7 @@ const blobName = single.blobName; const downloadRetrying = single.downloadRetrying; const linkIntoSnapshot = single.linkIntoSnapshot; const revisionOk = hub.revisionOk; +const credential = @import("sys").credential; const route = @import("pull_route.zig"); pub const GiB: u64 = 1 << 30; @@ -105,7 +106,7 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W if (kind.drafter) { try out.print("{s}: DFlash2 drafter ({s}), for serve --drafter\n", .{ repo, try safeModelType(a, model_type, auth) }); } else if (hub.family(model_type)) |family| { - try out.print("{s}: {s} ({s})\n", .{ repo, family.title, try safeModelType(a, family.model_type, auth) }); + try out.print("{s}: {s} ({s})\n", .{ repo, if (auth.reflects(family.title)) credential.withheld else family.title, try safeModelType(a, family.model_type, auth) }); } else { try err_out.print("{s}: no registered Zig family serves model_type {s}; the 0.6 line may: tensorfold@0.6\n", .{ repo, try safeModelType(a, model_type, auth) }); return 1; @@ -325,7 +326,7 @@ fn safeModelType(a: Allocator, text: []const u8, auth: Auth) ![]const u8 { break; }; const candidate = if (printable) out else "[unprintable model_type]"; - return if (auth.reflects(candidate)) "" else candidate; + return if (auth.reflects(candidate)) credential.withheld else candidate; } /// Valid UTF-8 without terminal controls, for a path before it reaches a URL, log or local filename. diff --git a/zig/src/cli/pull_auth.zig b/zig/src/cli/pull_auth.zig index b681cf88acc..3af4fb4cefc 100644 --- a/zig/src/cli/pull_auth.zig +++ b/zig/src/cli/pull_auth.zig @@ -56,11 +56,11 @@ pub const Auth = struct { return if (auth.owns(uri)) .{ .override = bearer } else .default; } - /// Whether server-controlled text contains this hub's bearer, directly or percent-encoded. + /// Complete credentials and decoded prefixes at ``credential.min_prefix`` match at any encoding depth. pub fn reflects(auth: Auth, text: []const u8) bool { const bearer = auth.bearer orelse return false; const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; - return containsCredential(text, secret); + return credential.contains(std.heap.page_allocator, text, &.{secret}) catch true; } /// Server-controlled text with each plain or repeatedly percent-encoded credential occurrence replaced. @@ -92,6 +92,10 @@ pub const Auth = struct { var at = uri; var rest = buf; while (true) { + const exact = std.fmt.allocPrint(client.allocator, "{f}", .{at}) catch return error.HubCredentialRedirect; + const reflected = auth.reflects(exact); + client.allocator.free(exact); + if (reflected) return error.HubCredentialRedirect; try @import("pull_route.zig").note(client.io, at); o.headers.authorization = auth.header(at); req.* = try client.request(method, at, o); @@ -136,11 +140,6 @@ fn origin(uri: std.Uri, buf: []u8) ?Origin { const port: u16 = uri.port orelse if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) 443 else if (std.ascii.eqlIgnoreCase(uri.scheme, "http")) 80 else return null; return .{ .scheme = uri.scheme, .host = host, .port = port }; } -fn containsCredential(text: []const u8, secret: []const u8) bool { - var matcher = credential.Matcher.init(std.heap.page_allocator, text); - defer matcher.deinit(); - return (matcher.spanFrom(0, secret) catch return true) != null; -} /// The first non-empty of HF_TOKEN and HUGGING_FACE_HUB_TOKEN, else the one token file the `hf` tools read. pub fn token(a: Allocator, io: std.Io, env: ?*const std.process.Environ.Map, problem: *[]const u8) !?Token { for ([_][:0]const u8{ "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN" }) |name| { diff --git a/zig/src/cli/pull_kp50_test.zig b/zig/src/cli/pull_kp50_test.zig index 70ecdb3bb6e..b71f2fc8618 100644 --- a/zig/src/cli/pull_kp50_test.zig +++ b/zig/src/cli/pull_kp50_test.zig @@ -218,6 +218,8 @@ fn noteAttack(head: []const u8) void { } fn reflectedRedirectFixture(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + if (std.mem.eql(u8, target(head), "/head") and std.mem.eql(u8, method(head), "HEAD")) + return redirect(fake, conn, std.fmt.allocPrint(fake.allocator, "/collect?credential={s}", .{attack_payload}) catch return false); if (std.mem.eql(u8, target(head), "/reflect")) { return redirect(fake, conn, std.fmt.allocPrint(fake.allocator, "/collect?credential={s}", .{attack_payload}) catch return false); } @@ -544,3 +546,55 @@ test "security KR69-4: a registered family and raw or nested model types contain try markerModelType(a, io, &fake, root, secret, model_type); } } + +test "security KR71: exact two-thirds prefixes fail closed at every hub boundary" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = std.testing.io; + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.route = reflectedRedirectFixture; + fake.start(); + defer fake.stopServer(); + var client = @import("pull_http.zig").client(a, io); + defer client.deinit(); + const raw = "abcdef"; + const once = try encoded(a, raw); + const twice = try encoded(a, once); + const attacks = [_]Attack{ + .{ .secret = "abcdefghi", .payload = raw, .variants = .{ raw, once, twice, raw } }, + .{ .secret = "abcdefghi", .payload = once, .variants = .{ raw, once, twice, raw } }, + .{ .secret = "abcdefghi", .payload = twice, .variants = .{ raw, once, twice, raw } }, + .{ .secret = "prefix-[redacted]-suffix", .payload = "prefix-prefix-[redacted]-suffix", .variants = .{ "prefix-prefix-[redacted]-suffix", "prefix-[redacted]", "prefix-[redacted]-suffix", "prefix-[redacted]" } }, + }; + for (attacks, 0..) |attack, index| { + const hub: Auth = .{ .endpoint = try fake.endpoint(a), .bearer = try std.fmt.allocPrint(a, "Bearer {s}", .{attack.secret}), .source = "HF_TOKEN" }; + try redirectAttack(a, &client, hub, attack); + resetAttack(attack.payload); + const result = runs.resolve(a, &client, hub, try std.fmt.allocPrint(a, "{s}/head", .{hub.endpoint})); + try std.testing.expectError(error.HubCredentialRedirect, result); + try std.testing.expectEqual(@as(u32, 0), attack_requests.load(.monotonic)); + try expectAttackAbsent(attack, request_log[0..request_log_len], ""); + const root = try std.fmt.allocPrint(a, ".tf-pull-kr71-{d}", .{index}); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + fake.route = reflectedTreeFixture; + try treeAttack(a, io, &fake, root, attack); + fake.route = reflectedRedirectFixture; + resetAttack(attack.payload); + const env = try envWithToken(a, &fake, attack.secret); + fake.config = try std.fmt.allocPrint(a, "{{\"model_type\":\"{s}\"}}", .{attack.payload}); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try expectAttackAbsent(attack, out.written(), err_out.written()); + try std.testing.expect(std.mem.indexOf(u8, err_out.written(), credential.withheld) != null); + } + fake.config = FakeHub.config_body; + const env = try envWithToken(a, &fake, "qwen4_expX"); + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 0), try pull.run(a, io, &out.writer, &err_out.writer, &env, ".tf-pull-kr71-registered", "Org/Flash")); + defer std.Io.Dir.cwd().deleteTree(io, ".tf-pull-kr71-registered") catch {}; + for ([_][]const u8{ out.written(), err_out.written() }) |text| try expectAbsent(text, "qwen4_exp"); + try std.testing.expect(std.mem.indexOf(u8, out.written(), "Qwen3.8 Flash Next ([withheld])") != null); +} diff --git a/zig/src/cli/pull_runs.zig b/zig/src/cli/pull_runs.zig index d85b94c1d7b..89e1173ca83 100644 --- a/zig/src/cli/pull_runs.zig +++ b/zig/src/cli/pull_runs.zig @@ -145,14 +145,14 @@ fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u var wait_ms: u64 = 250; for (0..attempts) |_| { const link = location(s, client, r.file) catch |e| { - if (e == error.HubDenied) return e; + if (e == error.HubDenied or e == error.HubCredentialRedirect) return e; last = e; std.Io.sleep(s.io, .fromMilliseconds(@intCast(wait_ms)), .awake) catch {}; wait_ms *= 2; continue; }; get(client, s.auth, link, r.first, buf) catch |e| { - if (e == error.HubDenied) return e; + if (e == error.HubDenied or e == error.HubCredentialRedirect) return e; last = e; if (e == error.Forbidden) forget(s, r.file, link); std.Io.sleep(s.io, .fromMilliseconds(@intCast(wait_ms)), .awake) catch {}; diff --git a/zig/src/platform/credential.zig b/zig/src/platform/credential.zig index ea981fee384..c7a2fa91198 100644 --- a/zig/src/platform/credential.zig +++ b/zig/src/platform/credential.zig @@ -2,8 +2,12 @@ const std = @import("std"); const Allocator = std.mem.Allocator; -pub const Match = struct { secret_len: usize = 0, consumed: usize = 0, hold: bool = false }; +pub const Match = struct { secret_len: usize = 0, prefix_len: usize = 0, consumed: usize = 0, hold: bool = false }; pub const Span = struct { start: usize, end: usize }; +/// A complete key of any length, or this many decoded prefix bytes, fails containment. +pub const min_prefix = 4; +/// Fixed non-derived outward text for a withheld candidate; not the redaction marker, which may itself be configured. +pub const withheld = "[withheld]"; /// A reusable matcher; memo entries retain every endpoint so nested escapes and literal bytes stay alternatives. pub const Matcher = struct { @@ -62,7 +66,7 @@ pub const Matcher = struct { m.next.deinit(m.a); } - /// The longest full key match at an original start; an unfinished later encoding holds the suffix. + /// The longest full key or decoded-prefix match; an unfinished later encoding holds the suffix. pub fn secretAt(m: *Matcher, start: usize, secrets: anytype) Allocator.Error!Match { var found: Match = .{}; var hold = false; @@ -70,8 +74,9 @@ pub const Matcher = struct { if (secret.len == 0) continue; const matched = try m.matchSecret(start, secret); hold = hold or matched.hold; - // Longest original span, then longest key, regardless of which key completes first. - if (matched.consumed > found.consumed or (matched.consumed == found.consumed and matched.secret_len > found.secret_len)) found = matched; + // Longest original span, then decoded prefix and key, regardless of which key completes first. + if (matched.consumed > found.consumed or (matched.consumed == found.consumed and + (matched.prefix_len > found.prefix_len or (matched.prefix_len == found.prefix_len and matched.secret_len > found.secret_len)))) found = matched; } found.hold = found.hold or hold; return found; @@ -96,7 +101,7 @@ pub const Matcher = struct { var states = &m.states; var next = &m.next; var hold = false; - for (secret) |wanted| { + for (secret, 0..) |wanted, matched_len| { next.clearRetainingCapacity(); for (states.items) |at| { if (at == m.text.len) { @@ -111,14 +116,22 @@ pub const Matcher = struct { hold = hold or decoded.partial; for (0..decoded.len()) |index| try appendUnique(m.a, next, decoded.at(index)); } - if (next.items.len == 0) return .{ .secret_len = secret.len, .hold = hold }; + if (next.items.len == 0) { + // An original '%' is a partial representation of the current decoded byte, even when its escape is cut. + var partial_byte = false; + for (states.items) |at| if (at < m.text.len and m.text[at] == '%') { + partial_byte = true; + break; + }; + return .{ .secret_len = secret.len, .prefix_len = matched_len + @intFromBool(partial_byte), .hold = hold }; + } const swap = states; states = next; next = swap; } var consumed: usize = 0; for (states.items) |end| consumed = @max(consumed, end - start); - return .{ .secret_len = secret.len, .consumed = consumed, .hold = hold }; + return .{ .secret_len = secret.len, .prefix_len = secret.len, .consumed = consumed, .hold = hold }; } /// One byte's literal or `%XX` representations; nested dependencies use heap frames, not call recursion. @@ -239,13 +252,40 @@ fn appendUnique(a: Allocator, ends: *std.ArrayList(usize), end: usize) Allocator try ends.append(a, end); } -/// Whether any configured secret occurs literally or at any percent-encoding depth. +/// A possible first matcher byte; percent can begin any literal or nested encoding. +fn prefixStart(text: []const u8, secrets: []const []const u8) bool { + if (text.len == 0) return false; + if (text[0] == '%') return secrets.len > 0; + for (secrets) |secret| if (secret.len > 0 and secret[0] == text[0]) return true; + return false; +} + +/// Original bytes forming a decoded credential prefix of at least ``min_prefix`` bytes before a disambiguating suffix. +pub fn sensitivePrefix(a: Allocator, text: []const u8, secrets: []const []const u8) Allocator.Error!usize { + if (!prefixStart(text, secrets)) return 0; + var sensitive: usize = 0; + // Hold and prefix length belong to one secret; combining them across secrets can consume a safe suffix. + for (secrets) |secret| { + if (secret.len == 0) continue; + for (1..text.len + 1) |end| { + var matcher = Matcher.init(a, text[0..end]); + defer matcher.deinit(); + const found = try matcher.matchSecret(0, secret); + if (found.prefix_len >= min_prefix) sensitive = @max(sensitive, if (found.hold) end else end - 1); + if (!found.hold) break; + } + } + return sensitive; +} + +/// Whether any complete credential or decoded prefix of at least ``min_prefix`` bytes occurs at any encoding depth. pub fn contains(a: Allocator, text: []const u8, secrets: []const []const u8) Allocator.Error!bool { var matcher = Matcher.init(a, text); defer matcher.deinit(); - for (secrets) |secret| { - if (secret.len == 0) continue; - if ((try matcher.spanFrom(0, secret)) != null) return true; + var i: usize = 0; + while (i < text.len) : (i += 1) { + if ((try matcher.secretAt(i, secrets)).consumed > 0) return true; + if (try sensitivePrefix(a, text[i..], secrets) > 0) return true; } return false; } diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index c3ad25ab66a..bfcce900752 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -226,7 +226,7 @@ pub fn refusal(a: Allocator, status: u16, body: []const u8) ![]const u8 { /// Redact decoded JSON text or a plain body independently, before terminal truncation. pub fn refusalRedacted(a: Allocator, status: u16, body: []const u8, secrets: []const []const u8) ![]const u8 { const decoded = try errorText(a, body); - const text = (try cleanContained(a, decoded, secrets, line_limit)) orelse ""; + const text = (try cleanContained(a, decoded, secrets, line_limit)) orelse credential.withheld; const candidate = if (text.len == 0) try std.fmt.allocPrint(a, "HTTP {d}", .{status}) else @@ -311,22 +311,22 @@ fn limited(a: Allocator, text: []const u8, limit: usize) ![]const u8 { /// Sanitize, replace, check before limiting, then limit and check the exact final candidate. pub fn cleanContained(a: Allocator, text: []const u8, secrets: []const []const u8, limit: usize) !?[]const u8 { const replaced = try redact(a, try sanitizeLine(a, text), secrets); - if (try containsSensitive(a, replaced, secrets)) return null; + if (try credential.contains(a, replaced, secrets)) return null; const candidate = try limited(a, replaced, limit); - if (try containsSensitive(a, candidate, secrets)) return null; + if (try credential.contains(a, candidate, secrets)) return null; return candidate; } /// Sanitize and redact without truncating; null means consume and suppress the candidate. pub fn redactContained(a: Allocator, text: []const u8, secrets: []const []const u8) !?[]const u8 { const candidate = try redact(a, try sanitizeLine(a, text), secrets); - if (try containsSensitive(a, candidate, secrets)) return null; + if (try credential.contains(a, candidate, secrets)) return null; return candidate; } -/// A generated candidate only when containment proves it safe; otherwise the empty terminal value. +/// A generated candidate only when containment proves it safe; otherwise fixed non-derived withholding text. pub fn suppress(a: Allocator, candidate: []const u8, secrets: []const []const u8) ![]const u8 { - return if (try containsSensitive(a, candidate, secrets)) "" else candidate; + return if (try credential.contains(a, candidate, secrets)) credential.withheld else candidate; } /// Terminal/error text with credentials replaced, longest original span first at any encoding depth. @@ -374,7 +374,7 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) i += found.consumed; continue; } - const prefix = try sensitivePrefix(a, rest, secrets); + const prefix = try credential.sensitivePrefix(a, rest, secrets); if (prefix > 0) { if (!changed) { try out.appendSlice(a, text[0..i]); @@ -389,41 +389,7 @@ pub fn redactPiece(a: Allocator, text: []const u8, secrets: []const []const u8) return .{ .text = if (changed) out.items else text, .rest = "" }; } -/// A possible first matcher byte; percent can begin any literal or nested encoding. -fn prefixStart(text: []const u8, secrets: []const []const u8) bool { - if (text.len == 0) return false; - if (text[0] == '%') return secrets.len > 0; - for (secrets) |secret| if (secret.len > 0 and secret[0] == text[0]) return true; - return false; -} - -/// The longest matched fragment exceeding two thirds of a credential before it is ruled out. -fn sensitivePrefix(a: Allocator, text: []const u8, secrets: []const []const u8) !usize { - if (!prefixStart(text, secrets)) return 0; - var sensitive: usize = 0; - for (1..text.len + 1) |end| { - var matcher = credential.Matcher.init(a, text[0..end]); - defer matcher.deinit(); - if (!(try matcher.secretAt(0, secrets)).hold) break; - sensitive = end; - } - for (secrets) |secret| if (secret.len > 1 and sensitive > (secret.len * 2) / 3) return sensitive; - return 0; -} - -/// Whether any complete credential or a disambiguated or unfinished credential prefix occurs. -fn containsSensitive(a: Allocator, text: []const u8, secrets: []const []const u8) !bool { - var matcher = credential.Matcher.init(a, text); - defer matcher.deinit(); - var i: usize = 0; - while (i < text.len) : (i += 1) { - const found = try matcher.secretAt(i, secrets); - if (found.consumed > 0) return true; - if (try sensitivePrefix(a, text[i..], secrets) > 0) return true; - } - return false; -} - +/// The transformed stream's emit/rest result; unresolved bytes are never released. pub const ContainedPiece = struct { emit: ?[]const u8, rest: []const u8 }; /// Transformed streamed output: suppress complete keys and truncated prefixes, or hold a possible suffix. @@ -437,7 +403,7 @@ pub fn containedPiece(a: Allocator, text: []const u8, secrets: []const []const u const found = try matcher.secretAt(i, secrets); if (found.consumed > 0) return .{ .emit = null, .rest = "" }; if (found.hold) return .{ .emit = if (changed) out.items else text[0..i], .rest = text[i..] }; - const prefix = try sensitivePrefix(a, text[i..], secrets); + const prefix = try credential.sensitivePrefix(a, text[i..], secrets); if (prefix > 0) { if (!changed) { try out.appendSlice(a, text[0..i]); @@ -504,13 +470,57 @@ test "chat CLI: KR69 whole raw, nested and mid-escape credential prefixes are su const a = arena.allocator(); const secrets = [_][]const u8{"abcde"}; for ([_][]const u8{ "abcd", "pre abcdX post", "abc%64", "abc%2564X", "abc%6X" }) |text| { - try std.testing.expectEqualStrings("", try suppress(a, text, &secrets)); + try std.testing.expectEqualStrings(credential.withheld, try suppress(a, text, &secrets)); try std.testing.expect((try redactContained(a, text, &secrets)) == null); try std.testing.expect((try cleanContained(a, text, &secrets, 2000)) == null); } try std.testing.expectEqualStrings("safe continuation", try suppress(a, "safe continuation", &secrets)); } +test "chat CLI: KR71 raw and decoded prefixes fail closed at every terminal boundary" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const secrets = [_][]const u8{"abcdefghi"}; + const cases = [_]struct { input: []const u8, expected: []const u8 }{ + .{ .input = "abcdefX", .expected = "X" }, + .{ .input = "%61%62%63%64%65%66X", .expected = "X" }, + .{ .input = "%2561%2562%2563%2564%2565%2566X", .expected = "X" }, + .{ .input = "abcde%6X", .expected = "X" }, + .{ .input = "pre abcdefX post", .expected = "pre X post" }, + }; + for (cases) |case| { + try std.testing.expectEqualStrings(credential.withheld, try suppress(a, case.input, &secrets)); + try std.testing.expect((try redactContained(a, case.input, &secrets)) == null); + try std.testing.expect((try cleanContained(a, case.input, &secrets, 2000)) == null); + const streamed = try redactPiece(a, case.input, &secrets); + try std.testing.expectEqualStrings(case.expected, streamed.text); + try std.testing.expectEqualStrings("", streamed.rest); + const checked = try containedPiece(a, case.input, &secrets); + try std.testing.expectEqualStrings(case.expected, checked.emit.?); + try std.testing.expectEqualStrings("", checked.rest); + } + try std.testing.expectEqualStrings("abcX", try suppress(a, "abcX", &secrets)); + try std.testing.expectEqualStrings("abcX", (try redactContained(a, "abcX", &secrets)).?); + try std.testing.expectEqualStrings("abcX", (try containedPiece(a, "abcX", &secrets)).emit.?); + try std.testing.expectEqualStrings(credential.withheld, try suppress(a, "abc", &.{"abc"})); + const mixed = [_][]const u8{ "%25abcde", "%aXcdef" }; + const mixed_input = "%25%61XY"; + try std.testing.expectEqualStrings(credential.withheld, try suppress(a, mixed_input, &mixed)); + const mixed_raw = try redactPiece(a, mixed_input, &mixed); + try std.testing.expectEqualStrings("XY", mixed_raw.text); + try std.testing.expectEqualStrings("", mixed_raw.rest); + const mixed_transformed = try containedPiece(a, mixed_input, &mixed); + try std.testing.expectEqualStrings("XY", mixed_transformed.emit.?); + try std.testing.expectEqualStrings("", mixed_transformed.rest); + try std.testing.expectEqualStrings(credential.withheld, try suppress(a, "example-model", &.{"example-key-1"})); + try std.testing.expectEqualStrings(credential.withheld, try suppress(a, "%2561%2562%2563", &.{"abc"})); + try std.testing.expectEqualStrings("%61%62%63X", try suppress(a, "%61%62%63X", &secrets)); + const below_encoded = try containedPiece(a, "%61%62%63X", &secrets); + try std.testing.expectEqualStrings("%61%62%63X", below_encoded.emit.?); + try std.testing.expectEqualStrings("", below_encoded.rest); +} + test "chat CLI: KR69 short coincidental credential openers leave safe text byte-identical" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -519,5 +529,4 @@ test "chat CLI: KR69 short coincidental credential openers leave safe text byte- const streamed = try redactPiece(a, "Hello there!", &secrets); try std.testing.expectEqualStrings("Hello there!", streamed.text); try std.testing.expectEqualStrings("", streamed.rest); - try std.testing.expectEqualStrings("example-model", try suppress(a, "example-model", &secrets)); } diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 110942f23e2..36f20de7ca2 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -11,6 +11,7 @@ const stream = @import("benchmark_stream.zig"); const sse = @import("benchmark_sse.zig"); const stop = @import("benchmark_stop.zig"); const environment = @import("sys").environment; +const credential = @import("sys").credential; const Allocator = std.mem.Allocator; const Sig = std.posix.SIG; @@ -142,7 +143,7 @@ fn served(ctx: *const Context, args: args_mod.Args, message: ?[]const u8) !u8 { try say(ctx.err, "Loading {s}; Ctrl-C cancels.", .{args.model.?}); var own = try child.start(setup, plan, &tail, &problem) orelse { if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); - const code = try fail(ctx, (try credentials.safe(ctx.a, problem)) orelse ""); + const code = try fail(ctx, (try credentials.safe(ctx.a, problem)) orelse credential.withheld); try lastLines(ctx, tail); return code; }; @@ -225,7 +226,7 @@ const Session = struct { /// Finds the model and its thinking switch, then holds one exchange (a piped message) or a conversation. fn session(ctx: *const Context, args: args_mod.Args, target: Target, message: ?[]const u8) !u8 { var problem: []const u8 = ""; - const url = try stream.endpoint(ctx.a, target.base, true, &problem) orelse return fail(ctx, problem); + const url = try stream.endpoint(ctx.a, target.base, true, &problem) orelse return fail(ctx, try target.credentials.check(ctx.a, problem)); const found = try discover(ctx, url, target); if (found.stopped) |sig| return stop.exitCode(sig); const model = found.model orelse return fail(ctx, try target.credentials.check(ctx.a, found.problem)); @@ -308,6 +309,7 @@ fn discover(ctx: *const Context, chat_url: []const u8, target: Target) !Found { var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = ctx.io }; defer client.deinit(); const url = try std.mem.concat(ctx.a, u8, &.{ chat_url[0 .. chat_url.len - "/chat/completions".len], "/models" }); + if (try credential.contains(ctx.a, url, target.credentials.forms)) return .{ .problem = credential.withheld }; const got = stream.fetch(ctx.a, ctx.io, &client, .{ .url = url, .limit = 4 << 20, .timeout_s = 10, .agent = turn.user_agent, .token = target.key }); if (got.failed == .stopped) return .{ .stopped = stop.requested() orelse .INT }; var doc: ?json.Value = null; @@ -327,7 +329,7 @@ fn discover(ctx: *const Context, chat_url: []const u8, target: Target) !Found { }; return .{ .problem = try std.fmt.allocPrint(ctx.a, "no model to chat with: {s} {s}; name one after the URL", .{ url, why }) }; }; - const name: ?[]const u8 = if (target.model == null) try target.credentials.clean(ctx.a, raw_name, sse.line_limit) else raw_name; + const name: ?[]const u8 = try target.credentials.clean(ctx.a, raw_name, sse.line_limit); return .{ .model = name orelse return .{ .problem = try target.credentials.check(ctx.a, "the server supplied an unsafe model name") }, .thinking_switch = if (doc) |d| stream.thinkingSwitch(d, raw_name) else null }; } diff --git a/zig/src/server/chat_cli_kr69_test.zig b/zig/src/server/chat_cli_kr69_test.zig index ccaaff68ee9..040d4a17236 100644 --- a/zig/src/server/chat_cli_kr69_test.zig +++ b/zig/src/server/chat_cli_kr69_test.zig @@ -337,3 +337,66 @@ test "chat CLI: KR69 a stopped Unicode reply cannot synthesize a key in the foll try std.testing.expectEqual(@as(usize, 1), postCount(f)); for (0..f.count()) |i| try absent(f.request(i).body, &.{"\\u00e9"}); } + +test "chat CLI: KR71 same-delta and cross-delta prefixes stay out of output, history and every following POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const hostile = [_][]const u8{ "abcdef", "%61%62%63%64%65%66", "%2561%2562%2563%2564%2565%2566" }; + for ([_]bool{ false, true }) |same_delta| for (hostile) |attack| { + var r = try fixtures.Run.init(a, &tmp); + const first_delta = if (same_delta) + try delta(a, try std.fmt.allocPrint(a, "{s}X", .{attack})) + else + try delta(a, attack); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ + try stream(a, try a.dupe([]const u8, &.{ + first_delta, + try delta(a, "X"), + try fake.event(a, "{\"choices\": [{\"index\": 0, \"delta\": {}, \"finish_reason\": \"stop\"}]}"), + try fake.event(a, "[DONE]"), + })), + try successful(a, "done"), + })); + defer f.stop(); + try r.env.put("TENSORFOLD_API_KEY", "abcdefghi"); + r.interactive = true; + r.input = "one\ntwo\n/bye\n"; + try std.testing.expectEqual(@as(u8, 0), try terminalCommand(&r, &.{ "--url", try f.url(a, "") })); + try absent(r.out.written(), &hostile); + try absent(r.err.written(), &hostile); + try std.testing.expectEqual(@as(usize, 2), postCount(f)); + for (0..f.count()) |i| try absent(f.request(i).body, &hostile); + }; +} + +test "chat CLI: KR71 one hostile table covers discovery and HTTP or SSE errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const hostile = [_][]const u8{ "abcdef", "%61%62%63%64%65%66", "%2561%2562%2563%2564%2565%2566" }; + for (hostile) |attack| { + var r = try fixtures.Run.init(a, &tmp); + try r.env.put("TENSORFOLD_API_KEY", "abcdefghi"); + r.input = "hi"; + const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{attack}); + const discovered = try fixtures.world(a, models, try a.dupe([]const fake.Write, &.{try successful(a, "unused")})); + defer discovered.stop(); + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try discovered.url(a, "") })); + try absent(r.out.written(), &hostile); + try absent(r.err.written(), &hostile); + try std.testing.expectEqual(@as(usize, 0), postCount(discovered)); + const f = try fixtures.world(a, fixtures.models_doc, try a.dupe([]const fake.Write, &.{ try httpError(a, attack), try sseError(a, attack) })); + defer f.stop(); + for (0..2) |_| { + try std.testing.expectEqual(@as(u8, 1), try terminalCommand(&r, &.{ "--url", try f.url(a, ""), "safe-model" })); + try absent(r.out.written(), &hostile); + try absent(r.err.written(), &hostile); + } + for (0..f.count()) |i| try absent(f.request(i).body, &hostile); + } +} diff --git a/zig/src/server/chat_cli_reply.zig b/zig/src/server/chat_cli_reply.zig index 987203ff0bb..91ecf088901 100644 --- a/zig/src/server/chat_cli_reply.zig +++ b/zig/src/server/chat_cli_reply.zig @@ -1,6 +1,7 @@ //! One streamed chat reply as its bytes arrive, however reads cut them: answer and reasoning pieces, finish, error. const std = @import("std"); const json = @import("json"); +const credential = @import("sys").credential; const sse = @import("benchmark_sse.zig"); const Allocator = std.mem.Allocator; @@ -134,7 +135,7 @@ fn streamFor(r: *Reply, kind: Kind) *Stream { /// An error event's ``message`` sanitized before matching and contained after every transformation. fn errorText(a: Allocator, e: json.Value, secrets: []const []const u8) ![]const u8 { const text = e.strField("message") orelse e.str() orelse "the server reported an error without a message"; - return (try sse.cleanContained(a, text, secrets, error_limit)) orelse ""; + return (try sse.cleanContained(a, text, secrets, error_limit)) orelse credential.withheld; } const Seen = struct { diff --git a/zig/src/server/chat_cli_test.zig b/zig/src/server/chat_cli_test.zig index cf0b35e5772..752ceb4e66f 100644 --- a/zig/src/server/chat_cli_test.zig +++ b/zig/src/server/chat_cli_test.zig @@ -189,7 +189,7 @@ test "chat CLI: --url sends TENSORFOLD_API_KEY's first key as the bearer, and a try std.testing.expectEqual(@as(usize, 5), f.refusals()); try std.testing.expectEqual(@as(usize, 0), f.count()); try r.env.put("TENSORFOLD_API_KEY", " ,example-key-1, example-key-2"); - try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", url })); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", url, "other-model" })); try std.testing.expectEqualStrings("Hello there!\n", r.out.written()); try std.testing.expect(f.refusals() == 5 and f.count() == 2); for (0..f.count()) |i| try std.testing.expectEqualStrings("Bearer example-key-1", f.header(i, "authorization").?); @@ -489,7 +489,7 @@ test "chat CLI: MODEL starts its own serve child in a process group of its own, var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var r = try Run.init(a, &tmp); - try r.env.put("TENSORFOLD_API_KEY", "example-user-key"); + try r.env.put("TENSORFOLD_API_KEY", "caller-user-key"); var gate: std.Io.Event = .unset; const held = try a.dupe(fake.Write, try streamed(a)); held[0].after = &gate; @@ -526,7 +526,7 @@ test "chat CLI: MODEL starts its own serve child in a process group of its own, try std.testing.expectEqualStrings(want, args); // the child's key came in its environment alone, fresh, never the user's, and the chat printed it nowhere const key = try std.Io.Dir.cwd().readFileAlloc(io, try r.path("key"), a, .limited(256)); - try std.testing.expect(key.len == 64 and !std.mem.eql(u8, key, "example-user-key")); + try std.testing.expect(key.len == 64 and !std.mem.eql(u8, key, "caller-user-key")); for ([_][]const u8{ r.out.written(), r.err.written(), args }) |text| try std.testing.expect(std.mem.indexOf(u8, text, key) == null); const bearer = try std.mem.concat(a, u8, &.{ "Bearer ", key }); try std.testing.expect(f.refusals() == 0 and f.count() >= 4); diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index ccf7032fd83..e75138da9bd 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -87,6 +87,8 @@ pub fn checkedBody(a: Allocator, s: Settings, history: *const History, user: []c /// One streamed turn to ``url``, the chat route, printed to ``out`` as it arrives; a stop signal ends it ``stopped``. pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credentials: Credentials, request: []u8, out: *std.Io.Writer, show: Show) !Ended { + if ((try credential.contains(a, url, credentials.forms)) or (try credential.contains(a, request, credentials.forms))) + return .{ .failed = .{ .reason = credential.withheld } }; var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = io }; client.connection_pool.free_size = 0; defer client.deinit(); @@ -191,7 +193,7 @@ const Exchange = struct { .lost => "the connection to the server broke during the reply", .http => try sse.refusalRedacted(x.a, x.status, x.refused, x.credentials.forms), .not_events => blk: { - const text = (try x.credentials.clean(x.a, x.content_type, sse.line_limit)) orelse ""; + const text = (try x.credentials.clean(x.a, x.content_type, sse.line_limit)) orelse credential.withheld; break :blk if (text.len == 0) "the server did not answer with an event stream" else diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index e17211fa820..7a3dffcea51 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -4,6 +4,7 @@ const builtin = @import("builtin"); const registry = @import("checkpoint_cli").start; const machine = @import("sys").machine; const child = @import("chat_cli_child.zig"); +const credential = @import("sys").credential; const turn = @import("chat_cli_turn.zig"); const history = @import("chat_cli_history.zig"); const stream = @import("benchmark_stream.zig"); @@ -189,7 +190,7 @@ fn serve(ctx: *const Context, args: Args, choice: registry.Choice, caller_key: ? try say(ctx.err, "Loading {s}; Ctrl-C cancels", .{choice.entry.repo}); var own = try child.start(setup, plan, &tail, &problem) orelse { if (problem.len == 0) return stop.exitCode(stop.requested() orelse .INT); - const code = try fail(ctx, 1, "{s}", .{(try credentials.safe(ctx.a, problem)) orelse ""}); + const code = try fail(ctx, 1, "{s}", .{(try credentials.safe(ctx.a, problem)) orelse credential.withheld}); try lastLines(ctx, tail); return code; }; @@ -221,7 +222,10 @@ fn firstReply(ctx: *const Context, own: *Child, credentials: turn.Credentials) ! return 0; }, .stopped => return stop.exitCode(stop.requested() orelse .INT), - .failed => |f| return fail(ctx, 1, "first reply failed: {s}", .{f.reason}), + .failed => |f| { + const reason = try std.fmt.allocPrint(ctx.a, "first reply failed: {s}", .{f.reason}); + return fail(ctx, 1, "{s}", .{try credentials.check(ctx.a, reason)}); + }, } } diff --git a/zig/src/server/start_cli_kr67_test.zig b/zig/src/server/start_cli_kr67_test.zig index c6db538dab7..030537a8432 100644 --- a/zig/src/server/start_cli_kr67_test.zig +++ b/zig/src/server/start_cli_kr67_test.zig @@ -176,3 +176,35 @@ test "start CLI: KR69 managed logs contain raw and nested already-truncated cred const log = try std.mem.concat(a, u8, &.{ key[0..255], "\n%66ixture-secre" }); try managedRun(a, &tmp, keys, key, log, &.{ key[0..255], "fixture-secre", "%66ixture-secre" }); } + +test "start CLI: KR71 managed logs contain raw and decoded exact two-thirds prefixes" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const hostile = "abcdef\n%61%62%63%64%65%66\n%2561%2562%2563%2564%2565%2566"; + try managedRun(a, &tmp, "abcdefghi", "abcdefghi", hostile, &.{ "abcdef", "%61%62%63%64%65%66", "%2561%2562%2563%2564%2565%2566" }); +} + +test "start CLI: KR71 a short readiness credential prevents every first-reply POST" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try Run.init(a, &tmp); + try r.env.put("TENSORFOLD_API_KEY", "short"); + try r.env.put("START_TEST_LOG_ENCODED", ""); + try r.cache(); + try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try r.path("credential"), .data = "short" }); + const f = try world(&r); + defer f.stop(); + try r.standIn(f.port); + try std.testing.expectEqual(@as(u8, 1), try r.command()); + try std.testing.expect(r.childGone()); + var posts: usize = 0; + for (0..f.count()) |i| posts += @intFromBool(std.mem.eql(u8, f.request(i).method, "POST")); + try std.testing.expectEqual(@as(usize, 0), posts); + for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, "short") == null); +} diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index 55371fbfc1a..da2a02f9c21 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -269,7 +269,7 @@ test "start CLI: a cached model answers once, prints no key and --check reaps it var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var r = try Run.init(a, &tmp); - try r.env.put("TENSORFOLD_API_KEY", "user-key-must-not-leak"); + try r.env.put("TENSORFOLD_API_KEY", "caller-key-must-not-leak"); try r.cache(); const f = try world(&r, try events(a, "Ready.")); defer f.stop(); @@ -280,7 +280,7 @@ test "start CLI: a cached model answers once, prints no key and --check reaps it try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "first-reply check passed; server stopped") != null); try std.testing.expect(r.childGone()); const key = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("child-key"), a, .limited(256)); - try std.testing.expect(key.len == 64 and !std.mem.eql(u8, key, "user-key-must-not-leak")); + try std.testing.expect(key.len == 64 and !std.mem.eql(u8, key, "caller-key-must-not-leak")); for ([_][]const u8{ r.out.written(), r.err.written() }) |text| try std.testing.expect(std.mem.indexOf(u8, text, key) == null); const args = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, try r.path("args"), a, .limited(4096)); const want = try std.fmt.allocPrint(a, "serve\n{s}/models--Org--Model/snapshots/{s}\n--host\n127.0.0.1\n--port\n0\n--name\n{s}\n--name\nModel\n--drafter\n{s}/models--Org--Draft/snapshots/{s}\n", .{ r.root, revision, revision, r.root, draft_revision }); From 8f7cf9dbac180a8d5f7a36875e4bbfc085039f00 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:28:49 +0000 Subject: [PATCH 097/361] chat: contain decoded request credentials --- zig/src/platform/credential.zig | 24 ++++++++---- zig/src/server/benchmark_sse.zig | 15 +++++++- zig/src/server/benchmark_stream_test.zig | 12 ++++++ zig/src/server/chat_cli_reply.zig | 18 ++++++++- zig/src/server/chat_cli_turn.zig | 48 +++++++++++++++++------- 5 files changed, 93 insertions(+), 24 deletions(-) diff --git a/zig/src/platform/credential.zig b/zig/src/platform/credential.zig index c7a2fa91198..ecbc7464a82 100644 --- a/zig/src/platform/credential.zig +++ b/zig/src/platform/credential.zig @@ -103,6 +103,7 @@ pub const Matcher = struct { var hold = false; for (secret, 0..) |wanted, matched_len| { next.clearRetainingCapacity(); + var partial_byte = false; for (states.items) |at| { if (at == m.text.len) { hold = true; @@ -113,16 +114,12 @@ pub const Matcher = struct { continue; } const decoded = try m.decode(at, wanted); + partial_byte = partial_byte or decoded.partial; hold = hold or decoded.partial; for (0..decoded.len()) |index| try appendUnique(m.a, next, decoded.at(index)); } if (next.items.len == 0) { - // An original '%' is a partial representation of the current decoded byte, even when its escape is cut. - var partial_byte = false; - for (states.items) |at| if (at < m.text.len and m.text[at] == '%') { - partial_byte = true; - break; - }; + // Unfinished decoding and a hex high nibble are partial; a non-hex continuation is not. return .{ .secret_len = secret.len, .prefix_len = matched_len + @intFromBool(partial_byte), .hold = hold }; } const swap = states; @@ -267,13 +264,24 @@ pub fn sensitivePrefix(a: Allocator, text: []const u8, secrets: []const []const // Hold and prefix length belong to one secret; combining them across secrets can consume a safe suffix. for (secrets) |secret| { if (secret.len == 0) continue; + var own: usize = 0; for (1..text.len + 1) |end| { var matcher = Matcher.init(a, text[0..end]); defer matcher.deinit(); const found = try matcher.matchSecret(0, secret); - if (found.prefix_len >= min_prefix) sensitive = @max(sensitive, if (found.hold) end else end - 1); - if (!found.hold) break; + if (found.hold) { + if (found.prefix_len >= min_prefix) own = @max(own, end); + continue; + } + if (found.prefix_len >= min_prefix) { + own = end - 1; + break; + } + // A disproved escape below the real decoded prefix minimum is safe. + own = 0; + break; } + sensitive = @max(sensitive, own); } return sensitive; } diff --git a/zig/src/server/benchmark_sse.zig b/zig/src/server/benchmark_sse.zig index bfcce900752..fdc7b797623 100644 --- a/zig/src/server/benchmark_sse.zig +++ b/zig/src/server/benchmark_sse.zig @@ -445,7 +445,7 @@ test "chat CLI: KR69 streaming suppresses disambiguated raw and nested credentia .{ .input = "abcdX", .expected = "X" }, .{ .input = "abc%64X", .expected = "X" }, .{ .input = "abc%2564X", .expected = "X" }, - .{ .input = "abc%6X", .expected = "X" }, + .{ .input = "abc%6X", .expected = "abc%6X" }, .{ .input = "pre abcdX post", .expected = "pre X post" }, }; for (cases) |case| { @@ -469,7 +469,7 @@ test "chat CLI: KR69 whole raw, nested and mid-escape credential prefixes are su defer arena.deinit(); const a = arena.allocator(); const secrets = [_][]const u8{"abcde"}; - for ([_][]const u8{ "abcd", "pre abcdX post", "abc%64", "abc%2564X", "abc%6X" }) |text| { + for ([_][]const u8{ "abcd", "pre abcdX post", "abc%64", "abc%2564X" }) |text| { try std.testing.expectEqualStrings(credential.withheld, try suppress(a, text, &secrets)); try std.testing.expect((try redactContained(a, text, &secrets)) == null); try std.testing.expect((try cleanContained(a, text, &secrets, 2000)) == null); @@ -500,6 +500,17 @@ test "chat CLI: KR71 raw and decoded prefixes fail closed at every terminal boun try std.testing.expectEqualStrings(case.expected, checked.emit.?); try std.testing.expectEqualStrings("", checked.rest); } + for ([_][]const u8{ "abc% safe", "abc%6X" }) |input| { + try std.testing.expectEqualStrings(input, try suppress(a, input, &secrets)); + try std.testing.expectEqualStrings(input, (try redactContained(a, input, &secrets)).?); + try std.testing.expectEqualStrings(input, (try cleanContained(a, input, &secrets, 2000)).?); + const streamed = try redactPiece(a, input, &secrets); + try std.testing.expectEqualStrings(input, streamed.text); + try std.testing.expectEqualStrings("", streamed.rest); + const checked = try containedPiece(a, input, &secrets); + try std.testing.expectEqualStrings(input, checked.emit.?); + try std.testing.expectEqualStrings("", checked.rest); + } try std.testing.expectEqualStrings("abcX", try suppress(a, "abcX", &secrets)); try std.testing.expectEqualStrings("abcX", (try redactContained(a, "abcX", &secrets)).?); try std.testing.expectEqualStrings("abcX", (try containedPiece(a, "abcX", &secrets)).emit.?); diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index 1df7abf3024..e60040ed1df 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -331,6 +331,18 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses } try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(0, "authorization").?); try std.testing.expect(std.mem.indexOf(u8, f.request(0).head, token) == null); + const unicode_secret = "\u{e9}abc"; + const unicode_credentials = try turn.Credentials.init(a, &.{unicode_secret}); + const unicode_body = try turn.body(a, .{ .model = "m" }, &h, unicode_secret); + const escape_at = std.mem.indexOf(u8, unicode_body, "\\u00e9abc").?; + unicode_body[escape_at + 4] = 'E'; + const unicode_refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), null, unicode_credentials, unicode_body, &out.writer, .{}); + switch (unicode_refused) { + .failed => |why| try std.testing.expectEqualStrings("[withheld]", why.reason), + else => return error.TestUnexpectedResult, + } + try std.testing.expectEqual(@as(usize, 1), f.count()); + try std.testing.expectEqual(@as(usize, 0), f.refusals()); const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (refused) { .failed => |why| try std.testing.expect(std.mem.indexOf(u8, why.reason, "fixture") == null), diff --git a/zig/src/server/chat_cli_reply.zig b/zig/src/server/chat_cli_reply.zig index 91ecf088901..0460faaf82d 100644 --- a/zig/src/server/chat_cli_reply.zig +++ b/zig/src/server/chat_cli_reply.zig @@ -238,7 +238,6 @@ test "chat CLI: KR69 source prefixes stay out of terminal and history across SSE .{ .held = "abcd", .continuation = "X" }, .{ .held = "abc%64", .continuation = "X" }, .{ .held = "abc%2564", .continuation = "X" }, - .{ .held = "abc%6", .continuation = "X" }, }; for (cases) |case| { var seen: Seen = .{ .a = a }; @@ -255,6 +254,23 @@ test "chat CLI: KR69 source prefixes stay out of terminal and history across SSE } } +test "chat CLI: an invalidated percent escape releases its complete safe text across SSE events" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var seen: Seen = .{ .a = a }; + var r: Reply = .{ .a = a, .sink = seen.sink(), .secrets = &.{"abcde"} }; + try r.feed(try contentDelta(a, "abc%6")); + try std.testing.expectEqualStrings("", seen.text.items); + try std.testing.expectEqualStrings("", r.content.items); + try r.feed(try contentDelta(a, "X")); + try r.feed(finishing_events); + try r.end(); + try std.testing.expectEqualStrings("abc%6X", seen.text.items); + try std.testing.expectEqualStrings("abc%6X", r.content.items); + try std.testing.expect(r.complete()); +} + test "chat CLI: KR69 transformed prefixes stay out of terminal and history across SSE events" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index e75138da9bd..304124889d0 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -78,16 +78,37 @@ pub fn body(a: Allocator, s: Settings, history: *const History, user: []const u8 return json.stringify(a, .{ .object = o }, .{}); } +fn containsRequest(a: Allocator, request: []const u8, forms: []const []const u8) Allocator.Error!bool { + if (try credential.contains(a, request, forms)) return true; + return switch (try json.parse(a, request)) { + .ok => |value| try containsJsonValue(a, value, forms), + .err => false, // Non-JSON direct callers retain the exact serialized-byte check above. + }; +} + +fn containsJsonValue(a: Allocator, value: json.Value, forms: []const []const u8) Allocator.Error!bool { + switch (value) { + .string => |text| return credential.contains(a, text, forms), + .array => |items| for (items) |item| if (try containsJsonValue(a, item, forms)) return true, + .object => |object| for (object.keys(), object.values()) |key, item| { + if (try credential.contains(a, key, forms)) return true; + if (try containsJsonValue(a, item, forms)) return true; + }, + else => {}, + } + return false; +} + /// The exact serialized request, or null when credential containment suppresses it; null must never be POSTed. pub fn checkedBody(a: Allocator, s: Settings, history: *const History, user: []const u8, credentials: Credentials) !?[]u8 { const request = try body(a, s, history, user); - if (try credential.contains(a, request, credentials.forms)) return null; + if (try containsRequest(a, request, credentials.forms)) return null; return request; } /// One streamed turn to ``url``, the chat route, printed to ``out`` as it arrives; a stop signal ends it ``stopped``. pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credentials: Credentials, request: []u8, out: *std.Io.Writer, show: Show) !Ended { - if ((try credential.contains(a, url, credentials.forms)) or (try credential.contains(a, request, credentials.forms))) + if ((try credential.contains(a, url, credentials.forms)) or (try containsRequest(a, request, credentials.forms))) return .{ .failed = .{ .reason = credential.withheld } }; var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = io }; client.connection_pool.free_size = 0; @@ -306,25 +327,26 @@ test "chat CLI: final request containment catches JSON escape synthesis in model var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const cases = [_]struct { secret: []const u8, decoded: []const u8 }{ - .{ .secret = "\\u00e9", .decoded = "\u{e9}" }, - .{ .secret = "\\n", .decoded = "\n" }, - .{ .secret = "\\\"", .decoded = "\"" }, - .{ .secret = "\\\\", .decoded = "\\" }, + const cases = [_]struct { secret: []const u8, decoded: []const u8, escaped: []const u8 }{ + .{ .secret = "\\u00e9", .decoded = "\u{e9}", .escaped = "\\u00e9" }, + .{ .secret = "\\n", .decoded = "\n", .escaped = "\\n" }, + .{ .secret = "\\\"", .decoded = "\"", .escaped = "\\\"" }, + .{ .secret = "\\\\", .decoded = "\\", .escaped = "\\\\" }, + .{ .secret = "\u{e9}abc", .decoded = "\u{e9}abc", .escaped = "\\u00e9abc" }, }; for (cases) |case| { const secrets = [_][]const u8{case.secret}; const credentials: Credentials = .{ .forms = &secrets }; var retained: History = .{ .a = a }; try retained.keep("question", case.decoded); - try std.testing.expect(std.mem.indexOf(u8, case.decoded, case.secret) == null); + if (!std.mem.eql(u8, case.secret, case.decoded)) try std.testing.expect(std.mem.indexOf(u8, case.decoded, case.secret) == null); const from_history = try body(a, .{ .model = "m" }, &retained, "next"); - try std.testing.expect(std.mem.indexOf(u8, from_history, case.secret) != null); + try std.testing.expect(std.mem.indexOf(u8, from_history, case.escaped) != null); try std.testing.expect((try checkedBody(a, .{ .model = "m" }, &retained, "next", credentials)) == null); var empty: History = .{ .a = a }; const from_model = try body(a, .{ .model = case.decoded }, &empty, "next"); - try std.testing.expect(std.mem.indexOf(u8, from_model, case.secret) != null); + try std.testing.expect(std.mem.indexOf(u8, from_model, case.escaped) != null); try std.testing.expect((try checkedBody(a, .{ .model = case.decoded }, &empty, "next", credentials)) == null); } } @@ -351,11 +373,11 @@ test "chat CLI: final request containment preserves an ordinary serialized body var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const forms = [_][]const u8{ "\\u00e9", "\\n", "\\\"", "\\\\" }; + const forms = [_][]const u8{ "\\u00e9", "\\n", "\\\"", "\\\\", "abcdefghi" }; var h: History = .{ .a = a }; try h.keep("one", "1"); - const expected = try body(a, .{ .model = "m" }, &h, "two"); - const checked = (try checkedBody(a, .{ .model = "m" }, &h, "two", .{ .forms = &forms })) orelse return error.TestUnexpectedResult; + const expected = try body(a, .{ .model = "m" }, &h, "abc% safe"); + const checked = (try checkedBody(a, .{ .model = "m" }, &h, "abc% safe", .{ .forms = &forms })) orelse return error.TestUnexpectedResult; try std.testing.expectEqualStrings(expected, checked); } From 106f20185fe761bf80991c7f26cd1a86c53fcf39 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:55:15 +0000 Subject: [PATCH 098/361] chat: scan every request JSON string --- zig/src/server/benchmark_stream_test.zig | 25 ++++++++++++++++++- zig/src/server/chat_cli_turn.zig | 31 ++++++++++++------------ zig/src/server/json.zig | 2 ++ zig/src/server/json_parse.zig | 21 +++++++++++++++- 4 files changed, 61 insertions(+), 18 deletions(-) diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index e60040ed1df..56105f956b5 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -343,12 +343,35 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses } try std.testing.expectEqual(@as(usize, 1), f.count()); try std.testing.expectEqual(@as(usize, 0), f.refusals()); + const malformed = "{\"model\":\"\\u00E9abc"; + var deep: std.ArrayList(u8) = .empty; + for (0..901) |_| try deep.appendSlice(a, "["); + try deep.appendSlice(a, "{\"model\":\"\\u00E9abc\"}"); + for (0..901) |_| try deep.append(a, ']'); + const hostile_first = "{\"model\":\"\\u00E9abc\",\"model\":\"safe\",\"messages\":[],\"stream\":true}"; + const hostile_last = "{\"model\":\"safe\",\"model\":\"\\u00E9abc\",\"messages\":[],\"stream\":true}"; + for ([_][]const u8{ malformed, deep.items, hostile_first, hostile_last }) |request| { + const attack = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, unicode_credentials, try a.dupe(u8, request), &out.writer, .{}); + switch (attack) { + .failed => |why| try std.testing.expectEqualStrings("[withheld]", why.reason), + else => {}, + } + } + try std.testing.expectEqual(@as(usize, 1), f.count()); + const safe_duplicate = "{\"model\":\"first\",\"model\":\"safe\",\"messages\":[],\"stream\":true}"; + const safe = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, unicode_credentials, try a.dupe(u8, safe_duplicate), &out.writer, .{}); + switch (safe) { + .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), + else => return error.TestUnexpectedResult, + } + try std.testing.expectEqual(@as(usize, 2), f.count()); + try std.testing.expectEqualStrings(safe_duplicate, f.request(1).body); const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); switch (refused) { .failed => |why| try std.testing.expect(std.mem.indexOf(u8, why.reason, "fixture") == null), else => return error.TestUnexpectedResult, } - try std.testing.expectEqual(@as(usize, 1), f.count()); + try std.testing.expectEqual(@as(usize, 2), f.count()); try std.testing.expectEqual(@as(usize, 0), f.refusals()); try std.testing.expect(std.mem.indexOf(u8, f.request(0).path, token) == null); try std.testing.expect(std.mem.indexOf(u8, out.written(), token) == null); diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index 304124889d0..6e30842e09c 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -78,27 +78,26 @@ pub fn body(a: Allocator, s: Settings, history: *const History, user: []const u8 return json.stringify(a, .{ .object = o }, .{}); } +const RequestStrings = struct { + a: Allocator, + forms: []const []const u8, + found: bool = false, + + fn visit(context: *anyopaque, text: []const u8) Allocator.Error!void { + const s: *RequestStrings = @ptrCast(@alignCast(context)); + if (!s.found) s.found = try credential.contains(s.a, text, s.forms); + } +}; + fn containsRequest(a: Allocator, request: []const u8, forms: []const []const u8) Allocator.Error!bool { if (try credential.contains(a, request, forms)) return true; - return switch (try json.parse(a, request)) { - .ok => |value| try containsJsonValue(a, value, forms), - .err => false, // Non-JSON direct callers retain the exact serialized-byte check above. + var strings: RequestStrings = .{ .a = a, .forms = forms }; + return switch (try json.scanStrings(a, request, &strings, &RequestStrings.visit)) { + .ok => strings.found, + .err => true, // A direct application/json body that cannot be parsed completely never leaves. }; } -fn containsJsonValue(a: Allocator, value: json.Value, forms: []const []const u8) Allocator.Error!bool { - switch (value) { - .string => |text| return credential.contains(a, text, forms), - .array => |items| for (items) |item| if (try containsJsonValue(a, item, forms)) return true, - .object => |object| for (object.keys(), object.values()) |key, item| { - if (try credential.contains(a, key, forms)) return true; - if (try containsJsonValue(a, item, forms)) return true; - }, - else => {}, - } - return false; -} - /// The exact serialized request, or null when credential containment suppresses it; null must never be POSTed. pub fn checkedBody(a: Allocator, s: Settings, history: *const History, user: []const u8, credentials: Credentials) !?[]u8 { const request = try body(a, s, history, user); diff --git a/zig/src/server/json.zig b/zig/src/server/json.zig index c0a035874fc..5515dec46ef 100644 --- a/zig/src/server/json.zig +++ b/zig/src/server/json.zig @@ -3,6 +3,8 @@ const std = @import("std"); const Allocator = std.mem.Allocator; pub const parse = @import("json_parse.zig").parse; +pub const scanStrings = @import("json_parse.zig").scanStrings; +pub const StringVisitor = @import("json_parse.zig").StringVisitor; pub const parseText = @import("json_parse.zig").parseText; pub const ParseResult = @import("json_parse.zig").Result; pub const wtf8Encode = @import("json_parse.zig").wtf8Encode; diff --git a/zig/src/server/json_parse.zig b/zig/src/server/json_parse.zig index 1bb671d0bfe..da210e2d2ea 100644 --- a/zig/src/server/json_parse.zig +++ b/zig/src/server/json_parse.zig @@ -9,16 +9,27 @@ pub const Result = union(enum) { err: []const u8, // ``str(exc)`` as Python words it }; +pub const StringVisitor = *const fn (context: *anyopaque, text: []const u8) Allocator.Error!void; + const max_depth = 900; // nesting past this answers as Python's RecursionError does const Failure = error{ Syntax, OutOfMemory }; /// Decode ``bytes`` as UTF-8 (a BOM dropped, surrogates passed) and parse one JSON document. pub fn parse(a: Allocator, bytes: []const u8) Allocator.Error!Result { + return parseWalk(a, bytes, null, null); +} + +/// Parse one complete document, visiting every decoded object key and string value before duplicate insertion. +pub fn scanStrings(a: Allocator, bytes: []const u8, context: *anyopaque, visit: StringVisitor) Allocator.Error!Result { + return parseWalk(a, bytes, context, visit); +} + +fn parseWalk(a: Allocator, bytes: []const u8, context: ?*anyopaque, visit: ?StringVisitor) Allocator.Error!Result { var text = bytes; if (std.mem.startsWith(u8, text, "\xef\xbb\xbf")) text = text[3..]; if (try utf8Error(a, text, if (text.ptr == bytes.ptr) 0 else 3)) |message| return .{ .err = message }; - var p: Parser = .{ .a = a, .s = text }; + var p: Parser = .{ .a = a, .s = text, .context = context, .visit = visit }; const start = p.skip(0); const value = p.value(start, 0) catch |e| switch (e) { error.OutOfMemory => return error.OutOfMemory, @@ -73,6 +84,8 @@ const Parser = struct { s: []const u8, pos: usize = 0, message: []const u8 = "", + context: ?*anyopaque = null, + visit: ?StringVisitor = null, fn skip(p: *const Parser, at: usize) usize { var i = at; @@ -181,6 +194,12 @@ const Parser = struct { } fn string(p: *Parser, begin: usize) Failure![]const u8 { + const text = try p.decodeString(begin); + if (p.visit) |visit| try visit(p.context.?, text); + return text; + } + + fn decodeString(p: *Parser, begin: usize) Failure![]const u8 { const s = p.s; var out: std.ArrayList(u8) = .empty; var i = begin; From f2cf4444c48a1ba3d21eeec7a5c5c04d40609b0e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:57:23 +0000 Subject: [PATCH 099/361] server: keep existing API keys working --- zig/src/server/auth.zig | 9 ++++--- zig/src/server/benchmark_stream.zig | 14 +++++++--- zig/src/server/benchmark_stream_test.zig | 26 ++++++++++++------- zig/src/server/chat_cli.zig | 19 ++++++++++++-- zig/src/server/chat_cli_key_test.zig | 33 ++++++++++++++++++++++++ zig/src/server/chat_cli_test.zig | 19 +++++++------- zig/src/server/chat_cli_turn.zig | 2 +- zig/src/server/root.zig | 1 + zig/src/server/start_cli.zig | 2 +- zig/src/server/start_cli_test.zig | 4 +-- 10 files changed, 97 insertions(+), 32 deletions(-) create mode 100644 zig/src/server/chat_cli_key_test.zig diff --git a/zig/src/server/auth.zig b/zig/src/server/auth.zig index 61492d14f0c..d9a54d47686 100644 --- a/zig/src/server/auth.zig +++ b/zig/src/server/auth.zig @@ -251,7 +251,7 @@ fn emptyDigest() [32]u8 { return out; } -/// An API key is 1-256 bytes of UTF-8 whose scalars fit Latin-1 and exclude whitespace or controls. +/// A managed-start key is 1-256 UTF-8 bytes whose scalars fit Latin-1 and exclude whitespace or controls. pub fn validKey(key: []const u8) bool { if (key.len == 0 or key.len > 256) return false; var view = std.unicode.Utf8View.init(key) catch return false; @@ -260,9 +260,12 @@ pub fn validKey(key: []const u8) bool { return true; } -/// SHA-256 of a key, or null when ``validKey`` rejects it. +/// SHA-256 of a server key, preserving main's acceptance of any-length UTF-8 without C0 controls or Unicode whitespace. fn digest(key: []const u8) ?[32]u8 { - if (!validKey(key)) return null; + if (key.len == 0) return null; + var view = std.unicode.Utf8View.init(key) catch return null; + var it = view.iterator(); + while (it.nextCodepoint()) |cp| if (cp < 32 or isSpace(cp)) return null; var out: [32]u8 = undefined; Sha256.hash(key, &out, .{}); return out; diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index 7083e44748d..fd74850f347 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -343,16 +343,24 @@ pub const Fetched = struct { failed: enum { none, network, too_large, stopped, deadline } = .none, }; -/// Python's raw Authorization header: Unicode scalar values encoded as Latin-1, never raw UTF-8. +/// Latin-1 uses Python's header bytes; other legacy UTF-8 keeps main's bytes, with C0 and DEL excluded. pub fn rawHeader(buf: []u8, token: []const u8) ?[]const u8 { const prefix = "Bearer "; if (prefix.len + token.len > buf.len) return null; @memcpy(buf[0..prefix.len], prefix); - var view = std.unicode.Utf8View.init(token) catch return null; + var view = std.unicode.Utf8View.init(token) catch { + for (token) |ch| if (ch < 0x20 or ch == 0x7f) return null; + @memcpy(buf[prefix.len..][0..token.len], token); + return buf[0 .. prefix.len + token.len]; + }; var it = view.iterator(); var n = prefix.len; while (it.nextCodepoint()) |cp| { - if (cp > 0xff or cp < 0x20 or (cp >= 0x7f and cp <= 0x9f)) return null; + if (cp < 0x20 or cp == 0x7f) return null; + if (cp > 0xff or (cp >= 0x7f and cp <= 0x9f)) { + @memcpy(buf[prefix.len..][0..token.len], token); + return buf[0 .. prefix.len + token.len]; + } buf[n] = @intCast(cp); n += 1; } diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index 56105f956b5..10ccac67673 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -273,7 +273,7 @@ test "chat CLI: a Latin-1 bearer uses the server's header bytes without exposing var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const f = try fake.Fake.start(std.testing.allocator, &.{.{ .method = "GET", .path = "/v1/models", .replies = &.{try fake.jsonReply(a, "200 OK", "{\"data\": []}")} }}); + const f = try fake.Fake.start(std.testing.allocator, &.{.{ .method = "GET", .path = "/v1/models", .replies = &.{ try fake.jsonReply(a, "200 OK", "{\"data\": []}"), try fake.jsonReply(a, "200 OK", "{\"data\": []}") } }}); defer f.stop(); var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = std.testing.io }; defer client.deinit(); @@ -283,29 +283,35 @@ test "chat CLI: a Latin-1 bearer uses the server's header bytes without exposing try std.testing.expectEqual(@as(u16, 200), got.status); try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", f.header(0, "authorization").?); try std.testing.expect(std.mem.indexOf(u8, f.request(0).head, token) == null); - const refused = stream.fetch(a, std.testing.io, &client, .{ .url = try f.url(a, "/v1/models"), .limit = 64, .timeout_s = 5, .token = "fixture-\u{20ac}" }); - try std.testing.expectEqual(.network, refused.failed); - try std.testing.expectEqual(@as(usize, 1), f.count()); + const legacy = stream.fetch(a, std.testing.io, &client, .{ .url = try f.url(a, "/v1/models"), .limit = 64, .timeout_s = 5, .token = "fixture-\u{20ac}" }); + try std.testing.expectEqual(.none, legacy.failed); + try std.testing.expectEqual(@as(u16, 200), legacy.status); + try std.testing.expectEqualStrings("Bearer fixture-\u{20ac}", f.header(1, "authorization").?); + try std.testing.expectEqual(@as(usize, 2), f.count()); } -test "chat CLI: the complete C1 range is refused by key validation and raw headers" { +test "chat CLI: managed validation rejects C1 while legacy raw headers retain main's bytes" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var buf: [300]u8 = undefined; - for (0x7f..0xa0) |cp| { - var encoded: [4]u8 = undefined; + var encoded: [4]u8 = undefined; + const del_len = try std.unicode.utf8Encode(0x7f, &encoded); + try std.testing.expect(stream.rawHeader(&buf, encoded[0..del_len]) == null); + for (0x80..0xa0) |cp| { const len = try std.unicode.utf8Encode(@intCast(cp), &encoded); const token = try std.mem.concat(a, u8, &.{ "fixture-", encoded[0..len] }); try std.testing.expect(!@import("auth.zig").validKey(token)); - try std.testing.expect(stream.rawHeader(&buf, token) == null); + const raw = stream.rawHeader(&buf, token).?; + try std.testing.expectEqualStrings("Bearer ", raw[0..7]); + try std.testing.expectEqualStrings(token, raw[7..]); } const latin1 = "fixture-caf\u{e9}"; try std.testing.expect(@import("auth.zig").validKey(latin1)); try std.testing.expectEqualStrings("Bearer fixture-caf\xe9", stream.rawHeader(&buf, latin1).?); } -test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses unsupported keys" { +test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and preserves unsupported legacy keys" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -372,7 +378,7 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and refuses else => return error.TestUnexpectedResult, } try std.testing.expectEqual(@as(usize, 2), f.count()); - try std.testing.expectEqual(@as(usize, 0), f.refusals()); + try std.testing.expectEqual(@as(usize, 1), f.refusals()); try std.testing.expect(std.mem.indexOf(u8, f.request(0).path, token) == null); try std.testing.expect(std.mem.indexOf(u8, out.written(), token) == null); } diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 36f20de7ca2..202adba11bb 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -98,10 +98,25 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { if (comptime windows) return fail(ctx, windows_child) else return served(ctx, args, message); } -pub const bad_key = "TENSORFOLD_API_KEY: expected Latin-1 keys without spaces or control characters, at most 256 bytes each"; +pub const bad_key = "TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each"; +pub const managed_bad_key = "TENSORFOLD_API_KEY: expected Latin-1 keys without spaces or control characters, at most 256 bytes each"; -/// The first nonempty valid entry for ``--url``; null when all are empty. Every entry is checked first. +/// The existing --url behavior: its first nonempty entry, with main's byte and length checks. pub fn envKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u8 { + const text = (environment.path("TENSORFOLD_API_KEY", environ.get("TENSORFOLD_API_KEY")) catch return error.Refused) orelse return null; + var keys = std.mem.splitScalar(u8, text, ','); + while (keys.next()) |raw| { + const key = std.mem.trim(u8, raw, " \t\r\n\x0b\x0c"); + if (key.len == 0) continue; + if (key.len > 256) return error.Refused; + for (key) |ch| if (ch < 0x21 or ch == 0x7f) return error.Refused; + return key; + } + return null; +} + +/// Managed start validates every entry against the bounded matcher's Latin-1 header representation. +pub fn managedKey(environ: *const std.process.Environ.Map) error{Refused}!?[]const u8 { const text = (environment.path("TENSORFOLD_API_KEY", environ.get("TENSORFOLD_API_KEY")) catch return error.Refused) orelse return null; var keys = std.mem.splitScalar(u8, text, ','); var selected: ?[]const u8 = null; diff --git a/zig/src/server/chat_cli_key_test.zig b/zig/src/server/chat_cli_key_test.zig new file mode 100644 index 00000000000..9b04b072cb3 --- /dev/null +++ b/zig/src/server/chat_cli_key_test.zig @@ -0,0 +1,33 @@ +const std = @import("std"); +const chat = @import("chat_cli.zig"); +const stream = @import("benchmark_stream.zig"); + +test "chat CLI: existing keys retain main's non-Latin-1 acceptance and bounded containment" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var env: std.process.Environ.Map = .init(a); + const key = "fixture-\u{20ac}"; + try env.put("TENSORFOLD_API_KEY", key); + try std.testing.expectEqualStrings(key, (try chat.envKey(&env)).?); + var buf: [300]u8 = undefined; + try std.testing.expectEqualStrings("Bearer " ++ key, stream.rawHeader(&buf, key).?); + const credentials = try @import("chat_cli_turn.zig").Credentials.init(a, &.{key}); + const safe = (try credentials.safe(a, "server reflected fixture-\u{20ac}")).?; + try std.testing.expect(std.mem.indexOf(u8, safe, key) == null); + const long: [257]u8 = @splat('k'); + try env.put("TENSORFOLD_API_KEY", &long); + try std.testing.expectError(error.Refused, chat.envKey(&env)); +} + +test "chat CLI: serve registration keeps main's long, non-Latin-1 and legacy-control acceptance" { + const long: [300]u8 = @splat('k'); + var problem: []const u8 = ""; + var store = try @import("auth.zig").Store.init(std.testing.allocator, &.{ &long, "fixture-\u{20ac}", "fixture-\u{007f}", "fixture-\u{009b}" }, "", null, false, &problem); + defer store.deinit(); + try std.testing.expectEqual(@as(usize, 4), store.static.items.len); + try std.testing.expectEqualStrings("cli-1", store.static.items[0].label); + try std.testing.expectEqualStrings("cli-2", store.static.items[1].label); + try std.testing.expectEqualStrings("cli-3", store.static.items[2].label); + try std.testing.expectEqualStrings("cli-4", store.static.items[3].label); +} diff --git a/zig/src/server/chat_cli_test.zig b/zig/src/server/chat_cli_test.zig index 752ceb4e66f..c20c7d0465a 100644 --- a/zig/src/server/chat_cli_test.zig +++ b/zig/src/server/chat_cli_test.zig @@ -195,7 +195,7 @@ test "chat CLI: --url sends TENSORFOLD_API_KEY's first key as the bearer, and a for (0..f.count()) |i| try std.testing.expectEqualStrings("Bearer example-key-1", f.header(i, "authorization").?); try r.env.put("TENSORFOLD_API_KEY", "two words"); try std.testing.expectEqual(@as(u8, 1), try r.command(&.{ "--url", url })); - try std.testing.expectEqualStrings("tensorfold chat: TENSORFOLD_API_KEY: expected Latin-1 keys without spaces or control characters, at most 256 bytes each\n", r.err.written()); + try std.testing.expectEqualStrings("tensorfold chat: TENSORFOLD_API_KEY: expected keys without spaces or control characters, at most 256 bytes each\n", r.err.written()); try std.testing.expect(f.refusals() == 5 and f.count() == 2); } @@ -249,7 +249,7 @@ test "chat CLI: attached responses redact credentials before every output bounda try std.testing.expect(std.mem.indexOf(u8, shown.items, "[redacted]") != null); } -test "chat CLI: C1 controls in any key entry are refused before any request" { +test "chat CLI: legacy C1 and later comma entries keep main's request behavior" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -260,16 +260,15 @@ test "chat CLI: C1 controls in any key entry are refused before any request" { const f = try world(a, models_doc, replies); defer f.stop(); r.input = "hi"; - var ok = true; - for ([_][]const u8{ "fixture-\u{009b}", "good-key,fixture-\u{009b}" }) |key| { + for ([_][]const u8{ "fixture-\u{009b}", "good-key,fixture-\u{009b}" }, 0..) |key, i| { try r.env.put("TENSORFOLD_API_KEY", key); - const code = try r.command(&.{ "--url", try f.url(a, "") }); - ok = ok and code == 1; - ok = ok and f.count() == 0; - ok = ok and std.mem.indexOf(u8, r.err.written(), "expected Latin-1 keys without spaces or control characters") != null; - ok = ok and std.mem.indexOf(u8, r.err.written(), key) == null; + const before = f.count(); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try std.testing.expectEqual(before + 2, f.count()); + const expected = if (i == 0) "Bearer fixture-\u{009b}" else "Bearer good-key"; + try std.testing.expectEqualStrings(expected, f.header(before, "authorization").?); + try std.testing.expectEqualStrings("", r.err.written()); } - try std.testing.expect(ok); } test "chat CLI: --no-thinking sends the documented switch, and is refused before any turn when the model has none" { diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index 6e30842e09c..63cb6be23c9 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -28,7 +28,7 @@ pub const Credentials = struct { if (secret.len == 0) continue; try forms.append(a, secret); var buf: [300]u8 = undefined; - if (stream.rawHeader(&buf, secret)) |raw| try forms.append(a, try a.dupe(u8, raw[7..])); + if (stream.rawHeader(&buf, secret)) |raw| if (!std.mem.eql(u8, raw[7..], secret)) try forms.append(a, try a.dupe(u8, raw[7..])); } return .{ .forms = forms.items }; } diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index d5a03823a54..00da6e09017 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -292,6 +292,7 @@ test { _ = @import("benchmark_stop_test.zig"); _ = @import("benchmark_sse_test.zig"); _ = @import("benchmark_stream_test.zig"); + _ = @import("chat_cli_key_test.zig"); _ = @import("benchmark_server_test.zig"); _ = @import("benchmark_facts_test.zig"); _ = @import("benchmark_rocm_test.zig"); diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index 7a3dffcea51..b864a368e32 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -134,7 +134,7 @@ pub fn command(ctx: *const Context, argv: []const []const u8) !u8 { } fn run(ctx: *const Context, args: Args) !u8 { - const caller_key = if (args.check) null else chat.envKey(ctx.environ) catch return fail(ctx, 2, chat.bad_key, .{}); + const caller_key = if (args.check) null else chat.managedKey(ctx.environ) catch return fail(ctx, 2, chat.managed_bad_key, .{}); if (!args.check and caller_key == null) return fail(ctx, 2, "persistent start requires a nonempty TENSORFOLD_API_KEY entry in the environment, or use --check for a private temporary key", .{}); const mc = ctx.given orelse machine.detect(ctx.a, ctx.io); diff --git a/zig/src/server/start_cli_test.zig b/zig/src/server/start_cli_test.zig index da2a02f9c21..76f6906107f 100644 --- a/zig/src/server/start_cli_test.zig +++ b/zig/src/server/start_cli_test.zig @@ -458,10 +458,10 @@ test "start CLI: persistent mode requires a valid environment credential before try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); } - for ([_][]const u8{ "\xc2\xa0", "good-key,bad key", "good-key,\xc2\xa0", "fixture-\u{009b}", "good-key,fixture-\u{009b}" }) |key| { + for ([_][]const u8{ "\xc2\xa0", "good-key,bad key", "good-key,\xc2\xa0", "fixture-\u{009b}", "good-key,fixture-\u{009b}", "fixture-\u{20ac}" }) |key| { try r.env.put("TENSORFOLD_API_KEY", key); try std.testing.expectEqual(@as(u8, 2), try r.command(&.{})); - try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "expected Latin-1 keys without spaces or control characters") != null); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), "expected Latin-1 keys without spaces or control characters") != null and std.mem.indexOf(u8, r.err.written(), key) == null); try std.testing.expectEqual(@as(usize, 0), r.pulls.items.len); try std.testing.expect(std.mem.indexOf(u8, r.out.written(), "Selected ") == null); } From 274c865d80087e0682899515eddc2acad58cf998 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:42:12 +0000 Subject: [PATCH 100/361] security: preserve legacy chat keys and contain artifact credentials --- zig/build/pull_tests.zig | 1 + zig/src/cli/pull.zig | 4 + zig/src/cli/pull_auth.zig | 79 +++++++++++ zig/src/cli/pull_exlr8.zig | 40 +++--- zig/src/cli/pull_file.zig | 28 +++- zig/src/cli/pull_kp50_test.zig | 4 +- zig/src/cli/pull_parts.zig | 49 ++++++- zig/src/cli/pull_runs.zig | 57 +++++++- zig/src/cli/pull_security_test.zig | 165 +++++++++++++++++++++++ zig/src/cli/pull_test.zig | 4 +- zig/src/server/benchmark_stream.zig | 8 +- zig/src/server/benchmark_stream_test.zig | 10 +- zig/src/server/chat_cli.zig | 4 +- zig/src/server/chat_cli_kia68_test.zig | 35 +++++ zig/src/server/chat_cli_turn.zig | 6 +- zig/src/server/root.zig | 1 + zig/src/server/start_cli.zig | 2 +- 17 files changed, 451 insertions(+), 46 deletions(-) create mode 100644 zig/src/server/chat_cli_kia68_test.zig diff --git a/zig/build/pull_tests.zig b/zig/build/pull_tests.zig index 2282185f0d2..230256c9586 100644 --- a/zig/build/pull_tests.zig +++ b/zig/build/pull_tests.zig @@ -42,6 +42,7 @@ pub fn add(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti .imports = &.{ .{ .name = "native_engines", .module = engines }, @import("exlr8.zig").cliImport(b, target, optimize, core) }, }) })); test_step.dependOn(&security.step); + b.step("test-pull-security-host", "Credential, metadata, cache and artifact-body containment against a local fake hub").dependOn(&security.step); } pub fn compile(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *std.Build.Module) void { diff --git a/zig/src/cli/pull.zig b/zig/src/cli/pull.zig index c6d77f60078..88cf10f4fda 100644 --- a/zig/src/cli/pull.zig +++ b/zig/src/cli/pull.zig @@ -142,6 +142,10 @@ pub fn runWith(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.W std.Io.Dir.cwd().deleteFile(io, blob_path) catch {}; break :blob_exists; } + if (auth.fileContains(a, io, blob_path) catch true) { + std.Io.Dir.cwd().deleteFile(io, blob_path) catch {}; + break :blob_exists; + } try out.print(" {s}: cached\n", .{e.path}); try linkIntoSnapshot(a, io, snapshot_dir, e.path, blob_name); continue; diff --git a/zig/src/cli/pull_auth.zig b/zig/src/cli/pull_auth.zig index 3af4fb4cefc..3107d1b34e2 100644 --- a/zig/src/cli/pull_auth.zig +++ b/zig/src/cli/pull_auth.zig @@ -63,6 +63,85 @@ pub const Auth = struct { return credential.contains(std.heap.page_allocator, text, &.{secret}) catch true; } + /// Refuse complete raw or encoded credentials; ambiguous suffixes stay buffered until later bytes decide. + pub const Body = struct { + auth: Auth, + pending: std.ArrayList(u8) = .empty, + + pub fn init(auth: Auth) Body { + return .{ .auth = auth }; + } + + pub fn deinit(b: *Body, a: Allocator) void { + b.pending.deinit(a); + } + + pub fn buffered(b: *const Body) usize { + return b.pending.items.len; + } + + /// The prefix now proven safe; the caller writes it once, then commits that exact length. + pub fn feed(b: *Body, a: Allocator, bytes: []const u8) ![]const u8 { + try b.pending.appendSlice(a, bytes); + const bearer = b.auth.bearer orelse return b.pending.items; + const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; + if (secret.len == 0) return b.pending.items; + const secrets = [_][]const u8{secret}; + var matcher = credential.Matcher.init(a, b.pending.items); + defer matcher.deinit(); + var i: usize = 0; + while (i < b.pending.items.len) : (i += 1) { + const found = try matcher.secretAt(i, &secrets); + if (found.consumed > 0) return error.HubCredentialBody; + if (found.hold and found.prefix_len > 0) return b.pending.items[0..i]; + } + return b.pending.items; + } + + pub fn commit(b: *Body, sent: usize) void { + const left = b.pending.items.len - sent; + std.mem.copyForwards(u8, b.pending.items[0..left], b.pending.items[sent..]); + b.pending.shrinkRetainingCapacity(left); + } + + /// The real end of a contiguous body: an incomplete encoding is data, a full key is not. + pub fn finish(b: *Body, a: Allocator) ![]const u8 { + const bearer = b.auth.bearer orelse return b.pending.items; + const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; + if (secret.len == 0) return b.pending.items; + var matcher = credential.Matcher.init(a, b.pending.items); + defer matcher.deinit(); + if (try matcher.spanFrom(0, secret) != null) return error.HubCredentialBody; + return b.pending.items; + } + }; + + /// A cached file with a complete raw or nested-encoded key, checked without whole-file allocation. + pub fn fileContains(auth: Auth, a: Allocator, io: std.Io, path: []const u8) !bool { + if (auth.bearer == null) return false; + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer file.close(io); + var body: Body = .init(auth); + defer body.deinit(a); + var buf: [64 << 10]u8 = undefined; + var offset: u64 = 0; + while (true) { + const n = try file.readPositionalAll(io, &buf, offset); + if (n == 0) break; + const safe = body.feed(a, buf[0..n]) catch |err| { + if (err == error.HubCredentialBody) return true; + return err; + }; + body.commit(safe.len); + offset += n; + } + _ = body.finish(a) catch |err| { + if (err == error.HubCredentialBody) return true; + return err; + }; + return false; + } + /// Server-controlled text with each plain or repeatedly percent-encoded credential occurrence replaced. pub fn redact(auth: Auth, a: Allocator, text: []const u8) ![]const u8 { const bearer = auth.bearer orelse return text; diff --git a/zig/src/cli/pull_exlr8.zig b/zig/src/cli/pull_exlr8.zig index 0198c78686f..20f1b0d24d1 100644 --- a/zig/src/cli/pull_exlr8.zig +++ b/zig/src/cli/pull_exlr8.zig @@ -76,7 +76,7 @@ pub fn run(a: Allocator, io: std.Io, out: *std.Io.Writer, err_out: *std.Io.Write .path = try std.fs.path.join(a, &.{ o.dir, pt.rel }), .size = pt.size, }; - const todo = try p.missing(a, io, targets); + const todo = if (auth.bearer != null) p.runs.items else try p.missing(a, io, targets); try out.print(" {d} width files, {d} halves ({d:.2} GiB); {d} of {d} runs to fetch\n", .{ targets.len, p.units.items.len, gib(p.expert_bytes), todo.len, p.runs.items.len }); try out.flush(); runs.fetch(a, io, targets, todo, p.check(), auth, out) catch |e| { @@ -119,7 +119,7 @@ pub fn fetchWhole(a: Allocator, io: std.Io, client: *std.http.Client, out: *std. for (whole) |e| { const final = try std.fs.path.join(a, &.{ dir, e.path }); if (std.fs.path.dirname(final)) |parent| try w.createDirPath(io, parent); - if (try present(a, io, final, e)) continue; + if (try present(a, io, final, e, auth)) continue; const url = try std.fmt.allocPrint(a, "{s}/{s}/resolve/{s}/{s}", .{ auth.endpoint, repo, sha, e.path }); if (e.sha256 != null) { // the storage link, not the hub's: pieces then skip a redirect each @@ -150,25 +150,29 @@ pub fn fetchWhole(a: Allocator, io: std.Io, client: *std.http.Client, out: *std. } /// Whether `path` already holds the entry's bytes (size, then its sha256 or git blob sha1). -fn present(a: Allocator, io: std.Io, path: []const u8, e: single.Entry) !bool { +fn present(a: Allocator, io: std.Io, path: []const u8, e: single.Entry, auth: Auth) !bool { const size = single.fileStat(io, path) catch return false; if (size != e.size) return false; - if (e.sha256) |want| return std.mem.eql(u8, &(try ranged.digest(a, io, path, size)), &want); - const want = e.git_sha1 orelse return false; - const file = try std.Io.Dir.cwd().openFile(io, path, .{}); - defer file.close(io); - var git = std.crypto.hash.Sha1.init(.{}); - var head: [32]u8 = undefined; - git.update(try std.fmt.bufPrint(&head, "blob {d}\x00", .{size})); - var buf: [64 << 10]u8 = undefined; - var off: u64 = 0; - while (off < size) { - const n = try file.readPositionalAll(io, buf[0..@intCast(@min(buf.len, size - off))], off); - if (n == 0) return false; - git.update(buf[0..n]); - off += n; + if (e.sha256) |want| { + if (!std.mem.eql(u8, &(try ranged.digest(a, io, path, size)), &want)) return false; + } else { + const want = e.git_sha1 orelse return false; + const file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer file.close(io); + var git = std.crypto.hash.Sha1.init(.{}); + var head: [32]u8 = undefined; + git.update(try std.fmt.bufPrint(&head, "blob {d}\x00", .{size})); + var buf: [64 << 10]u8 = undefined; + var off: u64 = 0; + while (off < size) { + const n = try file.readPositionalAll(io, buf[0..@intCast(@min(buf.len, size - off))], off); + if (n == 0) return false; + git.update(buf[0..n]); + off += n; + } + if (!std.mem.eql(u8, &git.finalResult(), &want)) return false; } - return std.mem.eql(u8, &git.finalResult(), &want); + return !(auth.fileContains(a, io, path) catch true); } /// `--exlr8 PROFILE --node R/N --dir DIR` after the repo; null when none of them is there. diff --git a/zig/src/cli/pull_file.zig b/zig/src/cli/pull_file.zig index b3c72d131e6..8ac94bd7c53 100644 --- a/zig/src/cli/pull_file.zig +++ b/zig/src/cli/pull_file.zig @@ -37,6 +37,10 @@ pub fn downloadRetrying(a: Allocator, io: std.Io, client: *std.http.Client, auth while (true) : (attempt += 1) { const stalls = route.stalls(); if (download(a, io, client, auth, out, url, blobs_dir, e)) |name| return name else |err| { + if (err == error.HubCredentialBody) { + std.Io.Dir.cwd().deleteFile(io, try partialPath(a, blobs_dir, e)) catch {}; + return err; + } if (route.stalls() != stalls) { // no bytes within the stall timeout: resume from the .incomplete bytes now resumes += 1; if (resumes > max_resumes) return error.Stalled; @@ -65,6 +69,7 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: if (fileStat(io, partial_path)) |size| resume_from = size else |_| {} } if (resume_from >= e.size) resume_from = 0; + if (resume_from > 0 and (auth.fileContains(a, io, partial_path) catch true)) return error.HubCredentialBody; var headers: [1]std.http.Header = undefined; var range_buf: [32]u8 = undefined; @@ -89,6 +94,8 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: // Read access too: a resumed blob feeds its on-disk prefix into the same digest. const file = try w.createFile(io, partial_path, .{ .read = true, .truncate = restart }); defer file.close(io); + var body: Auth.Body = .init(auth); + defer body.deinit(a); var hash = std.crypto.hash.sha2.Sha256.init(.{}); const check_git = e.sha256 == null and e.git_sha1 != null; var git = std.crypto.hash.Sha1.init(.{}); // git's blob id: sha1 of "blob SIZE\0" and the bytes @@ -103,6 +110,8 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: const read = file.readPositionalAll(io, prefix_buf[0..want], at) catch 0; if (read == 0) break; hash.update(prefix_buf[0..read]); + const safe = try body.feed(a, prefix_buf[0..read]); + body.commit(safe.len); at += read; } } @@ -116,7 +125,7 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: if (bytes.len > e.size - offset) return error.SizeMismatch; hash.update(bytes); if (check_git) git.update(bytes); - try file.writePositionalAll(io, bytes, offset); + try writeGuarded(a, io, file, &body, bytes, offset); offset += bytes.len; } r.toss(prefix.len); @@ -127,7 +136,7 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: if (bytes.len > e.size - offset) return error.SizeMismatch; hash.update(bytes); if (check_git) git.update(bytes); - try file.writePositionalAll(io, bytes, offset); + try writeGuarded(a, io, file, &body, bytes, offset); offset += bytes.len; } r.toss(left.len); @@ -142,6 +151,11 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: } else if (e.git_sha1) |want| { if (!std.mem.eql(u8, &git.finalResult(), &want)) return error.ShaMismatch; } + const tail = try body.finish(a); + if (tail.len > 0) { + try file.writePositionalAll(io, tail, total - @as(u64, @intCast(tail.len))); + body.commit(tail.len); + } try file.setLength(io, total); file.sync(io) catch {}; try std.Io.Dir.cwd().rename(partial_path, std.Io.Dir.cwd(), final_path, io); @@ -149,6 +163,16 @@ fn download(a: Allocator, io: std.Io, client: *std.http.Client, auth: Auth, out: return final_name; } +/// Write only the proven-safe prefix, retaining ambiguous bytes at `offset - held` until later input. +fn writeGuarded(a: Allocator, io: std.Io, file: std.Io.File, body: *Auth.Body, bytes: []const u8, offset: u64) !void { + if (body.auth.bearer == null) return file.writePositionalAll(io, bytes, offset); + const held = body.buffered(); + const safe = try body.feed(a, bytes); + if (safe.len == 0) return; + try file.writePositionalAll(io, safe, offset - @as(u64, @intCast(held))); + body.commit(safe.len); +} + /// Whether an existing cached blob still has the digest and byte count the hub advertised. pub fn cachedMatches(io: std.Io, path: []const u8, e: Entry) !bool { if (try fileStat(io, path) != e.size) return false; diff --git a/zig/src/cli/pull_kp50_test.zig b/zig/src/cli/pull_kp50_test.zig index b71f2fc8618..4792553cc9d 100644 --- a/zig/src/cli/pull_kp50_test.zig +++ b/zig/src/cli/pull_kp50_test.zig @@ -522,7 +522,7 @@ test "security KR67-2: raw percent and nested-encoded redaction markers are cont } } -test "security KR69-4: a registered family and raw or nested model types contain the HF token" { +test "security KR69-4: credential-bearing model types are contained and their config artifact is refused" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const a = arena_state.allocator(); @@ -536,7 +536,7 @@ test "security KR69-4: a registered family and raw or nested model types contain const env = try envWithToken(a, &fake, secret); var out: std.Io.Writer.Allocating = .init(a); var err_out: std.Io.Writer.Allocating = .init(a); - try std.testing.expectEqual(@as(u8, 0), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); try expectFinalContainment(a, out.written(), err_out.written(), secret); try std.testing.expect(std.mem.indexOf(u8, out.written(), "Qwen3.8 Flash Next ([redacted])") != null); diff --git a/zig/src/cli/pull_parts.zig b/zig/src/cli/pull_parts.zig index 05e2220c4ac..9e7494e2bce 100644 --- a/zig/src/cli/pull_parts.zig +++ b/zig/src/cli/pull_parts.zig @@ -30,6 +30,7 @@ const Shared = struct { files: []const File, handles: []const std.Io.File, todo: []const Piece, + bodies: []Auth.Body, next: std.atomic.Value(usize) = .init(0), bytes: std.atomic.Value(u64) = .init(0), running: std.atomic.Value(u32) = .init(0), @@ -44,21 +45,24 @@ pub fn fetch(a: Allocator, io: std.Io, files: []const File, bytes: u64, auth: Au defer for (handles[0..opened]) |h| h.close(io); var todo: std.ArrayList(Piece) = .empty; var left: u64 = 0; + const bodies = try a.alloc(Auth.Body, files.len); + for (bodies) |*body| body.* = .init(auth); + defer for (bodies) |*body| body.deinit(a); for (files, 0..) |f, k| { handles[k] = try w.createFile(io, f.path, .{ .read = true, .truncate = false }); opened += 1; try handles[k].setLength(io, f.size); for (0..count(f.size, bytes)) |i| { const m = try marker(a, f.path, i); - if (w.access(io, m, .{})) |_| continue else |_| {} + if (auth.bearer == null) if (w.access(io, m, .{})) |_| continue else |_| {}; try todo.append(a, .{ .file = k, .first = i * bytes, .end = @min(f.size, (i + 1) * bytes), .marker = m }); left += todo.getLast().end - todo.getLast().first; } } - var s: Shared = .{ .io = io, .auth = auth, .files = files, .handles = handles, .todo = todo.items }; + var s: Shared = .{ .io = io, .auth = auth, .files = files, .handles = handles, .todo = todo.items, .bodies = bodies }; var failures: [workers]?anyerror = @splat(null); var threads: [workers]std.Thread = undefined; - const n = @min(workers, todo.items.len); + const n = if (auth.bearer != null) @min(@as(usize, 1), todo.items.len) else @min(workers, todo.items.len); s.running.store(@intCast(n), .release); for (0..n) |i| threads[i] = std.Thread.spawn(.{}, worker, .{ &s, &failures[i] }) catch |e| { s.stop.store(true, .release); @@ -78,7 +82,22 @@ pub fn fetch(a: Allocator, io: std.Io, files: []const File, bytes: u64, auth: Au progress.?.flush() catch {}; } for (threads[0..n]) |t| t.join(); - for (failures[0..n]) |f| if (f) |e| return e; + for (failures[0..n]) |failure| if (failure) |e| { + if (e == error.HubCredentialBody) { + for (handles[0..opened]) |h| h.close(io); + opened = 0; + for (files) |f| discard(a, io, f, bytes); + } + return e; + }; + finish(&s) catch |e| { + if (e == error.HubCredentialBody) { + for (handles[0..opened]) |h| h.close(io); + opened = 0; + for (files) |f| discard(a, io, f, bytes); + } + return e; + }; for (files) |f| for (0..count(f.size, bytes)) |i| w.deleteFile(io, try marker(a, f.path, i)) catch {}; } @@ -110,7 +129,7 @@ fn get(s: *Shared, client: *std.http.Client, p: Piece) !void { var last: anyerror = error.ReadFailed; for (0..attempts) |_| { range(s, client, p, &done) catch |e| { - if (e == error.RangeUnsupported or e == error.HubDenied) return e; + if (e == error.RangeUnsupported or e == error.HubDenied or e == error.HubCredentialBody) return e; last = e; continue; }; @@ -137,12 +156,30 @@ fn range(s: *Shared, client: *std.http.Client, p: Piece, done: *u64) !void { const want: usize = @intCast(@min(chunk.len, p.end - p.first - done.*)); const n = r.readSliceShort(chunk[0..want]) catch return error.ReadFailed; if (n == 0) return error.ShortRange; - try s.handles[p.file].writePositionalAll(s.io, chunk[0..n], p.first + done.*); + if (s.auth.bearer == null) { + try s.handles[p.file].writePositionalAll(s.io, chunk[0..n], p.first + done.*); + } else { + const body = &s.bodies[p.file]; + const held = body.buffered(); + const safe = try body.feed(std.heap.page_allocator, chunk[0..n]); + if (safe.len > 0) { + try s.handles[p.file].writePositionalAll(s.io, safe, p.first + done.* - @as(u64, @intCast(held))); + body.commit(safe.len); + } + } done.* += n; _ = s.bytes.fetchAdd(n, .monotonic); } } +fn finish(s: *Shared) !void { + if (s.auth.bearer == null) return; + for (s.files, s.handles, s.bodies) |f, file, *body| { + const tail = try body.finish(std.heap.page_allocator); + if (tail.len > 0) try file.writePositionalAll(s.io, tail, f.size - @as(u64, @intCast(tail.len))); + } +} + /// The first byte a 206 says it carries (Content-Range: bytes FIRST-LAST/SIZE). fn startOf(head: std.http.Client.Response.Head) ?u64 { var it = head.iterateHeaders(); diff --git a/zig/src/cli/pull_runs.zig b/zig/src/cli/pull_runs.zig index 89e1173ca83..b5e1bfa6020 100644 --- a/zig/src/cli/pull_runs.zig +++ b/zig/src/cli/pull_runs.zig @@ -40,6 +40,8 @@ const Shared = struct { runs: []const Run, check: Check, max: u64, + bodies: []Auth.Body, + positions: []u64, next: std.atomic.Value(usize) = .init(0), bytes: std.atomic.Value(u64) = .init(0), running: std.atomic.Value(u32) = .init(0), @@ -51,11 +53,26 @@ pub fn fetch(a: Allocator, io: std.Io, targets: []const Target, runs: []const Ru if (runs.len == 0) return; const w = std.Io.Dir.cwd(); for (targets) |t| { + if (auth.bearer != null) { + const old = w.openFile(io, t.path, .{}) catch null; + if (old) |file| { + file.close(io); + if (auth.fileContains(a, io, t.path) catch true) { + w.deleteFile(io, t.path) catch {}; + return error.HubCredentialBody; + } + } + } const f = try w.createFile(io, t.path, .{ .read = true, .truncate = false }); defer f.close(io); // the file keeps its full size so the release's offsets hold; bytes no run brings stay holes on disk if ((try f.length(io)) != t.size) try f.setLength(io, t.size); } + const bodies = try a.alloc(Auth.Body, targets.len); + for (bodies) |*body| body.* = .init(auth); + defer for (bodies) |*body| body.deinit(a); + const positions = try a.alloc(u64, targets.len); + @memset(positions, 0); const links = try a.alloc(Link, targets.len); for (links) |*l| l.* = .{}; var max: u64 = 0; @@ -64,10 +81,10 @@ pub fn fetch(a: Allocator, io: std.Io, targets: []const Target, runs: []const Ru max = @max(max, r.end - r.first); left += r.end - r.first; } - var s: Shared = .{ .io = io, .auth = auth, .targets = targets, .links = links, .runs = runs, .check = check, .max = max }; + var s: Shared = .{ .io = io, .auth = auth, .targets = targets, .links = links, .runs = runs, .check = check, .max = max, .bodies = bodies, .positions = positions }; var failures: [workers]?anyerror = @splat(null); var threads: [workers]std.Thread = undefined; - const n = @min(workers, runs.len); + const n = if (auth.bearer != null) @min(@as(usize, 1), runs.len) else @min(workers, runs.len); s.running.store(@intCast(n), .release); for (0..n) |i| threads[i] = std.Thread.spawn(.{}, worker, .{ &s, &failures[i] }) catch |e| { s.stop.store(true, .release); @@ -88,7 +105,14 @@ pub fn fetch(a: Allocator, io: std.Io, targets: []const Target, runs: []const Ru progress.?.flush() catch {}; } for (threads[0..n]) |t| t.join(); - for (failures[0..n]) |f| if (f) |e| return e; + for (failures[0..n]) |failure| if (failure) |e| { + if (e == error.HubCredentialBody) for (targets) |t| w.deleteFile(io, t.path) catch {}; + return e; + }; + finish(&s) catch |e| { + if (e == error.HubCredentialBody) for (targets) |t| w.deleteFile(io, t.path) catch {}; + return e; + }; } fn worker(s: *Shared, failure: *?anyerror) void { @@ -141,6 +165,7 @@ const Open = struct { /// One run: fetched whole into `buf`, checked, then written; a stale link is resolved again. fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u8) !void { + if (s.auth.bearer != null and r.first != s.positions[r.file]) return error.RangeUnsupported; var last: anyerror = error.ReadFailed; var wait_ms: u64 = 250; for (0..attempts) |_| { @@ -163,13 +188,37 @@ fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u last = error.ChecksumMismatch; continue; } - try file.writePositionalAll(s.io, buf, r.first); + if (s.auth.bearer == null) { + try file.writePositionalAll(s.io, buf, r.first); + } else { + const body = &s.bodies[r.file]; + const held = body.buffered(); + const safe = try body.feed(std.heap.page_allocator, buf); + if (safe.len > 0) { + try file.writePositionalAll(s.io, safe, r.first - @as(u64, @intCast(held))); + body.commit(safe.len); + } + s.positions[r.file] = r.end; + } _ = s.bytes.fetchAdd(buf.len, .monotonic); return; } return last; } +fn finish(s: *Shared) !void { + if (s.auth.bearer == null) return; + for (s.targets, s.positions, s.bodies) |target, position, *body| { + if (position != target.size) return error.ShortRange; + const tail = try body.finish(std.heap.page_allocator); + if (tail.len > 0) { + const file = try std.Io.Dir.cwd().openFile(s.io, target.path, .{ .mode = .read_write }); + defer file.close(s.io); + try file.writePositionalAll(s.io, tail, target.size - @as(u64, @intCast(tail.len))); + } + } +} + /// The storage link the hub redirects `file` to, asked once and again when it grows old or is refused. fn location(s: *Shared, client: *std.http.Client, file: u32) ![]const u8 { const l = &s.links[file]; diff --git a/zig/src/cli/pull_security_test.zig b/zig/src/cli/pull_security_test.zig index 8ba113a23fe..ae14c56c4c8 100644 --- a/zig/src/cli/pull_security_test.zig +++ b/zig/src/cli/pull_security_test.zig @@ -4,6 +4,8 @@ const Allocator = std.mem.Allocator; const pull = @import("pull.zig"); const TestClient = @import("pull_test_client.zig").Client; const FakeHub = @import("pull_test.zig").FakeHub; +const ranged = @import("pull_parts.zig"); +const runs = @import("pull_runs.zig"); fn testEnv(a: Allocator, endpoint: []const u8) !std.process.Environ.Map { var env: std.process.Environ.Map = .{ .array_hash_map = .empty, .allocator = a }; @@ -105,3 +107,166 @@ test "security: poisoned cached LFS and git blobs download again and verify" { try std.testing.expectEqual(@as(u32, 2), fake.weight_requests.load(.monotonic)); try std.testing.expect(std.mem.indexOf(u8, cached.written(), "weights.safetensors: cached") != null); } + +fn gitHex(body: []const u8) [40]u8 { + var git = std.crypto.hash.Sha1.init(.{}); + var head: [32]u8 = undefined; + git.update(std.fmt.bufPrint(&head, "blob {d}\x00", .{body.len}) catch unreachable); + git.update(body); + return std.fmt.bytesToHex(git.finalResult(), .lower); +} + +fn reflectedConfig(fake: *FakeHub, conn: std.Io.net.Stream, head: []const u8) ?bool { + if (!std.mem.endsWith(u8, bodyPath(head), "/config.json")) return null; + var header: [192]u8 = undefined; + const text = std.fmt.bufPrint(&header, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: keep-alive\r\n\r\n", .{fake.config.len}) catch return false; + fake.sendAll(conn, text); + var at: usize = 0; + while (at < fake.config.len) : (at += 4) fake.sendAll(conn, fake.config[at..@min(at + 4, fake.config.len)]); + return true; +} + +test "security: a valid reflected config is refused before any blob write, including encoded and split forms" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + fake.route = reflectedConfig; + const secret = "fixture-reflected-token"; + for ([_][]const u8{ secret, "%66ixture-reflected-token", "%2566ixture-reflected-token" }, 0..) |reflection, i| { + fake.config = try std.fmt.allocPrint(a, "{{\"model_type\": \"qwen4_exp\", \"note\": \"{s}\"}}", .{reflection}); + fake.config_git_hex = gitHex(fake.config); + var env = try testEnv(a, try fake.endpoint(a)); + try env.put("HF_TOKEN", secret); + const root = try std.fmt.allocPrint(a, ".tf-pull-reflected-config-{d}-{d}", .{ std.Io.Clock.awake.now(io).toNanoseconds(), i }); + defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; + if (i == 2) { + const blobs = try std.fs.path.join(a, &.{ root, "models--Org--Flash/blobs" }); + try std.Io.Dir.cwd().createDirPath(io, blobs); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ blobs, &fake.config_git_hex }), .data = fake.config }); + } + var out: std.Io.Writer.Allocating = .init(a); + var err_out: std.Io.Writer.Allocating = .init(a); + try std.testing.expectEqual(@as(u8, 1), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); + const blob = try std.fs.path.join(a, &.{ root, "models--Org--Flash/blobs", &fake.config_git_hex }); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, blob, .{})); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, try std.fmt.allocPrint(a, "{s}.incomplete", .{blob}), .{})); + try std.testing.expect(std.mem.indexOf(u8, out.written(), secret) == null); + try std.testing.expect(std.mem.indexOf(u8, err_out.written(), secret) == null); + } +} + +test "security: a ranged body reflection never reaches its artifact" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const secret = "fixture-range-token"; + fake.weights = try std.mem.concat(a, u8, &.{ "safe-prefix-", secret, "-safe-suffix" }); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const file = ranged.File{ + .url = try std.fmt.allocPrint(a, "{s}{s}", .{ try fake.endpoint(a), FakeHub.weights_path }), + .path = try std.fs.path.join(a, &.{ root, "weights.ranges" }), + .size = fake.weights.len, + }; + const auth = @import("pull_auth.zig").Auth{ .bearer = "Bearer fixture-range-token" }; + try std.testing.expectError(error.HubCredentialBody, ranged.fetch(a, io, &.{file}, 7, auth, null)); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, file.path, .{})); +} + +test "security: an EXLR8 run reflection never reaches its artifact" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + const secret = "fixture-exlr8-token"; + fake.weights = try std.mem.concat(a, u8, &.{ "safe-prefix-", secret, "-safe-suffix" }); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const target = runs.Target{ + .url = try std.fmt.allocPrint(a, "{s}{s}", .{ try fake.endpoint(a), FakeHub.weights_path }), + .path = try std.fs.path.join(a, &.{ root, "width.exlr8" }), + .size = fake.weights.len, + }; + const one = runs.Run{ .file = 0, .first = 0, .end = fake.weights.len, .units = .{ 0, 0 } }; + const Accept = struct { + fn all(_: *const anyopaque, _: runs.Run, _: []const u8) bool { + return true; + } + }; + const context: u8 = 0; + const check = runs.Check{ .ctx = &context, .run = Accept.all }; + const auth = @import("pull_auth.zig").Auth{ .bearer = "Bearer fixture-exlr8-token" }; + try std.testing.expectError(error.HubCredentialBody, runs.fetch(a, io, &.{target}, &.{one}, check, auth, null)); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, target.path, .{})); +} + +test "security: artifact containment spans every byte split without refusing benign prefixes" { + const a = std.testing.allocator; + const secret = "fixture-unit-token"; + const Auth = @import("pull_auth.zig").Auth; + for ([_][]const u8{ "safe-fixture-unit-token-end", "safe-%66ixture-unit-token-end", "safe-%252566ixture-unit-token-end" }) |body| { + for (0..body.len) |cut| { + var guard: Auth.Body = .init(.{ .bearer = "Bearer fixture-unit-token" }); + defer guard.deinit(a); + var written: std.ArrayList(u8) = .empty; + defer written.deinit(a); + var refused = false; + if (guard.feed(a, body[0..cut])) |safe| { + try written.appendSlice(a, safe); + guard.commit(safe.len); + } else |err| { + try std.testing.expectEqual(error.HubCredentialBody, err); + refused = true; + } + if (!refused) { + if (guard.feed(a, body[cut..])) |safe| { + try written.appendSlice(a, safe); + guard.commit(safe.len); + } else |err| { + try std.testing.expectEqual(error.HubCredentialBody, err); + refused = true; + } + } + try std.testing.expect(refused); + var matcher = @import("sys").credential.Matcher.init(a, written.items); + defer matcher.deinit(); + try std.testing.expect(try matcher.spanFrom(0, secret) == null); + } + } + for ([_][]const u8{ "fixture-unit-prefix", "100% raw %66ixture-other", "%66ixture-unit-%" }) |benign| { + var guard: Auth.Body = .init(.{ .bearer = "Bearer fixture-unit-token" }); + defer guard.deinit(a); + var written: std.ArrayList(u8) = .empty; + defer written.deinit(a); + for (benign) |byte| { + const safe = try guard.feed(a, &.{byte}); + try written.appendSlice(a, safe); + guard.commit(safe.len); + } + const tail = try guard.finish(a); + try written.appendSlice(a, tail); + try std.testing.expectEqualSlices(u8, benign, written.items); + } +} diff --git a/zig/src/cli/pull_test.zig b/zig/src/cli/pull_test.zig index ba6d02afe2d..60f4eeab9e6 100644 --- a/zig/src/cli/pull_test.zig +++ b/zig/src/cli/pull_test.zig @@ -317,8 +317,8 @@ test "pull downloads, verifies, retries a cut body, resumes and refuses a family defer fake_hub.stopServer(); const root = try std.fmt.allocPrint(a, ".tf-pull-test-{d}", .{std.Io.Clock.awake.now(io).toNanoseconds()}); defer std.Io.Dir.cwd().deleteTree(io, root) catch {}; - const env = try testEnv(a, try fake_hub.endpoint(a)); - + var env = try testEnv(a, try fake_hub.endpoint(a)); + try env.put("HF_TOKEN", "fixture-resume-token"); var out: std.Io.Writer.Allocating = .init(a); var err_out: std.Io.Writer.Allocating = .init(a); try std.testing.expectEqual(@as(u8, 0), try pull.run(a, io, &out.writer, &err_out.writer, &env, root, "Org/Flash")); diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index fd74850f347..1cbb89702dc 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -331,6 +331,7 @@ pub const Fetch = struct { url: []const u8, body: ?[]const u8 = null, token: ?[]const u8 = null, + legacy_key: bool = false, limit: usize, timeout_s: f64, agent: []const u8 = user_agent, @@ -367,6 +368,11 @@ pub fn rawHeader(buf: []u8, token: []const u8) ?[]const u8 { return buf[0..n]; } +/// Legacy callers send the exact original key bytes, as main's Bearer concatenation did. +pub fn legacyHeader(buf: []u8, token: []const u8) ?[]const u8 { + return std.fmt.bufPrint(buf, "Bearer {s}", .{token}) catch null; +} + const FetchTask = struct { a: Allocator, client: *std.http.Client, @@ -378,7 +384,7 @@ const FetchTask = struct { x.out.failed = .network; const uri = std.Uri.parse(x.f.url) catch return; var auth_buf: [300]u8 = undefined; - const auth: std.http.Client.Request.Headers.Value = if (x.f.token) |tok| .{ .override = rawHeader(&auth_buf, tok) orelse return } else .omit; + const auth: std.http.Client.Request.Headers.Value = if (x.f.token) |tok| .{ .override = (if (x.f.legacy_key) legacyHeader(&auth_buf, tok) else rawHeader(&auth_buf, tok)) orelse return } else .omit; var req = x.client.request(x.f.method, uri, .{ .keep_alive = false, .redirect_behavior = .unhandled, diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index 10ccac67673..8a16d9de0da 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -330,7 +330,7 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and preserve defer f.stop(); var h: history.History = .{ .a = a }; var out: std.Io.Writer.Allocating = .init(a); - const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + const ended = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}, false); switch (ended) { .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), else => return error.TestUnexpectedResult, @@ -342,7 +342,7 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and preserve const unicode_body = try turn.body(a, .{ .model = "m" }, &h, unicode_secret); const escape_at = std.mem.indexOf(u8, unicode_body, "\\u00e9abc").?; unicode_body[escape_at + 4] = 'E'; - const unicode_refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), null, unicode_credentials, unicode_body, &out.writer, .{}); + const unicode_refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), null, unicode_credentials, unicode_body, &out.writer, .{}, false); switch (unicode_refused) { .failed => |why| try std.testing.expectEqualStrings("[withheld]", why.reason), else => return error.TestUnexpectedResult, @@ -357,7 +357,7 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and preserve const hostile_first = "{\"model\":\"\\u00E9abc\",\"model\":\"safe\",\"messages\":[],\"stream\":true}"; const hostile_last = "{\"model\":\"safe\",\"model\":\"\\u00E9abc\",\"messages\":[],\"stream\":true}"; for ([_][]const u8{ malformed, deep.items, hostile_first, hostile_last }) |request| { - const attack = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, unicode_credentials, try a.dupe(u8, request), &out.writer, .{}); + const attack = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, unicode_credentials, try a.dupe(u8, request), &out.writer, .{}, false); switch (attack) { .failed => |why| try std.testing.expectEqualStrings("[withheld]", why.reason), else => {}, @@ -365,14 +365,14 @@ test "chat CLI: a streamed reply authenticates Latin-1 bearer bytes and preserve } try std.testing.expectEqual(@as(usize, 1), f.count()); const safe_duplicate = "{\"model\":\"first\",\"model\":\"safe\",\"messages\":[],\"stream\":true}"; - const safe = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, unicode_credentials, try a.dupe(u8, safe_duplicate), &out.writer, .{}); + const safe = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), token, unicode_credentials, try a.dupe(u8, safe_duplicate), &out.writer, .{}, false); switch (safe) { .finished => |got| try std.testing.expectEqualStrings("Ready.", got.content), else => return error.TestUnexpectedResult, } try std.testing.expectEqual(@as(usize, 2), f.count()); try std.testing.expectEqualStrings(safe_duplicate, f.request(1).body); - const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}); + const refused = try turn.run(a, std.testing.io, try f.url(a, "/v1/chat/completions"), "fixture-\u{20ac}", .{}, try turn.body(a, .{ .model = "m" }, &h, "ready?"), &out.writer, .{}, false); switch (refused) { .failed => |why| try std.testing.expect(std.mem.indexOf(u8, why.reason, "fixture") == null), else => return error.TestUnexpectedResult, diff --git a/zig/src/server/chat_cli.zig b/zig/src/server/chat_cli.zig index 202adba11bb..8828bf16440 100644 --- a/zig/src/server/chat_cli.zig +++ b/zig/src/server/chat_cli.zig @@ -194,7 +194,7 @@ const Session = struct { /// One message and its streamed reply, in an arena of its own that lives until the turn is kept. fn ask(s: *Session, a: Allocator, message: []const u8) !turn.Ended { const request = try turn.checkedBody(a, s.settings, &s.history, message, s.target.credentials) orelse return .{ .failed = .{ .reason = "the serialized request contains configured credentials" } }; - return turn.run(a, s.ctx.io, s.url, s.target.key, s.target.credentials, request, s.ctx.out, s.show); + return turn.run(a, s.ctx.io, s.url, s.target.key, s.target.credentials, request, s.ctx.out, s.show, s.target.own == null); } /// A finished reply's notes: cut at its token limit, or nothing but reasoning that was hidden. @@ -325,7 +325,7 @@ fn discover(ctx: *const Context, chat_url: []const u8, target: Target) !Found { defer client.deinit(); const url = try std.mem.concat(ctx.a, u8, &.{ chat_url[0 .. chat_url.len - "/chat/completions".len], "/models" }); if (try credential.contains(ctx.a, url, target.credentials.forms)) return .{ .problem = credential.withheld }; - const got = stream.fetch(ctx.a, ctx.io, &client, .{ .url = url, .limit = 4 << 20, .timeout_s = 10, .agent = turn.user_agent, .token = target.key }); + const got = stream.fetch(ctx.a, ctx.io, &client, .{ .url = url, .limit = 4 << 20, .timeout_s = 10, .agent = turn.user_agent, .token = target.key, .legacy_key = target.own == null }); if (got.failed == .stopped) return .{ .stopped = stop.requested() orelse .INT }; var doc: ?json.Value = null; if (got.failed == .none and got.status == 200) switch (try json.parse(ctx.a, got.body)) { diff --git a/zig/src/server/chat_cli_kia68_test.zig b/zig/src/server/chat_cli_kia68_test.zig new file mode 100644 index 00000000000..e0e8cc75068 --- /dev/null +++ b/zig/src/server/chat_cli_kia68_test.zig @@ -0,0 +1,35 @@ +//! Legacy chat preserves the original key bytes on discovery and streamed turns. +const std = @import("std"); +const fake = @import("benchmark_fake.zig"); +const fixtures = @import("chat_cli_test.zig"); + +test "chat CLI: every accepted legacy key keeps main's exact discovery and POST bearer bytes" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var r = try fixtures.Run.init(a, &tmp); + const replies = [_]fake.Write{ + .{ .bytes = try fake.headOf(a, "200 OK", "text/event-stream") }, + .{ .bytes = try fake.event(a, "{\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Ready.\"},\"finish_reason\":\"stop\"}]}") }, + .{ .bytes = try fake.event(a, "[DONE]") }, + }; + const response = [_][]const fake.Write{&replies}; + const f = try fixtures.world(a, fixtures.models_doc, &response); + defer f.stop(); + var long: [256]u8 = undefined; + @memset(&long, 'k'); + const keys = [_][]const u8{ "fixture-caf\u{e9}", "fixture-\u{20ac}", "fixture-\u{009b}", "fixture-\xff", &long }; + r.input = "hi"; + for (keys) |key| { + try r.env.put("TENSORFOLD_API_KEY", key); + const before = f.count(); + try std.testing.expectEqual(@as(u8, 0), try r.command(&.{ "--url", try f.url(a, "") })); + try std.testing.expectEqual(before + 2, f.count()); + const expected = try std.mem.concat(a, u8, &.{ "Bearer ", key }); + try std.testing.expectEqualSlices(u8, expected, f.header(before, "authorization").?); + try std.testing.expectEqualSlices(u8, expected, f.header(before + 1, "authorization").?); + try std.testing.expect(std.mem.indexOf(u8, r.err.written(), key) == null); + } +} diff --git a/zig/src/server/chat_cli_turn.zig b/zig/src/server/chat_cli_turn.zig index 63cb6be23c9..96d31e6a36e 100644 --- a/zig/src/server/chat_cli_turn.zig +++ b/zig/src/server/chat_cli_turn.zig @@ -106,7 +106,7 @@ pub fn checkedBody(a: Allocator, s: Settings, history: *const History, user: []c } /// One streamed turn to ``url``, the chat route, printed to ``out`` as it arrives; a stop signal ends it ``stopped``. -pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credentials: Credentials, request: []u8, out: *std.Io.Writer, show: Show) !Ended { +pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credentials: Credentials, request: []u8, out: *std.Io.Writer, show: Show, legacy_key: bool) !Ended { if ((try credential.contains(a, url, credentials.forms)) or (try containsRequest(a, request, credentials.forms))) return .{ .failed = .{ .reason = credential.withheld } }; var client: std.http.Client = .{ .allocator = std.heap.smp_allocator, .io = io }; @@ -115,8 +115,8 @@ pub fn run(a: Allocator, io: std.Io, url: []const u8, key: ?[]const u8, credenti var printer: Printer = .{ .io = io, .out = out, .show = show }; var r: reply.Reply = .{ .a = a, .sink = printer.sink(), .secrets = credentials.forms }; var auth_buf: [300]u8 = undefined; - const bearer = if (key) |k| stream.rawHeader(&auth_buf, k) orelse return .{ .failed = .{ - .reason = "API key cannot be encoded as Latin-1 header text", + const bearer = if (key) |k| (if (legacy_key) stream.legacyHeader(&auth_buf, k) else stream.rawHeader(&auth_buf, k)) orelse return .{ .failed = .{ + .reason = "API key cannot be encoded as a bounded header", } } else null; var x: Exchange = .{ .a = a, .io = io, .client = &client, .uri = try std.Uri.parse(url), .bearer = bearer, .credentials = credentials, .body = request, .reply = &r }; const ended = stream.bounded(io, null, Exchange.run, &x); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 00da6e09017..02a414c2859 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -320,6 +320,7 @@ test { _ = @import("chat_cli_child.zig"); _ = @import("chat_cli_test.zig"); _ = @import("chat_cli_kr67_test.zig"); + _ = @import("chat_cli_kia68_test.zig"); _ = @import("chat_cli_kr69_test.zig"); _ = @import("start_cli_kr67_test.zig"); } diff --git a/zig/src/server/start_cli.zig b/zig/src/server/start_cli.zig index b864a368e32..af8a4fb5b44 100644 --- a/zig/src/server/start_cli.zig +++ b/zig/src/server/start_cli.zig @@ -216,7 +216,7 @@ fn firstReply(ctx: *const Context, own: *Child, credentials: turn.Credentials) ! var h: history.History = .{ .a = ctx.a }; const request = try turn.body(ctx.a, .{ .model = own.served, .temperature = 0, .max_tokens = 32 }, &h, "Reply with a short confirmation that the server is ready."); try say(ctx.out, "First reply:", .{}); - switch (try turn.run(ctx.a, ctx.io, url, own.key, credentials, request, ctx.out, .{ .terminal = true })) { + switch (try turn.run(ctx.a, ctx.io, url, own.key, credentials, request, ctx.out, .{ .terminal = true }, false)) { .finished => |f| { if (f.content.len == 0) return fail(ctx, 1, "first reply failed: the model returned no answer content", .{}); return 0; From e69757db18bf602745728d4a2f37f0130f207a56 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:09:27 +0000 Subject: [PATCH 101/361] pull: authenticated EXLR8 nodes pull their sparse runs again The authenticated run writer streamed each file through its credential scanner as one body from offset zero, so a node's normal sparse layout (runs with gaps between them, or holes after the last) was refused with RangeUnsupported or ShortRange, where main pulls it. The scanner's stream now carries over the bytes already on disk between and after runs: through them while it holds a possible match, then from the last byte before the next run that no raw or encoded credential can contain (not the secret's own byte, % or a hex digit; holes are zeros). Those bytes were checked clean before reuse, so only a match touching new bytes matters, and it is refused before any of its bytes are written, across a run's start or end as within it. Clean sparse pulls write the release's bytes and leave holes untouched, as without a key. --- zig/src/cli/pull_runs.zig | 78 +++++++++++++++++++------ zig/src/cli/pull_security_test.zig | 92 ++++++++++++++++++++++++++++++ 2 files changed, 154 insertions(+), 16 deletions(-) diff --git a/zig/src/cli/pull_runs.zig b/zig/src/cli/pull_runs.zig index b5e1bfa6020..169f267f796 100644 --- a/zig/src/cli/pull_runs.zig +++ b/zig/src/cli/pull_runs.zig @@ -165,7 +165,7 @@ const Open = struct { /// One run: fetched whole into `buf`, checked, then written; a stale link is resolved again. fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u8) !void { - if (s.auth.bearer != null and r.first != s.positions[r.file]) return error.RangeUnsupported; + if (s.auth.bearer != null and r.first < s.positions[r.file]) return error.RangeUnsupported; var last: anyerror = error.ReadFailed; var wait_ms: u64 = 250; for (0..attempts) |_| { @@ -191,14 +191,8 @@ fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u if (s.auth.bearer == null) { try file.writePositionalAll(s.io, buf, r.first); } else { - const body = &s.bodies[r.file]; - const held = body.buffered(); - const safe = try body.feed(std.heap.page_allocator, buf); - if (safe.len > 0) { - try file.writePositionalAll(s.io, safe, r.first - @as(u64, @intCast(held))); - body.commit(safe.len); - } - s.positions[r.file] = r.end; + try bridge(s, file, r.file, r.first); + try advance(s, file, r.file, buf); } _ = s.bytes.fetchAdd(buf.len, .monotonic); return; @@ -206,16 +200,68 @@ fn one(s: *Shared, client: *std.http.Client, file: std.Io.File, r: Run, buf: []u return last; } +/// Feeds the file's next `bytes` (at its stream position) through its scanner and writes the prefix proven safe. +fn advance(s: *Shared, file: std.Io.File, index: u32, bytes: []const u8) !void { + const body = &s.bodies[index]; + const held = body.buffered(); + const safe = try body.feed(std.heap.page_allocator, bytes); + if (safe.len > 0) { + try file.writePositionalAll(s.io, safe, s.positions[index] - @as(u64, @intCast(held))); + body.commit(safe.len); + } + s.positions[index] += bytes.len; +} + +/// Whether no raw or percent-encoded credential can contain `byte`: not the secret's own, `%` or a hex digit. +fn breaks(secret: []const u8, byte: u8) bool { + return byte != '%' and !std.ascii.isHex(byte) and std.mem.indexOfScalar(u8, secret, byte) == null; +} + +/// Carries the stream over on-disk bytes (checked clean, or holes) to `to`, from the last byte no match can contain. +fn bridge(s: *Shared, file: std.Io.File, index: u32, to: u64) !void { + var buf: [64 << 10]u8 = undefined; + while (s.positions[index] < to and s.bodies[index].buffered() > 0) try preserved(s, file, index, &buf, to); + if (s.positions[index] >= to) return; + const bearer = s.auth.bearer.?; + const secret = if (std.mem.startsWith(u8, bearer, "Bearer ")) bearer[7..] else bearer; + var end = to; + while (end > s.positions[index]) { + const n: usize = @intCast(@min(buf.len, end - s.positions[index])); + const from = end - n; + if (try file.readPositionalAll(s.io, buf[0..n], from) != n) return error.ShortRange; + var k = n; + while (k > 0) { + k -= 1; + if (breaks(secret, buf[k])) { + s.positions[index] = from + k; // nothing held: skipped clean bytes start no match + end = 0; + break; + } + } + if (end != 0) end = from; + } + while (s.positions[index] < to) try preserved(s, file, index, &buf, to); +} + +/// The next on-disk bytes before `to`, fed through the scanner and written back unchanged where safe. +fn preserved(s: *Shared, file: std.Io.File, index: u32, buf: []u8, to: u64) !void { + const n: usize = @intCast(@min(buf.len, to - s.positions[index])); + if (try file.readPositionalAll(s.io, buf[0..n], s.positions[index]) != n) return error.ShortRange; + try advance(s, file, index, buf[0..n]); +} + +/// Each file's held tail: settled over the bytes after its last run, or at its real end. fn finish(s: *Shared) !void { if (s.auth.bearer == null) return; - for (s.targets, s.positions, s.bodies) |target, position, *body| { - if (position != target.size) return error.ShortRange; + for (s.targets, s.bodies, 0..) |target, *body, i| { + if (body.buffered() == 0) continue; + const index: u32 = @intCast(i); + const file = try std.Io.Dir.cwd().openFile(s.io, target.path, .{ .mode = .read_write }); + defer file.close(s.io); + var buf: [64 << 10]u8 = undefined; + while (s.positions[index] < target.size and body.buffered() > 0) try preserved(s, file, index, &buf, target.size); const tail = try body.finish(std.heap.page_allocator); - if (tail.len > 0) { - const file = try std.Io.Dir.cwd().openFile(s.io, target.path, .{ .mode = .read_write }); - defer file.close(s.io); - try file.writePositionalAll(s.io, tail, target.size - @as(u64, @intCast(tail.len))); - } + if (tail.len > 0) try file.writePositionalAll(s.io, tail, target.size - @as(u64, @intCast(tail.len))); } } diff --git a/zig/src/cli/pull_security_test.zig b/zig/src/cli/pull_security_test.zig index ae14c56c4c8..474b6646365 100644 --- a/zig/src/cli/pull_security_test.zig +++ b/zig/src/cli/pull_security_test.zig @@ -270,3 +270,95 @@ test "security: artifact containment spans every byte split without refusing ben try std.testing.expectEqualSlices(u8, benign, written.items); } } + +const sparse_bearer = "Bearer fixture-sparse-token"; + +/// An authenticated EXLR8 pull of `ranges` from a 256-byte release, over `existing` bytes already on disk if any. +fn sparsePull(a: Allocator, io: std.Io, root: []const u8, weights: []const u8, ranges: []const [2]u64, existing: ?[]const u8, path: *[]const u8) !void { + var fake = FakeHub.open() catch return error.SkipZigTest; + fake.start(); + defer fake.stopServer(); + fake.weights = weights; + path.* = try std.fs.path.join(a, &.{ root, "width.exlr8" }); + if (existing) |bytes| try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path.*, .data = bytes }) else std.Io.Dir.cwd().deleteFile(io, path.*) catch {}; + const target = runs.Target{ .url = try std.fmt.allocPrint(a, "{s}{s}", .{ try fake.endpoint(a), FakeHub.weights_path }), .path = path.*, .size = weights.len }; + const list = try a.alloc(runs.Run, ranges.len); + for (list, ranges) |*r, range| r.* = .{ .file = 0, .first = range[0], .end = range[1], .units = .{ 0, 0 } }; + const Accept = struct { + fn all(_: *const anyopaque, _: runs.Run, _: []const u8) bool { + return true; + } + }; + const context: u8 = 0; + const auth = @import("pull_auth.zig").Auth{ .bearer = sparse_bearer }; + return runs.fetch(a, io, &.{target}, list, .{ .ctx = &context, .run = Accept.all }, auth, null); +} + +/// A 256-byte release of binary bytes, with `text` placed at `at` when given. +fn release(a: Allocator, text: []const u8, at: usize) ![]u8 { + const bytes = try a.alloc(u8, 256); + for (bytes, 0..) |*b, i| b.* = @intCast((i * 151 + 7) % 256); + @memcpy(bytes[at..][0..text.len], text); + return bytes; +} + +test "security: an authenticated EXLR8 node pulls its sparse runs and trailing holes as main does" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const weights = try release(a, "", 0); + for ([_][]const [2]u64{ &.{ .{ 0, 16 }, .{ 64, 80 } }, &.{.{ 16, 32 }}, &.{ .{ 8, 40 }, .{ 200, 256 } } }) |ranges| { + var path: []const u8 = undefined; + try sparsePull(a, io, root, weights, ranges, null, &path); + const got = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20)); + try std.testing.expectEqual(weights.len, got.len); + var next: usize = 0; + for (ranges) |r| { // each run is the release's bytes, every hole is left untouched + for (got[next..@intCast(r[0])]) |b| try std.testing.expectEqual(@as(u8, 0), b); + try std.testing.expectEqualSlices(u8, weights[@intCast(r[0])..@intCast(r[1])], got[@intCast(r[0])..@intCast(r[1])]); + next = @intCast(r[1]); + } + for (got[next..]) |b| try std.testing.expectEqual(@as(u8, 0), b); + // a second pull over the same file reuses it and leaves the same bytes + var again: []const u8 = undefined; + try sparsePull(a, io, root, weights, ranges, got, &again); + try std.testing.expectEqualSlices(u8, got, try std.Io.Dir.cwd().readFileAlloc(io, again, a, .limited(1 << 20))); + } +} + +test "security: a key completed across a sparse run's edge with bytes on disk is refused before it is written" { + var client_io: TestClient = undefined; + client_io.init(); + defer client_io.deinit(); + var arena_state = std.heap.ArenaAllocator.init(client_io.allocator()); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const io = client_io.io(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const root = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + const secret = sparse_bearer["Bearer ".len..]; + var path: []const u8 = undefined; + // inside a run, at a gap and at the release's end + try std.testing.expectError(error.HubCredentialBody, sparsePull(a, io, root, try release(a, secret, 70), &.{ .{ 0, 16 }, .{ 64, 96 } }, null, &path)); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, path, .{})); + // the key's head already on disk before a run, its rest brought by the run + var disk: [256]u8 = @splat(0); + @memcpy(disk[40..48], secret[0..8]); + const head = try release(a, secret[8..], 48); + try std.testing.expectError(error.HubCredentialBody, sparsePull(a, io, root, head, &.{.{ 48, 64 }}, &disk, &path)); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, path, .{})); + // a run's last bytes begin the key and the bytes after it on disk end it + var after: [256]u8 = @splat(0); + @memcpy(after[16..][0 .. secret.len - 8], secret[8..]); + const tail = try release(a, secret[0..8], 8); + try std.testing.expectError(error.HubCredentialBody, sparsePull(a, io, root, tail, &.{.{ 0, 16 }}, &after, &path)); + try std.testing.expectError(error.FileNotFound, std.Io.Dir.cwd().access(io, path, .{})); +} From 19b441bce7f6facf5256e5b8eb7f2c43031bd83b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:13:33 +0000 Subject: [PATCH 102/361] server tests: start_cli_kr67_test runs with the start CLI tests, not the server's root.zig imported start_cli_kr67_test.zig into the server's own test module, which has no checkpoint_cli import, so test-server-cpu stopped compiling. start_cli_test.zig already imports it in the start CLI's test module, which has that import and runs it (test-start-cli-host). No test is dropped. --- zig/src/server/root.zig | 1 - 1 file changed, 1 deletion(-) diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 02a414c2859..b7bface6549 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -322,7 +322,6 @@ test { _ = @import("chat_cli_kr67_test.zig"); _ = @import("chat_cli_kia68_test.zig"); _ = @import("chat_cli_kr69_test.zig"); - _ = @import("start_cli_kr67_test.zig"); } } From 6b8af3cfe0904c19895e5d1947d7db70a8a69a41 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:21:55 +0000 Subject: [PATCH 103/361] server: a managed child's output is redacted before it reaches its log file The managed serve child's stdout and stderr were the log file itself, so a key the child printed was written to disk raw; only the tail the parent later showed was redacted. The child now writes into a pipe. A parent thread reads it, replaces every configured key and its percent-encoded forms (benchmark_sse.redactPiece, holding back a suffix that could still become one), and appends only that text to the log, so no key byte is written. Without keys the bytes pass unchanged. Readiness still reads the serving line from the log; a tail read after the child exits first waits briefly for the stream to end, and stop joins the reader before closing the log. --- zig/src/server/benchmark_log.zig | 145 +++++++++++++++++++++++ zig/src/server/benchmark_server.zig | 33 +++++- zig/src/server/benchmark_server_test.zig | 24 ++++ zig/src/server/root.zig | 1 + 4 files changed, 201 insertions(+), 2 deletions(-) create mode 100644 zig/src/server/benchmark_log.zig diff --git a/zig/src/server/benchmark_log.zig b/zig/src/server/benchmark_log.zig new file mode 100644 index 00000000000..3f7d8cafb88 --- /dev/null +++ b/zig/src/server/benchmark_log.zig @@ -0,0 +1,145 @@ +//! A managed child's output reaches its log file only through the parent: read from a pipe, keys replaced first. +const std = @import("std"); +const sse = @import("benchmark_sse.zig"); +const posix = std.posix; + +/// Held bytes past this length are written as one replacement instead of waiting for more. +const hold_limit = 1 << 20; + +pub const Sink = struct { + io: std.Io, + log: std.Io.File, + read_fd: posix.fd_t, + /// The child's stdout and stderr; the parent closes its own copy once the child holds it. + child: std.Io.File, + secrets: []const []const u8, + offset: u64 = 0, + stop: std.atomic.Value(bool) = .init(false), + done: std.atomic.Value(bool) = .init(false), + thread: ?std.Thread = null, + + /// A pipe in front of `log`; `secrets` (raw keys) are replaced wherever they or their encodings occur. + pub fn open(gpa: std.mem.Allocator, io: std.Io, log: std.Io.File, secrets: []const []const u8) !*Sink { + var fds: [2]posix.fd_t = undefined; + if (std.c.pipe(&fds) != 0) return error.PipeFailed; + for (fds) |fd| _ = std.c.fcntl(fd, posix.F.SETFD, @as(c_int, posix.FD_CLOEXEC)); + const s = gpa.create(Sink) catch |e| { + for (fds) |fd| _ = std.c.close(fd); + return e; + }; + s.* = .{ .io = io, .log = log, .read_fd = fds[0], .child = .{ .handle = fds[1], .flags = .{ .nonblocking = false } }, .secrets = secrets }; + return s; + } + + /// The child holds its end now: the parent's copy closes, so the child's exit ends the stream. + pub fn started(s: *Sink) !void { + _ = std.c.close(s.child.handle); + s.thread = try std.Thread.spawn(.{}, run, .{s}); + } + + /// Waits up to `ms` for the stream to end (the child exited and its output is written). + pub fn settle(s: *Sink, ms: u32) void { + var waited: u32 = 0; + while (!s.done.load(.acquire) and waited < ms) : (waited += 10) s.io.sleep(.fromMilliseconds(10), .awake) catch {}; + } + + /// Stops reading once nothing more is ready, then closes the pipe; the log stays open for its owner. + pub fn close(s: *Sink, gpa: std.mem.Allocator) void { + s.stop.store(true, .release); + if (s.thread) |t| t.join() else _ = std.c.close(s.child.handle); + _ = std.c.close(s.read_fd); + gpa.destroy(s); + } + + fn append(s: *Sink, bytes: []const u8) void { + if (bytes.len == 0) return; + s.log.writePositionalAll(s.io, bytes, s.offset) catch return; + s.offset += bytes.len; + } + + fn run(s: *Sink) void { + defer s.done.store(true, .release); + var held: std.ArrayList(u8) = .empty; + defer held.deinit(std.heap.page_allocator); + var buf: [64 << 10]u8 = undefined; + var fds = [_]posix.pollfd{.{ .fd = s.read_fd, .events = posix.POLL.IN, .revents = 0 }}; + var after_stop: u32 = 0; + while (true) { + const stopping = s.stop.load(.acquire); + if (stopping) after_stop += 1; + const ready = posix.poll(&fds, if (stopping) 0 else 100) catch break; + if (ready == 0) { + if (stopping) break; + continue; + } + if (after_stop > 256) break; // a writer that never pauses cannot hold the stop + const n = posix.read(s.read_fd, &buf) catch break; + if (n == 0) break; + if (s.secrets.len == 0) { + s.append(buf[0..n]); + continue; + } + held.appendSlice(std.heap.page_allocator, buf[0..n]) catch break; + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const piece = sse.redactPiece(arena.allocator(), held.items, s.secrets) catch { + s.append("[redacted]"); + held.clearRetainingCapacity(); + continue; + }; + s.append(piece.text); + const rest = piece.rest.len; + std.mem.copyForwards(u8, held.items[0..rest], piece.rest); + held.shrinkRetainingCapacity(rest); + if (held.items.len > hold_limit) { + s.append("[redacted]"); + held.clearRetainingCapacity(); + } + } + // a suffix still held could become a key: its place is marked, its bytes are not written + if (held.items.len > 0) s.append("[redacted]"); + } +}; + +test "benchmark log: a key written to the child's stream reaches the file only as a replacement, at any split" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const secret = "fixture-log-key"; + const text = "start\nkey=fixture-log-key encoded=fixture%2Dlog%2Dkey\nready\n"; + for (0..text.len) |split| { + const log = try tmp.dir.createFile(io, "child.log", .{ .read = true, .truncate = true }); + defer log.close(io); + const s = try Sink.open(std.testing.allocator, io, log, &.{secret}); + const writer = std.c.dup(s.child.handle); + try s.started(); + _ = std.c.write(writer, text.ptr, split); + _ = std.c.write(writer, text[split..].ptr, text.len - split); + _ = std.c.close(writer); + s.settle(5000); + s.close(std.testing.allocator); + var out: [512]u8 = undefined; + const got = out[0..try log.readPositionalAll(io, &out, 0)]; + try std.testing.expect(std.mem.indexOf(u8, got, secret) == null); + try std.testing.expect(std.mem.indexOf(u8, got, "fixture%2Dlog") == null); + try std.testing.expect(std.mem.startsWith(u8, got, "start\nkey=[redacted]")); + try std.testing.expect(std.mem.endsWith(u8, got, "ready\n")); + } +} + +test "benchmark log: without keys the child's bytes reach the file unchanged" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const log = try tmp.dir.createFile(io, "child.log", .{ .read = true }); + defer log.close(io); + const s = try Sink.open(std.testing.allocator, io, log, &.{}); + const writer = std.c.dup(s.child.handle); + try s.started(); + _ = std.c.write(writer, "plain output\n", 13); + _ = std.c.close(writer); + s.settle(5000); + s.close(std.testing.allocator); + var out: [64]u8 = undefined; + try std.testing.expectEqualStrings("plain output\n", out[0..try log.readPositionalAll(io, &out, 0)]); +} diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 88975640627..93dd7aa2002 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -7,6 +7,7 @@ const cli = @import("cli.zig"); const stream = @import("benchmark_stream.zig"); const sse = @import("benchmark_sse.zig"); const stop_flag = @import("benchmark_stop.zig"); +const Sink = @import("benchmark_log.zig").Sink; const Allocator = std.mem.Allocator; const posix = std.posix; @@ -145,6 +146,8 @@ pub const Managed = struct { stuck: []const u8 = (Words{}).stuck, key: ?[]const u8 = null, secrets: []const []const u8 = &.{}, + /// The child's output, redacted before it is written to ``log``. + sink: ?*Sink = null, base_url: []const u8 = "", reaped: bool = false, closed: bool = false, @@ -169,7 +172,17 @@ pub const Managed = struct { return null; }; const group: ?posix.pid_t = if (o.own_group) 0 else null; - const child = std.process.spawn(io, .{ .argv = child_argv, .environ_map = &child_env, .stdin = .ignore, .stdout = .{ .file = log }, .stderr = .{ .file = log }, .pgid = group }) catch { + // the child writes into a pipe: keys are replaced before any byte reaches the log file + const sink: ?*Sink = Sink.open(std.heap.page_allocator, io, log, try sinkSecrets(a, o)) catch { + cwd.deleteFile(io, log_path) catch {}; + log.close(io); + if (lock) |l| l.close(io); + problem.* = o.words.spawn; + return null; + }; + const out: std.process.SpawnOptions.StdIo = .{ .file = sink.?.child }; + const child = std.process.spawn(io, .{ .argv = child_argv, .environ_map = &child_env, .stdin = .ignore, .stdout = out, .stderr = out, .pgid = group }) catch { + if (sink) |k| k.close(std.heap.page_allocator); cwd.deleteFile(io, log_path) catch {}; log.close(io); if (lock) |l| l.close(io); @@ -178,7 +191,12 @@ pub const Managed = struct { }; stop_flag.guardChild(child.id.?); cwd.deleteFile(io, log_path) catch {}; - var m: Managed = .{ .io = io, .pid = child.id.?, .log = log, .lock = lock, .grace_ms = o.grace_ms, .served = o.served, .stuck = o.words.stuck, .key = o.key, .secrets = o.secrets }; + var m: Managed = .{ .io = io, .pid = child.id.?, .log = log, .lock = lock, .grace_ms = o.grace_ms, .served = o.served, .stuck = o.words.stuck, .key = o.key, .secrets = o.secrets, .sink = sink }; + if (sink) |k| k.started() catch { + _ = m.stop(); + problem.* = o.words.spawn; + return null; + }; const ok = m.ready(a, o.startup_timeout_s, o.tail, o.words, problem) catch |e| { _ = m.stop(); return e; @@ -202,6 +220,7 @@ pub const Managed = struct { } if (m.exited()) { problem.* = words.exited; + if (m.sink) |k| k.settle(1000); if (tail) |t| t.* = try lastLinesRedacted(a, m.logEnd(&buf), m.secrets); return false; } @@ -237,6 +256,7 @@ pub const Managed = struct { /// The child's last log lines once it has exited on its own, else null. pub fn exitedTail(m: *Managed, a: Allocator) !?[]const []const u8 { if (m.closed or !m.exited()) return null; + if (m.sink) |k| k.settle(1000); var buf: [64 << 10]u8 = undefined; return try lastLinesRedacted(a, m.logEnd(&buf), m.secrets); } @@ -246,6 +266,8 @@ pub const Managed = struct { if (m.closed) return null; m.closed = true; defer { + if (m.sink) |k| k.close(std.heap.page_allocator); + m.sink = null; m.log.close(m.io); if (m.lock) |l| l.close(m.io); } @@ -298,6 +320,13 @@ pub fn ended(pid: posix.pid_t) bool { return got == pid; } +/// The forms the log sink replaces: every configured credential, and the probes' key when it is not among them. +fn sinkSecrets(a: Allocator, o: Options) ![]const []const u8 { + const key = o.key orelse return o.secrets; + for (o.secrets) |secret| if (std.mem.eql(u8, secret, key)) return o.secrets; + return std.mem.concat(a, []const u8, &.{ o.secrets, &.{key} }); +} + /// Up to three last ``tensorfold:`` or ``error:`` lines in order (an earlier variable hint first), else the last line. pub fn lastLines(a: Allocator, log: []const u8) ![]const []const u8 { return lastLinesRedacted(a, log, &.{}); diff --git a/zig/src/server/benchmark_server_test.zig b/zig/src/server/benchmark_server_test.zig index 7d5aad161c5..2fcf55780f2 100644 --- a/zig/src/server/benchmark_server_test.zig +++ b/zig/src/server/benchmark_server_test.zig @@ -518,3 +518,27 @@ test "the child's flags carry the cache format the benchmark asked for" { var u: cli.Usage = .{}; try std.testing.expectError(error.Usage, cli.parse(a, args[2..], &u)); } + +test "a managed child's key never reaches its log file, raw or encoded across writes, only its replacement" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); + const f = try fake.Fake.start(std.testing.allocator, &routes); + defer f.stop(); + const leak = "printf 'echo %s\\n' \"$TENSORFOLD_API_KEY\"; printf 'enc child%%2Dlog'; sleep 0.2; printf '%%2Dkey\\n'; "; + const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try std.mem.concat(a, u8, &.{ leak, try serving(a, f.port, "exec sleep 30") }) }); + var problem: []const u8 = ""; + var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 10, .bench_dir = s.bench, .key = "child-log-key" }, &problem)) orelse return error.TestUnexpectedResult; + defer _ = m.stop(); + // the file itself, not a cleaned tail: what reached the disk + var buf: [4096]u8 = undefined; + const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; + try std.testing.expect(std.mem.indexOf(u8, got, "child-log-key") == null); + try std.testing.expect(std.mem.indexOf(u8, got, "child%2Dlog%2Dkey") == null); + try std.testing.expect(std.mem.indexOf(u8, got, "echo [redacted]") != null); + try std.testing.expect(std.mem.indexOf(u8, got, "[tensorfold] serving .tensorfold-benchmark at http://127.0.0.1:") != null); +} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index b7bface6549..91c5da3906d 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -294,6 +294,7 @@ test { _ = @import("benchmark_stream_test.zig"); _ = @import("chat_cli_key_test.zig"); _ = @import("benchmark_server_test.zig"); + _ = @import("benchmark_log.zig"); _ = @import("benchmark_facts_test.zig"); _ = @import("benchmark_rocm_test.zig"); _ = @import("benchmark_manifest.zig"); From d3b5763fcdf6db1070402723f10e9e6d6c20f96d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:03:09 +0000 Subject: [PATCH 104/361] server: a managed child's log is checked line by line, and readiness is read before redaction The redacting pipe wrote its replacement text, its markers and a suffix held at the end of the stream without checking them, so a configured key could still reach the log file: a key spelled like the replacement, or a replacement that completed a longer key with the text after it. With keys configured, the pipe now writes whole lines. No accepted key holds a newline, so a line is the unit a key can occur in: each line has its keys replaced, and the exact text about to be written is checked for every key form; a line that still holds one is written as the fixed withheld text, or as its newline alone when that text is a key too. A line past 1 MiB is withheld through its newline. Without keys the bytes pass unchanged. The parent also found serve's port by reading the redacted log, so a valid key such as "serving", the served name or the address hid the serving line and a healthy child timed out. The pipe's reader now takes the port from the raw line in memory, before redaction, and the parent reads it there; the raw line never reaches the file. --- zig/src/server/benchmark_log.zig | 138 ++++++++++++++++++----- zig/src/server/benchmark_server.zig | 5 +- zig/src/server/benchmark_server_test.zig | 21 ++++ 3 files changed, 135 insertions(+), 29 deletions(-) diff --git a/zig/src/server/benchmark_log.zig b/zig/src/server/benchmark_log.zig index 3f7d8cafb88..b7fd4f9bc50 100644 --- a/zig/src/server/benchmark_log.zig +++ b/zig/src/server/benchmark_log.zig @@ -1,9 +1,10 @@ -//! A managed child's output reaches its log file only through the parent: read from a pipe, keys replaced first. +//! A managed child's output reaches its log file only through the parent: read from a pipe, a line at a time. const std = @import("std"); const sse = @import("benchmark_sse.zig"); +const credential = @import("sys").credential; const posix = std.posix; -/// Held bytes past this length are written as one replacement instead of waiting for more. +/// A line past this length is withheld through its newline instead of waiting for more. const hold_limit = 1 << 20; pub const Sink = struct { @@ -13,13 +14,16 @@ pub const Sink = struct { /// The child's stdout and stderr; the parent closes its own copy once the child holds it. child: std.Io.File, secrets: []const []const u8, + served: []const u8, offset: u64 = 0, + /// Serve's port from its serving line, read before redaction and never from the file (0: not yet). + port: std.atomic.Value(u16) = .init(0), stop: std.atomic.Value(bool) = .init(false), done: std.atomic.Value(bool) = .init(false), thread: ?std.Thread = null, /// A pipe in front of `log`; `secrets` (raw keys) are replaced wherever they or their encodings occur. - pub fn open(gpa: std.mem.Allocator, io: std.Io, log: std.Io.File, secrets: []const []const u8) !*Sink { + pub fn open(gpa: std.mem.Allocator, io: std.Io, log: std.Io.File, secrets: []const []const u8, served: []const u8) !*Sink { var fds: [2]posix.fd_t = undefined; if (std.c.pipe(&fds) != 0) return error.PipeFailed; for (fds) |fd| _ = std.c.fcntl(fd, posix.F.SETFD, @as(c_int, posix.FD_CLOEXEC)); @@ -27,7 +31,7 @@ pub const Sink = struct { for (fds) |fd| _ = std.c.close(fd); return e; }; - s.* = .{ .io = io, .log = log, .read_fd = fds[0], .child = .{ .handle = fds[1], .flags = .{ .nonblocking = false } }, .secrets = secrets }; + s.* = .{ .io = io, .log = log, .read_fd = fds[0], .child = .{ .handle = fds[1], .flags = .{ .nonblocking = false } }, .secrets = secrets, .served = served }; return s; } @@ -57,13 +61,43 @@ pub const Sink = struct { s.offset += bytes.len; } + /// Serve's port once its serving line has gone through the pipe. + pub fn servingPort(s: *const Sink) ?u16 { + const p = s.port.load(.acquire); + return if (p == 0) null else p; + } + + /// With keys, the exact text written for one line: its keys replaced, and the result itself free of every key. + fn written(s: *const Sink, a: std.mem.Allocator, raw: []const u8) []const u8 { + const candidate = sse.redact(a, raw, s.secrets) catch return s.marker(a); + return if (credential.contains(a, candidate, s.secrets) catch true) s.marker(a) else candidate; + } + + /// The fixed text in place of a withheld line, or nothing when that text is itself a key. + fn marker(s: *const Sink, a: std.mem.Allocator) []const u8 { + return if (credential.contains(a, credential.withheld, s.secrets) catch true) "" else credential.withheld; + } + + /// One whole line (`newline`: it ended in one, else the stream ended): readiness from its raw bytes, then the file. + fn line(s: *Sink, a: std.mem.Allocator, raw: []const u8, newline: bool) void { + if (s.served.len > 0 and s.port.load(.acquire) == 0) { + if (@import("benchmark_server.zig").servingPort(raw, s.served)) |p| s.port.store(p, .release); + } + if (s.secrets.len == 0) return; // written as it came + s.append(s.written(a, raw)); + if (newline) s.append("\n"); + } + fn run(s: *Sink) void { defer s.done.store(true, .release); - var held: std.ArrayList(u8) = .empty; + var held: std.ArrayList(u8) = .empty; // the current line, up to hold_limit defer held.deinit(std.heap.page_allocator); + var over = false; // the current line passed hold_limit: nothing more of it is kept or written var buf: [64 << 10]u8 = undefined; var fds = [_]posix.pollfd{.{ .fd = s.read_fd, .events = posix.POLL.IN, .revents = 0 }}; var after_stop: u32 = 0; + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); while (true) { const stopping = s.stop.load(.acquire); if (stopping) after_stop += 1; @@ -75,29 +109,31 @@ pub const Sink = struct { if (after_stop > 256) break; // a writer that never pauses cannot hold the stop const n = posix.read(s.read_fd, &buf) catch break; if (n == 0) break; - if (s.secrets.len == 0) { - s.append(buf[0..n]); - continue; - } - held.appendSlice(std.heap.page_allocator, buf[0..n]) catch break; - var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); - defer arena.deinit(); - const piece = sse.redactPiece(arena.allocator(), held.items, s.secrets) catch { - s.append("[redacted]"); - held.clearRetainingCapacity(); - continue; - }; - s.append(piece.text); - const rest = piece.rest.len; - std.mem.copyForwards(u8, held.items[0..rest], piece.rest); - held.shrinkRetainingCapacity(rest); - if (held.items.len > hold_limit) { - s.append("[redacted]"); + if (s.secrets.len == 0) s.append(buf[0..n]); + var rest = buf[0..n]; + while (rest.len > 0) { + const end = std.mem.indexOfScalar(u8, rest, '\n'); + const part = rest[0 .. end orelse rest.len]; + rest = if (end) |e| rest[e + 1 ..] else rest[rest.len..]; + if (!over) held.appendSlice(std.heap.page_allocator, part) catch { + over = true; + }; + if (!over and held.items.len > hold_limit) over = true; + if (over and held.items.len > 0) { + if (s.secrets.len > 0) s.append(s.marker(arena.allocator())); + held.clearRetainingCapacity(); + } + if (end == null) continue; + if (over) { + if (s.secrets.len > 0) s.append("\n"); + over = false; + } else s.line(arena.allocator(), held.items, true); held.clearRetainingCapacity(); + _ = arena.reset(.retain_capacity); } } - // a suffix still held could become a key: its place is marked, its bytes are not written - if (held.items.len > 0) s.append("[redacted]"); + // a last line without its newline is whole now: nothing can follow it + if (!over and held.items.len > 0) s.line(arena.allocator(), held.items, false); } }; @@ -110,7 +146,7 @@ test "benchmark log: a key written to the child's stream reaches the file only a for (0..text.len) |split| { const log = try tmp.dir.createFile(io, "child.log", .{ .read = true, .truncate = true }); defer log.close(io); - const s = try Sink.open(std.testing.allocator, io, log, &.{secret}); + const s = try Sink.open(std.testing.allocator, io, log, &.{secret}, ""); const writer = std.c.dup(s.child.handle); try s.started(); _ = std.c.write(writer, text.ptr, split); @@ -133,7 +169,7 @@ test "benchmark log: without keys the child's bytes reach the file unchanged" { defer tmp.cleanup(); const log = try tmp.dir.createFile(io, "child.log", .{ .read = true }); defer log.close(io); - const s = try Sink.open(std.testing.allocator, io, log, &.{}); + const s = try Sink.open(std.testing.allocator, io, log, &.{}, ""); const writer = std.c.dup(s.child.handle); try s.started(); _ = std.c.write(writer, "plain output\n", 13); @@ -143,3 +179,51 @@ test "benchmark log: without keys the child's bytes reach the file unchanged" { var out: [64]u8 = undefined; try std.testing.expectEqualStrings("plain output\n", out[0..try log.readPositionalAll(io, &out, 0)]); } + +/// What the sink wrote for `text`, sent in two writes split at `split`, under `secrets`. +fn through(io: std.Io, dir: std.Io.Dir, secrets: []const []const u8, text: []const u8, split: usize, out: []u8) ![]const u8 { + const log = try dir.createFile(io, "child.log", .{ .read = true, .truncate = true }); + defer log.close(io); + const s = try Sink.open(std.testing.allocator, io, log, secrets, ""); + const writer = std.c.dup(s.child.handle); + try s.started(); + _ = std.c.write(writer, text.ptr, split); + _ = std.c.write(writer, text[split..].ptr, text.len - split); + _ = std.c.close(writer); + s.settle(5000); + s.close(std.testing.allocator); + return out[0..try log.readPositionalAll(io, out, 0)]; +} + +test "benchmark log: no replacement, marker or held suffix writes a configured key, at any split" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const cases = [_]struct { secrets: []const []const u8, text: []const u8 }{ + .{ .secrets = &.{"[redacted]"}, .text = "a [redacted] b\nnext\n" }, // the key is the replacement text + // a replacement completes a key + .{ .secrets = &.{ "[redacted]-suffix", "fixture-log-key" }, .text = "fixture-log-key-suffix\nnext\n" }, + .{ .secrets = &.{ "[redacted]", "[withheld]" }, .text = "x [redacted]\nnext\n" }, // both fixed texts are keys + .{ .secrets = &.{"[redacted]"}, .text = "held [" }, // a suffix held at the end of the stream + }; + var out: [256]u8 = undefined; + for (cases) |case| for (0..case.text.len + 1) |split| { + const got = try through(io, tmp.dir, case.secrets, case.text, split, &out); + for (case.secrets) |k| try std.testing.expect(std.mem.indexOf(u8, got, k) == null); + if (std.mem.endsWith(u8, case.text, "next\n")) try std.testing.expect(std.mem.endsWith(u8, got, "\nnext\n")); + }; +} + +test "benchmark log: a line past the hold limit writes no configured key" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const long = try std.testing.allocator.alloc(u8, hold_limit + 4096 + 6); + defer std.testing.allocator.free(long); + @memset(long, 'x'); + @memcpy(long[long.len - 6 ..], "\nnext\n"); + var out: [4096]u8 = undefined; + const got = try through(io, tmp.dir, &.{"[redacted]"}, long, 1000, &out); + try std.testing.expect(std.mem.indexOf(u8, got, "[redacted]") == null); + try std.testing.expect(std.mem.endsWith(u8, got, "\nnext\n")); +} diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 93dd7aa2002..2145c5bd355 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -173,7 +173,7 @@ pub const Managed = struct { }; const group: ?posix.pid_t = if (o.own_group) 0 else null; // the child writes into a pipe: keys are replaced before any byte reaches the log file - const sink: ?*Sink = Sink.open(std.heap.page_allocator, io, log, try sinkSecrets(a, o)) catch { + const sink: ?*Sink = Sink.open(std.heap.page_allocator, io, log, try sinkSecrets(a, o), o.served) catch { cwd.deleteFile(io, log_path) catch {}; log.close(io); if (lock) |l| l.close(io); @@ -225,7 +225,8 @@ pub const Managed = struct { return false; } if (port == null) { - port = servingPort(m.logEnd(&buf), m.served); + // the sink reads it from the raw line: a key may have changed the file's copy + port = if (m.sink) |k| k.servingPort() else servingPort(m.logEnd(&buf), m.served); if (port) |p| m.base_url = try std.fmt.allocPrint(a, "http://127.0.0.1:{d}", .{p}); } if (port != null and try probe(a, m.io, &client, m.base_url, m.served, m.key)) return true; diff --git a/zig/src/server/benchmark_server_test.zig b/zig/src/server/benchmark_server_test.zig index 2fcf55780f2..121bfcdcb01 100644 --- a/zig/src/server/benchmark_server_test.zig +++ b/zig/src/server/benchmark_server_test.zig @@ -542,3 +542,24 @@ test "a managed child's key never reaches its log file, raw or encoded across wr try std.testing.expect(std.mem.indexOf(u8, got, "echo [redacted]") != null); try std.testing.expect(std.mem.indexOf(u8, got, "[tensorfold] serving .tensorfold-benchmark at http://127.0.0.1:") != null); } + +test "a valid key that overlaps the serving line still lets a healthy managed child become ready, and stays off disk" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); + const f = try fake.Fake.start(std.testing.allocator, &routes); + defer f.stop(); + for ([_][]const u8{ "serving", ".tensorfold-benchmark", "127.0.0.1" }) |key| { + const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try serving(a, f.port, "exec sleep 30") }); + var problem: []const u8 = ""; + var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 5, .bench_dir = s.bench, .key = key }, &problem)) orelse return error.TestUnexpectedResult; + var buf: [4096]u8 = undefined; + const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; + try std.testing.expect(std.mem.indexOf(u8, got, key) == null); + try std.testing.expect(m.stop() == null); + } +} From cb2a2562f2f05815849be97d4bb55766961ca5f8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:50:06 +0000 Subject: [PATCH 105/361] server: a failed log write ends the file, and an exited child's last line reaches its tail With keys configured, the log's containment rests on each checked line being followed by its newline. A failed write was ignored and the next write went to the same offset, so when the separator failed and the disk then recovered, two checked lines could join into a key in the file. Now any failed write with keys configured ends the file: nothing more is written, so it stays a prefix of the checked, separated lines. The sink writes a line once its newline or the end of the stream comes. When a child exited with an unterminated last line while a process it had started still held its output open, the stream did not end, and the startup error tail was read without that line. The parent now asks the reader to write the held line, checked and followed by a newline, before it reads an exited child's tail. Later output starts a new line. The managed-log tests move to their own file under the line cap, and test-managed-log-host runs them with the sink's and the managed child's tests. --- zig/build/cuda_server_host.zig | 1 + zig/src/server/benchmark_log.zig | 90 ++++++++++++++++-- zig/src/server/benchmark_server.zig | 2 + zig/src/server/benchmark_server_log_test.zig | 99 ++++++++++++++++++++ zig/src/server/benchmark_server_test.zig | 59 ++---------- zig/src/server/root.zig | 1 + 6 files changed, 193 insertions(+), 59 deletions(-) create mode 100644 zig/src/server/benchmark_server_log_test.zig diff --git a/zig/build/cuda_server_host.zig b/zig/build/cuda_server_host.zig index 8c6570c0f73..1af93d88a2a 100644 --- a/zig/build/cuda_server_host.zig +++ b/zig/build/cuda_server_host.zig @@ -27,6 +27,7 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod b.step("test-wait-reasons-server-host", "The ledger's wait, refusal and failure labels in /metrics and /v1/load").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"wait reason ledger:"} })).step); // the open-connection limit, one address's share under pressure and its flags (#3048), on Linux hosts too b.step("test-connection-admission-host", "Connection limit, per-address share, trusted proxies and idle shedding").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "security: ", "connection CLI:" } })).step); + b.step("test-managed-log-host", "A managed child's log without keys in the file, its readiness and its startup tail").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "benchmark log:", "benchmark_server_test.", "benchmark_server_log_test." } })).step); b.step("test-admission-http-host", "Admission places over HTTP: n choices, refusals and walk-aways return every place").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"admission HTTP:"} })).step); const flush = b.step("test-prompt-cache-flush-host", "The prompt cache flush: its hold, a cold next turn, withdrawal and who may call it"); flush.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native_modules.api, .filters = &.{"prompt cache flush:"} })).step); diff --git a/zig/src/server/benchmark_log.zig b/zig/src/server/benchmark_log.zig index b7fd4f9bc50..623b4f28c81 100644 --- a/zig/src/server/benchmark_log.zig +++ b/zig/src/server/benchmark_log.zig @@ -16,6 +16,13 @@ pub const Sink = struct { secrets: []const []const u8, served: []const u8, offset: u64 = 0, + /// Tests only: the `at`-th write (from 1) puts its first `keep` bytes in the file, then fails, once. + fault: struct { at: u32 = 0, keep: usize = 0 } = .{}, + writes: u32 = 0, + /// With keys, a write failed: nothing more is written, so the file stays a prefix of the checked lines. + broken: bool = false, + /// 1: the parent asks for the held last line now; 2: it is written (an exited child's tail is then whole). + cut: std.atomic.Value(u8) = .init(0), /// Serve's port from its serving line, read before redaction and never from the file (0: not yet). port: std.atomic.Value(u16) = .init(0), stop: std.atomic.Value(bool) = .init(false), @@ -56,11 +63,28 @@ pub const Sink = struct { } fn append(s: *Sink, bytes: []const u8) void { - if (bytes.len == 0) return; - s.log.writePositionalAll(s.io, bytes, s.offset) catch return; + if (bytes.len == 0 or s.broken) return; + s.writes += 1; + if (s.writes == s.fault.at) { + s.log.writePositionalAll(s.io, bytes[0..@min(s.fault.keep, bytes.len)], s.offset) catch {}; + s.broken = s.secrets.len > 0; + return; + } + s.log.writePositionalAll(s.io, bytes, s.offset) catch { + s.broken = s.secrets.len > 0; // a later line written here could join this one's text into a key + return; + }; s.offset += bytes.len; } + /// The held last line written now, checked and with a newline after it, for an exited child whose pipe stays open. + pub fn cutHeld(s: *Sink, ms: u32) void { + if (s.thread == null or s.done.load(.acquire)) return; + s.cut.store(1, .release); + var waited: u32 = 0; + while (s.cut.load(.acquire) != 2 and !s.done.load(.acquire) and waited < ms) : (waited += 10) s.io.sleep(.fromMilliseconds(10), .awake) catch {}; + } + /// Serve's port once its serving line has gone through the pipe. pub fn servingPort(s: *const Sink) ?u16 { const p = s.port.load(.acquire); @@ -99,6 +123,14 @@ pub const Sink = struct { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); while (true) { + if (s.cut.load(.acquire) == 1) { + if (over) { + if (s.secrets.len > 0) s.append("\n"); + } else if (held.items.len > 0) s.line(arena.allocator(), held.items, true); + over = false; + held.clearRetainingCapacity(); + s.cut.store(2, .release); + } const stopping = s.stop.load(.acquire); if (stopping) after_stop += 1; const ready = posix.poll(&fds, if (stopping) 0 else 100) catch break; @@ -182,9 +214,15 @@ test "benchmark log: without keys the child's bytes reach the file unchanged" { /// What the sink wrote for `text`, sent in two writes split at `split`, under `secrets`. fn through(io: std.Io, dir: std.Io.Dir, secrets: []const []const u8, text: []const u8, split: usize, out: []u8) ![]const u8 { + return faulted(io, dir, secrets, text, split, .{}, out); +} + +/// `through`, with the sink's `at`-th file write failing after `keep` bytes; the file is writable again after. +fn faulted(io: std.Io, dir: std.Io.Dir, secrets: []const []const u8, text: []const u8, split: usize, fault: @FieldType(Sink, "fault"), out: []u8) ![]const u8 { const log = try dir.createFile(io, "child.log", .{ .read = true, .truncate = true }); defer log.close(io); const s = try Sink.open(std.testing.allocator, io, log, secrets, ""); + s.fault = fault; const writer = std.c.dup(s.child.handle); try s.started(); _ = std.c.write(writer, text.ptr, split); @@ -205,11 +243,17 @@ test "benchmark log: no replacement, marker or held suffix writes a configured k .{ .secrets = &.{ "[redacted]-suffix", "fixture-log-key" }, .text = "fixture-log-key-suffix\nnext\n" }, .{ .secrets = &.{ "[redacted]", "[withheld]" }, .text = "x [redacted]\nnext\n" }, // both fixed texts are keys .{ .secrets = &.{"[redacted]"}, .text = "held [" }, // a suffix held at the end of the stream + .{ .secrets = &.{"[redacted]"}, .text = "a %5Bredacted%5D b\nnext\n" }, // encoded forms of the same + .{ .secrets = &.{"[redacted]"}, .text = "a %255Bredacted%255D b\nnext\n" }, + .{ .secrets = &.{ "[redacted]-suffix", "fixture-log-key" }, .text = "fixture%2Dlog%2Dkey-suffix\nnext\n" }, + .{ .secrets = &.{ "[redacted]", "[withheld]" }, .text = "x %5Bredacted%5D\nnext\n" }, + .{ .secrets = &.{"[redacted]"}, .text = "held %5B" }, }; var out: [256]u8 = undefined; for (cases) |case| for (0..case.text.len + 1) |split| { const got = try through(io, tmp.dir, case.secrets, case.text, split, &out); for (case.secrets) |k| try std.testing.expect(std.mem.indexOf(u8, got, k) == null); + try std.testing.expect(!try credential.contains(std.testing.allocator, got, case.secrets)); // at any depth if (std.mem.endsWith(u8, case.text, "next\n")) try std.testing.expect(std.mem.endsWith(u8, got, "\nnext\n")); }; } @@ -220,10 +264,42 @@ test "benchmark log: a line past the hold limit writes no configured key" { defer tmp.cleanup(); const long = try std.testing.allocator.alloc(u8, hold_limit + 4096 + 6); defer std.testing.allocator.free(long); - @memset(long, 'x'); - @memcpy(long[long.len - 6 ..], "\nnext\n"); var out: [4096]u8 = undefined; - const got = try through(io, tmp.dir, &.{"[redacted]"}, long, 1000, &out); - try std.testing.expect(std.mem.indexOf(u8, got, "[redacted]") == null); - try std.testing.expect(std.mem.endsWith(u8, got, "\nnext\n")); + for ([_][]const u8{ "", "%5Bredacted%5D", "%255Bredacted%255D" }) |planted| { + @memset(long, 'x'); + @memcpy(long[10..][0..planted.len], planted); // before the limit + @memcpy(long[long.len - 6 - planted.len ..][0..planted.len], planted); // past it + @memcpy(long[long.len - 6 ..], "\nnext\n"); + const got = try through(io, tmp.dir, &.{"[redacted]"}, long, 1000, &out); + try std.testing.expect(!try credential.contains(std.testing.allocator, got, &.{"[redacted]"})); + try std.testing.expect(std.mem.endsWith(u8, got, "\nnext\n")); + } +} + +test "benchmark log: a write that fails, whole or in part, never lets later lines join into a key in the file" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const secrets: []const []const u8 = &.{"abcdef"}; + var out: [256]u8 = undefined; + // writes: 1 "abc", 2 its newline, 3 "def", 4 its newline; then the encoded halves + for ([_]struct { text: []const u8, at: u32, keep: usize }{ + .{ .text = "abc\ndef\n", .at = 2, .keep = 0 }, // the separator fails, then the disk recovers + .{ .text = "abc\ndef\n", .at = 1, .keep = 2 }, // a line written in part + .{ .text = "abc\ndef\n", .at = 3, .keep = 1 }, + .{ .text = "%61bc\n%64ef\n", .at = 2, .keep = 0 }, // encoded halves + .{ .text = "ab%2563\ndef\n", .at = 2, .keep = 0 }, // nested + }) |c| for (0..c.text.len + 1) |split| { + const got = try faulted(io, tmp.dir, secrets, c.text, split, .{ .at = c.at, .keep = c.keep }, &out); + try std.testing.expect(!try credential.contains(std.testing.allocator, got, secrets)); + }; +} + +test "benchmark log: without keys, ordinary bytes pass unchanged to the end of the stream" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const text = "one\ntwo %5B\n[redacted]\nlast without newline"; + var out: [256]u8 = undefined; + for (0..text.len + 1) |split| try std.testing.expectEqualStrings(text, try through(io, tmp.dir, &.{}, text, split, &out)); } diff --git a/zig/src/server/benchmark_server.zig b/zig/src/server/benchmark_server.zig index 2145c5bd355..d2a86cceaee 100644 --- a/zig/src/server/benchmark_server.zig +++ b/zig/src/server/benchmark_server.zig @@ -221,6 +221,7 @@ pub const Managed = struct { if (m.exited()) { problem.* = words.exited; if (m.sink) |k| k.settle(1000); + if (m.sink) |k| k.cutHeld(1000); // a descendant may hold the pipe: the last line is written now if (tail) |t| t.* = try lastLinesRedacted(a, m.logEnd(&buf), m.secrets); return false; } @@ -258,6 +259,7 @@ pub const Managed = struct { pub fn exitedTail(m: *Managed, a: Allocator) !?[]const []const u8 { if (m.closed or !m.exited()) return null; if (m.sink) |k| k.settle(1000); + if (m.sink) |k| k.cutHeld(1000); var buf: [64 << 10]u8 = undefined; return try lastLinesRedacted(a, m.logEnd(&buf), m.secrets); } diff --git a/zig/src/server/benchmark_server_log_test.zig b/zig/src/server/benchmark_server_log_test.zig new file mode 100644 index 00000000000..376067930d0 --- /dev/null +++ b/zig/src/server/benchmark_server_log_test.zig @@ -0,0 +1,99 @@ +//! A managed child's log with keys configured: no key in the file, readiness, and the startup tail. +const std = @import("std"); +const server = @import("benchmark_server.zig"); +const fake = @import("benchmark_fake.zig"); +const credential = @import("sys").credential; +const t = @import("benchmark_server_test.zig"); +const Setup = t.Setup; +const plan = t.plan; +const healthy = t.healthy; +const serving = t.serving; +const none = t.none; +const lines = t.lines; + +test "managed log: a managed child's key never reaches its log file, raw or encoded across writes, only its replacement" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); + const f = try fake.Fake.start(std.testing.allocator, &routes); + defer f.stop(); + const leak = "printf 'echo %s\\n' \"$TENSORFOLD_API_KEY\"; printf 'enc child%%2Dlog'; sleep 0.2; printf '%%2Dkey\\n'; "; + const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try std.mem.concat(a, u8, &.{ leak, try serving(a, f.port, "exec sleep 30") }) }); + var problem: []const u8 = ""; + var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 10, .bench_dir = s.bench, .key = "child-log-key" }, &problem)) orelse return error.TestUnexpectedResult; + defer _ = m.stop(); + // the file itself, not a cleaned tail: what reached the disk + var buf: [4096]u8 = undefined; + const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; + try std.testing.expect(std.mem.indexOf(u8, got, "child-log-key") == null); + try std.testing.expect(std.mem.indexOf(u8, got, "child%2Dlog%2Dkey") == null); + try std.testing.expect(std.mem.indexOf(u8, got, "echo [redacted]") != null); + try std.testing.expect(std.mem.indexOf(u8, got, "[tensorfold] serving .tensorfold-benchmark at http://127.0.0.1:") != null); +} + +test "managed log: a valid key that overlaps the serving line still lets a healthy managed child become ready, and stays off disk" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); + const f = try fake.Fake.start(std.testing.allocator, &routes); + defer f.stop(); + for ([_][]const u8{ "serving", ".tensorfold-benchmark", "127.0.0.1" }) |key| { + const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try serving(a, f.port, "exec sleep 30") }); + var problem: []const u8 = ""; + var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 5, .bench_dir = s.bench, .key = key }, &problem)) orelse return error.TestUnexpectedResult; + var buf: [4096]u8 = undefined; + const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; + try std.testing.expect(std.mem.indexOf(u8, got, key) == null); + try std.testing.expect(m.stop() == null); + } +} + +test "managed log: an exited child's last diagnostic without a newline reaches its startup tail, also while a descendant holds the pipe" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + for ([_][]const u8{ + "sleep 4 & printf 'loading\\nerror: bad model child-log-key'; exit 3", // a descendant keeps the pipe open + "printf 'loading\\nerror: bad model child-log-key'; exit 3", // ordinary end of stream + }) |script| { + var problem: []const u8 = ""; + var tail: []const []const u8 = &.{}; + const argv = try a.dupe([]const u8, &.{ "/bin/sh", "-c", script }); + const t0 = std.Io.Clock.awake.now(std.testing.io); + try none(try server.Managed.start(a, std.testing.io, &s.env, plan, .{ .startup_timeout_s = 10, .bench_dir = s.bench, .argv = argv, .tail = &tail, .key = "child-log-key" }, &problem)); + try std.testing.expectEqualStrings("Benchmark server exited during startup; check the checkpoint and backend toolchain", problem); + try lines(&.{"error: bad model [redacted]"}, tail); + const took = t0.durationTo(std.Io.Clock.awake.now(std.testing.io)).toMilliseconds(); + try std.testing.expect(took < 4000); // bounded: no wait for the descendant + } +} + +test "managed log: a key whose encoded form is printed beside the serving line still lets the child become ready, and stays off disk" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var s = try Setup.init(a, &tmp); + const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); + const f = try fake.Fake.start(std.testing.allocator, &routes); + defer f.stop(); + const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try std.mem.concat(a, u8, &.{ "printf 's%%65rving s%%2565rving\\n'; ", try serving(a, f.port, "exec sleep 30") }) }); + var problem: []const u8 = ""; + var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 5, .bench_dir = s.bench, .key = "serving" }, &problem)) orelse return error.TestUnexpectedResult; + var buf: [4096]u8 = undefined; + const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; + try std.testing.expect(!try credential.contains(a, got, &.{"serving"})); + try std.testing.expect(m.stop() == null); +} diff --git a/zig/src/server/benchmark_server_test.zig b/zig/src/server/benchmark_server_test.zig index 121bfcdcb01..63d6942239b 100644 --- a/zig/src/server/benchmark_server_test.zig +++ b/zig/src/server/benchmark_server_test.zig @@ -7,7 +7,7 @@ const stop = @import("benchmark_stop.zig"); const fake = @import("benchmark_fake.zig"); const posix = std.posix; -const plan: server.Plan = .{ .exe = "/opt/example/tensorfold-native", .dir = "/models/x", .backend = "", .tokens = 256, .context = 4096, .drafter_dir = null, .serial = true }; +pub const plan: server.Plan = .{ .exe = "/opt/example/tensorfold-native", .dir = "/models/x", .backend = "", .tokens = 256, .context = 4096, .drafter_dir = null, .serial = true }; test "the child's flags parse as serve flags and carry none that native serve refuses; adding --tp fails" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); @@ -67,13 +67,13 @@ test "the port comes from serve's serving line, whose format serve.zig still pri try std.testing.expect(std.mem.indexOf(u8, serve_source, "\"serving {s} on http://{s}:{d}/v1 (") == null); } -const Setup = struct { +pub const Setup = struct { a: std.mem.Allocator, env: std.process.Environ.Map, dir: []const u8, bench: []const u8, - fn init(a: std.mem.Allocator, tmp: *std.testing.TmpDir) !Setup { + pub fn init(a: std.mem.Allocator, tmp: *std.testing.TmpDir) !Setup { var env: std.process.Environ.Map = .init(a); try env.put("PATH", "/usr/bin:/bin"); const dir = try fake.tmpPath(a, tmp); @@ -86,7 +86,7 @@ const Setup = struct { } }; -fn healthy(a: std.mem.Allocator, health: []const u8, model_id: []const u8) ![2]fake.Route { +pub fn healthy(a: std.mem.Allocator, health: []const u8, model_id: []const u8) ![2]fake.Route { const models = try std.fmt.allocPrint(a, "{{\"data\": [{{\"id\": \"{s}\"}}]}}", .{model_id}); return .{ .{ .method = "GET", .path = "/health", .replies = try a.dupe([]const fake.Write, &.{try fake.jsonReply(a, "200 OK", health)}) }, @@ -94,7 +94,7 @@ fn healthy(a: std.mem.Allocator, health: []const u8, model_id: []const u8) ![2]f }; } -fn serving(a: std.mem.Allocator, port: u16, tail: []const u8) ![]const u8 { +pub fn serving(a: std.mem.Allocator, port: u16, tail: []const u8) ![]const u8 { return std.fmt.allocPrint(a, "printf '[tensorfold] serving .tensorfold-benchmark at http://127.0.0.1:%s/v1 (x)\\n' {d}; {s}", .{ port, tail }); } @@ -104,7 +104,7 @@ fn gone(pid: posix.pid_t) bool { } /// Passes when ``start`` gave no child; a child it did give is stopped before the test fails. -fn none(got: ?server.Managed) !void { +pub fn none(got: ?server.Managed) !void { var m = got orelse return; _ = m.stop(); return error.TestUnexpectedResult; @@ -183,7 +183,7 @@ test "a child that exits during startup hands back its last log lines, cleaned f try std.testing.expect(cut.len == 302 and std.mem.endsWith(u8, cut, "...") and std.unicode.utf8ValidateSlice(cut)); } -fn lines(want: []const []const u8, got: []const []const u8) !void { +pub fn lines(want: []const []const u8, got: []const []const u8) !void { try std.testing.expectEqual(want.len, got.len); for (want, got) |w, g| try std.testing.expectEqualStrings(w, g); } @@ -518,48 +518,3 @@ test "the child's flags carry the cache format the benchmark asked for" { var u: cli.Usage = .{}; try std.testing.expectError(error.Usage, cli.parse(a, args[2..], &u)); } - -test "a managed child's key never reaches its log file, raw or encoded across writes, only its replacement" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var s = try Setup.init(a, &tmp); - const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); - const f = try fake.Fake.start(std.testing.allocator, &routes); - defer f.stop(); - const leak = "printf 'echo %s\\n' \"$TENSORFOLD_API_KEY\"; printf 'enc child%%2Dlog'; sleep 0.2; printf '%%2Dkey\\n'; "; - const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try std.mem.concat(a, u8, &.{ leak, try serving(a, f.port, "exec sleep 30") }) }); - var problem: []const u8 = ""; - var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 10, .bench_dir = s.bench, .key = "child-log-key" }, &problem)) orelse return error.TestUnexpectedResult; - defer _ = m.stop(); - // the file itself, not a cleaned tail: what reached the disk - var buf: [4096]u8 = undefined; - const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; - try std.testing.expect(std.mem.indexOf(u8, got, "child-log-key") == null); - try std.testing.expect(std.mem.indexOf(u8, got, "child%2Dlog%2Dkey") == null); - try std.testing.expect(std.mem.indexOf(u8, got, "echo [redacted]") != null); - try std.testing.expect(std.mem.indexOf(u8, got, "[tensorfold] serving .tensorfold-benchmark at http://127.0.0.1:") != null); -} - -test "a valid key that overlaps the serving line still lets a healthy managed child become ready, and stays off disk" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var s = try Setup.init(a, &tmp); - const routes = try healthy(a, "{\"status\": \"ok\"}", ".tensorfold-benchmark"); - const f = try fake.Fake.start(std.testing.allocator, &routes); - defer f.stop(); - for ([_][]const u8{ "serving", ".tensorfold-benchmark", "127.0.0.1" }) |key| { - const sh = try a.dupe([]const u8, &.{ "/bin/sh", "-c", try serving(a, f.port, "exec sleep 30") }); - var problem: []const u8 = ""; - var m = (try server.Managed.spawn(a, std.testing.io, &s.env, sh, .{ .startup_timeout_s = 5, .bench_dir = s.bench, .key = key }, &problem)) orelse return error.TestUnexpectedResult; - var buf: [4096]u8 = undefined; - const got = buf[0..try m.log.readPositionalAll(std.testing.io, &buf, 0)]; - try std.testing.expect(std.mem.indexOf(u8, got, key) == null); - try std.testing.expect(m.stop() == null); - } -} diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 91c5da3906d..51bb4a550fe 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -294,6 +294,7 @@ test { _ = @import("benchmark_stream_test.zig"); _ = @import("chat_cli_key_test.zig"); _ = @import("benchmark_server_test.zig"); + _ = @import("benchmark_server_log_test.zig"); _ = @import("benchmark_log.zig"); _ = @import("benchmark_facts_test.zig"); _ = @import("benchmark_rocm_test.zig"); From ea57d961f936ee32c3aae56126574ec88a2d4ce8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:28 +0000 Subject: [PATCH 106/361] changelog: #4852 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c62b43a35b0..8ca401858df 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 +- `tensorfold start` selects a fitting catalog model, downloads it with consent, starts a local server and checks its reply; startup, chat, pull and the managed server's log keep API keys out of output (#4852). + - 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). From d4f65876690056e62bcc5f8ad79c99d3ea6a4039 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:48:13 +0100 Subject: [PATCH 107/361] KV pool: host tier A Tier beside the Pool for families whose pages are cached on the device from a host store. The pool stays the only owner of page ids and of what is promised; the tier adds a second currency (device frames a stream may pin at once), the page-to-frame mapping, an LRU order, pins for the frames a call reads, a dirty flag so a frame is dropped only once its rows reached the host store, and a generation per frame so a table written before a frame was recycled is told from a current one. A stream can also be lent frames for its life, mapped to no page, for a family that manages them itself. The pool tells the tier when a page loses its last holder. It moves no bytes and uses no device API: the family copies what a miss names, and a snapshot reads canonical rows from the host store. Tests: reservation conservation in both currencies, eviction order, pin rules, lent frames, generation safety, canonical rows, a randomised serving loop that audits the mapping and checks every row read against the last write, two ranks in lockstep (and a step or a lent count taken by one rank caught by the digest), and mutants (no generation, no pin rule, dirty frames unpinned) that the checks fail on. A failed batch unmaps the misses it mapped (their generation moves on), a page is marked dirty only under a pin of the marking lease, a stream cannot end while it holds the last pin of a dirty page, and a family can lend a run of consecutive frames (lendRun). --- zig/src/core/kv_pool.zig | 12 + zig/src/core/kv_tier.zig | 432 ++++++++++++++++++++++++++ zig/src/core/kv_tier_test.zig | 564 ++++++++++++++++++++++++++++++++++ 3 files changed, 1008 insertions(+) create mode 100644 zig/src/core/kv_tier.zig create mode 100644 zig/src/core/kv_tier_test.zig diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index 19784f68602..8b9f28a4f74 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -217,6 +217,12 @@ pub const Notify = struct { /// A family's pool as the load ledger reads it: tokens a page, and the contiguous run it needs (0: none). pub const Source = struct { pool: *Pool, page_tokens: u32, run_pages: u32 = 0 }; +/// A tier's notice that a page lost its last holder (its frame, if any, is free again). +pub const Freed = struct { + ctx: *anyopaque, + call: *const fn (ctx: *anyopaque, id: u32) void, +}; + /// What an idle pool must show: nothing promised, every page free or the store's alone, none waiting on readers. pub const Census = struct { total: usize, free: usize, promised: usize, kept: usize, leased: usize, pending: usize = 0 }; @@ -238,6 +244,7 @@ pub const Pool = struct { ledger: ?Gate = null, // the lane host's ledger, the only test a promise passes; null: the pool's own pages depth: u8 = 0, // public changes in progress: the outermost one notifies, after nested calls and rollbacks retired: retirement.Retired = .{}, // pages a lease gave back mid-stream, until their readers are done + freed: ?Freed = null, pub fn init(gpa: Allocator, count: usize, page_bytes: u64) !Pool { const refs = try gpa.alloc(u32, count); @@ -558,8 +565,13 @@ pub const Pool = struct { } }; +/// The host tier: logical pages in host RAM and device frames that cache them (kv_tier.zig). +pub const tier = @import("kv_tier.zig"); +pub const Tier = tier.Tier; + test { _ = @import("kv_pool_test.zig"); + _ = @import("kv_tier.zig"); _ = @import("kv_pool_counts_test.zig"); _ = @import("kv_pool_walk_test.zig"); _ = @import("kv_pool_notify_test.zig"); diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig new file mode 100644 index 00000000000..3d40f1d98ca --- /dev/null +++ b/zig/src/core/kv_tier.zig @@ -0,0 +1,432 @@ +//! A host tier for the page pool: logical pages whose canonical rows live in host RAM, cached by device frames. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const Allocator = std.mem.Allocator; + +/// No frame (for a page) or no page (for a frame). +pub const none: u32 = std.math.maxInt(u32); + +/// What the ranks of one model agree on before they open a tier: the smallest of each. +pub const Shape = struct { + host_pages: usize, + frames: usize, + + pub fn agree(a: Shape, b: Shape) Shape { + return .{ .host_pages = @min(a.host_pages, b.host_pages), .frames = @min(a.frames, b.frames) }; + } +}; + +/// A deliberate bug a test turns on to show that the check beside it fails without the rule: never set outside tests. +pub const Fault = enum { none, keep_generation, ignore_pins, ignore_dirty, unpinned_dirty, keep_failed_miss }; + +/// A page a call pinned: its frame, the frame's generation, and whether the family must copy the page in. +pub const Fill = struct { page: u32, frame: u32, gen: u32, miss: bool }; + +/// A page's frame as a device table saw it: current while the frame's generation is the same. +pub const Ticket = struct { frame: u32, gen: u32 }; + +/// A stream's reservation in both currencies: pages (the pool's lease) and the frames it may pin at once. +pub const Lease = struct { + pages: kv.Lease = .{}, + frames: usize = 0, + pins: std.ArrayList(u32) = .empty, // one entry per pin, a page id + lent: std.ArrayList(u32) = .empty, // frames lent to the stream: mapped to no page, the family's to manage +}; + +pub const Census = struct { frames: usize, free: usize, resident: usize, pinned: usize, dirty: usize, promised: usize, lent: usize }; + +pub const Tier = struct { + gpa: Allocator, + pool: kv.Pool, // logical pages; the host store holds `pool.total()` of them + host: []u8, // canonical rows, `pool.total() * page_bytes`, borrowed (pinned host memory in a server) + frame_of: []u32, // per page: its frame or `none` + dirty: []bool, // per page: the frame holds rows the host store lacks + page_of: []u32, // per frame: its page or `none` + gen: []u32, // per frame: changes whenever the frame stops holding the page it held + stamp: []u64, // per frame: the LRU clock at its last use + pinned: []u32, // per frame: calls reading it + free_frames: []u32, + lent_mark: []bool, // per frame: lent to a lease + nfree: usize, + promised: usize = 0, // frames promised, summed over leases + nlent: usize = 0, // frames lent, summed over leases + clock: u64 = 0, + fault: Fault = .none, + + /// In place (the pool's release hook points here): `host.len / page_bytes` logical pages, `frames` frames. + pub fn init(t: *Tier, gpa: Allocator, host: []u8, frames: usize, page_bytes: u64) !void { + const npages: usize = @intCast(host.len / page_bytes); + var pool = try kv.Pool.init(gpa, npages, page_bytes); + errdefer pool.deinit(); + const frame_of = try gpa.alloc(u32, npages); + errdefer gpa.free(frame_of); + const dirty = try gpa.alloc(bool, npages); + errdefer gpa.free(dirty); + const page_of = try gpa.alloc(u32, frames); + errdefer gpa.free(page_of); + const gen = try gpa.alloc(u32, frames); + errdefer gpa.free(gen); + const stamp = try gpa.alloc(u64, frames); + errdefer gpa.free(stamp); + const pinned = try gpa.alloc(u32, frames); + errdefer gpa.free(pinned); + const free_frames = try gpa.alloc(u32, frames); + errdefer gpa.free(free_frames); + const lent_mark = try gpa.alloc(bool, frames); + @memset(frame_of, none); + @memset(dirty, false); + @memset(page_of, none); + @memset(gen, 0); + @memset(stamp, 0); + @memset(pinned, 0); + @memset(lent_mark, false); + for (free_frames, 0..) |*f, i| f.* = @intCast(frames - 1 - i); // frame 0 first + t.* = .{ .gpa = gpa, .pool = pool, .host = host, .frame_of = frame_of, .dirty = dirty, .page_of = page_of, .gen = gen, .stamp = stamp, .pinned = pinned, .free_frames = free_frames, .lent_mark = lent_mark, .nfree = frames }; + t.pool.freed = .{ .ctx = t, .call = freed }; + } + + pub fn deinit(t: *Tier) void { + t.pool.deinit(); + t.gpa.free(t.frame_of); + t.gpa.free(t.dirty); + t.gpa.free(t.page_of); + t.gpa.free(t.gen); + t.gpa.free(t.stamp); + t.gpa.free(t.pinned); + t.gpa.free(t.free_frames); + t.gpa.free(t.lent_mark); + t.* = undefined; + } + + pub fn count(t: *const Tier) usize { + return t.page_of.len; + } + + pub fn shape(t: *const Tier) Shape { + return .{ .host_pages = t.pool.total(), .frames = t.count() }; + } + + /// Promise `pages` pages and `n` frames to `l`, or neither: LaneMemory or FrameMemory, whichever does not fit. + pub fn reserve(t: *Tier, l: *Lease, pages: usize, n: usize) error{ LaneMemory, FrameMemory }!void { + if (t.promised + n > t.count()) return error.FrameMemory; + try t.pool.promise(&l.pages, pages); + t.promised += n; + l.frames += n; + } + + /// Whether `pages` and `n` frames could be promised now (the store's idle pages counted). + pub fn fits(t: *const Tier, pages: usize, n: usize) bool { + return t.promised + n <= t.count() and t.pool.fits(pages); + } + + /// `l` covers `n` pages, as `Pool.cover`. + pub fn cover(t: *Tier, l: *Lease, n: usize, table: ?kv.Table) !void { + return t.pool.cover(&l.pages, n, table); + } + + /// The frame of `id`, if it has one. + pub fn resident(t: *const Tier, id: u32) ?Ticket { + const f = t.frame_of[id]; + return if (f == none) null else .{ .frame = f, .gen = t.gen[f] }; + } + + /// Whether a table entry written from `tk` still names `id`'s rows. + pub fn valid(t: *const Tier, id: u32, tk: Ticket) bool { + return t.page_of[tk.frame] == id and t.gen[tk.frame] == tk.gen; + } + + /// Pin `id` for a call: a frame if it has none (a miss: copy `host_page(id)` in); FrameMemory past the promise. + pub fn pin(t: *Tier, l: *Lease, id: u32) error{ FrameMemory, OutOfMemory }!Fill { + if (t.pool.refs[id] == 0) std.debug.panic("kv tier: page {d} pinned while free", .{id}); + if (l.pins.items.len + l.lent.items.len >= l.frames) return error.FrameMemory; + try l.pins.ensureUnusedCapacity(t.gpa, 1); + var miss = false; + if (t.frame_of[id] == none) { + const f = t.takeFrame() orelse return error.FrameMemory; + t.page_of[f] = id; + t.frame_of[id] = f; + miss = true; + } + const f = t.frame_of[id]; + t.pinned[f] += 1; + t.touch(id); + l.pins.appendAssumeCapacity(id); + return .{ .page = id, .frame = f, .gen = t.gen[f], .miss = miss }; + } + + /// Pin every page of `ids` into `out`, or none of them. + pub fn fill(t: *Tier, l: *Lease, ids: []const u32, out: []Fill) !void { + std.debug.assert(out.len >= ids.len); + var done: usize = 0; + errdefer { + for (ids[0..done]) |id| t.unpin(l, id) catch {}; + for (out[0..done]) |o| t.undo(o); // a miss was never copied in: its frame must not stay mapped + } + for (ids, 0..) |id, i| { + out[i] = try t.pin(l, id); + done += 1; + } + } + + /// The frame a failed batch took for a miss goes back unmapped (generation moved on), unless something pins it. + fn undo(t: *Tier, o: Fill) void { + if (t.fault == .keep_failed_miss or !o.miss or t.frame_of[o.page] != o.frame or t.pinned[o.frame] != 0) return; + t.unmap(o.frame); + t.free_frames[t.nfree] = o.frame; + t.nfree += 1; + } + + /// One pin of `id` fewer. Dirty: the last pin of a page whose rows the host store lacks cannot go (sync it first). + pub fn unpin(t: *Tier, l: *Lease, id: u32) error{ NotPinned, Dirty }!void { + var i = l.pins.items.len; + while (i > 0) : (i -= 1) if (l.pins.items[i - 1] == id) break; + if (i == 0) return error.NotPinned; + const f = t.frame_of[id]; + if (t.pinned[f] == 1 and t.dirty[id] and t.fault != .ignore_dirty) return error.Dirty; + _ = l.pins.orderedRemove(i - 1); + t.pinned[f] -= 1; + } + + /// Lend `n` frames to `l` for its life: mapped to no page, never a victim, counted in its promise like pins. + pub fn lend(t: *Tier, l: *Lease, n: usize) error{ FrameMemory, OutOfMemory }!void { + if (l.pins.items.len + l.lent.items.len + n > l.frames) return error.FrameMemory; + try l.lent.ensureUnusedCapacity(t.gpa, n); + var taken: usize = 0; + errdefer t.giveBackTo(l, l.lent.items.len - taken); + while (taken < n) : (taken += 1) { + const f = t.takeFrame() orelse return error.FrameMemory; + t.gen[f] +%= 1; + t.lent_mark[f] = true; + l.lent.appendAssumeCapacity(f); + t.nlent += 1; + } + } + + /// Lend `l` `n` consecutive free frames (a family's state run) for its life; the first frame, or FrameMemory. + pub fn lendRun(t: *Tier, l: *Lease, n: usize) error{ FrameMemory, OutOfMemory }!u32 { + if (n == 0 or l.pins.items.len + l.lent.items.len + n > l.frames) return error.FrameMemory; + var start: usize = 0; + var run: usize = 0; + for (t.page_of, t.lent_mark, 0..) |p, m, f| { + if (p == none and !m) run += 1 else run = 0; + if (run == n) { + start = f + 1 - n; + break; + } + } else return error.FrameMemory; + try l.lent.ensureUnusedCapacity(t.gpa, n); + var kept: usize = 0; + for (t.free_frames[0..t.nfree]) |f| if (f < start or f >= start + n) { + t.free_frames[kept] = f; + kept += 1; + }; + t.nfree = kept; + for (start..start + n) |f| { + t.gen[f] +%= 1; + t.lent_mark[f] = true; + l.lent.appendAssumeCapacity(@intCast(f)); + } + t.nlent += n; + return @intCast(start); + } + + /// The frames lent to `l` go back to the free frames, their generation moved on. + pub fn giveBack(t: *Tier, l: *Lease) void { + t.giveBackTo(l, 0); + } + + fn giveBackTo(t: *Tier, l: *Lease, keep: usize) void { + while (l.lent.items.len > keep) { + const f = l.lent.pop().?; + t.gen[f] +%= 1; + t.lent_mark[f] = false; + t.free_frames[t.nfree] = f; + t.nfree += 1; + t.nlent -= 1; + } + } + + /// The LRU clock moves on for `id` (a hit the device saw, or a call that read it). + pub fn touch(t: *Tier, id: u32) void { + const f = t.frame_of[id]; + if (f == none) return; + t.clock += 1; + t.stamp[f] = t.clock; + } + + /// Rows were written into `id`'s frame, which `l` pins: the host store lacks them until `sync`. + pub fn markDirty(t: *Tier, l: *const Lease, id: u32) error{NotPinned}!void { + if (t.fault != .unpinned_dirty and std.mem.indexOfScalar(u32, l.pins.items, id) == null) return error.NotPinned; + if (t.frame_of[id] == none) std.debug.panic("kv tier: page {d} written with no frame", .{id}); + t.dirty[id] = true; + } + + /// The family copied `id`'s frame to `host_page(id)`: the frame may be dropped. + pub fn sync(t: *Tier, id: u32) void { + t.dirty[id] = false; + } + + /// Where a page's canonical rows go (a flush writes here). + pub fn host_page(t: *Tier, id: u32) []u8 { + const b: usize = @intCast(t.pool.page_bytes); + return t.host[id * b ..][0..b]; + } + + /// The canonical rows of `id` for a snapshot or a fill; Unsynced while its frame holds rows not flushed yet. + pub fn canonical(t: *const Tier, id: u32) error{Unsynced}![]const u8 { + if (t.dirty[id]) return error.Unsynced; + const b: usize = @intCast(t.pool.page_bytes); + return t.host[id * b ..][0..b]; + } + + /// Drop up to `n` unpinned frames, least recently used first; the count dropped. + pub fn evict(t: *Tier, n: usize) usize { + var done: usize = 0; + while (done < n) : (done += 1) { + const f = t.victim() orelse break; + t.unmap(f); + t.free_frames[t.nfree] = f; + t.nfree += 1; + } + return done; + } + + /// Whether `l` can end: none of its pinned pages is left dirty and unpinned (a page only it holds goes with it). + pub fn canFinish(t: *const Tier, l: *const Lease) bool { + if (t.fault == .ignore_dirty) return true; + for (l.pins.items) |id| { + if (!t.dirty[id]) continue; + const f = t.frame_of[id]; + var mine: usize = 0; // this lease's own pins of the page + for (l.pins.items) |q| mine += @intFromBool(q == id); + if (f != none and t.pinned[f] > mine) continue; // another stream still pins it + const own = std.mem.indexOfScalar(u32, l.pages.ids.items, id) != null; + if (!own or t.pool.refs[id] > 1) return false; + } + for (l.pages.ids.items) |id| if (t.dirty[id] and t.pool.refs[id] > 1) return false; + return true; + } + + /// The stream ended: its pins, frames, promise and pages go back (a page nobody else holds loses its frame). + pub fn finish(t: *Tier, l: *Lease) void { + if (t.fault == .none and !t.canFinish(l)) std.debug.panic("kv tier: a stream ended with unflushed rows pinned or shared", .{}); + for (l.pins.items) |id| { + const f = t.frame_of[id]; + if (f != none) t.pinned[f] -= 1 else if (t.fault == .none) std.debug.panic("kv tier: pinned page {d} lost its frame", .{id}); + } + l.pins.deinit(t.gpa); + t.giveBack(l); + l.lent.deinit(t.gpa); + t.promised -= l.frames; + t.pool.finish(&l.pages); + l.* = .{}; + } + + pub fn census(t: *const Tier) Census { + var c: Census = .{ .frames = t.count(), .free = t.nfree, .resident = 0, .pinned = 0, .dirty = 0, .promised = t.promised, .lent = t.nlent }; + for (t.page_of, t.pinned) |p, n| { + c.resident += @intFromBool(p != none); + c.pinned += @intFromBool(n > 0); + } + for (t.dirty) |d| c.dirty += @intFromBool(d); + return c; + } + + /// Nothing promised, pinned or dirty, and every frame free or holding a page still held (the store's). + pub fn idle(t: *const Tier) bool { + const c = t.census(); + return t.pool.idle() and c.promised == 0 and c.pinned == 0 and c.dirty == 0 and c.lent == 0 and c.free + c.resident == c.frames; + } + + /// The mapping's own consistency; an error names the broken rule. Tests call it after every step. + pub fn audit(t: *const Tier) error{Broken}!void { + var mapped: usize = 0; + for (t.page_of, 0..) |p, f| { + if (p == none) { + if (t.pinned[f] != 0) return error.Broken; // a pin on an empty frame + continue; + } + mapped += 1; + if (t.frame_of[p] != f) return error.Broken; // page and frame disagree + if (t.pool.refs[p] == 0) return error.Broken; // a free page keeps a frame + } + if (mapped + t.nfree + t.nlent != t.count()) return error.Broken; // frames neither free, mapped nor lent, or two + for (t.free_frames[0..t.nfree]) |f| if (t.page_of[f] != none or t.lent_mark[f]) return error.Broken; + var marked: usize = 0; + for (t.lent_mark, t.page_of) |m, p| { + marked += @intFromBool(m); + if (m and p != none) return error.Broken; // a lent frame holds a page + } + if (marked != t.nlent) return error.Broken; + for (t.frame_of, 0..) |f, p| { + if (f != none and t.page_of[f] != p) return error.Broken; + if (t.dirty[p] and f == none) return error.Broken; // unflushed rows with no frame + } + if (t.promised > t.count()) return error.Broken; + } + + /// A hash of what two ranks must hold alike: mapping, generations, LRU order, pins, holders and promises. + pub fn digest(t: *const Tier) u64 { + var h = std.hash.Wyhash.init(0); + h.update(std.mem.sliceAsBytes(t.frame_of)); + h.update(std.mem.sliceAsBytes(t.page_of)); + h.update(std.mem.sliceAsBytes(t.gen)); + h.update(std.mem.sliceAsBytes(t.stamp)); + h.update(std.mem.sliceAsBytes(t.pinned)); + h.update(std.mem.sliceAsBytes(t.free_frames[0..t.nfree])); + h.update(std.mem.sliceAsBytes(t.pool.refs)); + h.update(std.mem.sliceAsBytes(t.pool.free[0..t.pool.nfree])); + const counts = [_]u64{ t.promised, t.pool.promised, t.clock, t.nlent }; + h.update(std.mem.sliceAsBytes(&counts)); + return h.final(); + } + + /// A free frame, or the least recently used unpinned one dropped. + fn takeFrame(t: *Tier) ?u32 { + if (t.nfree > 0) { + t.nfree -= 1; + return t.free_frames[t.nfree]; + } + const f = t.victim() orelse return null; + t.unmap(f); + return f; + } + + /// The mapped frame with the oldest stamp, not pinned and with no unflushed rows (the lowest index among equals). + fn victim(t: *const Tier) ?u32 { + var best: ?u32 = null; + for (t.page_of, 0..) |p, f| { + if (p == none) continue; + if (t.pinned[f] > 0 and t.fault != .ignore_pins) continue; + if (t.dirty[p] and t.fault != .ignore_dirty) continue; + if (best == null or t.stamp[f] < t.stamp[best.?]) best = @intCast(f); + } + return best; + } + + /// The frame stops holding its page: the generation moves on so a table naming it is stale. + fn unmap(t: *Tier, f: u32) void { + const p = t.page_of[f]; + if (t.dirty[p] and t.fault != .ignore_dirty) std.debug.panic("kv tier: frame {d} dropped with page {d} unflushed", .{ f, p }); + t.frame_of[p] = none; + t.dirty[p] = false; + t.page_of[f] = none; + if (t.fault != .keep_generation) t.gen[f] +%= 1; + } + + /// The pool freed `id` (its last holder let go): its frame is free again. + fn freed(ctx: *anyopaque, id: u32) void { + const t: *Tier = @ptrCast(@alignCast(ctx)); + const f = t.frame_of[id]; + if (f == none) return; + if (t.pinned[f] != 0 and t.fault == .none) std.debug.panic("kv tier: page {d} freed while pinned", .{id}); + t.dirty[id] = false; // the page is gone: rows nobody can read need no flush + t.unmap(f); + t.free_frames[t.nfree] = f; + t.nfree += 1; + } +}; + +test { + _ = @import("kv_tier_test.zig"); +} diff --git a/zig/src/core/kv_tier_test.zig b/zig/src/core/kv_tier_test.zig new file mode 100644 index 00000000000..95437b2bea6 --- /dev/null +++ b/zig/src/core/kv_tier_test.zig @@ -0,0 +1,564 @@ +//! The host tier: two currencies, eviction order, pins, generations, canonical rows, lockstep ranks, mutants. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const kt = @import("kv_tier.zig"); +const Tier = kt.Tier; +const Lease = kt.Lease; +const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; +const gpa = std.testing.allocator; + +const page_bytes = 8; + +/// A tier of `pages` logical pages and `frames` frames over a host store and a fake device. +const Rig = struct { + host: []u8, + dev: []u8, + tier: Tier, + + fn open(r: *Rig, pages: usize, frames: usize) !void { + r.host = try gpa.alloc(u8, pages * page_bytes); + errdefer gpa.free(r.host); + @memset(r.host, 0); + r.dev = try gpa.alloc(u8, frames * page_bytes); + errdefer gpa.free(r.dev); + @memset(r.dev, 0); + try r.tier.init(gpa, r.host, frames, page_bytes); + } + + fn close(r: *Rig) void { + r.tier.deinit(); + gpa.free(r.host); + gpa.free(r.dev); + } + + fn frame(r: *Rig, f: u32) []u8 { + return r.dev[f * page_bytes ..][0..page_bytes]; + } + + /// A stream with `pages` pages covered and `frames` frames promised. + fn lease(r: *Rig, pages: usize, frames: usize) !Lease { + return r.leaseLent(pages, frames, 0); + } + + /// A stream that also has `lent` of its frames lent for its life. + fn leaseLent(r: *Rig, pages: usize, frames: usize, lent: usize) !Lease { + var l: Lease = .{}; + errdefer r.tier.finish(&l); + try r.tier.reserve(&l, pages, frames); + try r.tier.cover(&l, pages, null); + try r.tier.lend(&l, lent); + return l; + } + + /// Pin `id`, copying its canonical rows in on a miss. + fn pin(r: *Rig, l: *Lease, id: u32) !kt.Fill { + const f = try r.tier.pin(l, id); + if (f.miss) @memcpy(r.frame(f.frame), r.tier.host_page(id)); + return f; + } + + /// Write `b` into every row byte of the pinned page and flush it to the host store. + fn write(r: *Rig, l: *const Lease, id: u32, b: u8) void { + const tk = r.tier.resident(id).?; + @memset(r.frame(tk.frame), b); + r.tier.markDirty(l, id) catch unreachable; + } + + fn flush(r: *Rig, id: u32) void { + const tk = r.tier.resident(id).?; + @memcpy(r.tier.host_page(id), r.frame(tk.frame)); + r.tier.sync(id); + } +}; + +test "two currencies: a promise that fits one and not the other takes nothing, and finishing returns both" { + var r: Rig = undefined; + try r.open(8, 3); + defer r.close(); + const t = &r.tier; + var a = try r.lease(4, 2); + try std.testing.expectError(error.FrameMemory, t.reserve(&a, 1, 2)); // frames: 2 + 2 > 3 + try expectEqual(@as(usize, 0), a.pages.promised); + try expectEqual(@as(usize, 2), t.promised); + var b: Lease = .{}; + try std.testing.expectError(error.LaneMemory, t.reserve(&b, 5, 1)); // pages: 4 + 5 > 8 + try expectEqual(@as(usize, 2), t.promised); // the frame promise was not kept + try expectEqual(@as(usize, 0), t.pool.promised); + try expect(!t.fits(5, 1) and t.fits(4, 1) and !t.fits(4, 2)); + var c = try r.lease(4, 1); + try expect(!t.fits(1, 0)); // every page is promised or taken + t.finish(&a); + t.finish(&c); + t.finish(&b); + try expect(t.idle()); + try t.audit(); +} + +test "a lease cannot pin more frames than it promised, and a failed batch pins nothing" { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + const t = &r.tier; + var a = try r.lease(4, 2); + var out: [3]kt.Fill = undefined; + const ids = a.pages.ids.items; + try std.testing.expectError(error.FrameMemory, t.fill(&a, ids[0..3], &out)); + try expectEqual(@as(usize, 0), t.census().pinned); + try expectEqual(@as(usize, 0), a.pins.items.len); + try expect(t.resident(ids[0]) == null and t.resident(ids[1]) == null); // the misses of the failed batch were unmapped + try t.fill(&a, ids[0..2], out[0..2]); + try expect(out[0].miss and out[1].miss); + try expectEqual(@as(usize, 2), t.census().pinned); + try std.testing.expectError(error.FrameMemory, t.pin(&a, ids[2])); + t.finish(&a); + try expect(t.idle()); +} + +test "eviction takes the least recently used unpinned frame, and a touch moves a page to the back" { + var r: Rig = undefined; + try r.open(8, 3); + defer r.close(); + const t = &r.tier; + var a = try r.lease(6, 1); + const ids = a.pages.ids.items; + for (ids[0..3]) |id| { // one frame promised: pin, read, unpin, three times over + _ = try r.pin(&a, id); + try t.unpin(&a, id); + } + try expectEqual(@as(usize, 3), t.census().resident); + t.touch(ids[0]); // order now 1, 2, 0 + const f = try r.pin(&a, ids[3]); // evicts page 1 + try expect(f.miss); + try expect(t.resident(ids[1]) == null and t.resident(ids[0]) != null and t.resident(ids[2]) != null); + try t.unpin(&a, ids[3]); + try expectEqual(@as(usize, 1), t.evict(1)); // page 2 is next + try expect(t.resident(ids[2]) == null and t.resident(ids[0]) != null); + try expectEqual(@as(usize, 2), t.evict(5)); // 0 and 3: all that is left + try expectEqual(@as(usize, 3), t.census().free); + try t.audit(); + t.finish(&a); +} + +test "pinned frames are never evicted, and a dirty page stays until its rows reach the host store" { + var r: Rig = undefined; + try r.open(8, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 1); + var b = try r.lease(2, 1); + const pa = a.pages.ids.items[0]; + const pb = b.pages.ids.items; + _ = try r.pin(&a, pa); + r.write(&a, pa, 7); + _ = try r.pin(&b, pb[0]); + try t.unpin(&b, pb[0]); + _ = try r.pin(&b, pb[1]); // the one frame that can go is pb[0]'s + try expect(t.resident(pa) != null and t.resident(pb[0]) == null); + try std.testing.expectError(error.Dirty, t.unpin(&a, pa)); + try expectEqual(@as(usize, 0), t.evict(2)); // pa pinned and dirty, pb[1] pinned + try t.unpin(&b, pb[1]); + try expectEqual(@as(usize, 1), t.evict(2)); // only pb[1] + try expect(t.resident(pa) != null); + try std.testing.expectError(error.Unsynced, t.canonical(pa)); + r.flush(pa); + try t.unpin(&a, pa); + try expectEqual(@as(u8, 7), (try t.canonical(pa))[3]); + try expectEqual(@as(usize, 1), t.evict(2)); + t.finish(&a); + t.finish(&b); + try expect(t.idle()); +} + +/// Whether a table entry written before a frame was dropped and filled again with the same page is taken for current. +fn staleAccepted(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 1); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(2, 1); + defer r.tier.finish(&a); + const p = a.pages.ids.items; + const f0 = try r.pin(&a, p[0]); + const old: kt.Ticket = .{ .frame = f0.frame, .gen = f0.gen }; + try r.tier.unpin(&a, p[0]); + _ = try r.pin(&a, p[1]); // the only frame is recycled + try r.tier.unpin(&a, p[1]); + _ = try r.pin(&a, p[0]); // and returns to the first page: same frame, new contents + try r.tier.unpin(&a, p[0]); + return r.tier.valid(p[0], old); +} + +test "generations: a recycled frame is not read through a table written before" { + try expect(!try staleAccepted(.none)); + try expect(try staleAccepted(.keep_generation)); // mutation: without the generation the stale table passes +} + +/// Whether a frame a call pins survives another stream's miss. +fn pinnedSurvives(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(1, 1); + defer r.tier.finish(&a); + var b = try r.lease(2, 1); + defer r.tier.finish(&b); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); // the oldest stamp, and pinned + _ = try r.pin(&b, b.pages.ids.items[0]); + try r.tier.unpin(&b, b.pages.ids.items[0]); + _ = try r.pin(&b, b.pages.ids.items[1]); + return r.tier.resident(pa) != null; +} + +test "pin rule: the frame a call holds survives a miss; mutation: ignoring pins evicts it" { + try expect(try pinnedSurvives(.none)); + try expect(!try pinnedSurvives(.ignore_pins)); +} + +test "freeing a page (its last holder lets go) frees its frame; a page the store still holds keeps it" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 2); + const p = try gpa.dupe(u32, a.pages.ids.items); // ids outlive the lease + defer gpa.free(p); + _ = try r.pin(&a, p[0]); + r.write(&a, p[0], 5); + r.flush(p[0]); + _ = try r.pin(&a, p[1]); + t.pool.retain(p[0]); // the prompt store keeps the first page + t.finish(&a); + try expect(t.resident(p[0]) != null and t.resident(p[1]) == null); + try expectEqual(@as(usize, 1), t.census().free); + try expectEqual(@as(u8, 5), (try t.canonical(p[0]))[0]); + try t.pool.drop(p[0]); + try expect(t.resident(p[0]) == null and t.idle()); + try t.audit(); +} + +/// A fake serving loop: streams open, pin, write, flush, unpin, finish; every row read equals the page's last write. +const Sim = struct { + r: Rig, + rng: std.Random.DefaultPrng, + slots: [3]?Lease = .{ null, null, null }, + model: [16]u8 = @splat(0), // the byte last written to a page (0: none) + next: u8 = 1, + misses: usize = 0, + reads: usize = 0, + + fn open(s: *Sim, seed: u64, frames: usize) !void { + s.* = .{ .r = undefined, .rng = .init(seed) }; + try s.r.open(16, frames); + } + + fn close(s: *Sim) void { + for (&s.slots) |*l| if (l.*) |*x| s.r.tier.finish(x); + s.r.close(); + } + + fn check(s: *Sim, id: u32, tk: kt.Ticket) !void { + if (s.model[id] == 0) return; + for (s.r.frame(tk.frame)) |x| try expectEqual(s.model[id], x); + s.reads += 1; + } + + fn step(s: *Sim) !void { + const t = &s.r.tier; + const rnd = s.rng.random(); + const op = rnd.uintLessThan(u32, 100); + const k = rnd.uintLessThan(usize, s.slots.len); + const l: *Lease = if (s.slots[k]) |*x| x else { + if (op < 60) s.slots[k] = s.r.leaseLent(4, 3, 1) catch null; + return; + }; + const ids = l.pages.ids.items; + const id = ids[rnd.uintLessThan(usize, ids.len)]; + switch (op) { + 0...34 => { + const f = s.r.pin(l, id) catch |e| { + if (e == error.FrameMemory and l.pins.items.len + l.lent.items.len >= l.frames) return; + return e; + }; + s.misses += @intFromBool(f.miss); + try s.check(id, .{ .frame = f.frame, .gen = f.gen }); + }, + 35...59 => if (l.pins.items.len > 0) { + const p = l.pins.items[rnd.uintLessThan(usize, l.pins.items.len)]; + s.model[p] = s.next; + s.next = if (s.next == 255) 1 else s.next + 1; + s.r.write(l, p, s.model[p]); + }, + 60...79 => if (l.pins.items.len > 0) { + const p = l.pins.items[rnd.uintLessThan(usize, l.pins.items.len)]; + if (t.dirty[p]) s.r.flush(p); + try t.unpin(l, p); + }, + 80...89 => _ = t.evict(1), + else => { + for (l.pins.items) |p| if (t.dirty[p]) s.r.flush(p); + for (ids) |p| s.model[p] = 0; + t.finish(l); + s.slots[k] = null; + }, + } + try t.audit(); + for (t.page_of, 0..) |p, f| if (p != kt.none and !t.dirty[p]) try s.check(p, .{ .frame = @intCast(f), .gen = t.gen[f] }); + } +}; + +test "a random serving loop with fewer frames than pages: the audit holds, every read equals the last write, and it ends idle" { + inline for (.{ 1, 2, 3 }) |seed| { + var s: Sim = undefined; + try s.open(seed, 6); + defer s.close(); + for (0..4000) |_| try s.step(); + try expect(s.misses > 100 and s.reads > 500); + for (&s.slots) |*l| if (l.*) |*x| { + for (x.pins.items) |p| if (s.r.tier.dirty[p]) s.r.flush(p); + s.r.tier.finish(x); + l.* = null; + }; + _ = s.r.tier.evict(100); + try expect(s.r.tier.idle()); + } +} + +test "two ranks in lockstep: the same openings and pins give the same frames, generations and order, step after step" { + var a: Sim = undefined; + var b: Sim = undefined; + try a.open(9, 6); + defer a.close(); + try b.open(9, 6); + defer b.close(); + for (0..3000) |_| { + try a.step(); + try b.step(); + try expectEqual(a.r.tier.digest(), b.r.tier.digest()); + } +} + +test "two ranks: a step only one rank takes is caught by the digest at once" { + var a: Sim = undefined; + var b: Sim = undefined; + try a.open(9, 6); + defer a.close(); + try b.open(9, 6); + defer b.close(); + var caught: ?usize = null; + for (0..3000) |i| { + try a.step(); + if (i == 1500) _ = b.r.tier.evict(1) else try b.step(); // rank 1 evicts instead of the step rank 0 took + if (a.r.tier.digest() != b.r.tier.digest()) { + caught = i; + break; + } + } + try expect(caught != null); +} + +test "ranks agree on the smaller shape before they open" { + const a: kt.Shape = .{ .host_pages = 100, .frames = 40 }; + const b: kt.Shape = .{ .host_pages = 90, .frames = 48 }; + try expectEqual(kt.Shape{ .host_pages = 90, .frames = 40 }, a.agree(b)); + try expectEqual(a.agree(b), b.agree(a)); +} + +test "lent frames: counted in the frame promise, never victims or mapped, back at finish with a new generation" { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + const t = &r.tier; + var a = try r.leaseLent(4, 3, 2); // two lent, one left to pin + try expectEqual(@as(usize, 2), t.census().lent); + try expectEqual(@as(usize, 2), a.lent.items.len); + try std.testing.expectError(error.FrameMemory, t.lend(&a, 2)); + const gen0 = t.gen[a.lent.items[0]]; + var b = try r.lease(4, 1); + const ids = a.pages.ids.items; + _ = try r.pin(&a, ids[0]); + try std.testing.expectError(error.FrameMemory, t.pin(&a, ids[1])); // the lent frames used the promise + try t.unpin(&a, ids[0]); + for (b.pages.ids.items) |id| { // misses cycle through the two frames left; the lent ones are never taken + _ = try r.pin(&b, id); + try t.unpin(&b, id); + _ = try r.pin(&a, ids[1]); + try t.unpin(&a, ids[1]); + for (a.lent.items) |f| try expect(t.page_of[f] == kt.none); + } + try expect(t.evict(10) <= 2); // only the mapped frames can go, the lent ones are not among them + try t.audit(); + const lent0 = a.lent.items[0]; + t.finish(&a); + try expect(t.gen[lent0] != gen0); + try expectEqual(@as(usize, 0), t.census().lent); + t.finish(&b); + try expect(t.idle()); + try t.audit(); +} + +test "ranks lending a different count are told apart by the digest" { + var a: Rig = undefined; + var b: Rig = undefined; + try a.open(8, 4); + defer a.close(); + try b.open(8, 4); + defer b.close(); + var la = try a.leaseLent(4, 3, 2); + defer a.tier.finish(&la); + var lb = try b.leaseLent(4, 3, 2); + defer b.tier.finish(&lb); + try expectEqual(a.tier.digest(), b.tier.digest()); + try b.tier.lend(&lb, 0); + var lc = try b.leaseLent(0, 1, 1); + defer b.tier.finish(&lc); + try expect(a.tier.digest() != b.tier.digest()); +} + +test "a lent run is consecutive frames, leaves the free frames, and comes back at finish" { + var r: Rig = undefined; + try r.open(8, 6); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 4); + _ = try r.pin(&a, a.pages.ids.items[0]); // a mapped frame in the way + const first = try t.lendRun(&a, 3); + try expectEqual(@as(usize, 3), t.census().lent); + for (a.lent.items, 0..) |f, i| try expectEqual(first + i, f); + try t.audit(); + var b = try r.lease(2, 2); + try std.testing.expectError(error.FrameMemory, t.lendRun(&b, 3)); // past b's promise + _ = try r.pin(&b, b.pages.ids.items[0]); + _ = try r.pin(&b, b.pages.ids.items[1]); + try std.testing.expectEqual(@as(usize, 0), t.nfree); // 1 mapped (a) + 3 lent + 2 mapped (b) + t.finish(&a); + t.finish(&b); + try expect(t.idle()); + try t.audit(); + var c = try r.lease(1, 6); + defer t.finish(&c); + try expectEqual(@as(u32, 0), try t.lendRun(&c, 6)); +} + +/// A failed batch, then the same pages pinned again through the rig: the frames must equal the host pages. +fn failedFillReads(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(8, 4); + defer r.close(); + r.tier.fault = fault; + for (r.host, 0..) |*b, i| b.* = @intCast(1 + i / page_bytes); // page k holds k + 1 + @memset(r.dev, 0xee); // the frames hold something else + var a = try r.lease(4, 2); + defer r.tier.finish(&a); + const ids = a.pages.ids.items; + var out: [3]kt.Fill = undefined; + try std.testing.expectError(error.FrameMemory, r.tier.fill(&a, ids[0..3], &out)); + try r.tier.audit(); + for (ids[0..2]) |id| { + const f = try r.pin(&a, id); + if (!std.mem.eql(u8, r.frame(f.frame), r.tier.host_page(id))) return false; + } + return true; +} + +test "a failed batch leaves no miss mapped: the pages pinned again read the host rows; mutation: keeping the mapping reads stale frames" { + try expect(try failedFillReads(.none)); + try expect(!try failedFillReads(.keep_failed_miss)); +} + +test "a failed batch moves the generation of the frames it unmapped" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + var a = try r.lease(3, 2); + defer r.tier.finish(&a); + const ids = a.pages.ids.items; + var out: [3]kt.Fill = undefined; + const before = [2]u32{ r.tier.gen[0], r.tier.gen[1] }; + try std.testing.expectError(error.FrameMemory, r.tier.fill(&a, ids[0..3], &out)); + try expect(r.tier.gen[0] != before[0] and r.tier.gen[1] != before[1]); + try expectEqual(@as(usize, 2), r.tier.census().free); +} + +test "dirty needs a pin by the lease: an unpinned frame cannot be marked; mutation: a dirty frame nobody pins starves a lease inside its promise" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + var a = try r.lease(1, 1); + defer r.tier.finish(&a); + var b = try r.lease(1, 1); + defer r.tier.finish(&b); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); + try r.tier.unpin(&a, pa); + try std.testing.expectError(error.NotPinned, r.tier.markDirty(&a, pa)); + try std.testing.expectError(error.NotPinned, r.tier.markDirty(&b, pa)); // pinned by nobody of b + try r.tier.audit(); + // the mutant lets the mark through on a frame no lease pins, and the only frame is then stuck + var m: Rig = undefined; + try m.open(4, 2); + defer m.close(); + m.tier.fault = .unpinned_dirty; + var c = try m.lease(2, 1); + defer m.tier.finish(&c); + var d = try m.lease(1, 1); + defer m.tier.finish(&d); + for (c.pages.ids.items) |pc| { // both frames hold c's pages, unpinned + _ = try m.pin(&c, pc); + try m.tier.unpin(&c, pc); + } + for (c.pages.ids.items) |pc| try m.tier.markDirty(&c, pc); + try std.testing.expectError(error.FrameMemory, m.pin(&d, d.pages.ids.items[0])); +} + +/// A lease that pins a dirty page it does not own, after the owner let go of its pin: whether it may end. +fn endsWithForeignDirty(fault: kt.Fault) !bool { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + r.tier.fault = fault; + var a = try r.lease(1, 1); + var b = try r.lease(1, 1); + const pa = a.pages.ids.items[0]; + _ = try r.pin(&a, pa); + _ = try r.pin(&b, pa); + r.write(&a, pa, 9); + try r.tier.unpin(&a, pa); // b still pins it + const ok = r.tier.canFinish(&b); + if (ok) { + r.tier.finish(&b); + r.flush(pa); // too late for a real stream; the test only wants the tier consistent to close + } else { + r.flush(pa); + r.tier.finish(&b); + } + r.tier.finish(&a); + return ok; +} + +test "a stream cannot end while it holds the last pin of a dirty page, its own table or not; mutation: ignoring dirty lets it" { + try expect(!try endsWithForeignDirty(.none)); + try expect(try endsWithForeignDirty(.ignore_dirty)); +} + +test "a stream ends cleanly once the dirty pages it pins are flushed, and one that shares a dirty page of its own cannot" { + var r: Rig = undefined; + try r.open(4, 2); + defer r.close(); + const t = &r.tier; + var a = try r.lease(2, 2); + const p = a.pages.ids.items; + _ = try r.pin(&a, p[0]); + r.write(&a, p[0], 3); + try expect(t.canFinish(&a)); // its own page and its only holder: the page goes with it + t.pool.retain(p[0]); + try expect(!t.canFinish(&a)); // now another holder would read rows the host lacks + r.flush(p[0]); + try expect(t.canFinish(&a)); + const keep = p[0]; + t.finish(&a); + try t.pool.drop(keep); + try expect(t.idle()); +} From ef714116fd69f34a8e622bad600213a0464935a6 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:00:07 +0100 Subject: [PATCH 108/361] Validate host KV tier geometry before allocation --- zig/src/core/kv_tier.zig | 2 ++ zig/src/core/kv_tier_test.zig | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig index 3d40f1d98ca..fbd0ce23e33 100644 --- a/zig/src/core/kv_tier.zig +++ b/zig/src/core/kv_tier.zig @@ -55,6 +55,8 @@ pub const Tier = struct { /// In place (the pool's release hook points here): `host.len / page_bytes` logical pages, `frames` frames. pub fn init(t: *Tier, gpa: Allocator, host: []u8, frames: usize, page_bytes: u64) !void { + if (page_bytes == 0 or host.len % page_bytes != 0 or frames == 0 or host.len == 0) + return error.BadTierGeometry; const npages: usize = @intCast(host.len / page_bytes); var pool = try kv.Pool.init(gpa, npages, page_bytes); errdefer pool.deinit(); diff --git a/zig/src/core/kv_tier_test.zig b/zig/src/core/kv_tier_test.zig index 95437b2bea6..760c7d3d189 100644 --- a/zig/src/core/kv_tier_test.zig +++ b/zig/src/core/kv_tier_test.zig @@ -10,6 +10,33 @@ const gpa = std.testing.allocator; const page_bytes = 8; +test "tier geometry: zero page bytes, partial host pages, zero frames and zero pages refuse before allocation" { + var host: [9]u8 = undefined; + const Case = struct { bytes: usize, frames: usize = 1, page: u64 = page_bytes }; + for ([_]Case{ + .{ .bytes = 8, .page = 0 }, + .{ .bytes = 7 }, + .{ .bytes = 9 }, + .{ .bytes = 8, .frames = 0 }, + .{ .bytes = 0 }, + }) |c| { + var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); + var tier: Tier = undefined; + try std.testing.expectError(error.BadTierGeometry, tier.init(failing.allocator(), host[0..c.bytes], c.frames, c.page)); + try expect(!failing.has_induced_failure); + } +} + +test "tier geometry: one byte, one page and one frame is the smallest valid tier" { + var host = [_]u8{7}; + var tier: Tier = undefined; + try tier.init(gpa, &host, 1, 1); + defer tier.deinit(); + try expectEqual(@as(usize, 1), tier.pool.total()); + try expectEqual(@as(usize, 1), tier.count()); + try std.testing.expectEqualSlices(u8, &host, tier.host_page(0)); +} + /// A tier of `pages` logical pages and `frames` frames over a host store and a fake device. const Rig = struct { host: []u8, From 43a828305e0af2bd8120d0acc0c594776d53e413 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:57:44 -0800 Subject: [PATCH 109/361] KV pool: notify the host tier when retired pages become reusable --- zig/src/core/kv_pool.zig | 3 +- zig/src/core/kv_pool_freed_test.zig | 64 +++++++++++++++++++++++++++++ zig/src/core/kv_pool_retire.zig | 2 + 3 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 zig/src/core/kv_pool_freed_test.zig diff --git a/zig/src/core/kv_pool.zig b/zig/src/core/kv_pool.zig index 8b9f28a4f74..298c5da1461 100644 --- a/zig/src/core/kv_pool.zig +++ b/zig/src/core/kv_pool.zig @@ -217,7 +217,7 @@ pub const Notify = struct { /// A family's pool as the load ledger reads it: tokens a page, and the contiguous run it needs (0: none). pub const Source = struct { pool: *Pool, page_tokens: u32, run_pages: u32 = 0 }; -/// A tier's notice that a page lost its last holder (its frame, if any, is free again). +/// A tier's notice that a page has no holders or readers and its frame, if any, is free again. pub const Freed = struct { ctx: *anyopaque, call: *const fn (ctx: *anyopaque, id: u32) void, @@ -572,6 +572,7 @@ pub const Tier = tier.Tier; test { _ = @import("kv_pool_test.zig"); _ = @import("kv_tier.zig"); + _ = @import("kv_pool_freed_test.zig"); _ = @import("kv_pool_counts_test.zig"); _ = @import("kv_pool_walk_test.zig"); _ = @import("kv_pool_notify_test.zig"); diff --git a/zig/src/core/kv_pool_freed_test.zig b/zig/src/core/kv_pool_freed_test.zig new file mode 100644 index 00000000000..80ba1438a2d --- /dev/null +++ b/zig/src/core/kv_pool_freed_test.zig @@ -0,0 +1,64 @@ +//! A tier frees frames only when the pool makes their pages reusable, including after delayed readers finish. +const std = @import("std"); +const kv = @import("kv_pool.zig"); +const t = std.testing; + +const Seen = struct { + calls: usize = 0, + fn call(ctx: *anyopaque, id: u32) void { + const s: *Seen = @ptrCast(@alignCast(ctx)); + std.debug.assert(id == 0); + s.calls += 1; + } +}; + +test "pool freed hook: lease, store and run release notify once after the last holder" { + for (0..3) |mode| { + var p = try kv.Pool.init(t.allocator, 1, 64); + defer p.deinit(); + var seen: Seen = .{}; + p.freed = .{ .ctx = &seen, .call = Seen.call }; + var l: kv.Lease = .{}; + try p.promise(&l, 1); + if (mode == 2) { + const id = p.claimRun(&l, 1).?; + p.releaseRun(id, 1); + p.finish(&l); + } else { + const id = try p.take(&l); + if (mode == 1) p.retain(id); + p.finish(&l); + if (mode == 1) { + try t.expectEqual(@as(usize, 0), seen.calls); + p.release(id); + } + } + try t.expectEqual(@as(usize, 1), seen.calls); + try t.expect(p.idle()); + } +} + +test "pool freed hook: a retired pinned frame survives until its reader settles" { + var host: [64]u8 = @splat(0); + var tier: kv.Tier = undefined; + try tier.init(t.allocator, &host, 1, 64); + defer tier.deinit(); + var l: kv.tier.Lease = .{}; + defer tier.finish(&l); + try tier.reserve(&l, 1, 1); + try tier.cover(&l, 1, null); + const id = l.pages.ids.items[0]; + const fill = try tier.pin(&l, id); + const ticket: kv.tier.Ticket = .{ .frame = fill.frame, .gen = fill.gen }; + try kv.retirement.retire(&tier.pool, &l.pages, 0, 7); + try t.expect(tier.valid(id, ticket)); + try t.expectEqual(@as(usize, 0), tier.nfree); + try kv.retirement.settle(&tier.pool, 6); + try t.expect(tier.valid(id, ticket)); + try tier.unpin(&l, id); + try kv.retirement.settle(&tier.pool, 7); + try t.expect(!tier.valid(id, ticket)); + try t.expectEqual(@as(usize, 1), tier.nfree); + try kv.retirement.settle(&tier.pool, 7); + try t.expectEqual(@as(usize, 1), tier.nfree); +} diff --git a/zig/src/core/kv_pool_retire.zig b/zig/src/core/kv_pool_retire.zig index ea592e6de16..6fdf1290619 100644 --- a/zig/src/core/kv_pool_retire.zig +++ b/zig/src/core/kv_pool_retire.zig @@ -83,6 +83,7 @@ pub fn freeOrPend(p: *Pool, id: u32) void { const r = &p.retired; if (r.token(id) > r.settled) return r.pending.appendAssumeCapacity(id); // reserved before its mark clear(p, id); + if (p.freed) |f| f.call(f.ctx, id); p.free[p.nfree] = id; p.nfree += 1; } @@ -100,6 +101,7 @@ pub fn settle(p: *Pool, token: u64) error{LaneMemory}!void { keep += 1; } else { clear(p, id); + if (p.freed) |f| f.call(f.ctx, id); p.free[p.nfree] = id; p.nfree += 1; } From 23d6181b4a1731564d27d8dd3834f3b94c0f786e Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:39:02 +0100 Subject: [PATCH 110/361] kv tier: skip retired page sentinels when finishing Avoid indexing tier state with the pool sentinel left by a retired page. --- zig/src/core/kv_tier.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig index fbd0ce23e33..c3296fa2e82 100644 --- a/zig/src/core/kv_tier.zig +++ b/zig/src/core/kv_tier.zig @@ -305,7 +305,7 @@ pub const Tier = struct { const own = std.mem.indexOfScalar(u32, l.pages.ids.items, id) != null; if (!own or t.pool.refs[id] > 1) return false; } - for (l.pages.ids.items) |id| if (t.dirty[id] and t.pool.refs[id] > 1) return false; + for (l.pages.ids.items) |id| if (id != none and t.dirty[id] and t.pool.refs[id] > 1) return false; return true; } From 6e37f2a5ba537e840715c2d946032ab4cbf46474 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:45:48 +0100 Subject: [PATCH 111/361] core: allocate the read-ahead spans exactly once ArrayList.toOwnedSlice remaps in place when it can, so the pack reader's allocation count varied with allocator state and checkAllAllocationFailures reported NondeterministicMemoryUsage. Duplicate the slice so the count is fixed. --- zig/src/core/checkpoint_read_ahead.zig | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/zig/src/core/checkpoint_read_ahead.zig b/zig/src/core/checkpoint_read_ahead.zig index 13e212e345f..219fbd841db 100644 --- a/zig/src/core/checkpoint_read_ahead.zig +++ b/zig/src/core/checkpoint_read_ahead.zig @@ -192,7 +192,9 @@ fn packInner(gpa: std.mem.Allocator, io: std.Io, p: anytype, prefix: []const u8, } } } - const owned = try spans.toOwnedSlice(gpa); + // an exact copy, so the slice's allocation never depends on an in-place remap + const owned = try gpa.dupe(Span, spans.items); + spans.clearAndFree(gpa); const reader = try start(gpa, io, owned, count); return .{ .reader = reader, .arena = arena }; } From 28eee7b2897274c5c18886756ace9e36b4e87663 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:14:55 +0100 Subject: [PATCH 112/361] kv tier: the lockstep digest covers which pages are dirty - a rank holding an unflushed page it cannot evict no longer matches one that flushed, so the open check sees it --- zig/src/core/kv_tier.zig | 6 +++-- zig/src/core/kv_tier_digest_test.zig | 37 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 zig/src/core/kv_tier_digest_test.zig diff --git a/zig/src/core/kv_tier.zig b/zig/src/core/kv_tier.zig index c3296fa2e82..55cb54413e8 100644 --- a/zig/src/core/kv_tier.zig +++ b/zig/src/core/kv_tier.zig @@ -137,7 +137,7 @@ pub const Tier = struct { return t.page_of[tk.frame] == id and t.gen[tk.frame] == tk.gen; } - /// Pin `id` for a call: a frame if it has none (a miss: copy `host_page(id)` in); FrameMemory past the promise. + /// Pin `id` in the lease's `frames` until its device work ends: a frame, or a miss to copy `host_page(id)` in. pub fn pin(t: *Tier, l: *Lease, id: u32) error{ FrameMemory, OutOfMemory }!Fill { if (t.pool.refs[id] == 0) std.debug.panic("kv tier: page {d} pinned while free", .{id}); if (l.pins.items.len + l.lent.items.len >= l.frames) return error.FrameMemory; @@ -367,7 +367,7 @@ pub const Tier = struct { if (t.promised > t.count()) return error.Broken; } - /// A hash of what two ranks must hold alike: mapping, generations, LRU order, pins, holders and promises. + /// A hash of what two ranks must hold alike: mapping, generations, LRU order, pins, holders, promises, dirty pages. pub fn digest(t: *const Tier) u64 { var h = std.hash.Wyhash.init(0); h.update(std.mem.sliceAsBytes(t.frame_of)); @@ -375,6 +375,7 @@ pub const Tier = struct { h.update(std.mem.sliceAsBytes(t.gen)); h.update(std.mem.sliceAsBytes(t.stamp)); h.update(std.mem.sliceAsBytes(t.pinned)); + h.update(std.mem.sliceAsBytes(t.dirty)); h.update(std.mem.sliceAsBytes(t.free_frames[0..t.nfree])); h.update(std.mem.sliceAsBytes(t.pool.refs)); h.update(std.mem.sliceAsBytes(t.pool.free[0..t.pool.nfree])); @@ -431,4 +432,5 @@ pub const Tier = struct { test { _ = @import("kv_tier_test.zig"); + _ = @import("kv_tier_digest_test.zig"); } diff --git a/zig/src/core/kv_tier_digest_test.zig b/zig/src/core/kv_tier_digest_test.zig new file mode 100644 index 00000000000..6754c39cba0 --- /dev/null +++ b/zig/src/core/kv_tier_digest_test.zig @@ -0,0 +1,37 @@ +//! The lockstep digest: two ranks holding different unflushed pages can serve different rows, so they must differ. +const std = @import("std"); +const kt = @import("kv_tier.zig"); +const gpa = std.testing.allocator; + +test "ranks holding different dirty pages are told apart by the digest" { + var host_a: [32]u8 = @splat(0); + var host_b: [32]u8 = @splat(0); + var a: kt.Tier = undefined; + try a.init(gpa, &host_a, 4, 8); + defer a.deinit(); + var b: kt.Tier = undefined; + try b.init(gpa, &host_b, 4, 8); + defer b.deinit(); + var la: kt.Lease = .{}; + defer a.finish(&la); + var lb: kt.Lease = .{}; + defer b.finish(&lb); + try a.reserve(&la, 4, 2); + try a.cover(&la, 4, null); + try b.reserve(&lb, 4, 2); + try b.cover(&lb, 4, null); + const ids = la.pages.ids.items; + try std.testing.expectEqualSlices(u32, ids, lb.pages.ids.items); + for ([_]u32{ 1, 2 }) |i| { + _ = try a.pin(&la, ids[i]); + _ = try b.pin(&lb, ids[i]); + } + try std.testing.expectEqual(a.digest(), b.digest()); + a.markDirty(&la, ids[1]) catch unreachable; // a's rows are not in its store; b's still are + try std.testing.expect(a.digest() != b.digest()); + b.markDirty(&lb, ids[2]) catch unreachable; // both hold one unflushed page, a different one + try std.testing.expect(a.digest() != b.digest()); + b.sync(ids[2]); + a.sync(ids[1]); + try std.testing.expectEqual(a.digest(), b.digest()); +} From c9181f9741169c6c3a893f096a3fa6d8fcb8ae49 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:15:46 +0100 Subject: [PATCH 113/361] changelog: the host KV tier's page, pin and digest behaviour under Unreleased --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ca401858df..06100abe6fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -223,6 +223,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.5/3.8 on CUDA: `TF_Q35_DFLASH_ABSORB_BATCH=1` (opt-in) absorbs a DFlash2 round's streams in one pass, reading the drafter's weights once a round; about 1-2% faster at 4 streams on GB10, tokens unchanged. +- KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking, and the ranks' lockstep open check hashes dirty pages, so two ranks that cannot evict the same page refuse to open together (#1501). ## 1.3.4 From bd181ecba2a5d557be488176d84cbee5ea4c1903 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:46 +0000 Subject: [PATCH 114/361] changelog: #1501's line from lines/1501.txt in place of its own --- CHANGELOG.md | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06100abe6fe..d3859f9fc19 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 +- Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. + - `tensorfold start` selects a fitting catalog model, downloads it with consent, starts a local server and checks its reply; startup, chat, pull and the managed server's log keep API keys out of output (#4852). - 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). @@ -22,52 +24,36 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - TP: the 4-rank RoCE ring relay forwards each half as soon as it arrives, lowering gather latency with the opt-in relay; bytes are unchanged (#4798). Thanks @GrgaPalcic. - - - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_GRAPH_PARITY=1` keys the verify-window CUDA graph on which of the two swapped state buffers a round uses, so full-accept rounds replay a resident graph instead of refreshing it; a counter reports graph updates and replays; off by default (#4492). - Qwen3.5 on CUDA: shared prefixes are saved at page boundaries, and `TF_QWEN_KV_SNAPSHOT_GPU=1` keeps prefix snapshots on the device instead of pinned host memory, falling back to host snapshots when device memory is short (#4473). - - - Kernel contract: MiniMax-H3-Image's 19 Metal kernels register with the contract, in 31 registrations with 34 planted controls, instead of being gated only by each tool's own self-test (#2808). - MiniMax-H3-Image on Metal: `tf-h3-image-prompt` writes a whole text-to-image case from a size and a seed (the canvas, the size and the seed's starting rows), so text to image runs end to end with TensorFold's own tools, and `tf-h3-image ... free` exits 0 when there is no reference to gate against (#2781). - - - Flash Next on Metal: `TF_FN_GX_SHARED=1` (opt-in) routes eligible shared rounds through the existing bit-preserving grouped expert kernels; off keeps per-pair launches (#4834). - Metal: the two pairs of u32 copy kernels build from one source, with the kernels unchanged (#4740). Thanks @jschmied. - - - CUDA and HIP: one core gate decides `--vision` at startup: `--vision` on a checkpoint without a vision tower is refused as "--vision given but this checkpoint has no vision tower", on Qwen3.5 on HIP (which served text) and Flash Next on CUDA too; LFM2 on CUDA loads its tower only with `--vision`; a cluster model's `"vision"` that is not true or false is refused, and the System One picture refusal now says to start with `--vision` (#3456). Thanks to @jschmied. - Qwen 3.5 diagnostics: large output files are written in chunks of at most 256 MiB, with the same bytes in the same order (#4296). - - - Lanes: window-cost tables are measured in interleaved sweeps and saved tables are repaired at startup inside a fixed time budget; a table with no valid timing is refused. Tokens unchanged (#4755). - Drama 3 on CUDA: semantic guidance (`--cfg-gamma` and the other guidance flags) now works, as it does on Metal (#4153). Thanks @plotarmordev. - - - Server: `TENSORFOLD_PRIORITY_AGE_MS` (default 0, unchanged order) lets a background request that has waited that long start before foreground work, without letting any request wait forever (#4833) - MiniMax-M3 on Metal: shared decode rounds of 12 to 32 rows are timed at load instead of priced at 2x and 4x the 8-row window, so window choice uses measured costs; tokens are unchanged, and a `--context` under 256 tokens leaves those rounds untimed instead of failing to open the model (#3120). - - - Tools: `tools/exact_restarts.py` checks the exact path end to end, comparing token ids across fresh restarts, `--parallel` levels, busy versus alone requests, and drafting on versus off (#4574). - Gemma 4 on CUDA (assistant and DFlash drafters) and one more MoE family's CUDA loader: loading now refuses a checkpoint with tensors the engine never binds, each scoped to its own directory or prefix (#4566). - Flash Next on CUDA: `TF_FLASHNEXT_GDN_CHAIN_TPR=1` runs short verify windows (under 64 rows) on the existing two-threads-a-row GDN chain kernel, which keeps the same bits with one shuffle level instead of five; off by default until the GB10 measurements (#4484). - - - CUDA qmmf: `TF_QMMF_HALF_BN=1` uses half-column (32-wide) tiles for FP4, FP8 and FP8-group GEMVs on GPUs with many SMs, splitting only along output columns so each output keeps its accumulation; GB10 behaviour is unchanged when off (#4533). - Inkling 2 Mini: native serving on CUDA (one rank, NVFP4 and MXFP8 experts) and Metal, with kernel contracts on both (#4387). @@ -223,7 +209,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.5/3.8 on CUDA: `TF_Q35_DFLASH_ABSORB_BATCH=1` (opt-in) absorbs a DFlash2 round's streams in one pass, reading the drafter's weights once a round; about 1-2% faster at 4 streams on GB10, tokens unchanged. -- KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking, and the ranks' lockstep open check hashes dirty pages, so two ranks that cannot evict the same page refuse to open together (#1501). ## 1.3.4 From 1359325ec9fd064a459e5a6d3ebc3f41d3e07174 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:46 +0000 Subject: [PATCH 115/361] changelog: #1501's line from lines/1501.txt in place of its own --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3859f9fc19..060c8aadfaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. + + - `tensorfold start` selects a fitting catalog model, downloads it with consent, starts a local server and checks its reply; startup, chat, pull and the managed server's log keep API keys out of output (#4852). - 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). From 1dfcfc6df81ed8bc22cfa53b7662cb74826e41f1 Mon Sep 17 00:00:00 2001 From: BadAd84 Date: Sat, 21 Nov 2026 13:03:32 +0000 Subject: [PATCH 116/361] Flash Next on CUDA: part holds the MTP head's fc_h lane partRows sized the pass scratch's part for two consumers: an out projection's slice plus the zero slice at cap rows, and a legacy lane tile's out_sk slices below 64 rows. The MTP head's fc_h lane is a third one. It runs over streams * rows rows (four streams by a pass's rows), and the lane writes one fp32 slice of them and zeroes a second, so it needs 2 * streams * rows rows of part. cuda_tiles.matmul zeroes at part + m rows and cuda_batch_ops.sumSlices then reads that slice back, so a head pass over more than cap / 4 rows leaves part: at four streams and a 256-row piece the lane needs 2,048 rows, against 2 * cap below a 1,024-row scratch, and 4 * cap while the piece is half the scratch. A head pass takes at most piece_rows rows (cuda_mtp_ops.zig's forwardHead and headGroup), so any pass over 63 rows can ask for more than part below a 1,024-row scratch. The single-stream path, whose piece is half the scratch, first overruns at 128 rows, a prompt chunk of about 128 tokens, and runs short to 1,023. partRows now takes the maximum over every consumer, the head's term being 2 * streams * min(cap, piece_rows). The term changes nothing from a 1,024-row scratch up, where the out projection's two cap-stride slices already dominate, so a long cache's part keeps its 671,088,640 bytes at 32,768 rows. Below that it costs at most 15,728,640 bytes, at 256 rows. The host test sweeps every cap against each consumer's write range, with the head's lane under both a reachable pass and the widest pass the lane admits. --- .../families/flashnext/cuda_scratch_sizes.zig | 15 ++- .../flashnext/cuda_scratch_sizes_test.zig | 120 ++++++++++++++++++ 2 files changed, 133 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/flashnext/cuda_scratch_sizes_test.zig diff --git a/zig/src/families/flashnext/cuda_scratch_sizes.zig b/zig/src/families/flashnext/cuda_scratch_sizes.zig index 315655b7a56..65435565220 100644 --- a/zig/src/families/flashnext/cuda_scratch_sizes.zig +++ b/zig/src/families/flashnext/cuda_scratch_sizes.zig @@ -1,8 +1,10 @@ //! The prompt scratch's buffers sized by use (Scratch.bytes / alloc): head_local, native_part, hc_part and part. const wt = @import("cuda_prompt_wt.zig"); +const mtp = @import("cuda_mtp.zig"); const hc_sk = wt.hc_sk; const out_sk = wt.out_sk; +const streams = wt.streams; const att_rows = @import("cuda_batch_state.zig").att_rows; /// head_local's rows on one GPU: the draft head's lanes (<= 16) times its ids; a split head needs a pass's rows. @@ -16,9 +18,14 @@ pub fn hcPartRows(cap: usize) usize { return @max(cap, @max(hc_sk * @min(cap, 63), @as(usize, 8) * @min(cap, 255))); } -/// part's rows of dims: an out projection's slice plus the zero slice, or a legacy lane tile's out_sk below 64 rows. +/// part's rows of dims: an out projection's two cap-stride slices or a legacy lane tile's out_sk, or the head's lane. pub fn partRows(cap: usize) usize { - return @max(2 * cap, out_sk * @min(cap, 63)); + return @max(@max(2 * cap, out_sk * @min(cap, 63)), headRows(cap)); +} + +/// The head's fc_h lane: streams * rows fp32 plus the zero slice after it, for a pass of at most piece_rows rows. +fn headRows(cap: usize) usize { + return 2 * streams * @min(cap, mtp.piece_rows); } /// The block scores' row stride for a cache of `cap` tokens: its blocks rounded up to 16 (the captured _scores'). @@ -30,3 +37,7 @@ pub fn scoreStride(cap: usize) usize { pub fn scoreBytes(cap: usize, rows: usize) usize { return @min(rows, att_rows) * scoreStride(cap) * 4; } + +test { + _ = @import("cuda_scratch_sizes_test.zig"); +} diff --git a/zig/src/families/flashnext/cuda_scratch_sizes_test.zig b/zig/src/families/flashnext/cuda_scratch_sizes_test.zig new file mode 100644 index 00000000000..6f962fa536d --- /dev/null +++ b/zig/src/families/flashnext/cuda_scratch_sizes_test.zig @@ -0,0 +1,120 @@ +//! part's rows against every consumer in the pass's scratch: the out projection, a legacy out lane and the head. +const std = @import("std"); +const sizes = @import("cuda_scratch_sizes.zig"); +const plan = @import("cuda_mtp_plan.zig"); +const mtp = @import("cuda_mtp.zig"); +const wt = @import("cuda_prompt_wt.zig"); + +const streams = wt.streams; +const out_sk = wt.out_sk; +const fc_sk = mtp.fc_sk; +const piece_rows = mtp.piece_rows; + +/// part's rows a lane over m rows writes (cuda_tiles.matmul): two of the native lane, sk below 64, one when K folds. +fn laneRows(native: bool, m: usize, sk: usize) usize { + if (sk == 1) return 0; + if (native) return 2 * m; + return if (m >= 64) m else sk * m; +} + +/// An out projection over a pass of `n` rows: its own slices, and the writeback reading the zero slice at cap rows. +fn outRows(cap: usize, native: bool, n: usize) usize { + return @max(laneRows(native, n, out_sk), cap + n); +} + +/// The head's widest reachable pass at `cap` rows: the plan's piece, or one grouped lane's rows (a verify window). +fn headPass(cap: usize) usize { + return @min(cap, @max(plan.plan(cap, cap).piece, mtp.max_rows)); +} + +/// The head's fc_h lane over streams * rows rows, whichever lane the projection gets. +fn headNeed(cap: usize) usize { + const m = streams * headPass(cap); + return @max(laneRows(true, m, fc_sk), laneRows(false, m, fc_sk)); +} + +/// The head's widest pass the lane itself admits: forwardHeadMany refuses only a lane over piece_rows rows. +fn headWidest(cap: usize) usize { + const m = streams * @min(cap, piece_rows); + return @max(laneRows(true, m, fc_sk), laneRows(false, m, fc_sk)); +} + +/// Caps at or above this one carry a head pass: the plan's reserveRows floors the scratch at 32 rows. +const head_floor: usize = 32; + +/// A sweep's record of the caps whose requirement left part: the count, the first and last, the first's numbers. +const Short = struct { + caps: usize = 0, + first: usize = 0, + last: usize = 0, + need: usize = 0, + have: usize = 0, +}; + +fn one(s: *Short, cap: usize, need: usize, have: usize) void { + if (need <= have) return; + s.caps += 1; + if (s.caps == 1) { + s.first = cap; + s.need = need; + s.have = have; + } + s.last = cap; +} + +fn report(what: []const u8, s: Short) void { + if (s.caps == 0) return; + std.debug.print("part rows: {s} is short at {d} caps, {d} to {d}\n", .{ what, s.caps, s.first, s.last }); + std.debug.print("part rows: first cap {d} needs {d} rows, partRows gives {d}\n", .{ s.first, s.need, s.have }); +} + +/// The caps every sweep ends with: a full window's cache and the long ones a paged draft admits. +const far_caps = [_]usize{ 4096, 8192, 16384, 32768, 65536, 131072, 262144 }; + +fn sweep(comptime need: fn (usize) usize, from: usize) Short { + var s: Short = .{}; + var cap = from; + while (cap < far_caps[0]) : (cap += 1) one(&s, cap, need(cap), sizes.partRows(cap)); + for (far_caps) |c| one(&s, c, need(c), sizes.partRows(c)); + return s; +} + +test "Flash Next part rows: the out projection and a legacy out lane fit at every cap" { + var s: Short = .{}; + var cap: usize = 1; + while (cap < far_caps[0]) : (cap += 1) oneOut(&s, cap); + for (far_caps) |c| oneOut(&s, c); + report("the out projection", s); + try std.testing.expectEqual(@as(usize, 0), s.caps); +} + +/// A pass's rows where a lane's write changes: one row, the 16-row tile's last (63), the prompt tile's first, all. +fn oneOut(s: *Short, cap: usize) void { + const have = sizes.partRows(cap); + for ([_]usize{ 1, @min(cap, 63), @min(cap, 64), cap }) |n| { + one(s, cap, outRows(cap, true, n), have); + one(s, cap, outRows(cap, false, n), have); + } +} + +test "Flash Next part rows: the MTP head's fc_h lane fits part at every cap it runs" { + // a head pass runs on a scratch of at least the plan's floor, whatever chunk ran before it + try std.testing.expectEqual(head_floor, plan.reserveRows(1)); + try std.testing.expectEqual(head_floor, plan.reserveRows(head_floor / 4)); + // a pass of `head_floor` rows carries no head piece yet: the lane's own rows are the floor there + try std.testing.expectEqual(head_floor, headPass(head_floor)); + try std.testing.expectEqual(@as(usize, 2 * head_floor), headPass(4 * head_floor)); + const reachable = sweep(headNeed, head_floor); + report("the head's fc_h lane over a pass", reachable); + try std.testing.expectEqual(@as(usize, 0), reachable.caps); + const widest = sweep(headWidest, head_floor); + report("the head's fc_h lane over piece_rows", widest); + try std.testing.expectEqual(@as(usize, 0), widest.caps); +} + +test "Flash Next part rows: a long cache's part is still two cap-stride slices" { + try std.testing.expectEqual(@as(usize, 2 * 32768), sizes.partRows(32768)); + try std.testing.expectEqual(@as(usize, 2 * 131072), sizes.partRows(131072)); + // and the head's term does not grow it: the piece stops at piece_rows + try std.testing.expectEqual(@as(usize, 2 * 262144), sizes.partRows(262144)); +} From cb440a086f42590d4e22190fc1dabe1e0d7f3890 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:48 +0000 Subject: [PATCH 117/361] changelog: #4801 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 060c8aadfaf..d89e930c547 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 +- Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. + - Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. From 08b108f1f29467be1eccb0427fb4a65281be30f8 Mon Sep 17 00:00:00 2001 From: ultradaoto Date: Wed, 18 Nov 2026 11:48:35 -0800 Subject: [PATCH 118/361] feat(glm): the image tower on vit full attention, behind TF_GLM_VISION_FUSED --- docs/environment.md | 1 + docs/kernel-contract.md | 5 + docs/profiles.md | 1 + docs/recipes/glm-5.3-flash-cuda.md | 5 + zig/kernels/cuda/contract_controls_set.cu | 1 + .../cuda/contract_glm_vision_controls.cuh | 10 + zig/kernels/cuda/glm_vis_qk.cuh | 36 +++ zig/kernels/cuda/glm_vision.cu | 9 + zig/kernels/cuda/prefill_attention.cu | 5 +- zig/src/core/contract/glm_cuda_records.zig | 3 + zig/src/core/profile.zig | 2 + zig/src/cuda/vit.zig | 2 +- zig/src/families/glm/cuda.zig | 1 + zig/src/families/glm/cuda_env_test.zig | 2 + zig/src/families/glm/cuda_vision.zig | 71 ++---- zig/src/families/glm/cuda_vision_attn.zig | 104 +++++++++ zig/src/platform/environment.zig | 1 + zig/tests/cuda/contract_family_sets.zig | 5 + zig/tests/cuda/contract_glm_vision.zig | 208 ++++++++++++++++++ zig/tests/cuda/contract_moss_image_attn.zig | 158 +------------ zig/tests/cuda/contract_vit_full.zig | 163 ++++++++++++++ zig/tests/fixtures/gradient-serving.tsv | 4 +- 22 files changed, 581 insertions(+), 216 deletions(-) create mode 100644 zig/kernels/cuda/contract_glm_vision_controls.cuh create mode 100644 zig/kernels/cuda/glm_vis_qk.cuh create mode 100644 zig/src/families/glm/cuda_vision_attn.zig create mode 100644 zig/tests/cuda/contract_glm_vision.zig create mode 100644 zig/tests/cuda/contract_vit_full.zig diff --git a/docs/environment.md b/docs/environment.md index adacafbe024..bb59bc353e8 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -69,6 +69,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_DRAMA_REFERENCE_CACHE` | Drama 3 on CUDA: kept reference states, 0 (off) through 16; default 0. Checked when the checkpoint opens, with its own message | | `TF_GLM_HOST_CACHE` | Exactly `0` or `1`; default off (kept GLM states on the device) | | `TF_GLM_VISION_HOST` | Exactly `0` or `1`; default off (GLM vision weights on the device) | +| `TF_GLM_VISION_FUSED` | Exactly `0` or `1`; default off (the GLM vision tower's attention as cuBLASLt products around a softmax kernel) | | `TF_GLM_PAIR_EXPERTS` | Exactly `0` or `1`; default off. On, GLM paired CUDA prompt chunks share 128-pair routed NVFP4 expert items, with separate per-chunk outputs and unchanged slot combines | | `TF_GLM_PROF` | Exactly `0` or `1`; default off (no GLM section timing). On, all four prompt traces are created before readiness; startup, gate, final-draw, cache-admission and memory-counter records go to the log. A prompt step is one chunk, with no pair or solo steps, so its prompt timings are of that shape | | `TF_GLM_LINK_WAIT` | Exactly `0` or `1`; default off (short GLM steps go to the other ranks unwaited) | diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index bd756c25362..55b60422ca8 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -635,6 +635,11 @@ of the two branches), each output within float64's range at its bf16 points, and `contract_attn.zig`'s float64 reference (`audio-contract`; eight controls built from `nemo_audio.cuh` with one thing dropped each). +CUDA also checks GLM-5.3-Flash's image tower on that attention: `vision_kernel` at head dim 64 against the same +float64 reference (`contract_vit_full.zig`, the MOSS-Image test's type at any head dim), and `glm_vis_qk`, which +norms and rotates q and k in place in the rows it reads, bit-equal to `glm_vis_qkv` at segments of one row (one +control: the rotation before a head's bf16 rounding). + CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn, diff --git a/docs/profiles.md b/docs/profiles.md index 2b54701868e..a4ad1fceafe 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -99,6 +99,7 @@ still carries each resolved value, so ranks that disagree still stop before weig | --- | --- | --- | --- | | `TENSORFOLD_KOLIBRI_KV_PAGES` | CUDA, Kolibri-1 | arithmetic | Exact `0`, which disables otherwise requested pages | | `TENSORFOLD_DORY_KV_PAGES` | CUDA, Dory | arithmetic | Every present value except exact `0`, including empty text | +| `TF_GLM_VISION_FUSED` | CUDA, GLM | arithmetic | Exact `1`, which runs the vision tower's attention as the towers' shared full-attention kernel | | `GEMMA_DRAFT_BF16` | Metal, Gemma 4 | debug | `all`, `fc`, `self_attn.q_proj`, `self_attn.k_proj`, `self_attn.o_proj`, `mlp.gate_proj`, `mlp.down_proj` | | `TF_ANE_COLUMNS` | Metal, Qwen3.5 dense adapter | experimental | Nonzero columns; admission still decides whether the share is supported | | `TF_PROMPT_ROWS` | Metal, Qwen3.5 dense/MoE adapter | arithmetic | Every explicit native prompt width | diff --git a/docs/recipes/glm-5.3-flash-cuda.md b/docs/recipes/glm-5.3-flash-cuda.md index bc2627e8696..cde8f587b69 100644 --- a/docs/recipes/glm-5.3-flash-cuda.md +++ b/docs/recipes/glm-5.3-flash-cuda.md @@ -54,6 +54,11 @@ drafted at one stream, and about 1,430 prompt tokens a second from 2,048 to 65,5 `TF_GLM_VISION_HOST=1` keeps the tower's bf16 weights in pinned host memory and copies each part of a pass into one device slot as it runs (240 MiB for GLM-5.3-Flash's tower instead of its 1.05 GiB), leaving rank 0 that much more room for KV pages. Checked on two RTX PRO 6000 Blackwell cards. + `TF_GLM_VISION_FUSED=1` (opt-in) runs the tower's attention as the full-attention kernel the other towers use + (`vision_kernel` at head dim 64, the same code as RADIO's and MOSS-Image's) instead of two cuBLASLt products + around a softmax kernel: no scores or weights are written, so a large image's first token comes much sooner. + That kernel takes its maximum a 64-key tile at a time and sums in another order than cuBLASLt, so a reply to a + prompt with images can differ from the unset path's; text-only prompts are untouched. - Nonstreaming `/v1/completions` requests return `prompt_logprobs`, structured output follows its schema with drafts on, and required and named tool calls use the model's tool markup ([1.1.1](../../CHANGELOG.md#111): #1016 to #1018). - `--kv-cache fp8` is an opt-in FP8 latent cache ([1.1.2](../../CHANGELOG.md#112)); BF16 remains the default and the diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index 29d0a35f8cd..38717e38f80 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -12,3 +12,4 @@ #include "contract_controls_idol_decoder.cuh" #include "contract_qwen3_asr_controls.cuh" #include "contract_ricursive_controls.cuh" +#include "contract_glm_vision_controls.cuh" diff --git a/zig/kernels/cuda/contract_glm_vision_controls.cuh b/zig/kernels/cuda/contract_glm_vision_controls.cuh new file mode 100644 index 00000000000..f5de93a08b1 --- /dev/null +++ b/zig/kernels/cuda/contract_glm_vision_controls.cuh @@ -0,0 +1,10 @@ +// Planted control for glm_vision's in-place q and k: the rotation of a head before its bf16 rounding. + +#include "glm_vis_qk.cuh" + +extern "C" __global__ void tf_ctl_glm_vis_qk_unrounded(__nv_bfloat16* qkv, const __nv_bfloat16* __restrict__ qn, + const __nv_bfloat16* __restrict__ kn, + const int* __restrict__ pos, const float* __restrict__ inv_freq, + int N, int H, float eps) { + glm_vis_rows::qk(qkv, qn, kn, pos, inv_freq, N, H, eps); +} diff --git a/zig/kernels/cuda/glm_vis_qk.cuh b/zig/kernels/cuda/glm_vis_qk.cuh new file mode 100644 index 00000000000..76356950fe0 --- /dev/null +++ b/zig/kernels/cuda/glm_vis_qk.cuh @@ -0,0 +1,36 @@ +// GLM image tower: glm_vis_qkv's q and k, in place in the rows vit's full attention reads. +#pragma once + +#include + +namespace glm_vis_rows { + +// A warp a (row, head) of qkv [N, 3 H 64]: q and k head-RMSNormed, then rotated by the row's 2D angles; MID as served. +template +__device__ __forceinline__ void qk(__nv_bfloat16* qkv, const __nv_bfloat16* __restrict__ qn, + const __nv_bfloat16* __restrict__ kn, const int* __restrict__ pos, + const float* __restrict__ inv_freq, int N, int H, float eps) { + const long long item = blockIdx.x * (long long)(blockDim.x >> 5) + (threadIdx.x >> 5); + if (item >= (long long)N * H) return; + const int lane = threadIdx.x & 31; + const int n = (int)(item / H), h = (int)(item % H); + const int p = lane < 16 ? pos[2 * n] : pos[2 * n + 1]; + const float ang = (float)p * inv_freq[lane & 15]; + const float c = cosf(ang), s = sinf(ang); + for (int which = 0; which < 2; ++which) { + __nv_bfloat16* x = qkv + ((long long)n * 3 + which) * H * 64 + h * 64; + const __nv_bfloat16* wn = which ? kn : qn; + float a = __bfloat162float(x[lane]), b = __bfloat162float(x[lane + 32]); + float ss = a * a + b * b; + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + const float inv = rsqrtf(ss / 64.f + eps); + a = a * inv * __bfloat162float(wn[lane]); + b = b * inv * __bfloat162float(wn[lane + 32]); + if (MID) a = __bfloat162float(__float2bfloat16_rn(a)), b = __bfloat162float(__float2bfloat16_rn(b)); + // rotate_half: dims l < 32 take -x[l + 32], dims l + 32 take x[l] + x[lane] = __float2bfloat16_rn(a * c - b * s); + x[lane + 32] = __float2bfloat16_rn(b * c + a * s); + } +} + +} // namespace glm_vis_rows diff --git a/zig/kernels/cuda/glm_vision.cu b/zig/kernels/cuda/glm_vision.cu index 9887b23f457..ff69c83244c 100644 --- a/zig/kernels/cuda/glm_vision.cu +++ b/zig/kernels/cuda/glm_vision.cu @@ -4,6 +4,8 @@ #include #include "glm_pdl.cuh" +#include "glm_vis_qk.cuh" + namespace { __device__ __forceinline__ float bf(__nv_bfloat16 x) { return __bfloat162float(x); } __device__ __forceinline__ __nv_bfloat16 tobf(float x) { return __float2bfloat16_rn(x); } @@ -108,6 +110,13 @@ extern "C" __global__ void glm_vis_qkv(const __nv_bfloat16* __restrict__ qkv, co vt[(blk * 64 + lane + 32) * seg + j] = v[lane + 32]; } +// vit's full attention inputs: glm_vis_qkv's q and k, in place in qkv's rows [N, 3 H 64]; a warp a (row, head). +extern "C" __global__ void glm_vis_qk(__nv_bfloat16* qkv, const __nv_bfloat16* __restrict__ qn, + const __nv_bfloat16* __restrict__ kn, const int* __restrict__ pos, + const float* __restrict__ inv_freq, int N, int H, float eps) { + glm_vis_rows::qk(qkv, qn, kn, pos, inv_freq, N, H, eps); +} + // A scores row's softmax: pr = bf16(exp(scale (s - max))) and its sum (of the bf16 values), a block a row extern "C" __global__ void glm_vis_softmax(const float* __restrict__ sc, __nv_bfloat16* __restrict__ pr, float* __restrict__ sums, int n, float scale) { diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index d0be0a7b089..502f1bf400a 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -332,10 +332,7 @@ template __global__ void tf_prefill_attention::tree_kernel<64, 8, 4, 8>(const __ // Head dim 72, eight warps of one head, eight staging slots (SigLIP2's tower, 72 dims padded to 80 inside). template __global__ void tf_prefill_attention::full_kernel<72, 8, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, float); -// Head dim 80, eight warps, two blocks an SM (RADIO's tower, 16 heads of 80): full_kernel<80>'s bits, 1.35x faster. -template __global__ void tf_prefill_attention::vision_kernel<80, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, - float); -// Head dim 64, eight warps (Qwen3-ASR's audio tower, 14 or 16 heads of 64 over a window of its rows). +// Head dim 64, eight warps (Qwen3-ASR's audio tower and GLM-5.3-Flash's image tower over their respective windows or frame groups). template __global__ void tf_prefill_attention::vision_kernel<64, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, float); // Head dim 128, eight warps (MOSS-Image's denoiser, 24 heads of 128 over its image and prompt rows). diff --git a/zig/src/core/contract/glm_cuda_records.zig b/zig/src/core/contract/glm_cuda_records.zig index 1e027f2dd7d..5bc70c05ad7 100644 --- a/zig/src/core/contract/glm_cuda_records.zig +++ b/zig/src/core/contract/glm_cuda_records.zig @@ -62,6 +62,9 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "glm_ops tf_glm_kvh_copy_cached", .symbol = "tf_glm_kvh_copy_cached", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 42, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "glm_ops tf_glm_kvh_keep", .symbol = "tf_glm_kvh_keep", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 }, .{ .regs = 38, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "glm_ops tf_glm_kvh_unmark", .symbol = "tf_glm_kvh_unmark", .image = "glm_ops", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "glm_vision glm_vis_qk", .symbol = "glm_vis_qk", .image = "glm_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 27, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 }, .{ .regs = 25, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "glm_vision tf_ctl_glm_vis_qk_unrounded", .symbol = "tf_ctl_glm_vis_qk_unrounded", .image = "contract_controls", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 28, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 }, .{ .regs = 24, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "glm_vision vit vision_kernel<64, 8>", .symbol = "_ZN20tf_prefill_attention13vision_kernelILi64ELi8EEEvPK13__nv_bfloat16PS1_iif", .image = "prefill_attention", .threads = 256, .dynamic = 36864 }, .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 } } }, }; /// nvcc 13.2's usage where it differs from 13.0's. diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 9131634a82d..12b4c9eb7fc 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -24,6 +24,7 @@ pub const Switch = enum { TF_GLM_HOST_CACHE, TF_GLM_PAIR_EXPERTS, TF_GLM_VISION_HOST, + TF_GLM_VISION_FUSED, TF_GLM_PDL, TF_GLM_PROMPT_STEPS, TF_GLM_SHARED, @@ -167,6 +168,7 @@ pub const entries = [_]Entry{ .{ .id = .TF_GLM_HOST_CACHE, .families = &.{"glm5_next"}, .class = .identical, .syntax = .one, .effect = "Keep kept prompt states in pinned host memory instead of on the device", .evidence = "#2370" }, .{ .id = .TF_GLM_VISION_HOST, .families = &.{"glm5_next"}, .class = .identical, .syntax = .one, .effect = "Keep the vision tower's weights in pinned host memory, staged a unit at a time", .evidence = "#2370" }, .{ .id = .TF_GLM_PAIR_EXPERTS, .families = &.{"glm5_next"}, .class = .identical, .syntax = .one, .effect = "Route two paired CUDA prompt chunks through 128-pair NVFP4 expert items", .evidence = "REV25 E1; default-off; host gates; device A/B required" }, + .{ .id = .TF_GLM_VISION_FUSED, .families = &.{"glm5_next"}, .class = .arithmetic, .syntax = .one, .effect = "Run the vision tower's attention as vit's full-attention kernel; its sums run in another order than cuBLASLt's", .evidence = "#3614" }, .{ .id = .TF_GLM_PDL, .families = &.{"glm5_next"}, .class = .identical, .report_values = &.{"0"}, .effect = "Exact 0 turns off the forward's dependent launches", .evidence = "#2370" }, .{ .id = .TF_GLM_PROMPT_STEPS, .families = &.{"glm5_next"}, .class = .identical, .report_values = &.{"0"}, .effect = "Exact 0 runs rank 0's prompt passes whole, not in chunks", .evidence = "#2370" }, .{ .id = .TF_GLM_SHARED, .families = &.{"glm5_next"}, .class = .identical, .report_values = &.{"0"}, .effect = "Exact 0 runs each of rank 0's windows in its own forward", .evidence = "#2370" }, diff --git a/zig/src/cuda/vit.zig b/zig/src/cuda/vit.zig index 0e9068dab46..6d56690b677 100644 --- a/zig/src/cuda/vit.zig +++ b/zig/src/cuda/vit.zig @@ -297,7 +297,7 @@ const Full = struct { /// Full attention by head dim: Qwen3-ASR's 64, SigLIP2's 72, RADIO's 80 (full_kernel's bits), MOSS-Image's 128. const fulls = [_]Full{ - .{ .dim = 64, .warps = 8 }, + .{ .dim = 64, .warps = 8 }, // Qwen3-ASR's audio tower and GLM-5.3-Flash's image tower .{ .dim = 72, .warps = 8, .slots = 8 }, .{ .dim = 80, .warps = 8 }, .{ .dim = 128, .warps = 8 }, diff --git a/zig/src/families/glm/cuda.zig b/zig/src/families/glm/cuda.zig index 394e488e33e..01f1a145d45 100644 --- a/zig/src/families/glm/cuda.zig +++ b/zig/src/families/glm/cuda.zig @@ -3,6 +3,7 @@ pub const experts = @import("cuda_experts.zig"); pub const exl3 = @import("cuda_exl3.zig"); pub const vision = @import("cuda_vision.zig"); +pub const vision_attn = @import("cuda_vision_attn.zig"); pub const mm = @import("cuda_mm.zig"); pub const vision_config = @import("vision_config.zig"); pub const image_core = @import("image_core.zig"); diff --git a/zig/src/families/glm/cuda_env_test.zig b/zig/src/families/glm/cuda_env_test.zig index cf54528635f..41ca0dfbe4b 100644 --- a/zig/src/families/glm/cuda_env_test.zig +++ b/zig/src/families/glm/cuda_env_test.zig @@ -10,6 +10,7 @@ const Name = struct { name: [:0]const u8, default: bool = false }; const switches = [_]Name{ .{ .name = "TF_GLM_HOST_CACHE" }, .{ .name = "TF_GLM_VISION_HOST" }, + .{ .name = "TF_GLM_VISION_FUSED" }, .{ .name = "TF_GLM_PROF" }, .{ .name = "TF_GLM_LINK_WAIT" }, .{ .name = "TF_GLM_PDL", .default = true }, @@ -129,6 +130,7 @@ test "GLM strict env: the actual readers and the open's check keep defaults, 0 a const cases = [_]Case{ .{ .name = "TF_GLM_HOST_CACHE", .read = @import("cuda_snapshot_pages.zig").onHost }, .{ .name = "TF_GLM_VISION_HOST", .read = @import("cuda_vision_weights.zig").onHost }, + .{ .name = "TF_GLM_VISION_FUSED", .read = @import("cuda_vision_attn.zig").wanted }, .{ .name = "TF_GLM_PROF", .read = @import("cuda_prof.zig").Prof.wanted }, .{ .name = "TF_GLM_WIDE_EXPERT_TILE", .read = @import("cuda_experts.zig").wideExpertTile }, }; diff --git a/zig/src/families/glm/cuda_vision.zig b/zig/src/families/glm/cuda_vision.zig index 75bc5129782..d121194544f 100644 --- a/zig/src/families/glm/cuda_vision.zig +++ b/zig/src/families/glm/cuda_vision.zig @@ -7,19 +7,20 @@ const core = @import("core"); const formats = @import("cuda_formats.zig"); const projection = @import("cuda_proj.zig"); const tower_names = @import("vision_names.zig"); +const attn = @import("cuda_vision_attn.zig"); const H: i64 = 1024; // hidden -const HEADS: i64 = 16; -const HD: i64 = 64; // a head's width +const HEADS = attn.HEADS; +const HD = attn.HD; const MLP: i64 = 4096; const PATCH: i64 = 1176; // 3 channels x 2 frames x 14 x 14 const MERGE: i64 = 2; const OUT: i64 = 4096; // the merged rows' width (the language model's) const PROJ: i64 = 10240; // the merger's SwiGLU width pub const DEPTH = 24; -const CHUNK: i64 = 2048; // query rows a scores product covers +const CHUNK = attn.CHUNK; const ROWS: i64 = 4096; // rows a linear's fp32 product covers (the scratch's bound) -const EPS: f32 = 1e-5; +pub const EPS: f32 = 1e-5; const LIMIT: f32 = 10.0; const weights = @import("cuda_vision_weights.zig"); @@ -107,6 +108,7 @@ pub const Funcs = struct { embed32: cuda.Function, rmsnorm: cuda.Function, qkv: cuda.Function, + qk: cuda.Function, softmax: cuda.Function, head_out: cuda.Function, swiglu: cuda.Function, @@ -120,7 +122,7 @@ pub const Funcs = struct { } }; -fn launch(r: *const Run, f: cuda.Function, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { +pub fn launch(r: *const Run, f: cuda.Function, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { try cuda_pdl.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, r.stream, a); } @@ -149,6 +151,7 @@ pub const Tower = struct { bytes: u64 = 0, staged: ?staging.Stage = null, // TF_GLM_VISION_HOST: the units' copies from host memory into one device slot stages: ?[]f32 = null, // checks: the fp32 stream after the patch embedding and after every block, read back + full: ?cuda.vit.Attention = null, // TF_GLM_VISION_FUSED=1: vit's full attention, no scores or weights written /// The tower's tensors (either prefix) in one allocation: bf16 as stored, MXFP8 and NVFP4 packed for ``ql``. pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, ql: cuda.qlinear.Linear) !Tower { @@ -173,6 +176,10 @@ pub const Tower = struct { }; var t: Tower = .{ .gpa = gpa, .d = d, .lt = try cuda.cublaslt.Library.open(), .mem = try weights.Weights.alloc(d, total, try weights.onHost()), .ql = ql, .inv_freq = try cuda.DeviceBuffer.alloc(d, 16 * 4), .linears = .init(gpa), .ws = undefined }; errdefer t.deinit(); + if (try attn.wanted()) { + t.full = try cuda.vit.Attention.load(d); + std.log.info("glm: the image tower's attention as vit's full attention (TF_GLM_VISION_FUSED)", .{}); + } t.bytes = t.mem.deviceBytes(); t.ws = try cuda.DeviceBuffer.alloc(d, t.ws_len); var at: u64 = 0; @@ -249,6 +256,7 @@ pub const Tower = struct { while (it.next()) |l| l.deinit(); t.linears.deinit(); if (t.staged) |*s| s.deinit(); + if (t.full) |*f| f.unload(); t.mem.free(); t.inv_freq.free(); t.ws.free(); @@ -269,7 +277,7 @@ pub const Tower = struct { } /// D[m, n] = X[m, k] . W[n, k]^T (fp32 or bf16 out), a plan per shape kept for the next image. - fn linear(t: *Tower, ru: *const Run, x: u64, w: u64, d: u64, m: i64, n: i64, kk: i64, f32_out: bool) !void { + pub fn linear(t: *Tower, ru: *const Run, x: u64, w: u64, d: u64, m: i64, n: i64, kk: i64, f32_out: bool) !void { const key: LinKey = .{ .m = @intCast(m), .n = @intCast(n), .k = @intCast(kk), .f32_out = f32_out }; const gop = try t.linears.getOrPut(key); if (!gop.found_existing) { @@ -330,7 +338,7 @@ pub const Tower = struct { return ptr; } - fn grid1(n: i64) cuda.Dim3 { + pub fn grid1(n: i64) cuda.Dim3 { return .{ .x = @intCast(@min(std.math.divCeil(i64, n, 256) catch unreachable, 65535)) }; } @@ -461,58 +469,15 @@ pub const Tower = struct { try launch(ru, ru.f.embed32, grid1(rows * H), 256, &b); } } - const scale: f32 = 1.0 / @sqrt(@as(f32, HD)); if (t.stages) |dst| try t.stage(ru, dst, 0, x32, N); + const ab: attn.Buffers = .{ .qkv = big, .qh = qh, .kh = kh, .vt = vt, .att = att, .sc = sc, .pr = pr, .oh = oh, .sums = sums }; for (t.blocks, 1..) |bl, bi| { defer if (t.stages) |dst| t.stage(ru, dst, bi, x32, N) catch {}; try t.bring(ru, bi); try rmsnorm(ru, x32, bl.n1, xn, N, H); try t.dense(ru, xn, bl.qkv_w, bl.qkv_b, big, 0, acc, N, 3 * H, H); - { - var a: cuda.Args = .{}; - a.add(big); - a.add(bl.qn); - a.add(bl.kn); - a.add(dpos); - a.add(t.inv_freq.ptr); - a.add(qh); - a.add(kh); - a.add(vt); - a.add(@as(i32, @intCast(N))); - a.add(@as(i32, @intCast(seg))); - a.add(@as(i32, @intCast(HEADS))); - a.add(EPS); - try launch(ru, ru.f.qkv, .{ .x = @intCast(std.math.divCeil(i64, N * HEADS, 8) catch unreachable) }, 256, &a); - } - // each frame group attends within itself, per head, in query chunks (q, k [t, H, seg, 64]; v transposed) - var g: i64 = 0; - while (g < gt) : (g += 1) { - var h: i64 = 0; - while (h < HEADS) : (h += 1) { - const blk: u64 = @intCast((g * HEADS + h) * seg * HD * 2); - var c: i64 = 0; - while (c < seg) : (c += CHUNK) { - const rows = @min(CHUNK, seg - c); - try t.linear(ru, qh + blk + @as(u64, @intCast(c * HD * 2)), kh + blk, sc, rows, seg, HD, true); - var a: cuda.Args = .{}; - a.add(sc); - a.add(pr); - a.add(sums); - a.add(@as(i32, @intCast(seg))); - a.add(scale); - try launch(ru, ru.f.softmax, .{ .x = @intCast(rows) }, 256, &a); - try t.linear(ru, pr, vt + blk, oh, rows, HD, seg, true); - var b: cuda.Args = .{}; - b.add(oh); - b.add(sums); - b.add(att + @as(u64, @intCast((g * seg + c) * H * 2))); - b.add(@as(i32, @intCast(rows))); - b.add(@as(i32, @intCast(HEADS))); - b.add(@as(i32, @intCast(h))); - try launch(ru, ru.f.head_out, grid1(rows * HD), 256, &b); - } - } - } + try attn.heads(t, ru, ab, bl.qn, bl.kn, dpos, N, seg); + try attn.run(t, ru, ab, gt, seg); try t.dense(ru, att, bl.proj_w, bl.proj_b, 0, x32, acc, N, H, H); try rmsnorm(ru, x32, bl.n2, xn, N, H); try t.swiglu(ru, xn, bl.g_w, bl.g_b, bl.u_w, bl.u_b, big, acc, acc2, N, MLP, H); diff --git a/zig/src/families/glm/cuda_vision_attn.zig b/zig/src/families/glm/cuda_vision_attn.zig new file mode 100644 index 00000000000..eb1885b80a2 --- /dev/null +++ b/zig/src/families/glm/cuda_vision_attn.zig @@ -0,0 +1,104 @@ +//! The image tower's attention on CUDA: each frame group attends within itself. + +const std = @import("std"); +const cuda = @import("cuda"); +const vision = @import("cuda_vision.zig"); + +pub const HEADS: i64 = 16; +pub const HD: i64 = 64; // a head's width +pub const CHUNK: i64 = 2048; // query rows a scores product covers + +/// TF_GLM_VISION_FUSED=1: rank 0's tower runs vit's full attention; unset or 0, a head in chunks around cuBLASLt. +pub fn wanted() !bool { + return @import("sys").environment.value(bool, "TF_GLM_VISION_FUSED", @import("profile").lookup("TF_GLM_VISION_FUSED"), false); +} + +/// A pass's rows: qkv [N, 3 x 1024], att [N, 1024]; the chunked path's q and k [t, 16, seg, 64], v transposed, scratch. +pub const Buffers = struct { qkv: u64, qh: u64, kh: u64, vt: u64, att: u64, sc: u64, pr: u64, oh: u64, sums: u64 }; + +/// A block's q and k head-normed and rotated: in place in `b.qkv` for `t.full`, else into `b.qh`, `b.kh` and `b.vt`. +pub fn heads(t: *const vision.Tower, ru: *const vision.Run, b: Buffers, qn: u64, kn: u64, pos: u64, n: i64, seg: i64) !void { + const rows = t.full != null; + var a: cuda.Args = .{}; + for ([_]u64{ b.qkv, qn, kn, pos, t.inv_freq.ptr }) |p| a.add(p); + if (!rows) for ([_]u64{ b.qh, b.kh, b.vt }) |p| a.add(p); + a.add(@as(i32, @intCast(n))); + if (!rows) a.add(@as(i32, @intCast(seg))); + a.add(@as(i32, @intCast(HEADS))); + a.add(vision.EPS); + const grid: cuda.Dim3 = .{ .x = @intCast(std.math.divCeil(i64, n * HEADS, 8) catch unreachable) }; + try vision.launch(ru, if (rows) ru.f.qk else ru.f.qkv, grid, 256, &a); +} + +/// Every frame group's heads into `b.att`: `t.full` over the group's rows, else two products around a softmax a head. +pub fn run(t: *vision.Tower, ru: *const vision.Run, b: Buffers, gt: i64, seg: i64) !void { + const scale: f32 = 1.0 / @sqrt(@as(f32, HD)); + var g: i64 = 0; + while (g < gt) : (g += 1) { + const at: u64 = @intCast(g * seg * HEADS * HD * 2); + if (t.full) |*f| { + try f.full(ru.stream, b.qkv + 3 * at, b.att + at, @intCast(seg), HEADS, HD, scale); + continue; + } + var h: i64 = 0; + while (h < HEADS) : (h += 1) try chunked(t, ru, b, @intCast((g * HEADS + h) * seg * HD * 2), b.att + at, seg, h, scale); + } +} + +/// The head in query chunks: the scores product, glm_vis_softmax, the values product, glm_vis_head_out. +fn chunked(t: *vision.Tower, ru: *const vision.Run, b: Buffers, blk: u64, att: u64, seg: i64, h: i64, scale: f32) !void { + var c: i64 = 0; + while (c < seg) : (c += CHUNK) { + const rows = @min(CHUNK, seg - c); + try t.linear(ru, b.qh + blk + @as(u64, @intCast(c * HD * 2)), b.kh + blk, b.sc, rows, seg, HD, true); + var a: cuda.Args = .{}; + a.add(b.sc); + a.add(b.pr); + a.add(b.sums); + a.add(@as(i32, @intCast(seg))); + a.add(scale); + try vision.launch(ru, ru.f.softmax, .{ .x = @intCast(rows) }, 256, &a); + try t.linear(ru, b.pr, b.vt + blk, b.oh, rows, HD, seg, true); + var o: cuda.Args = .{}; + o.add(b.oh); + o.add(b.sums); + o.add(att + @as(u64, @intCast(c * HEADS * HD * 2))); + o.add(@as(i32, @intCast(rows))); + o.add(@as(i32, @intCast(HEADS))); + o.add(@as(i32, @intCast(h))); + try vision.launch(ru, ru.f.head_out, vision.Tower.grid1(rows * HD), 256, &o); + } +} + +const Seen = struct { + var n: usize = 0; + var grid: [8][2]u32 = undefined; + var block: [8]u32 = undefined; + fn launch(_: cuda.abi.Function, gx: c_uint, gy: c_uint, _: c_uint, bx: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, _: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + grid[n] = .{ gx, gy }; + block[n] = bx; + n += 1; + return cuda.abi.success; + } +}; + +test "with vit's attention a block is one q and k launch and one attention launch a frame group, for any segment" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Seen.launch; + const f: cuda.Function = .{ .d = &d, .handle = null }; + var ru: vision.Run = .{ .stream = .{ .d = &d, .handle = null }, .f = undefined }; + ru.f.qk = f; + var tower: vision.Tower = undefined; + tower.inv_freq.ptr = 0; + tower.full = .{ .mod = undefined, .fns = @splat(f) }; + const b: Buffers = .{ .qkv = 0, .qh = 0, .kh = 0, .vt = 0, .att = 0, .sc = 0, .pr = 0, .oh = 0, .sums = 0 }; + inline for (.{ .{ 4, 16, 1 }, .{ 128, 512, 1 }, .{ 129, 516, 2 }, .{ 6528, 26112, 51 } }) |case| { + Seen.n = 0; + try heads(&tower, &ru, b, 0, 0, 0, 2 * case[0], case[0]); + try run(&tower, &ru, b, 2, case[0]); + try std.testing.expectEqual(@as(usize, 3), Seen.n); + try std.testing.expectEqual([2]u32{ case[1], 1 }, Seen.grid[0]); + for (1..3) |i| try std.testing.expectEqual([2]u32{ case[2], HEADS }, Seen.grid[i]); + try std.testing.expectEqualSlices(u32, &.{ 256, 256, 256 }, Seen.block[0..3]); + } +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 6ac566e7a3a..4b9e39b6df0 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -171,6 +171,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_NEMOTRON_WIDE_ROUNDS", .scope = .nemotron, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_GLM_HOST_CACHE", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_VISION_HOST", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_GLM_VISION_FUSED", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROF", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_LINK_WAIT", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PDL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 387e93eb9ae..23c0f21bba0 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -17,6 +17,7 @@ pub const Sets = struct { moss: *@import("contract_moss_image.zig").Set, nemo_audio: *@import("contract_nemo_audio.zig").Set, qwen3_asr: *@import("contract_qwen3_asr.zig").Set, + glm_vision: *@import("contract_glm_vision.zig").Set, modelopt: *@import("contract_flashnext_modelopt.zig").Set, grouped: *Grouped, flashnext: *@import("contract_flashnext_more.zig").Set, @@ -46,6 +47,8 @@ pub const Sets = struct { errdefer nemo_audio.deinit(); const qwen3_asr = try @import("contract_qwen3_asr.zig").Set.init(gpu, s, a, list); errdefer qwen3_asr.deinit(); + const glm_vision = try @import("contract_glm_vision.zig").Set.init(gpu, s, a, list); + errdefer glm_vision.deinit(); const modelopt = try @import("contract_flashnext_modelopt.zig").Set.init(gpu, s, a, list); errdefer modelopt.deinit(); const grouped = try gpu.gpa.create(Grouped); @@ -88,6 +91,7 @@ pub const Sets = struct { .moss = moss, .nemo_audio = nemo_audio, .qwen3_asr = qwen3_asr, + .glm_vision = glm_vision, .modelopt = modelopt, .grouped = grouped, .flashnext = flashnext, @@ -120,6 +124,7 @@ pub const Sets = struct { sets.modelopt.deinit(); sets.qwen3_asr.deinit(); sets.nemo_audio.deinit(); + sets.glm_vision.deinit(); sets.moss.deinit(); sets.inkling2.deinit(); sets.minimax.deinit(); diff --git a/zig/tests/cuda/contract_glm_vision.zig b/zig/tests/cuda/contract_glm_vision.zig new file mode 100644 index 00000000000..e693ebfc7d3 --- /dev/null +++ b/zig/tests/cuda/contract_glm_vision.zig @@ -0,0 +1,208 @@ +//! GLM's image tower on vit's full attention under the contract: glm_vis_qk's rows, then vision_kernel<64, 8>. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const glm = @import("glm_cuda"); +const check_ = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const D = 64; +const H = 16; // heads +const W = H * D; + +const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +}; + +/// Shape: heads (rows), head width (n), a frame group's patches (k): two heads at an image's sizes, 16 at small ones. +pub const Full = @import("contract_vit_full.zig").Full(D, "cuda glm_vision vit vision_kernel<64, 8> (full attention)", &.{ .{ .rows = 2, .n = D, .k = 6528 }, .{ .rows = 2, .n = D, .k = 1024 }, .{ .rows = H, .n = D, .k = 196 }, .{ .rows = H, .n = D, .k = 36 }, .{ .rows = H, .n = D, .k = 4 } }); + +/// A lane's two squares, then the warp's 5 shuffles. +fn qkDepth(_: c.Shape) usize { + return 2 + 5; +} + +/// Shape: patches (rows), heads (n), head width (k). +fn qkSpec(control: bool) c.Spec { + return .{ + .name = if (control) "control: glm_vis_qk rotates a head before its bf16 rounding" else "cuda glm_vision glm_vis_qk (q and k head norm and 2D rotation, in place)", + .accum = .f32, + .depth = qkDepth, + .out = .bf16, + .in_place = true, + .replaces = "glm_vis_qkv at segments of one row", + .nan = .{ .stated = "byte-identical to glm_vis_qkv's rows, including non-finite inputs" }, + .served = &.{ .{ .rows = 6528, .n = H, .k = D }, .{ .rows = 1024, .n = H, .k = D }, .{ .rows = 196, .n = H, .k = D }, .{ .rows = 4, .n = H, .k = D } }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "a head's sum of squares is checked against the replaced kernel's bytes" }, + }; +} + +/// glm_vis_qk through cuda_vision_attn.heads, on a copy of the rows [rows, 3 x 1024], against glm_vis_qkv. +pub const Qk = struct { + rig: rig_.Rig, + run_: glm.vision.Run, + att: *cuda.vit.Attention, + control: bool = false, + shape: c.Shape = undefined, + qkv: u64 = 0, + norms: u64 = 0, + pos: u64 = 0, + freq: u64 = 0, + out: u64 = 0, + /// glm_vis_qkv's q, k and v at segments of one row: [rows, 1024] each + old: [3]u64 = @splat(0), + base: []u8 = &.{}, + msg: [200]u8 = undefined, + + pub fn deinit(self: *Qk) void { + self.rig.gpu.gpa.free(self.base); + self.rig.deinit(); + } + + const vt = g.hooks(Qk); + + pub fn kernel(self: *Qk) g.Kernel { + return .{ .spec = qkSpec(self.control), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn prepare(self: *Qk, sh: c.Shape, fill: g.Fill, seed: u64) !bool { + if (sh.rows == 0 or sh.n != H or sh.k != D) return false; + self.rig.reset(); + self.shape = sh; + const a = self.rig.gpu.gpa; + const x = try a.alloc(u16, self.count()); + defer a.free(x); + const pos = try a.alloc(i32, 2 * sh.rows); + defer a.free(pos); + var norms: [2 * D]u16 = undefined; + var freq: [16]f32 = undefined; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (x) |*v| v.* = c.toBf16(rng.float(f32) * 8 - 4); + for (&norms) |*v| v.* = c.toBf16(0.25 + rng.float(f32) * 1.75); + for (pos) |*p| p.* = rng.intRangeLessThan(i32, 0, 275); + for (&freq, 0..) |*v, i| v.* = 1.0 / std.math.pow(f32, 10000.0, @as(f32, @floatFromInt(2 * i)) / 32.0); + if (fill == .nonfinite) for (x, 0..) |*v, i| switch (i % (3 * W + 7)) { + 0 => v.* = c.toBf16(std.math.nan(f32)), + 1 => v.* = c.toBf16(std.math.inf(f32)), + 2 => v.* = c.toBf16(-std.math.inf(f32)), + else => {}, + }; + if (fill == .stress) { // every q and k element 8 under unit weights at the origin: each head norms to ones + for (0..sh.rows) |r| @memset(x[r * 3 * W ..][0 .. 2 * W], c.toBf16(8)); + @memset(&norms, c.toBf16(1)); + @memset(pos, 0); + } + self.qkv = try self.rig.input(std.mem.sliceAsBytes(x)); + self.norms = try self.rig.input(std.mem.sliceAsBytes(&norms)); + self.pos = try self.rig.input(std.mem.sliceAsBytes(pos)); + self.freq = try self.rig.input(std.mem.sliceAsBytes(&freq)); + self.out = try self.rig.output(self.count() * 2); + for (&self.old) |*o| o.* = try self.rig.scratch(sh.rows * W * 2); + a.free(self.base); + self.base = &.{}; + self.base = try a.alloc(u8, self.count() * 2); + return true; + } + + pub fn count(self: *Qk) usize { + return self.shape.rows * 3 * W; + } + + fn heads(self: *Qk, rows: bool, qkv: u64) !void { + var tower: glm.vision.Tower = undefined; + tower.full = if (rows) self.att.* else null; + tower.inv_freq.ptr = self.freq; + const b: glm.vision_attn.Buffers = .{ .qkv = qkv, .qh = self.old[0], .kh = self.old[1], .vt = self.old[2], .att = 0, .sc = 0, .pr = 0, .oh = 0, .sums = 0 }; + try glm.vision_attn.heads(&tower, &self.run_, b, self.norms, self.norms + D * 2, self.pos, @intCast(self.shape.rows), 1); + } + + pub fn run(self: *Qk) !void { + try (cuda.DeviceBuffer{ .d = self.rig.gpu.d, .ptr = self.out, .len = self.count() * 2 }).copyFrom(0, self.qkv, self.count() * 2, self.rig.s.handle); + try self.heads(true, self.out); + try self.rig.s.synchronize(); + } + + /// glm_vis_qkv's bytes as rows of q, k, v: at segments of one row its head-major q and k are row-major. + pub fn replaced(self: *Qk) ![]const u8 { + try self.heads(false, self.qkv); + const row = W * 2; + for (self.old, 0..) |ptr, which| { + const part = try self.rig.bytes(ptr, self.shape.rows * row); + for (0..self.shape.rows) |r| @memcpy(self.base[(r * 3 + which) * row ..][0..row], part[r * row ..][0..row]); + } + return self.base; + } + + pub fn reference(self: *Qk, want: []f64, mag: []f64) !void { + const bytes = try self.replaced(); + for (want, mag, 0..) |*w, *m, i| { + w.* = c.read(.bf16, bytes, i); + m.* = @abs(w.*); + } + } + + /// The stress rows: 64 squares of 8 a head, then 8 / sqrt(their mean) as bf16; v's 8s as they are. + pub fn simulate(self: *Qk, acc: c.Accum, order: g.Order, out: []f64) !void { + const squares: [D]f64 = @splat(64); + const ss = core.contract.rows.sumIn(acc, order, &squares); + const one = c.fromBf16(c.toBf16(@floatCast(8 / @sqrt(ss / D + 1e-5)))); + for (0..self.shape.rows) |r| { + @memset(out[r * 3 * W ..][0 .. 2 * W], one); + for (out[(r * 3 + 2) * W ..][0..W], 0..) |*v, i| v.* = c.read(.bf16, self.base, (r * 3 + 2) * W + i); + } + } + + pub fn check(self: *Qk, _: g.Gate) !?[]const u8 { + const a = self.rig.gpu.gpa; + const got = try a.dupe(u8, try self.rig.outputBytes()); + defer a.free(got); + const want = try self.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&self.msg, "byte {d} of {d} differs from glm_vis_qkv's rows", .{ at, got.len }); + for (0..self.count()) |i| if (c.classOf(c.read(.bf16, got, i)) != .finite) return null; + return "no output is non-finite: the planted values prove nothing"; + } +}; + +/// The tower's q and k rows with their control, and its attention, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + mod: cuda.Module, + ctl: cuda.Module, + att: cuda.vit.Attention, + qk: [2]Qk = undefined, + full: Full = undefined, + + /// The set, its kernels appended to `list` (the control after the kernel it breaks). + pub fn init(gpu: check_.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var mod = try cuda.Module.load(gpu.d, cuda.kernels.glm_vision); + errdefer mod.unload(); + var ctl = try cuda.Module.load(gpu.d, &controls.bytes); + errdefer ctl.unload(); + set.* = .{ .gpa = gpu.gpa, .mod = mod, .ctl = ctl, .att = try cuda.vit.Attention.load(gpu.d) }; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + const f = try glm.vision.Funcs.load(mod); + var broken = f; + broken.qk = try ctl.function("tf_ctl_glm_vis_qk_unrounded"); + set.qk[0] = .{ .rig = rig, .run_ = .{ .stream = s, .f = f }, .att = &set.att }; + set.qk[1] = .{ .rig = rig, .run_ = .{ .stream = s, .f = broken }, .att = &set.att, .control = true }; + set.full = .{ .rig = rig, .att = &set.att }; + for (&set.qk) |*x| try list.append(a, x.kernel()); + try list.append(a, set.full.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.qk) |*x| x.deinit(); + set.full.deinit(); + set.att.unload(); + set.ctl.unload(); + set.mod.unload(); + set.gpa.destroy(set); + } +}; diff --git a/zig/tests/cuda/contract_moss_image_attn.zig b/zig/tests/cuda/contract_moss_image_attn.zig index 176c9cf4e02..e8a01067b51 100644 --- a/zig/tests/cuda/contract_moss_image_attn.zig +++ b/zig/tests/cuda/contract_moss_image_attn.zig @@ -1,161 +1,7 @@ //! prefill_attention.cu's vision_kernel<128, 8> under the contract: MOSS-Image's full attention, head by head. -const std = @import("std"); -const cuda = @import("cuda"); -const core = @import("core"); -const rig_ = @import("contract_rig.zig"); -const attn = @import("contract_attn.zig"); - -const c = core.contract.spec; -const g = core.contract.gates; +const full = @import("contract_vit_full.zig"); const D = 128; -/// The P x V chain of a row: every key, a 64-key tile at a time. -fn keyChain(s: c.Shape) usize { - return s.k + 64; -} - -fn scale() f32 { - return 1.0 / @sqrt(@as(f32, D)); -} - /// Shape: heads (rows), head width (n), rows L (k); 24 heads at prompt lengths, two stand for them at joint ones. -pub fn spec() c.Spec { - return .{ - .name = "cuda moss image vit vision_kernel<128, 8> (full attention)", - .accum = .f32, - .depth = keyChain, - .ops = 1, - .out = .bf16, - .tiles = .{ .{}, .{}, .{ .size = 128 } }, - .served = &.{ .{ .rows = 2, .n = D, .k = 4188 }, .{ .rows = 2, .n = D, .k = 4135 }, .{ .rows = 2, .n = D, .k = 4130 }, .{ .rows = 2, .n = D, .k = 4106 }, .{ .rows = 24, .n = D, .k = 63 }, .{ .rows = 24, .n = D, .k = 34 }, .{ .rows = 24, .n = D, .k = 10 } }, - .sums = .{ .why = attn.why }, - }; -} - -pub const Full = struct { - rig: rig_.Rig, - att: *const cuda.vit.Attention, - r: ?attn.Ref = null, - shape: c.Shape = undefined, - /// [L, 3 heads 128]: q heads, then k, then v (tf_moss_qk's packed rows) - qkv: []u16 = &.{}, - dev: u64 = 0, - out: u64 = 0, - - pub fn deinit(self: *Full) void { - self.rig.gpu.gpa.free(self.qkv); - if (self.r) |*r| r.deinit(); - self.rig.deinit(); - } - - pub fn kernel(self: *Full) g.Kernel { - return .{ .spec = spec(), .ctx = self, .vt = &vt }; - } - - const vt = g.hooks(Full); - - fn stride(self: *const Full) usize { - return 3 * self.shape.rows * D; - } - - fn at(self: *const Full, row: usize, which: usize, head: usize) []u16 { - return self.qkv[row * self.stride() + (which * self.shape.rows + head) * D ..][0..D]; - } - - pub fn prepare(self: *Full, shape: c.Shape, fill: g.Fill, seed: u64) !bool { - self.rig.reset(); - if (shape.n != D or shape.rows == 0 or shape.k == 0) return false; - const a = self.rig.gpu.gpa; - self.shape = shape; - const L = shape.k; - var prng = std.Random.DefaultPrng.init(seed); - const rng = prng.random(); - if (self.r) |*r| r.deinit(); - self.r = null; - self.r = try attn.Ref.init(a, D, L); - a.free(self.qkv); - self.qkv = &.{}; - self.qkv = try a.alloc(u16, L * self.stride()); - for (self.qkv) |*e| e.* = attn.normal(rng); - switch (fill) { - .random => {}, - .nonfinite => self.plant(), - .stress => try self.stress(rng), - } - self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); - self.out = try self.rig.output(L * shape.rows * D * 2); - return true; - } - - /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. - fn plant(self: *Full) void { - const L = self.shape.k; - const nan = c.toBf16(std.math.nan(f32)); - const inf = c.toBf16(std.math.inf(f32)); - const ninf = c.toBf16(-std.math.inf(f32)); - self.at(0, 0, 0)[3] = nan; - self.at(L - 1, 2, 0)[7] = inf; - self.at(L / 2, 2, 0)[9] = ninf; - if (L >= 3) { - self.at(1, 2, 0)[11] = inf; - self.at(2, 2, 0)[11] = ninf; - } - if (self.shape.rows > 1) self.at(L / 3, 1, 1)[5] = nan; - } - - /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. - fn stress(self: *Full, rng: std.Random) !void { - const a = self.rig.gpu.gpa; - const L = self.shape.k; - const key = try a.alloc(u16, D); - defer a.free(key); - for (key) |*e| e.* = attn.normal(rng); - const col = try a.alloc(f32, L); - defer a.free(col); - for (0..self.shape.rows) |h| { - for (0..L) |j| @memcpy(self.at(j, 1, h), key); - for (0..D) |e| { - attn.mirrored(rng, col); - for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); - } - } - } - - pub fn run(self: *Full) !void { - try self.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, D, scale()); - try self.rig.s.synchronize(); - } - - pub fn count(self: *Full) usize { - return self.shape.k * self.shape.rows * D; - } - - /// Output head i (row i / heads, head i % heads) over every row's key and value. - pub fn load(self: *Full, i: usize, hd: *attn.Head) !void { - const row = i / self.shape.rows; - const head = i % self.shape.rows; - for (hd.q, self.at(row, 0, head)) |*y, x| y.* = c.fromBf16(x); - for (0..self.shape.k) |j| for (0..D) |e| { - hd.k[j * D + e] = c.fromBf16(self.at(j, 1, head)[e]); - hd.v[j * D + e] = c.fromBf16(self.at(j, 2, head)[e]); - }; - hd.n = self.shape.k; - } - - fn heads(self: *Full) usize { - return self.shape.k * self.shape.rows; - } - - pub fn check(self: *Full, gate: g.Gate) !?[]const u8 { - return self.r.?.check(self, self.heads(), scale(), try self.rig.outputBytes(), gate); - } - - pub fn reference(self: *Full, want: []f64, mag: []f64) !void { - return self.r.?.reference(self, self.heads(), scale(), want, mag); - } - - pub fn simulate(self: *Full, acc: c.Accum, order: g.Order, out: []f64) !void { - return self.r.?.simulate(self, self.heads(), scale(), acc, order, out); - } -}; +pub const Full = full.Full(D, "cuda moss image vit vision_kernel<128, 8> (full attention)", &.{ .{ .rows = 2, .n = D, .k = 4188 }, .{ .rows = 2, .n = D, .k = 4135 }, .{ .rows = 2, .n = D, .k = 4130 }, .{ .rows = 2, .n = D, .k = 4106 }, .{ .rows = 24, .n = D, .k = 63 }, .{ .rows = 24, .n = D, .k = 34 }, .{ .rows = 24, .n = D, .k = 10 } }); diff --git a/zig/tests/cuda/contract_vit_full.zig b/zig/tests/cuda/contract_vit_full.zig new file mode 100644 index 00000000000..1d69c09c582 --- /dev/null +++ b/zig/tests/cuda/contract_vit_full.zig @@ -0,0 +1,163 @@ +//! prefill_attention.cu's vision_kernel under the contract: a tower's full attention, head by head. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +/// The P x V chain of a row: every key, a 64-key tile at a time. +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +/// The test type at head dim `D`, registered as `name` at the shapes `served`: heads (rows), D (n), rows L (k). +pub fn Full(comptime D: usize, comptime name: []const u8, comptime served: []const c.Shape) type { + return struct { + const Self = @This(); + + fn scale() f32 { + return 1.0 / @sqrt(@as(f32, D)); + } + + pub fn spec() c.Spec { + return .{ + .name = name, + .accum = .f32, + .depth = keyChain, + .ops = 1, + .out = .bf16, + .tiles = .{ .{}, .{}, .{ .size = 128 } }, + .served = served, + .sums = .{ .why = attn.why }, + }; + } + + rig: rig_.Rig, + att: *const cuda.vit.Attention, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + /// [L, 3 heads D]: q heads, then k, then v + qkv: []u16 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn deinit(self: *Self) void { + self.rig.gpu.gpa.free(self.qkv); + if (self.r) |*r| r.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Self) g.Kernel { + return .{ .spec = spec(), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Self); + + fn stride(self: *const Self) usize { + return 3 * self.shape.rows * D; + } + + fn at(self: *const Self, row: usize, which: usize, head: usize) []u16 { + return self.qkv[row * self.stride() + (which * self.shape.rows + head) * D ..][0..D]; + } + + pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != D or shape.rows == 0 or shape.k == 0) return false; + const a = self.rig.gpu.gpa; + self.shape = shape; + const L = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(a, D, L); + a.free(self.qkv); + self.qkv = &.{}; + self.qkv = try a.alloc(u16, L * self.stride()); + for (self.qkv) |*e| e.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.out = try self.rig.output(L * shape.rows * D * 2); + return true; + } + + /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. + fn plant(self: *Self) void { + const L = self.shape.k; + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + self.at(0, 0, 0)[3] = nan; + self.at(L - 1, 2, 0)[7] = inf; + self.at(L / 2, 2, 0)[9] = ninf; + if (L >= 3) { + self.at(1, 2, 0)[11] = inf; + self.at(2, 2, 0)[11] = ninf; + } + if (self.shape.rows > 1) self.at(L / 3, 1, 1)[5] = nan; + } + + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. + fn stress(self: *Self, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const L = self.shape.k; + const key = try a.alloc(u16, D); + defer a.free(key); + for (key) |*e| e.* = attn.normal(rng); + const col = try a.alloc(f32, L); + defer a.free(col); + for (0..self.shape.rows) |h| { + for (0..L) |j| @memcpy(self.at(j, 1, h), key); + for (0..D) |e| { + attn.mirrored(rng, col); + for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); + } + } + } + + pub fn run(self: *Self) !void { + try self.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, D, scale()); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Self) usize { + return self.shape.k * self.shape.rows * D; + } + + /// Output head i (row i / heads, head i % heads) over every row's key and value. + pub fn load(self: *Self, i: usize, hd: *attn.Head) !void { + const row = i / self.shape.rows; + const head = i % self.shape.rows; + for (hd.q, self.at(row, 0, head)) |*y, x| y.* = c.fromBf16(x); + for (0..self.shape.k) |j| for (0..D) |e| { + hd.k[j * D + e] = c.fromBf16(self.at(j, 1, head)[e]); + hd.v[j * D + e] = c.fromBf16(self.at(j, 2, head)[e]); + }; + hd.n = self.shape.k; + } + + fn heads(self: *Self) usize { + return self.shape.k * self.shape.rows; + } + + pub fn check(self: *Self, gate: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.heads(), scale(), try self.rig.outputBytes(), gate); + } + + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.heads(), scale(), want, mag); + } + + pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.heads(), scale(), acc, order, out); + } + }; +} diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index aa0c37b2a87..c3a61f99dfd 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -46,7 +46,7 @@ zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) zig/kernels/cuda/nvfp4_experts.cu dc78d37c1eb1d9a9fff6c1ba9c5f0a9b0eb485a47a56e7b0b2fdbb8bbf1b223b raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items) zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw -zig/kernels/cuda/prefill_attention.cu 4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged) +zig/kernels/cuda/prefill_attention.cu 4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (one new vision_kernel instance at head dim 64; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) zig/kernels/cuda/probe.cu 94a3118894b3066e0f0f6fc1cfc3c03828d291077cb26c437b62fcc9b177a210 raw glm-pdl-order's slow writer, planted early reader and glm_pdl::enter() reader zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt @@ -113,7 +113,7 @@ zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125d zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0bd5f468ace3 raw main 13d7450fd (#2354), 7ead07c92 (bounded peer warm-up, #2512) zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw -zig/src/cuda/vit.zig 0a9200b161e331cf3f5937ff5dcc5c65bcb15e3de8127c277f6a31595d2e5296 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged) +zig/src/cuda/vit.zig 0a9200b161e331cf3f5937ff5dcc5c65bcb15e3de8127c277f6a31595d2e5296 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw zig/src/families/flashnext/cuda_batch.zig b368dc5784c9d7e82d9e29ce26f37b3471d31a21e12a144127d365bdcc4ead96 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged From a41b3b05fdea9e2ccfacc495ec495ec41e0c832e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:55:54 +0000 Subject: [PATCH 119/361] glm vision: wait before the new dependent image-tower launch reads Follow main 7948cc42d3f74b3b5e6d4ef8776c3777172c20d0, which routes the vision launch helper through cuda_pdl.launch. The new glm_vis_qk entry must open with glm_pdl::enter() before reading its predecessor outputs, like every existing GLM vision entry. Keep the incoming arithmetic and both current serving pins unchanged. --- zig/kernels/cuda/glm_vision.cu | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/kernels/cuda/glm_vision.cu b/zig/kernels/cuda/glm_vision.cu index ff69c83244c..7ab52c84cc1 100644 --- a/zig/kernels/cuda/glm_vision.cu +++ b/zig/kernels/cuda/glm_vision.cu @@ -114,6 +114,7 @@ extern "C" __global__ void glm_vis_qkv(const __nv_bfloat16* __restrict__ qkv, co extern "C" __global__ void glm_vis_qk(__nv_bfloat16* qkv, const __nv_bfloat16* __restrict__ qn, const __nv_bfloat16* __restrict__ kn, const int* __restrict__ pos, const float* __restrict__ inv_freq, int N, int H, float eps) { + glm_pdl::enter(); glm_vis_rows::qk(qkv, qn, kn, pos, inv_freq, N, H, eps); } From eb17dc00d9f4a05012e35aebf584bf7036500ee4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:01:00 +0000 Subject: [PATCH 120/361] glm vision: the fused-attention launch test records through cuLaunchKernelEx Follows main's 7948cc42d (GLM's CUDA kernels as dependent launches), which sends every GLM launch through cuLaunchKernelEx; the test hands those to its recording cuLaunchKernel with cuda_pdl.forwardEx, as main's GLM tests do. --- zig/src/families/glm/cuda_vision_attn.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/families/glm/cuda_vision_attn.zig b/zig/src/families/glm/cuda_vision_attn.zig index eb1885b80a2..00869fe9818 100644 --- a/zig/src/families/glm/cuda_vision_attn.zig +++ b/zig/src/families/glm/cuda_vision_attn.zig @@ -85,6 +85,7 @@ const Seen = struct { test "with vit's attention a block is one q and k launch and one attention launch a frame group, for any segment" { var d: cuda.Driver = undefined; d.api.cuLaunchKernel = Seen.launch; + d.api.cuLaunchKernelEx = @import("cuda_pdl.zig").forwardEx(Seen.launch); const f: cuda.Function = .{ .d = &d, .handle = null }; var ru: vision.Run = .{ .stream = .{ .d = &d, .handle = null }, .f = undefined }; ru.f.qk = f; From 0b119dfad3d7b56068cbdac8d6d41641476b6d84 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:44:00 +0000 Subject: [PATCH 121/361] glm vision: register the fused-attention launch tests Reference the new vision_attn module from the GLM CUDA test block so the default GLM host test root discovers its launch-geometry coverage. --- zig/src/families/glm/cuda.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/families/glm/cuda.zig b/zig/src/families/glm/cuda.zig index 01f1a145d45..8129f4c9407 100644 --- a/zig/src/families/glm/cuda.zig +++ b/zig/src/families/glm/cuda.zig @@ -82,6 +82,7 @@ test { _ = experts; _ = exl3; _ = vision; + _ = vision_attn; _ = @import("vision_names.zig"); _ = mm; _ = image_core; From b3d00ebf77d9224c03068a49fbcd10a89021f960 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:04:24 +0000 Subject: [PATCH 122/361] glm vision: restore the contract image resolution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Combine the PR glm_vision image entry with main’s expanded image list, including idol_decoder and all four Inkling2 images, so every registered CUDA launch resolves its own image. --- zig/tests/cuda/contract_limits.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 8a929670786..18778dd193f 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -31,7 +31,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "glm_vision", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; From 5cd13706ccc93f956d98943d3cd1c0d567800d48 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:23:13 +0000 Subject: [PATCH 123/361] glm vision: retain RADIO and re-pin shared attention --- zig/kernels/cuda/prefill_attention.cu | 5 ++++- zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index 502f1bf400a..23afe7f9cbb 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -332,7 +332,10 @@ template __global__ void tf_prefill_attention::tree_kernel<64, 8, 4, 8>(const __ // Head dim 72, eight warps of one head, eight staging slots (SigLIP2's tower, 72 dims padded to 80 inside). template __global__ void tf_prefill_attention::full_kernel<72, 8, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, float); -// Head dim 64, eight warps (Qwen3-ASR's audio tower and GLM-5.3-Flash's image tower over their respective windows or frame groups). +// Head dim 80, eight warps, two blocks an SM (RADIO's tower, 16 heads of 80): full_kernel<80>'s bits, 1.35x faster. +template __global__ void tf_prefill_attention::vision_kernel<80, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, + float); +// Head dim 64, eight warps (Qwen3-ASR audio and GLM-5.3-Flash image towers; existing instances unchanged). template __global__ void tf_prefill_attention::vision_kernel<64, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, float); // Head dim 128, eight warps (MOSS-Image's denoiser, 24 heads of 128 over its image and prompt rows). diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index c3a61f99dfd..19ce88cfbe4 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -46,7 +46,7 @@ zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) zig/kernels/cuda/nvfp4_experts.cu dc78d37c1eb1d9a9fff6c1ba9c5f0a9b0eb485a47a56e7b0b2fdbb8bbf1b223b raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items) zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw -zig/kernels/cuda/prefill_attention.cu 4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (one new vision_kernel instance at head dim 64; existing instances unchanged) +zig/kernels/cuda/prefill_attention.cu e4cb5bd5e4e9bf8157e5612b45f3dcf78ea31f4ab0822573da495c7aa63728d5.raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (GLM-5.3-Flash's image tower reuses the head-64 vision_kernel instance; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) zig/kernels/cuda/probe.cu 94a3118894b3066e0f0f6fc1cfc3c03828d291077cb26c437b62fcc9b177a210 raw glm-pdl-order's slow writer, planted early reader and glm_pdl::enter() reader zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt @@ -113,7 +113,7 @@ zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125d zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0bd5f468ace3 raw main 13d7450fd (#2354), 7ead07c92 (bounded peer warm-up, #2512) zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw -zig/src/cuda/vit.zig 0a9200b161e331cf3f5937ff5dcc5c65bcb15e3de8127c277f6a31595d2e5296 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) +zig/src/cuda/vit.zig 3a22b6aaf70bcf83a1d3c7624c8c554e262e69d12be07b6e6b389702f77b5877 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw zig/src/families/flashnext/cuda_batch.zig b368dc5784c9d7e82d9e29ce26f37b3471d31a21e12a144127d365bdcc4ead96 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged From 8d1175e07758f335a81ffade522f4da8e7300969 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:32:21 +0000 Subject: [PATCH 124/361] glm vision: finish fused attention cleanup and pin coverage --- zig/dense_serving_test.zig | 4 ++-- zig/src/core/contract/glm_cuda_records.zig | 1 + zig/src/families/glm/cuda_vision.zig | 4 ++-- zig/tests/cuda/contract_glm_vision.zig | 1 + zig/tests/fixtures/gradient-serving.tsv | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index 6bfdfd2b9cf..980556f25f3 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -11,8 +11,8 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt try std.testing.expectEqualStrings("5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc", &hash(@embedFile("kernels/cuda/experts_prefill.cu"))); try std.testing.expectEqualStrings("e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228", &hash(@embedFile("kernels/cuda/gdn.cu"))); try std.testing.expectEqualStrings("dba5aae94115571ed48933d80f646fff31b2a7da226569867c74a1dc061d2ca2", &hash(@embedFile("kernels/cuda/lane_gemv.cu"))); - // #2239 adds vision_kernel<64, 8> for Qwen3-ASR's tower; every function main had keeps its SASS (sm_80 to sm_121) - try std.testing.expectEqualStrings("4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741", &hash(@embedFile("kernels/cuda/prefill_attention.cu"))); + // #2239 adds head-64 attention for Qwen3-ASR; #3790 reuses it for GLM; existing instances keep their SASS + try std.testing.expectEqualStrings("e4cb5bd5e4e9bf8157e5612b45f3dcf78ea31f4ab0822573da495c7aa63728d5", &hash(@embedFile("kernels/cuda/prefill_attention.cu"))); const group = @embedFile("kernels/cuda/qmm_group.cu"); try std.testing.expectEqualStrings("ceff4ee13e97b5aa93cbe7a1edc9a524c78aaa145dd1e5c82dcb05a3011aae23", &hash(group[0..16095])); try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group)); diff --git a/zig/src/core/contract/glm_cuda_records.zig b/zig/src/core/contract/glm_cuda_records.zig index 5bc70c05ad7..4c725cd07b0 100644 --- a/zig/src/core/contract/glm_cuda_records.zig +++ b/zig/src/core/contract/glm_cuda_records.zig @@ -72,6 +72,7 @@ pub const cuda_132 = [_]registry.Override{ .{ .name = "glm_mm16_16", .usage = .{ .{ .regs = 95, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 }, .{ .regs = 95, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 }, .{ .regs = 56, .static = 0, .bound = 128 } } }, .{ .name = "glm_mm8_16", .usage = .{ .{ .regs = 93, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 94, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 }, .{ .regs = 58, .static = 0, .bound = 128 } } }, .{ .name = "glm_mm8_32", .usage = .{ .{ .regs = 128, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 }, .{ .regs = 126, .static = 0, .bound = 128 }, .{ .regs = 74, .static = 0, .bound = 128 }, .{ .regs = 74, .static = 0, .bound = 128 } } }, + .{ .name = "glm_vision vit vision_kernel<64, 8>", .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, .{ .name = "df_block_qkv", .usage = .{ .{ .regs = 32, .static = 8, .bound = 0 }, .{ .regs = 30, .static = 8, .bound = 0 }, .{ .regs = 30, .static = 8, .bound = 0 }, .{ .regs = 32, .static = 8, .bound = 0 }, .{ .regs = 32, .static = 8, .bound = 0 } } }, .{ .name = "df_ctx_kv", .usage = .{ .{ .regs = 30, .static = 8, .bound = 0 }, .{ .regs = 30, .static = 8, .bound = 0 }, .{ .regs = 30, .static = 8, .bound = 0 }, .{ .regs = 28, .static = 8, .bound = 0 }, .{ .regs = 28, .static = 8, .bound = 0 } } }, .{ .name = "df_top16_merge", .usage = .{ .{ .regs = 23, .static = 8416, .bound = 256 }, .{ .regs = 23, .static = 8416, .bound = 256 }, .{ .regs = 23, .static = 8416, .bound = 256 }, .{ .regs = 28, .static = 8416, .bound = 256 }, .{ .regs = 28, .static = 8416, .bound = 256 } } }, diff --git a/zig/src/families/glm/cuda_vision.zig b/zig/src/families/glm/cuda_vision.zig index d121194544f..c034213320c 100644 --- a/zig/src/families/glm/cuda_vision.zig +++ b/zig/src/families/glm/cuda_vision.zig @@ -176,12 +176,12 @@ pub const Tower = struct { }; var t: Tower = .{ .gpa = gpa, .d = d, .lt = try cuda.cublaslt.Library.open(), .mem = try weights.Weights.alloc(d, total, try weights.onHost()), .ql = ql, .inv_freq = try cuda.DeviceBuffer.alloc(d, 16 * 4), .linears = .init(gpa), .ws = undefined }; errdefer t.deinit(); + t.bytes = t.mem.deviceBytes(); + t.ws = try cuda.DeviceBuffer.alloc(d, t.ws_len); if (try attn.wanted()) { t.full = try cuda.vit.Attention.load(d); std.log.info("glm: the image tower's attention as vit's full attention (TF_GLM_VISION_FUSED)", .{}); } - t.bytes = t.mem.deviceBytes(); - t.ws = try cuda.DeviceBuffer.alloc(d, t.ws_len); var at: u64 = 0; var names = std.StringHashMap(u64).init(gpa); defer names.deinit(); diff --git a/zig/tests/cuda/contract_glm_vision.zig b/zig/tests/cuda/contract_glm_vision.zig index e693ebfc7d3..94aead30afe 100644 --- a/zig/tests/cuda/contract_glm_vision.zig +++ b/zig/tests/cuda/contract_glm_vision.zig @@ -185,6 +185,7 @@ pub const Set = struct { var ctl = try cuda.Module.load(gpu.d, &controls.bytes); errdefer ctl.unload(); set.* = .{ .gpa = gpu.gpa, .mod = mod, .ctl = ctl, .att = try cuda.vit.Attention.load(gpu.d) }; + errdefer set.att.unload(); const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; const f = try glm.vision.Funcs.load(mod); var broken = f; diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 19ce88cfbe4..ef642c2196b 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -46,7 +46,7 @@ zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) zig/kernels/cuda/nvfp4_experts.cu dc78d37c1eb1d9a9fff6c1ba9c5f0a9b0eb485a47a56e7b0b2fdbb8bbf1b223b raw #2266 (decode cp.async rings, GB10 SASS unchanged); #4493 (opt-in paired prompt experts, 128-row items) zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw -zig/kernels/cuda/prefill_attention.cu e4cb5bd5e4e9bf8157e5612b45f3dcf78ea31f4ab0822573da495c7aa63728d5.raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (GLM-5.3-Flash's image tower reuses the head-64 vision_kernel instance; existing instances unchanged) +zig/kernels/cuda/prefill_attention.cu e4cb5bd5e4e9bf8157e5612b45f3dcf78ea31f4ab0822573da495c7aa63728d5 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged); #3790 (GLM-5.3-Flash's image tower reuses the head-64 vision_kernel instance; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) zig/kernels/cuda/probe.cu 94a3118894b3066e0f0f6fc1cfc3c03828d291077cb26c437b62fcc9b177a210 raw glm-pdl-order's slow writer, planted early reader and glm_pdl::enter() reader zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt From 2353e8765f785e58a08d4a81abb37f1f33b9c371 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:02:28 +0000 Subject: [PATCH 125/361] changelog: #3790 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d89e930c547..5a8a8640d71 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 +- GLM-5.3-Flash on CUDA: `TF_GLM_VISION_FUSED=1` (off by default) runs the image tower's attention on the shared full-attention vision kernel instead of two cuBLASLt products around a softmax; its sums run in another order, so replies to prompts with images can differ from the default path, which is unchanged (#3790, refs #3614). Thanks to @ultradaoto. + - Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. - Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. From 240e92f491b1bb8cee7045b6ba550f2dceaaaf34 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:46 +0000 Subject: [PATCH 126/361] changelog: #1501's line from lines/1501.txt in place of its own --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a8a8640d71..f5c5134201f 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 +- Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. + - GLM-5.3-Flash on CUDA: `TF_GLM_VISION_FUSED=1` (off by default) runs the image tower's attention on the shared full-attention vision kernel instead of two cuBLASLt products around a softmax; its sums run in another order, so replies to prompts with images can differ from the default path, which is unchanged (#3790, refs #3614). Thanks to @ultradaoto. - Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. From af553f00c219d626831c16b5f65496a1ea2abf0b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:48 +0000 Subject: [PATCH 127/361] changelog: #4801 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5c5134201f..0e1a2c86c99 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 +- Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. + - Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. - GLM-5.3-Flash on CUDA: `TF_GLM_VISION_FUSED=1` (off by default) runs the image tower's attention on the shared full-attention vision kernel instead of two cuBLASLt products around a softmax; its sums run in another order, so replies to prompts with images can differ from the default path, which is unchanged (#3790, refs #3614). Thanks to @ultradaoto. From 878350109b0eda66ab6726ddb015a633cc013971 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:23:18 +0000 Subject: [PATCH 128/361] retain recent states through prompt cache flush --- docs/api.md | 20 +-- zig/src/core/lane_host_flush_test.zig | 169 ++++++++++++++++++++++++-- zig/src/core/rows_ask.zig | 41 ++++++- zig/src/server/cache_flush.zig | 35 +++++- zig/src/server/cache_flush_test.zig | 40 +++++- zig/src/server/routes.zig | 1 - 6 files changed, 279 insertions(+), 27 deletions(-) diff --git a/docs/api.md b/docs/api.md index c0c1c2f8b94..d92fc600065 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1742,15 +1742,17 @@ a proxied server keys. ## Flush the prompt cache `POST /v1/prompt_cache/flush` drops every prompt state the server keeps for resuming conversations: those in RAM, and -those on disk when it keeps them there (`--prompt-cache-disk DIR`, `--learn-conversations` or `--spill-gib`). It waits -for the requests already running to end, so their replies are unchanged, and requests that arrive meanwhile wait in the -queue and start after it. Then it answers 200 with `{"object": "prompt_cache.flush", "states": ..., "ram_bytes": ..., -"disk_bytes": ..., "disk": ..., "waited_seconds": ...}`: the states dropped from RAM and the bytes they held in the -cache's budget, the bytes deleted from the server's own state folder, whether this server keeps states on disk, and how -long the flush waited. The next turn of any conversation prefills its whole prompt and gives the tokens it would have -given resumed. Two flushes asked together run one after the other, and the second finds nothing left. States `--learn` -keeps for shared prompt prefixes stay on disk, as they do after `DELETE /v1/imprint`, so with `--learn` a later prompt -may still resume from one. The body, if any, is ignored. +those on disk when it keeps them there (`--prompt-cache-disk DIR`, `--learn-conversations` or `--spill-gib`). The JSON +body may contain `"retain": N`, a nonnegative 32-bit integer, to retain the N most recently used complete RAM states by +the cache's existing clock and their matching disk states instead. Other states and their disk bytes are dropped; `retain` +is zero by default, so an absent, empty or unrecognized body is still a full flush. It waits for the requests already +running to end, so their replies are unchanged, and requests that arrive meanwhile wait in the queue and start after it. +Then it answers 200 with `{"object": "prompt_cache.flush", "states": ..., "ram_bytes": ..., "disk_bytes": ..., "disk": +..., "waited_seconds": ...}`: the states dropped from RAM and the bytes they held in the cache's budget, the bytes deleted +from the server's own state folder, whether this server keeps states on disk, and how long the flush waited. After a full +flush the next turn prefills its whole prompt and gives the tokens it would have given resumed. Two flushes asked together +run one after the other. States `--learn` keeps for shared prompt prefixes stay on disk, as they do after +`DELETE /v1/imprint`, so with `--learn` a later prompt may still resume from one. An engine without the shared prompt cache (its cache turned off, or a backend that keeps its states its own way) answers 501 `not_supported` at once and holds nothing back. If the running requests have not ended within 10 minutes, diff --git a/zig/src/core/lane_host_flush_test.zig b/zig/src/core/lane_host_flush_test.zig index db871d6db08..58cb841b24b 100644 --- a/zig/src/core/lane_host_flush_test.zig +++ b/zig/src/core/lane_host_flush_test.zig @@ -1,5 +1,6 @@ //! A prompt-cache flush drops every kept state once the requests in flight end; a later turn prefills cold. const std = @import("std"); +const fixture = @import("rows_async_fixture.zig"); const lanes = @import("lanes"); const api = @import("engine_api.zig"); const pc = @import("prompt_cache.zig"); @@ -32,6 +33,7 @@ const Snaps = struct { const Box = struct { mutex: std.Io.Mutex = .init, tokens: std.ArrayList(u32) = .empty, + logprobs: std.ArrayList(api.LogprobRow) = .empty, cached: ?u32 = null, done: ?Reason = null, ended: std.atomic.Value(bool) = .init(false), @@ -51,7 +53,8 @@ const Box = struct { b.flushed_at_prefill = answered; b.peer_ended_at_prefill = if (b.peer) |p| p.ended.load(.acquire) else null; }, - .logprobs, .prompt_logprobs, .audio => {}, + .logprobs => |rows| b.logprobs.appendSlice(gpa, rows) catch @panic("OOM"), + .prompt_logprobs, .audio => {}, .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, .finished => |f| { b.done = f.reason; @@ -138,11 +141,31 @@ fn run(e: api.Engine, id: Id, r: *const Request) !struct { tokens: std.ArrayList return .{ .tokens = b.tokens, .cached = b.cached }; } +const Exact = struct { + tokens: std.ArrayList(u32), + logprobs: std.ArrayList(api.LogprobRow), + cached: ?u32, + + fn deinit(x: *Exact) void { + x.tokens.deinit(gpa); + x.logprobs.deinit(gpa); + } +}; + +fn exact(e: api.Engine, id: Id, r: *const Request) !Exact { + var b: Box = .{}; + var request = r.*; + request.logprobs = 3; + try e.submit(id, &request, .{ .ctx = &b, .event = Box.event }); + try std.testing.expectEqual(Reason.length, try b.wait()); + return .{ .tokens = b.tokens, .logprobs = b.logprobs, .cached = b.cached }; +} + const t1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 }; -/// The next turn after `t1` and its reply `first`: the history, four reply tokens, a tool result, a new prompt. -fn nextTurn(first: []const u32) ![]u32 { - return std.mem.concat(gpa, u32, &.{ &t1, first[0..4], &.{ 7, 7, 5, 3 } }); +/// The next turn after the initial prompt and its reply `first`. +fn nextTurn(first: []const u32, base: []const u32) ![]u32 { + return std.mem.concat(gpa, u32, &.{ base, first[0..4], &.{ 7, 7, 5, 3 } }); } /// Two turns of one conversation, the second resumed from the first's kept state; its request and tokens. @@ -160,17 +183,23 @@ const Warm = struct { } }; -fn warm(e: api.Engine) !Warm { - var first = try run(e, 1, &.{ .prompt = &t1, .max_tokens = 6, .history_len = 8 }); +fn warmAt(e: api.Engine, salt: u32) !Warm { + var base = t1; + base[0] += salt; + var first = try run(e, 1, &.{ .prompt = &base, .max_tokens = 6, .history_len = 8 }); errdefer first.tokens.deinit(gpa); - const prompt = try nextTurn(first.tokens.items); + const prompt = try nextTurn(first.tokens.items, &base); errdefer gpa.free(prompt); const r: Request = .{ .prompt = prompt, .max_tokens = 12, .history_len = @intCast(prompt.len - 2) }; const second = try run(e, 2, &r); - try std.testing.expectEqual(@as(?u32, 8), second.cached); // resumed from the first turn's kept state + try std.testing.expectEqual(@as(?u32, 8), second.cached); return .{ .first = first.tokens, .prompt = prompt, .second = second.tokens }; } +fn warm(e: api.Engine) !Warm { + return warmAt(e, 0); +} + test "prompt cache flush: every kept state goes, and the resumed turn then prefills cold with the same tokens" { var r = try rig(); try r.start(true); @@ -197,6 +226,98 @@ test "prompt cache flush: every kept state goes, and the resumed turn then prefi try std.testing.expectEqualSlices(u32, w.second.items, cold.tokens.items); } +fn expectReplay(w: *const Warm, want: *const Exact, got: *const Exact, cached: ?u32) !void { + try std.testing.expectEqual(cached, got.cached); + try std.testing.expectEqualSlices(u32, w.second.items, got.tokens.items); + try std.testing.expectEqual(want.logprobs.items.len, got.logprobs.items.len); + for (want.logprobs.items, got.logprobs.items) |a, b| { + try std.testing.expectEqual(a.token, b.token); + try std.testing.expectEqual(a.logprob, b.logprob); + try std.testing.expectEqualSlices(u32, a.ids[0..a.count], b.ids[0..b.count]); + try std.testing.expectEqualSlices(f32, a.logprobs[0..a.count], b.logprobs[0..b.count]); + } +} + +test "prompt cache flush: retain one resumes exactly and drops the other RAM state" { + var r = try rig(); + try r.start(true); + defer r.deinit(); + const e = r.engine(); + var w0 = try warmAt(e, 0); + defer w0.deinit(); + var w1 = try warmAt(e, 20); + defer w1.deinit(); + var w2 = try warmAt(e, 40); + defer w2.deinit(); + while (r.store.entries.items.len > 3) { + var removed = false; + for (r.store.entries.items, 0..) |entry, i| { + if (entry.at == 8) { + r.store.remove(i); + removed = true; + break; + } + } + try std.testing.expect(removed); + } + try std.testing.expectEqual(@as(usize, 3), r.store.entries.items.len); + var b0 = try exact(e, 10, &w0.request()); + defer b0.deinit(); + var b1 = try exact(e, 11, &w1.request()); + defer b1.deinit(); + var b2 = try exact(e, 12, &w2.request()); + defer b2.deinit(); + const retained = r.store.find(w2.prompt, &.{}, &.{}) orelse return error.MissingState; + try std.testing.expectEqual(@as(usize, 3), r.store.entries.items.len); + const held = r.store.held; + var ask: api.ImprintAsk = .{ .op = .flush, .retain = 1 }; + ask.answer(&r.store, .{}); + try std.testing.expectEqual(@as(usize, 2), ask.dropped); + try std.testing.expectEqual(@as(usize, 1), r.store.entries.items.len); + try std.testing.expectEqual(retained.bytes, r.store.held); + try std.testing.expectEqual(held - retained.bytes, ask.ram_freed); + try std.testing.expect(r.store.find(w0.prompt, &.{}, &.{}) == null); + try std.testing.expect(r.store.find(w1.prompt, &.{}, &.{}) == null); + try std.testing.expect(r.store.find(w2.prompt, &.{}, &.{}) == retained); + var hit = try exact(e, 20, &w2.request()); + defer hit.deinit(); + try expectReplay(&w2, &b2, &hit, retained.at); + var cold0 = try exact(e, 21, &w0.request()); + defer cold0.deinit(); + try expectReplay(&w0, &b0, &cold0, 0); + var cold1 = try exact(e, 22, &w1.request()); + defer cold1.deinit(); + try expectReplay(&w1, &b1, &cold1, 0); +} + +test "prompt cache flush: retain one removes only the other two disk states" { + const x = try fixture.Fixture.open("flush-retain", .off, true, 1 << 20); + defer x.close(); + const p0 = fixture.prompt(70); + const p1 = fixture.prompt(71); + const p2 = fixture.prompt(72); + for ([_]*const [1100]u32{ &p0, &p1, &p2 }, 0..) |p, i| try x.keep(p, @intCast(300 + i * 300)); + try x.idle(3); + try std.testing.expectEqual(@as(usize, 3), x.s.entries.items.len); + try std.testing.expectEqual(@as(usize, 3), x.r.states.items.len); + const kept_disk = x.r.states.items[x.r.best(&p2, &.{}, &.{}, 0).?].own + x.r.states.items[x.r.best(&p2, &.{}, &.{}, 0).?].rows; + const held_ram = x.s.held; + const held_disk = x.r.held(); + const kept_ram = x.s.entries.items[2].bytes; + var ask: api.ImprintAsk = .{ .op = .flush, .retain = 1 }; + ask.answer(&x.s, .{}); + try std.testing.expectEqual(@as(usize, 2), ask.dropped); + try std.testing.expectEqual(held_ram - kept_ram, ask.ram_freed); + try std.testing.expectEqual(kept_ram, x.s.held); + try std.testing.expectEqual(held_disk - kept_disk, ask.freed); + try std.testing.expectEqual(kept_disk, x.r.held()); + try std.testing.expectEqual(@as(usize, 1), x.s.entries.items.len); + try std.testing.expectEqual(@as(usize, 1), x.r.states.items.len); + try std.testing.expect(x.r.best(&p0, &.{}, &.{}, 0) == null); + try std.testing.expect(x.r.best(&p1, &.{}, &.{}, 0) == null); + try std.testing.expect(x.r.best(&p2, &.{}, &.{}, 0) != null); +} + test "prompt cache flush: a request in flight finishes unchanged and the flush answers after it; arrivals wait" { var r = try rig(); try r.start(true); @@ -234,6 +355,38 @@ test "prompt cache flush: a request in flight finishes unchanged and the flush a try std.testing.expectEqualSlices(u32, w.second.items, later.tokens.items); } +test "prompt cache flush: retain one while the newest conversation is in flight" { + var r = try rig(); + try r.start(true); + defer r.deinit(); + const e = r.engine(); + var w = try warm(e); + defer w.deinit(); + var ask: api.ImprintAsk = .{ .op = .flush, .retain = 1 }; + const req = w.request(); + r.gate.armed.store(true, .release); + var b: Box = .{ .flush = &ask }; + defer b.tokens.deinit(gpa); + try e.submit(3, &req, .{ .ctx = &b, .event = Box.event }); + try r.gate.entered(); + try std.testing.expect(e.imprintAsk(&ask)); + var later: Box = .{ .flush = &ask }; + defer later.tokens.deinit(gpa); + try e.submit(4, &req, .{ .ctx = &later, .event = Box.event }); + r.gate.open.store(true, .release); + try std.testing.expect(ask.wait(io, 5000)); + try std.testing.expectEqual(Reason.length, try b.wait()); + try std.testing.expectEqual(@as(?bool, false), b.flushed_at_end); + try std.testing.expect(b.cached.? > 0); + try std.testing.expectEqualSlices(u32, w.second.items, b.tokens.items); + try std.testing.expectEqual(@as(u32, 1), ask.dropped); + try std.testing.expectEqual(Reason.length, try later.wait()); + try std.testing.expectEqual(@as(?bool, true), later.flushed_at_prefill); + try std.testing.expect(later.cached.? > 0); + try std.testing.expectEqualSlices(u32, w.second.items, later.tokens.items); + try std.testing.expectEqual(@as(usize, 1), r.store.entries.items.len); +} + test "prompt cache flush: a withdrawn flush releases the hold at once and drops nothing" { var r = try rig(); try r.start(true); diff --git a/zig/src/core/rows_ask.zig b/zig/src/core/rows_ask.zig index 77873afaac8..47ace3a7d78 100644 --- a/zig/src/core/rows_ask.zig +++ b/zig/src/core/rows_ask.zig @@ -15,6 +15,7 @@ pub const Claim = enum(u8) { queued, taken, withdrawn }; /// One question: a rendered conversation (its tokens, chunk starts and decoded spans), and the answer once `done`. pub const Ask = struct { op: Op, + retain: u32 = 0, prompt: []const u32 = &.{}, starts: []const u32 = &.{}, spans: []const [2]u32 = &.{}, @@ -71,11 +72,45 @@ pub const Ask = struct { } }; -/// Every kept state dropped and the store's plans reset, as on a fresh store; then its states on disk deleted. +fn newer(a: *const pc.Entry, b: *const pc.Entry) bool { + return a.used > b.used or (a.used == b.used and a.serial > b.serial); +} + +fn forgetExcept(r: *@import("rows_store.zig").Rows, entries: []const *pc.Entry) u64 { + const before = r.held(); + var i = r.states.items.len; + while (i > 0) { + i -= 1; + const s = &r.states.items[i]; + var kept = false; + for (entries) |e| { + if (e.expired or e.salt != null) continue; + if (r.matches(s, e.tokens, &.{}, e.decode_spans)) { + kept = true; + break; + } + } + if (!kept) r.remove(i); + } + return before - r.held(); +} + +/// Every state except the newest `retain` complete states dropped, with their Rows disk states; the plans reset. fn flush(a: *Ask, s: *pc.Store) void { const n = s.entries.items.len; const bytes = s.held; - for (s.entries.items) |e| e.expired = true; // expired first: nothing is staged for disk on its way out + var cutoff: ?*pc.Entry = null; + for (0..a.retain) |_| { + var best: ?*pc.Entry = null; + for (s.entries.items) |e| { + if (e.expired or (cutoff != null and !newer(cutoff.?, e))) continue; + if (best == null or newer(e, best.?)) best = e; + } + cutoff = best orelse break; + } + for (s.entries.items) |e| { + if (a.retain == 0 or (cutoff != null and newer(cutoff.?, e))) e.expired = true; // expired first: nothing is staged on its way out + } s.collectExpired(); // a borrowed one (none while no request is in flight) goes when its lookup ends a.dropped = @intCast(n - s.entries.items.len); a.ram_freed = bytes - s.held; @@ -83,7 +118,7 @@ fn flush(a: *Ask, s: *pc.Store) void { s.repeat_log.keys.clearRetainingCapacity(); s.active_rewind_at = 0; s.active_rewind_key = 0; - if (s.disk) |r| a.freed = r.forgetAll(); // the store's own folder and names: DELETE /v1/imprint's call + if (s.disk) |r| a.freed = if (a.retain == 0) r.forgetAll() else forgetExcept(r, s.entries.items); // the store's own folder and names } /// A host's side of disk states: the asks waiting for its engine thread, and when the engine last went quiet. diff --git a/zig/src/server/cache_flush.zig b/zig/src/server/cache_flush.zig index 2ba1edc3038..88fa5da9b41 100644 --- a/zig/src/server/cache_flush.zig +++ b/zig/src/server/cache_flush.zig @@ -1,4 +1,4 @@ -//! POST /v1/prompt_cache/flush: every kept prompt state dropped, in RAM and on disk, after the requests in flight end. +//! POST /v1/prompt_cache/flush: full by default, or retain the newest states after active requests end. const std = @import("std"); const api = @import("engine_api"); const json = @import("json"); @@ -9,6 +9,7 @@ const Server = @import("server.zig").Server; const Conn = @import("http_conn.zig").Conn; const Allocator = std.mem.Allocator; const Ask = api.ImprintAsk; +const http_body = @import("http_body.zig"); pub const path = "/v1/prompt_cache/flush"; @@ -19,9 +20,14 @@ pub const Reply = struct { status: u16, body: json.Value }; /// The flush asked of `engine` and waited for: 200 with what it dropped, 501 where no store keeps states, else 503. pub fn answer(gpa: Allocator, io: std.Io, a: Allocator, engine: api.Engine, ms: u32) !Reply { + return answerRetaining(gpa, io, a, engine, ms, 0); +} + +/// A full flush at `retain == 0`; otherwise retain that many newest complete states on the store's existing clock. +pub fn answerRetaining(gpa: Allocator, io: std.Io, a: Allocator, engine: api.Engine, ms: u32, retain: u32) !Reply { // the ask lives in the server's memory: once the engine holds it past a 503, it leaks rather than be freed under it const ask = try gpa.create(Ask); - ask.* = .{ .op = .flush }; + ask.* = .{ .op = .flush, .retain = retain }; const t0 = std.Io.Clock.awake.now(io); if (!engine.imprintAsk(ask)) { gpa.destroy(ask); @@ -57,8 +63,23 @@ fn failure(a: Allocator, message: []const u8, kind: []const u8, code: []const u8 return .{ .object = o }; } +fn retainFromBody(a: Allocator, raw: []const u8) (Allocator.Error || error{InvalidRetain})!u32 { + if (raw.len == 0) return 0; + const parsed = try json.parse(a, raw); + const body = switch (parsed) { + .ok => |v| v, + .err => return 0, // a body without usable retain JSON remains the old full flush + }; + if (body != .object) return 0; + const field = body.get("retain") orelse return 0; + if (field != .int) return error.InvalidRetain; + const n = field.int64() orelse return error.InvalidRetain; + if (n < 0 or n > std.math.maxInt(u32)) return error.InvalidRetain; + return @intCast(n); +} /// POST /v1/prompt_cache/flush under the request cancel route's rule: an admin key, or a direct loopback caller. pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { + const body = http_body.read(conn, a, http_body.limit) catch return conn.sendError(a, 500, "out of memory", null) catch {}; const keyed = if (srv.keys) |k| k.enabled() else false; if (!cancel_ids.allowed(keyed, conn)) { if (keyed) return @import("auth_scope_reply.zig").deny(conn, false, .route); @@ -73,7 +94,15 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { const message = "the model is unloaded: no state is in RAM, and those on disk stay until a flush while it is loaded"; return routes.sendValue(conn, a, 503, failure(a, message, "server_error", "model_unloaded") catch return); }; - const got = answer(srv.gpa, srv.io, a, srv.engine, wait_ms) catch return conn.sendError(a, 500, "out of memory", null) catch {}; + const raw = switch (body) { + .ok => |b| b, + .refused => |message| return routes.sendValue(conn, a, 400, failure(a, message, "invalid_request_error", "invalid_request_error") catch return), + }; + const retain = retainFromBody(a, raw) catch |err| switch (err) { + error.OutOfMemory => return conn.sendError(a, 500, "out of memory", null) catch {}, + error.InvalidRetain => return routes.sendValue(conn, a, 400, failure(a, "retain must be a nonnegative 32-bit integer", "invalid_request_error", "invalid_request_error") catch return), + }; + const got = answerRetaining(srv.gpa, srv.io, a, srv.engine, wait_ms, retain) catch return conn.sendError(a, 500, "out of memory", null) catch {}; routes.sendValue(conn, a, got.status, got.body); } diff --git a/zig/src/server/cache_flush_test.zig b/zig/src/server/cache_flush_test.zig index ff124f58eaa..503aa455c12 100644 --- a/zig/src/server/cache_flush_test.zig +++ b/zig/src/server/cache_flush_test.zig @@ -18,6 +18,7 @@ const Engine = struct { answers: bool = true, takes: bool = false, // with `answers` false: taken by the engine thread, so its caller cannot withdraw it held: ?*Ask = null, + retain_seen: u32 = 0, fn engine(e: *Engine) api.Engine { return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory, .imprint = imprint } }; } @@ -27,6 +28,7 @@ const Engine = struct { fn imprint(ctx: *anyopaque, ask: *Ask) bool { const e: *Engine = @ptrCast(@alignCast(ctx)); e.asks += 1; + e.retain_seen = ask.retain; if (!e.answers) { if (e.takes) ask.claim.store(.taken, .release); e.held = ask; @@ -69,13 +71,14 @@ const Wire = struct { } }; -const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full }; +const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full, body: []const u8 = "{}" }; /// One flush through the dispatcher, as the connection thread hands it over after the key gate; status and body. fn call(srv: *Server, a: Allocator, c: Caller) !struct { status: u16, body: json.Value } { var wire: Wire = .{ .a = a }; - const headers = try std.mem.concat(a, http.Header, &.{ &.{.{ .name = "Content-Length", .value = "2" }}, c.headers }); - var conn: http.Conn = .{ .fd = -1, .peer = c.peer, .buf = try a.dupe(u8, "{}"), .end = 2, .gpa = a, .version = "HTTP/1.1", .method = "POST", .path = flush.path, .headers = headers, .write_hooks = .{ .ctx = &wire, .write = Wire.write }, .key_label = c.key, .key_scopes = c.scopes }; + const length = try std.fmt.allocPrint(a, "{d}", .{c.body.len}); + const headers = try std.mem.concat(a, http.Header, &.{ &.{.{ .name = "Content-Length", .value = length }}, c.headers }); + var conn: http.Conn = .{ .fd = -1, .peer = c.peer, .buf = try a.dupe(u8, c.body), .end = c.body.len, .gpa = a, .version = "HTTP/1.1", .method = "POST", .path = flush.path, .headers = headers, .write_hooks = .{ .ctx = &wire, .write = Wire.write }, .key_label = c.key, .key_scopes = c.scopes }; routes.dispatch(srv, &conn, a); const out = wire.bytes.items; const at = std.mem.indexOf(u8, out, "\r\n\r\n") orelse return error.MissingHttpHead; @@ -167,6 +170,37 @@ test "prompt cache flush: 501 where no store keeps states, and a 503 whose flush try t.expect(std.mem.indexOf(u8, taken.body.get("error").?.strField("message").?, "withdrawn") == null); } +test "prompt cache flush: the body retains explicitly, while absent and unrecognized bodies still flush all" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var e: Engine = .{}; + const srv = try serve(e.engine(), null); + defer srv.deinit(); + for ([_]struct { body: []const u8, retain: u32 }{ + .{ .body = "{}", .retain = 0 }, + .{ .body = "", .retain = 0 }, + .{ .body = "not JSON", .retain = 0 }, + .{ .body = "[]", .retain = 0 }, + .{ .body = "{\"unrelated\":1}", .retain = 0 }, + .{ .body = "{\"retain\":0}", .retain = 0 }, + .{ .body = "{\"retain\":2}", .retain = 2 }, + .{ .body = "{\"retain\":1,\"unrelated\":true}", .retain = 1 }, + }) |c| { + const before = e.asks; + const got = try call(srv, a, .{ .body = c.body }); + try t.expectEqual(@as(u16, 200), got.status); + try t.expectEqual(before + 1, e.asks); + try t.expectEqual(c.retain, e.retain_seen); + } + for ([_][]const u8{ "{\"retain\":-1}", "{\"retain\":1.5}", "{\"retain\":\"1\"}", "{\"retain\":4294967296}" }) |body| { + const before = e.asks; + const got = try call(srv, a, .{ .body = body }); + try t.expectEqual(@as(u16, 400), got.status); + try t.expectEqual(before, e.asks); + } +} + test "prompt cache flush: a model --idle-unload parked answers 503 unloaded, neither asked nor woken" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); diff --git a/zig/src/server/routes.zig b/zig/src/server/routes.zig index e07e65b0033..74e13ff95b7 100644 --- a/zig/src/server/routes.zig +++ b/zig/src/server/routes.zig @@ -139,7 +139,6 @@ fn post(srv: *Server, conn: *Conn, a: Allocator) void { return @import("responses_background.zig").cancel(srv, conn, a, rid); } if (std.mem.eql(u8, route, flush.path)) { // an admin action outside admission: it waits for requests, holding no slot - discardBody(conn, a); return flush.post(srv, conn, a); } for (tokens.paths) |r| if (std.mem.eql(u8, route, r)) return tokens.post(srv, conn, a, route); From 6db2eaa9d304adeed6d92b487d81995d8701e6f8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:42:32 +0000 Subject: [PATCH 129/361] prompt cache flush: a partial flush keeps exactly the retained states' disk states A retain count above zero chose disk states with the resume predicate, which accepts any state whose tokens are a proper prefix of a retained entry's: a shorter state on the retained conversation's own path survived, while the retained entry's own state was deleted with no lookahead (its position equals its token count) and under planned chunk starts (empty starts never match a recorded schedule). A disk state now stays only when it is a retained entry's own: the same position, tokens and decoded spans. A dropped entry's write already staged on the I/O worker owns no entry, and the flush fenced the writer only when it removed a published state, so such a write could publish afterwards. The flush now fences whenever a staged write is not a retained entry's own. A retain count of zero still takes the full flush unchanged. --- zig/src/core/lane_host_tests.zig | 1 + zig/src/core/rows_ask.zig | 30 +++++++---- zig/src/core/rows_async_fixture.zig | 11 ++-- zig/src/core/rows_flush_retain_test.zig | 68 +++++++++++++++++++++++++ 4 files changed, 97 insertions(+), 13 deletions(-) create mode 100644 zig/src/core/rows_flush_retain_test.zig diff --git a/zig/src/core/lane_host_tests.zig b/zig/src/core/lane_host_tests.zig index 207204e8188..df277bcdab0 100644 --- a/zig/src/core/lane_host_tests.zig +++ b/zig/src/core/lane_host_tests.zig @@ -35,6 +35,7 @@ test { test { _ = @import("lane_activity_test.zig"); _ = @import("lane_host_flush_test.zig"); + _ = @import("rows_flush_retain_test.zig"); } test { diff --git a/zig/src/core/rows_ask.zig b/zig/src/core/rows_ask.zig index 47ace3a7d78..afbed834a0c 100644 --- a/zig/src/core/rows_ask.zig +++ b/zig/src/core/rows_ask.zig @@ -2,6 +2,7 @@ const std = @import("std"); const pc = @import("prompt_cache.zig"); const rows = pc.rows; +const modes = @import("cache_modes.zig"); /// flush: every kept state dropped, in RAM and on disk, once no request is in flight (a waiting one holds admissions). pub const Op = enum { where, load, forget, flush }; @@ -76,21 +77,30 @@ fn newer(a: *const pc.Entry, b: *const pc.Entry) bool { return a.used > b.used or (a.used == b.used and a.serial > b.serial); } -fn forgetExcept(r: *@import("rows_store.zig").Rows, entries: []const *pc.Entry) u64 { +/// Whether a disk state or staged write is a kept entry's own: the same position, tokens and decoded spans. +fn ownOf(entries: []const *pc.Entry, at: u32, tokens: []const u32, spans: []const modes.Span) bool { + for (entries) |e| { + if (e.expired or e.salt != null or e.at != at or !std.mem.eql(u32, e.tokens, tokens)) continue; + if (modes.equal(e.decode_spans, spans, at)) return true; + } + return false; +} + +fn forgetExcept(r: *rows.Rows, entries: []const *pc.Entry) u64 { const before = r.held(); + if (r.worker) |w| { + var jobs: [rows.write.io.max_jobs]?*rows.write.io.Job = undefined; + w.cancellations(&jobs); + for (jobs) |job| if (job) |j| if (!ownOf(entries, j.at, j.tokens, j.spans)) { + rows.write.fence(r); // a dropped entry's staged write must not publish; ones not yet staged went with it + break; + }; + } var i = r.states.items.len; while (i > 0) { i -= 1; const s = &r.states.items[i]; - var kept = false; - for (entries) |e| { - if (e.expired or e.salt != null) continue; - if (r.matches(s, e.tokens, &.{}, e.decode_spans)) { - kept = true; - break; - } - } - if (!kept) r.remove(i); + if (!ownOf(entries, s.at, s.tokens, s.spans)) r.remove(i); } return before - r.held(); } diff --git a/zig/src/core/rows_async_fixture.zig b/zig/src/core/rows_async_fixture.zig index 12993528f7e..601017327e7 100644 --- a/zig/src/core/rows_async_fixture.zig +++ b/zig/src/core/rows_async_fixture.zig @@ -20,14 +20,19 @@ pub const Fixture = struct { /// A store whose permit also takes one state of `longest` tokens whole (rows.Options.longest). pub fn sized(tag: []const u8, spill: rows.Spill, synchronous: bool, limit: u64, longest: u32) !*Fixture { + return keyed(tag, spill, synchronous, limit, longest, 1, false); + } + + /// A store keeping `lookahead` tokens past each state; `planned`: keyed by its chunk starts (`f.starts`). + pub fn keyed(tag: []const u8, spill: rows.Spill, synchronous: bool, limit: u64, longest: u32, lookahead: u32, planned: bool) !*Fixture { const x = try a.create(Fixture); errdefer a.destroy(x); const tmp = if (platform.c.getenv("TMPDIR")) |p| std.mem.span(p) else "."; const root = try std.fmt.allocPrint(a, "{s}/tf-rows-{s}-{d}", .{ tmp, tag, platform.c.getpid() }); errdefer a.free(root); - x.* = .{ .root = root, .f = .{ .gpa = a }, .s = undefined, .r = undefined }; - x.s = pc.Store.init(a, x.f.snapshots(), .{ .lookahead = 1, .min_prompt = 0, .min_gap = 1 }, 1 << 30); - x.r = try rows.attach(a, &x.s, .{ .root = root, .identity = 7, .cap = 1 << 30, .floor = 0, .daily = 1 << 30, .lookahead = 1, .spill = spill, .sync_writes = synchronous, .staging_bytes = limit, .longest = longest }); + x.* = .{ .root = root, .f = .{ .gpa = a, .planned = planned }, .s = undefined, .r = undefined }; + x.s = pc.Store.init(a, x.f.snapshots(), .{ .lookahead = lookahead, .min_prompt = 0, .min_gap = 1, .planned = planned }, 1 << 30); + x.r = try rows.attach(a, &x.s, .{ .root = root, .identity = 7, .cap = 1 << 30, .floor = 0, .daily = 1 << 30, .lookahead = lookahead, .planned = planned, .spill = spill, .sync_writes = synchronous, .staging_bytes = limit, .longest = longest }); return x; } diff --git a/zig/src/core/rows_flush_retain_test.zig b/zig/src/core/rows_flush_retain_test.zig new file mode 100644 index 00000000000..b00d6800f1b --- /dev/null +++ b/zig/src/core/rows_flush_retain_test.zig @@ -0,0 +1,68 @@ +//! A partial flush keeps on disk only the retained states' own disk states; no dropped state's write publishes. +const std = @import("std"); +const fixture = @import("rows_async_fixture.zig"); +const api = @import("engine_api.zig"); + +/// The newest of `prompts` kept at `ats` survives a retain-one flush alone, on disk and in the store's folder. +fn retainNewest(x: *fixture.Fixture, prompts: []const *const [1100]u32, ats: []const u32) !void { + for (prompts, ats) |p, at| try x.keep(p, at); + try x.idle(prompts.len); + try std.testing.expectEqual(prompts.len, x.s.entries.items.len); + try std.testing.expectEqual(prompts.len, x.r.states.items.len); + const last = ats[ats.len - 1]; + var kept_disk: u64 = 0; + for (x.r.states.items) |s| if (s.at == last) { + kept_disk = s.own + s.rows; + }; + const held_disk = x.r.held(); + var ask: api.ImprintAsk = .{ .op = .flush, .retain = 1 }; + ask.answer(&x.s, .{}); + try std.testing.expectEqual(@as(usize, 1), x.s.entries.items.len); + try std.testing.expectEqual(@as(usize, 1), x.r.states.items.len); + try std.testing.expectEqual(last, x.r.states.items[0].at); + try std.testing.expectEqualSlices(u32, x.s.entries.items[0].tokens, x.r.states.items[0].tokens); + try std.testing.expectEqual(held_disk - kept_disk, ask.freed); + try std.testing.expectEqual(kept_disk, x.r.held()); + try std.testing.expectEqual(@as(usize, 1), fixture.files(x.r.dir, ".st")); // what a restart reads back +} + +test "prompt cache flush: retain one drops a shorter disk state on the retained state's own path" { + const x = try fixture.Fixture.open("flush-prefix", .off, true, 1 << 20); + defer x.close(); + const p = fixture.prompt(80); + try retainNewest(x, &.{ &p, &p }, &.{ 300, 600 }); +} + +test "prompt cache flush: retain one keeps the retained state's disk state with no lookahead" { + const x = try fixture.Fixture.keyed("flush-ahead0", .off, true, 1 << 20, 0, 0, false); + defer x.close(); + const p0 = fixture.prompt(81); + const p1 = fixture.prompt(82); + try retainNewest(x, &.{ &p0, &p1 }, &.{ 300, 600 }); +} + +test "prompt cache flush: retain one keeps the retained state's disk state under its planned chunk starts" { + const x = try fixture.Fixture.keyed("flush-planned", .off, true, 1 << 20, 0, 1, true); + defer x.close(); + x.f.starts = &.{ 150, 300, 450, 600 }; + const p0 = fixture.prompt(83); + const p1 = fixture.prompt(84); + try retainNewest(x, &.{ &p0, &p1 }, &.{ 300, 600 }); +} + +test "prompt cache flush: retain one stops a dropped state's staged write from publishing" { + const x = try fixture.Fixture.open("flush-staged", .off, false, 1 << 30); + defer x.close(); + const p0 = fixture.prompt(85); + const p1 = fixture.prompt(86); + try x.keep(&p0, 300); // staged on the writer; published only when the engine reaps it + try std.testing.expectEqual(@as(usize, 0), x.r.states.items.len); + try x.keep(&p1, 600); + var ask: api.ImprintAsk = .{ .op = .flush, .retain = 1 }; + ask.answer(&x.s, .{}); + try std.testing.expectEqual(@as(usize, 1), x.s.entries.items.len); + try std.testing.expectEqual(@as(u32, 600), x.s.entries.items[0].at); + try x.settle(); + for (x.r.states.items) |s| try std.testing.expect(s.at != 300); + try std.testing.expect(x.r.best(&p0, &.{}, &.{}, 0) == null); +} From 3f3b97173025eb503e5d84c065c966f226709366 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:12:43 +0000 Subject: [PATCH 130/361] prompt cache flush: a body that is not read, or is refused, keeps main's full flush Main read the flush route's body and dropped it, whatever its framing, and then flushed every state with a 200 reply. The retention change answered a refused body (one past the 32 MiB limit, an invalid or short length, or a length beside a transfer coding) with a 400 and flushed nothing, and a failed read with a 500. Such a body now means no retention, as on main: the full flush with its usual reply, and the connection still closes after a refused body as before. When a readable body's JSON cannot be parsed for lack of memory, a body that cannot name retain is the full flush too. Only a body that names retain takes the new path; a retain value that is present but not a nonnegative 32-bit integer is still refused with a 400. --- zig/src/server/cache_flush.zig | 15 ++++++++----- zig/src/server/cache_flush_test.zig | 35 +++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/zig/src/server/cache_flush.zig b/zig/src/server/cache_flush.zig index 88fa5da9b41..ffadc031221 100644 --- a/zig/src/server/cache_flush.zig +++ b/zig/src/server/cache_flush.zig @@ -79,7 +79,11 @@ fn retainFromBody(a: Allocator, raw: []const u8) (Allocator.Error || error{Inval } /// POST /v1/prompt_cache/flush under the request cancel route's rule: an admin key, or a direct loopback caller. pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { - const body = http_body.read(conn, a, http_body.limit) catch return conn.sendError(a, 500, "out of memory", null) catch {}; + // main read and dropped the body here and flushed all: a body not read, or refused, is still that full flush + const raw: []const u8 = if (http_body.read(conn, a, http_body.limit)) |body| switch (body) { + .ok => |b| b, + .refused => "", + } else |_| ""; const keyed = if (srv.keys) |k| k.enabled() else false; if (!cancel_ids.allowed(keyed, conn)) { if (keyed) return @import("auth_scope_reply.zig").deny(conn, false, .route); @@ -94,12 +98,11 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { const message = "the model is unloaded: no state is in RAM, and those on disk stay until a flush while it is loaded"; return routes.sendValue(conn, a, 503, failure(a, message, "server_error", "model_unloaded") catch return); }; - const raw = switch (body) { - .ok => |b| b, - .refused => |message| return routes.sendValue(conn, a, 400, failure(a, message, "invalid_request_error", "invalid_request_error") catch return), - }; const retain = retainFromBody(a, raw) catch |err| switch (err) { - error.OutOfMemory => return conn.sendError(a, 500, "out of memory", null) catch {}, + // a body that cannot name retain (raw or escaped) is main's full flush even when its JSON cannot be read + error.OutOfMemory => if (std.mem.indexOf(u8, raw, "retain") == null and std.mem.indexOfScalar(u8, raw, '\\') == null) 0 else { + return conn.sendError(a, 500, "out of memory", null) catch {}; + }, error.InvalidRetain => return routes.sendValue(conn, a, 400, failure(a, "retain must be a nonnegative 32-bit integer", "invalid_request_error", "invalid_request_error") catch return), }; const got = answerRetaining(srv.gpa, srv.io, a, srv.engine, wait_ms, retain) catch return conn.sendError(a, 500, "out of memory", null) catch {}; diff --git a/zig/src/server/cache_flush_test.zig b/zig/src/server/cache_flush_test.zig index 503aa455c12..f51f257cb94 100644 --- a/zig/src/server/cache_flush_test.zig +++ b/zig/src/server/cache_flush_test.zig @@ -71,12 +71,12 @@ const Wire = struct { } }; -const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full, body: []const u8 = "{}" }; +const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full, body: []const u8 = "{}", length: ?[]const u8 = null }; /// One flush through the dispatcher, as the connection thread hands it over after the key gate; status and body. fn call(srv: *Server, a: Allocator, c: Caller) !struct { status: u16, body: json.Value } { var wire: Wire = .{ .a = a }; - const length = try std.fmt.allocPrint(a, "{d}", .{c.body.len}); + const length = c.length orelse try std.fmt.allocPrint(a, "{d}", .{c.body.len}); const headers = try std.mem.concat(a, http.Header, &.{ &.{.{ .name = "Content-Length", .value = length }}, c.headers }); var conn: http.Conn = .{ .fd = -1, .peer = c.peer, .buf = try a.dupe(u8, c.body), .end = c.body.len, .gpa = a, .version = "HTTP/1.1", .method = "POST", .path = flush.path, .headers = headers, .write_hooks = .{ .ctx = &wire, .write = Wire.write }, .key_label = c.key, .key_scopes = c.scopes }; routes.dispatch(srv, &conn, a); @@ -201,6 +201,37 @@ test "prompt cache flush: the body retains explicitly, while absent and unrecogn } } +test "prompt cache flush: a body that cannot be read, or is refused, still gets main's full flush and reply" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var e: Engine = .{}; + const srv = try serve(e.engine(), null); + defer srv.deinit(); + const te: []const http.Header = &.{.{ .name = "Transfer-Encoding", .value = "chunked" }}; + for ([_]Caller{ + .{ .body = "{\"retain\":0}", .length = "33554433" }, // past the 32 MiB body limit + .{ .body = "{\"retain\":2}", .length = "33554433" }, + .{ .body = "{}", .length = "4x" }, // an invalid length + .{ .body = "{\"retain\":2}", .length = "40" }, // shorter than its length + .{ .body = "{}", .headers = te }, // a length and a transfer coding together + .{ .body = "" }, + .{ .body = "{}" }, + .{ .body = "{\"retain\":0}" }, + }) |c| { + const before = e.asks; + e.retain_seen = 99; + const got = try call(srv, a, c); + try t.expectEqual(@as(u16, 200), got.status); + try t.expectEqual(before + 1, e.asks); + try t.expectEqual(@as(u32, 0), e.retain_seen); // the full flush + try t.expectEqualStrings("prompt_cache.flush", got.body.strField("object").?); + try t.expectEqual(@as(i64, 3), got.body.get("states").?.int64().?); + try t.expectEqual(@as(i64, 4096), got.body.get("ram_bytes").?.int64().?); + try t.expectEqual(@as(i64, 512), got.body.get("disk_bytes").?.int64().?); + } +} + test "prompt cache flush: a model --idle-unload parked answers 503 unloaded, neither asked nor woken" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); From 5d967bb2ce914985a5e3a26954f5a5660042137d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:56:42 +0000 Subject: [PATCH 131/361] prompt cache flush: preserve the full flush when body parsing fails --- zig/src/server/cache_flush.zig | 5 +- zig/src/server/cache_flush_test.zig | 86 ++++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 6 deletions(-) diff --git a/zig/src/server/cache_flush.zig b/zig/src/server/cache_flush.zig index ffadc031221..f16a2b7ac44 100644 --- a/zig/src/server/cache_flush.zig +++ b/zig/src/server/cache_flush.zig @@ -99,10 +99,7 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator) void { return routes.sendValue(conn, a, 503, failure(a, message, "server_error", "model_unloaded") catch return); }; const retain = retainFromBody(a, raw) catch |err| switch (err) { - // a body that cannot name retain (raw or escaped) is main's full flush even when its JSON cannot be read - error.OutOfMemory => if (std.mem.indexOf(u8, raw, "retain") == null and std.mem.indexOfScalar(u8, raw, '\\') == null) 0 else { - return conn.sendError(a, 500, "out of memory", null) catch {}; - }, + error.OutOfMemory => 0, // no retention count was read: main dropped the body and flushed all error.InvalidRetain => return routes.sendValue(conn, a, 400, failure(a, "retain must be a nonnegative 32-bit integer", "invalid_request_error", "invalid_request_error") catch return), }; const got = answerRetaining(srv.gpa, srv.io, a, srv.engine, wait_ms, retain) catch return conn.sendError(a, 500, "out of memory", null) catch {}; diff --git a/zig/src/server/cache_flush_test.zig b/zig/src/server/cache_flush_test.zig index f51f257cb94..af0a6e0787e 100644 --- a/zig/src/server/cache_flush_test.zig +++ b/zig/src/server/cache_flush_test.zig @@ -7,6 +7,7 @@ const scope = @import("auth_scope.zig"); const flush = @import("cache_flush.zig"); const routes = @import("routes.zig"); const http = @import("http_conn.zig"); +const http_body = @import("http_body.zig"); const Server = @import("server.zig").Server; const Allocator = std.mem.Allocator; const Ask = api.ImprintAsk; @@ -71,7 +72,7 @@ const Wire = struct { } }; -const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full, body: []const u8 = "{}", length: ?[]const u8 = null }; +const Caller = struct { peer: []const u8 = "127.0.0.1", headers: []const http.Header = &.{}, key: ?[]const u8 = null, scopes: scope.Scopes = scope.full, body: []const u8 = "{}", length: ?[]const u8 = null, fail_parse: bool = false }; /// One flush through the dispatcher, as the connection thread hands it over after the key gate; status and body. fn call(srv: *Server, a: Allocator, c: Caller) !struct { status: u16, body: json.Value } { @@ -79,7 +80,18 @@ fn call(srv: *Server, a: Allocator, c: Caller) !struct { status: u16, body: json const length = c.length orelse try std.fmt.allocPrint(a, "{d}", .{c.body.len}); const headers = try std.mem.concat(a, http.Header, &.{ &.{.{ .name = "Content-Length", .value = length }}, c.headers }); var conn: http.Conn = .{ .fd = -1, .peer = c.peer, .buf = try a.dupe(u8, c.body), .end = c.body.len, .gpa = a, .version = "HTTP/1.1", .method = "POST", .path = flush.path, .headers = headers, .write_hooks = .{ .ctx = &wire, .write = Wire.write }, .key_label = c.key, .key_scopes = c.scopes }; - routes.dispatch(srv, &conn, a); + var fault: FailOnce = .{ .child = a }; + const request_a = if (c.fail_parse) blk: { + var probe = conn; + const body = try http_body.read(&probe, fault.allocator(), http_body.limit); + try t.expect(body == .ok); + try t.expectEqualStrings(c.body, body.ok); + fault.fail_at = fault.calls; // fail the first allocation after the same body read, without a fixed index + fault.calls = 0; + break :blk fault.allocator(); + } else a; + routes.dispatch(srv, &conn, request_a); + if (c.fail_parse) try t.expect(fault.failed); const out = wire.bytes.items; const at = std.mem.indexOf(u8, out, "\r\n\r\n") orelse return error.MissingHttpHead; return .{ .status = try std.fmt.parseInt(u16, out["HTTP/1.1 ".len..][0..3], 10), .body = (try json.parse(a, out[at + 4 ..])).ok }; @@ -253,3 +265,73 @@ test "prompt cache flush: a model --idle-unload parked answers 503 unloaded, nei try t.expectEqual(@as(u32, 1), e.asks); try t.expectEqual(@as(u32, 0), manager.active); } + +test "prompt cache flush: parse allocation failure with retain text or escapes still flushes all" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var e: Engine = .{}; + const srv = try serve(e.engine(), null); + defer srv.deinit(); + for ([_][]const u8{ + "\"\\u0061\"", + "{\"note\":\"retain\"}", + "{\"other\":\"\\u0061\"}", + "\"\\uZZZZ\"", + "{\"retain\":0}", + "{\"retain\":2}", + }) |body| { + const before = e.asks; + e.retain_seen = 99; + const got = try call(srv, a, .{ .body = body, .fail_parse = true }); + try t.expectEqual(@as(u16, 200), got.status); + try t.expectEqual(before + 1, e.asks); + try t.expectEqual(@as(u32, 0), e.retain_seen); + try t.expectEqualStrings("prompt_cache.flush", got.body.strField("object").?); + try t.expectEqual(@as(i64, 3), got.body.get("states").?.int64().?); + try t.expectEqual(@as(i64, 4096), got.body.get("ram_bytes").?.int64().?); + try t.expectEqual(@as(i64, 512), got.body.get("disk_bytes").?.int64().?); + try t.expect(got.body.get("disk").?.bool); + try t.expect(got.body.get("waited_seconds") != null); + } +} + +/// Count allocation calls, then fail one chosen call while allowing the reply's later allocations. +const FailOnce = struct { + child: Allocator, + calls: usize = 0, + fail_at: ?usize = null, + failed: bool = false, + + fn allocator(f: *FailOnce) Allocator { + return .{ .ptr = f, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + + fn of(ctx: *anyopaque) *FailOnce { + return @ptrCast(@alignCast(ctx)); + } + + fn alloc(ctx: *anyopaque, n: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const f = of(ctx); + const at = f.calls; + f.calls += 1; + if (f.fail_at) |want| if (at == want) { + f.failed = true; + f.fail_at = null; + return null; + }; + return f.child.rawAlloc(n, alignment, ra); + } + + fn resize(ctx: *anyopaque, old: []u8, alignment: std.mem.Alignment, n: usize, ra: usize) bool { + return of(ctx).child.rawResize(old, alignment, n, ra); + } + + fn remap(ctx: *anyopaque, old: []u8, alignment: std.mem.Alignment, n: usize, ra: usize) ?[*]u8 { + return of(ctx).child.rawRemap(old, alignment, n, ra); + } + + fn free(ctx: *anyopaque, old: []u8, alignment: std.mem.Alignment, ra: usize) void { + of(ctx).child.rawFree(old, alignment, ra); + } +}; From 1bf981c46fc0e406d4f474c7478f71609174a1b5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:17:02 +0000 Subject: [PATCH 132/361] prompt cache flush tests: a reply that is not JSON fails on its status, not with a panic The dispatcher helper read every reply body as JSON and took its ok field, so a plain 500 (as the parse-failure path answered before its fix) ended the test run with an inactive-union panic. A body that is not JSON now reads as null, and the test reports the status it expected and found. --- zig/src/server/cache_flush_test.zig | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/zig/src/server/cache_flush_test.zig b/zig/src/server/cache_flush_test.zig index af0a6e0787e..a61b590bdc7 100644 --- a/zig/src/server/cache_flush_test.zig +++ b/zig/src/server/cache_flush_test.zig @@ -94,7 +94,12 @@ fn call(srv: *Server, a: Allocator, c: Caller) !struct { status: u16, body: json if (c.fail_parse) try t.expect(fault.failed); const out = wire.bytes.items; const at = std.mem.indexOf(u8, out, "\r\n\r\n") orelse return error.MissingHttpHead; - return .{ .status = try std.fmt.parseInt(u16, out["HTTP/1.1 ".len..][0..3], 10), .body = (try json.parse(a, out[at + 4 ..])).ok }; + // a reply that is not JSON (a plain 500) reads as null, so its status is what a test reports, not a panic + const body: json.Value = switch (try json.parse(a, out[at + 4 ..])) { + .ok => |v| v, + .err => .null, + }; + return .{ .status = try std.fmt.parseInt(u16, out["HTTP/1.1 ".len..][0..3], 10), .body = body }; } fn code(body: json.Value) []const u8 { From 23984f4175fa9886c5f268d6a0f6e9f1043a0937 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:16:49 +0000 Subject: [PATCH 133/361] changelog: #4856 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e1a2c86c99..1fb1b4fb261 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 +- Server: `POST /v1/prompt_cache/flush` takes an optional `retain` count that keeps the most recently used prompt states in RAM and on disk; without it the flush is unchanged (#4856). + - Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. - Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. From 5c9e83e8b6dde56be9423b3ec9b402613a9aa845 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:15:53 +0000 Subject: [PATCH 134/361] changelog: each line once under Unreleased --- CHANGELOG.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fb1b4fb261..e89de008c24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,12 +12,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - GLM-5.3-Flash on CUDA: `TF_GLM_VISION_FUSED=1` (off by default) runs the image tower's attention on the shared full-attention vision kernel instead of two cuBLASLt products around a softmax; its sums run in another order, so replies to prompts with images can differ from the default path, which is unchanged (#3790, refs #3614). Thanks to @ultradaoto. -- Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. - -- Core KV pool: a host tier keeps logical pages in host RAM behind device frames, with leases, pins and per-page dirty tracking; it refuses empty or partial geometry before it allocates, and the ranks' lockstep check covers dirty pages (#1501, refs #1113). Thanks @BlivionIaG. - - - - `tensorfold start` selects a fitting catalog model, downloads it with consent, starts a local server and checks its reply; startup, chat, pull and the managed server's log keep API keys out of output (#4852). - 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). From 8040521968e0c5f9babd39543adef2bffd1c36ea Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:22:17 +0000 Subject: [PATCH 135/361] minimax_m3 cuda: opt-in CUDA graphs for one-stream decode verify windows TF_MINIMAX_GRAPHS=1 (default off) runs a one-stream decode verify window's launches through cuda.graph_cache, keyed by rows, sparse attention and taps. MiniMax's attention takes each round's positions and block counts as launch arguments, so a held graph cannot be replayed as captured: graph_cache gains a refresh mode in which a hit records the body again with this round's arguments and updates the executable in place (a new one when the launches changed), every rank voting each step, so a failed record sends all ranks to eager together. The same kernels with the same arguments in the same order; the ids upload and the draw stay outside the graph. --- docs/environment.md | 1 + zig/src/cuda/graph_cache.zig | 26 ++- zig/src/cuda/graph_cache_refresh_test.zig | 198 +++++++++++++++++++ zig/src/cuda/graph_refresh.zig | 30 +++ zig/src/cuda/root.zig | 1 + zig/src/families/minimax_m3/cuda.zig | 1 + zig/src/families/minimax_m3/cuda_engine.zig | 4 +- zig/src/families/minimax_m3/cuda_forward.zig | 19 +- zig/src/families/minimax_m3/cuda_graphs.zig | 107 ++++++++++ zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 3 + 11 files changed, 387 insertions(+), 4 deletions(-) create mode 100644 zig/src/cuda/graph_cache_refresh_test.zig create mode 100644 zig/src/cuda/graph_refresh.zig create mode 100644 zig/src/families/minimax_m3/cuda_graphs.zig diff --git a/docs/environment.md b/docs/environment.md index bb59bc353e8..684543619c6 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -93,6 +93,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_NEMOTRON_WIDE_ROUNDS` | Exactly `0` or `1`, checked when the CUDA backend starts; default off. `1` lets Nemotron's shared rounds hold 16 streams and 32 rows on GB10 (one rank, non-latent, not Bolt, no `--precision checkpoint`, no bf16 experts, no Sliding Weights or saved lessons; refused with a log line naming why), each row's bits as in two 16-row rounds; a lone stream's window is unchanged | | `TF_MINIMAX_RANK` | MiniMax-M3.1-Flash on CUDA: a whole rank index, 0 or 1 at two ranks, set with `TF_MINIMAX_WORLD`; unset with it gives one rank | | `TF_MINIMAX_WORLD` | MiniMax-M3.1-Flash on CUDA: a whole rank count, 2 at CUDA, set with `TF_MINIMAX_RANK`; unset with it gives one rank | +| `TF_MINIMAX_GRAPHS` | MiniMax-M3.1-Flash on CUDA: exactly `0` or `1`, the same on every rank; default off. `1` records each one-stream decode verify window's launches as a CUDA graph and updates the held graph with that round's arguments before launching it (one graph per row count, sparse or dense attention, and taps); the same kernels with the same arguments in the same order, so tokens keep their bits. A refused capture or refresh on any rank sends every rank back to eager launches | | `TF_PROMPT_ROWS` | Native serving: a multiple of 16 from 128 through 2048; unset keeps the chip/family default | | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | | `TF_LFM3_METAL_WARM_TURNS` | Exactly `0` or `1`; default off. Uses one-row LFM3 Metal prefill even with caching disabled. A prompt cache enables background warm turns. | diff --git a/zig/src/cuda/graph_cache.zig b/zig/src/cuda/graph_cache.zig index 75270cfaba5..91fdfe669b8 100644 --- a/zig/src/cuda/graph_cache.zig +++ b/zig/src/cuda/graph_cache.zig @@ -25,6 +25,8 @@ pub const Engine = struct { capture: *const fn (ctx: *anyopaque, stream: Stream, body: Body) anyerror!*anyopaque, launch: *const fn (ctx: *anyopaque, exec: *anyopaque, stream: Stream) anyerror!void, free: *const fn (ctx: *anyopaque, exec: *anyopaque) void, + /// Refresh: a hit records the body again with this step's arguments into `exec` (or its replacement); null: replay. + refresh: ?*const fn (ctx: *anyopaque, exec: *anyopaque, stream: Stream, body: Body) anyerror!*anyopaque = null, }; pub const Settings = struct { @@ -183,6 +185,19 @@ pub fn Cache(comptime Key: type) type { c.tick += 1; if (c.entries.getPtr(key)) |e| { e.used = c.tick; + // refresh mode: every rank records this step and votes, so a failed record sends all to eager together + if (c.engine.refresh) |refresh| { + const fresh: ?*anyopaque = refresh(c.engine.ctx, e.exec, stream, body) catch |err| blk: { + if (!quiet) std.log.warn("graph refresh failed: {s} (key {any})", .{ @errorName(err), key }); + break :blk null; + }; + if (fresh) |x| e.exec = x; + if (!try c.agreed(fresh != null)) { + c.failed = true; + c.dropAll(); + return c.eager(stream, body); + } + } try c.engine.launch(c.engine.ctx, e.exec, stream); c.stats.replayed += 1; return .replayed; @@ -246,7 +261,14 @@ pub const CudaEngine = struct { return .{ .ctx = e, .capture = capture, .launch = launch, .free = free }; } - const Held = struct { exec: graph.Exec }; + /// The same engine in refresh mode (Engine.refresh, graph_refresh.zig): host arguments that change every step. + pub fn refreshing(e: *CudaEngine) Engine { + var out = e.engine(); + out.refresh = @import("graph_refresh.zig").refresh; + return out; + } + + pub const Held = struct { exec: graph.Exec }; fn capture(ctx: *anyopaque, stream: Stream, body: Body) anyerror!*anyopaque { const e: *CudaEngine = @ptrCast(@alignCast(ctx)); @@ -275,7 +297,7 @@ pub const CudaEngine = struct { try h.exec.launchOn(stream); } - fn free(_: *anyopaque, exec: *anyopaque) void { + pub fn free(_: *anyopaque, exec: *anyopaque) void { const h: *Held = @ptrCast(@alignCast(exec)); h.exec.deinit(); std.heap.c_allocator.destroy(h); diff --git a/zig/src/cuda/graph_cache_refresh_test.zig b/zig/src/cuda/graph_cache_refresh_test.zig new file mode 100644 index 00000000000..37fc5f45564 --- /dev/null +++ b/zig/src/cuda/graph_cache_refresh_test.zig @@ -0,0 +1,198 @@ +//! graph_cache in refresh mode on a fake engine: every hit records again and votes; a failed record goes eager. +const std = @import("std"); +const t = std.testing; +const gc = @import("graph_cache.zig"); +const Stream = @import("stream.zig").Stream; + +/// A fake driver: captures and refreshes count (and may fail), launches name the executable they ran. +const Fake = struct { + captures: u32 = 0, + refreshes: u32 = 0, + launched: ?*anyopaque = null, + launches: u32 = 0, + live: u32 = 0, + fail_refresh: bool = false, + reshape: bool = false, // the next refresh's launches have another shape: a new executable replaces the old + slots: [8]u8 = undefined, + + fn engine(f: *Fake) gc.Engine { + return .{ .ctx = f, .capture = cap, .launch = lau, .free = fre, .refresh = ref }; + } + fn cap(ctx: *anyopaque, _: Stream, body: gc.Body) anyerror!*anyopaque { + const f: *Fake = @ptrCast(@alignCast(ctx)); + try body.run(body.ctx, undefined); // a capture records the body: its host side runs, nothing launches + f.captures += 1; + f.live += 1; + return &f.slots[f.live % f.slots.len]; + } + fn ref(ctx: *anyopaque, exec: *anyopaque, _: Stream, body: gc.Body) anyerror!*anyopaque { + const f: *Fake = @ptrCast(@alignCast(ctx)); + if (f.fail_refresh) return error.CaptureFailed; + try body.run(body.ctx, undefined); + f.refreshes += 1; + if (!f.reshape) return exec; + f.reshape = false; + fre(ctx, exec); + f.live += 1; + return &f.slots[(f.live + 3) % f.slots.len]; + } + fn lau(ctx: *anyopaque, exec: *anyopaque, _: Stream) anyerror!void { + const f: *Fake = @ptrCast(@alignCast(ctx)); + f.launched = exec; + f.launches += 1; + } + fn fre(ctx: *anyopaque, _: *anyopaque) void { + const f: *Fake = @ptrCast(@alignCast(ctx)); + f.live -= 1; + } +}; + +/// The body's host side: how many times it ran, recorded or eager. +const Body = struct { + runs: u32 = 0, + fn run(ctx: *anyopaque, _: Stream) anyerror!void { + const b: *Body = @ptrCast(@alignCast(ctx)); + b.runs += 1; + } + fn body(b: *Body) gc.Body { + return .{ .ctx = b, .run = run }; + } +}; + +/// The other ranks' vote: true unless told otherwise; counts the votes taken. +const Votes = struct { + others: bool = true, + taken: u32 = 0, + fn all(ctx: *anyopaque, ok: bool) anyerror!bool { + const v: *Votes = @ptrCast(@alignCast(ctx)); + v.taken += 1; + return ok and v.others; + } +}; + +test "graph cache refresh: each hit records the body once, votes and launches what the refresh returned" { + var f: Fake = .{}; + var votes: Votes = .{}; + var c = gc.Cache(u32).init(t.allocator, f.engine(), .{ .on = true, .max = 4 }); + defer c.deinit(); + c.agree = .{ .ctx = &votes, .all = Votes.all }; + var b: Body = .{}; + const s: Stream = undefined; + // a miss captures (the body's host side runs once), then each hit refreshes (once each) and replays + try t.expectEqual(gc.Outcome.captured, try c.run(7, s, 1, b.body())); + for (0..3) |_| try t.expectEqual(gc.Outcome.replayed, try c.run(7, s, 1, b.body())); + try t.expectEqual([4]u32{ 1, 3, 4, 4 }, [4]u32{ f.captures, f.refreshes, f.launches, b.runs }); + try t.expectEqual(@as(u32, 1 + 1 + 3), votes.taken); // the miss's room and capture, then every hit + // launches of another shape: the refresh's new executable is the one launched and held + f.reshape = true; + _ = try c.run(7, s, 1, b.body()); + const swapped = f.launched; + _ = try c.run(7, s, 1, b.body()); + try t.expectEqual(swapped, f.launched); + try t.expectEqual(@as(u32, 1), f.live); +} + +test "graph cache refresh: a failed record on any rank sends every rank eager, the graphs freed, for good" { + for ([_]bool{ true, false }) |here| { + var f: Fake = .{}; + var votes: Votes = .{}; + var c = gc.Cache(u32).init(t.allocator, f.engine(), .{ .on = true, .max = 4 }); + defer c.deinit(); + c.agree = .{ .ctx = &votes, .all = Votes.all }; + var b: Body = .{}; + const s: Stream = undefined; + _ = try c.run(3, s, 1, b.body()); + if (here) f.fail_refresh = true else votes.others = false; // this rank's record fails, or another rank's + try t.expectEqual(gc.Outcome.eager, try c.run(3, s, 1, b.body())); + try t.expectEqual(@as(u32, 0), f.live); + f.fail_refresh = false; + votes.others = true; + const taken = votes.taken; + try t.expectEqual(gc.Outcome.eager, try c.run(3, s, 1, b.body())); + try t.expectEqual(taken, votes.taken); // an off cache never votes again + try t.expectEqual(@as(u32, 1), f.launches); // only the capture's launch ever ran a graph + } +} + +test "graph cache refresh: an engine without refresh replays as captured, as before" { + var f: Fake = .{}; + var e = f.engine(); + e.refresh = null; + var c = gc.Cache(u32).init(t.allocator, e, .{ .on = true, .max = 4 }); + defer c.deinit(); + var b: Body = .{}; + const s: Stream = undefined; + _ = try c.run(1, s, 1, b.body()); + for (0..3) |_| try t.expectEqual(gc.Outcome.replayed, try c.run(1, s, 1, b.body())); + try t.expectEqual([3]u32{ 1, 0, 1 }, [3]u32{ f.captures, f.refreshes, b.runs }); +} + +/// Launches as (kernel, argument) words: a body writes them where `sink` points, the log or a recording. +const Launches = struct { + var sink: *std.ArrayList(u64) = undefined; + var log: std.ArrayList(u64) = .empty; + var recorded: [4]std.ArrayList(u64) = @splat(.empty); + var used: usize = 0; + + /// A capture or refresh: the body writes into the executable's recording, which a launch then plays. + fn engine() gc.Engine { + return .{ .ctx = undefined, .capture = cap, .launch = lau, .free = fre, .refresh = ref }; + } + fn record(r: *std.ArrayList(u64), body: gc.Body) !void { + r.clearRetainingCapacity(); + const was = sink; + sink = r; + defer sink = was; + try body.run(body.ctx, undefined); + } + fn cap(_: *anyopaque, _: Stream, body: gc.Body) anyerror!*anyopaque { + const r = &recorded[used]; + used += 1; + try record(r, body); + return r; + } + fn ref(_: *anyopaque, exec: *anyopaque, _: Stream, body: gc.Body) anyerror!*anyopaque { + try record(@ptrCast(@alignCast(exec)), body); + return exec; + } + fn lau(_: *anyopaque, exec: *anyopaque, _: Stream) anyerror!void { + const r: *std.ArrayList(u64) = @ptrCast(@alignCast(exec)); + try log.appendSlice(t.allocator, r.items); + } + fn fre(_: *anyopaque, _: *anyopaque) void {} +}; + +/// A window's launches: three kernels, the second taking this step's position. +const Window = struct { + pos: u64, + fn run(ctx: *anyopaque, _: Stream) anyerror!void { + const w: *Window = @ptrCast(@alignCast(ctx)); + for ([_]u64{ 1, 2, 3 }, [_]u64{ 0, w.pos, 0 }) |k, arg| try Launches.sink.appendSlice(t.allocator, &.{ k, arg }); + } +}; + +test "graph cache refresh: eager and graphed steps launch the same kernels with each step's own arguments" { + defer { + Launches.log.deinit(t.allocator); + for (&Launches.recorded) |*r| r.deinit(t.allocator); + } + var logs: [2][]u64 = undefined; + for ([_]bool{ false, true }, 0..) |graphed, i| { + Launches.log = .empty; + Launches.sink = &Launches.log; + Launches.used = 0; + var c = gc.Cache(u32).init(t.allocator, Launches.engine(), .{ .on = graphed, .max = 4 }); + defer c.deinit(); + for (0..6) |step| { + var w: Window = .{ .pos = 100 + step }; + _ = try c.run(@intCast(step % 2), undefined, 1, .{ .ctx = &w, .run = Window.run }); + } + logs[i] = try t.allocator.dupe(u64, Launches.log.items); + Launches.log.deinit(t.allocator); + Launches.log = .empty; + } + defer for (logs) |l| t.allocator.free(l); + try t.expectEqualSlices(u64, logs[0], logs[1]); + try t.expectEqual(@as(usize, 6 * 6), logs[1].len); + try t.expectEqual(@as(u64, 105), logs[1][logs[1].len - 3]); // the last step's own position, not a captured one +} diff --git a/zig/src/cuda/graph_refresh.zig b/zig/src/cuda/graph_refresh.zig new file mode 100644 index 00000000000..f411ff47d2a --- /dev/null +++ b/zig/src/cuda/graph_refresh.zig @@ -0,0 +1,30 @@ +//! graph_cache's refresh step on the driver: a hit's body recorded again, its executable updated or replaced. +const std = @import("std"); +const graph = @import("graph.zig"); +const Stream = @import("stream.zig").Stream; +const gc = @import("graph_cache.zig"); +const Held = gc.CudaEngine.Held; + +/// The body recorded now and its parameters taken in place; launches of another shape get a new executable. +pub fn refresh(ctx: *anyopaque, exec: *anyopaque, stream: Stream, body: gc.Body) anyerror!*anyopaque { + const h: *Held = @ptrCast(@alignCast(exec)); + try graph.beginCapture(stream, .thread_local); + body.run(body.ctx, stream) catch |err| { + // end the capture so the stream is usable again; the partial graph is dropped + if (graph.endCapture(stream)) |g| { + var gg = g; + gg.deinit(); + } else |_| {} + return err; + }; + var g = try graph.endCapture(stream); + defer g.deinit(); + if (try h.exec.update(g) == .success) return h; + const fresh = try std.heap.c_allocator.create(Held); + errdefer std.heap.c_allocator.destroy(fresh); + fresh.exec = try g.instantiate(); + errdefer fresh.exec.deinit(); + try fresh.exec.upload(stream); + gc.CudaEngine.free(ctx, exec); + return fresh; +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index a00354ee677..cdcc06ec4c8 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -183,6 +183,7 @@ test { _ = @import("graph_cache_regression_test.zig"); _ = @import("graph_cache_ranks_test.zig"); _ = @import("graph_cache_shapes_test.zig"); + _ = @import("graph_cache_refresh_test.zig"); _ = exl3.block.dense; _ = exl3.block.experts; _ = exl3.block.lin2; diff --git a/zig/src/families/minimax_m3/cuda.zig b/zig/src/families/minimax_m3/cuda.zig index f93ad5539a9..0bd1e3c1fdf 100644 --- a/zig/src/families/minimax_m3/cuda.zig +++ b/zig/src/families/minimax_m3/cuda.zig @@ -23,4 +23,5 @@ test { _ = follow; _ = native; _ = @import("cuda_prompt_tail.zig"); // which prompt rows the last layer runs + _ = @import("cuda_graphs.zig"); // TF_MINIMAX_GRAPHS } diff --git a/zig/src/families/minimax_m3/cuda_engine.zig b/zig/src/families/minimax_m3/cuda_engine.zig index 3bee5402ad0..ee4c9f6eede 100644 --- a/zig/src/families/minimax_m3/cuda_engine.zig +++ b/zig/src/families/minimax_m3/cuda_engine.zig @@ -73,6 +73,7 @@ pub const Engine = struct { picks_host: []u8, smp: sampler.Sampler, drafter: ?*dspark.Drafter = null, + graphs: @import("cuda_graphs.zig").Graphs = .{}, // TF_MINIMAX_GRAPHS: verify windows as CUDA graphs images: ?*vision.Images = null, tap_at: []i32 = &.{}, snaps: std.AutoHashMapUnmanaged(u64, Snap) = .empty, // kept prompt states by id (the same ids on every rank) @@ -157,6 +158,7 @@ pub const Engine = struct { e.smp.deinit(); e.gpa.free(e.picks_host); e.picks.free(); + e.graphs.deinit(e.gpa); e.bs.deinit(); e.bd.deinit(); e.bp.deinit(); @@ -338,7 +340,7 @@ pub const Engine = struct { const f = e.forward(&e.bd); const seg = [_]fw.Seg{.{ .st = &e.cur.st, .row0 = 0, .rows = ids.len }}; const at = e.cur.st.pos; - try f.run(@ptrCast(ids), &seg); + try e.graphs.run(e.gpa, &f, @ptrCast(ids), &seg); try e.stashTaps(&e.bd, 0, ids.len); try e.draw(&e.bd, 0, ids.len, at + 1, bits, out[0..ids.len]); } diff --git a/zig/src/families/minimax_m3/cuda_forward.zig b/zig/src/families/minimax_m3/cuda_forward.zig index 53a311636e8..7c19a6360c7 100644 --- a/zig/src/families/minimax_m3/cuda_forward.zig +++ b/zig/src/families/minimax_m3/cuda_forward.zig @@ -145,9 +145,14 @@ pub const Forward = struct { /// `ids` at each segment's positions: the last row's logits (a prompt chunk) or every row's, the caches written. pub fn run(f: *const Forward, ids: []const i32, segs: []const Seg) !void { + try f.upload(ids, segs); + return f.launches(ids.len, segs); + } + + /// The window's checks and its ids' upload, ahead of its launches. + pub fn upload(f: *const Forward, ids: []const i32, segs: []const Seg) !void { const R = ids.len; const b = f.b; - const co = f.c(); if (R == 0 or R > b.rows or segs.len == 0) return error.BadWindow; var total: usize = 0; for (segs) |g| { @@ -156,6 +161,12 @@ pub const Forward = struct { } if (total != R) return error.BadWindow; try cuda.copy_source.enqueue(f.d, b.ids, std.mem.sliceAsBytes(ids), f.stream); + } + + /// `run` past its ids' upload: every launch, with no host wait, read or upload (a graph records it whole). + pub fn launches(f: *const Forward, R: usize, segs: []const Seg) !void { + const b = f.b; + const co = f.c(); try kern.embed(&f.m.k, f.stream, b.ids, f.w.embed, b.resid, R, co.hidden); if (f.images) |im| if (segs.len == 1) try @import("cuda_vision.zig").splice(&f.m.k, f.stream, im.rows, im.spans, segs[0].st.pos, segs[0].st.pos + R, b.resid); try kern.norm(&f.m.k, f.stream, b.resid, f.w.layers[0].in_norm, b.x, R, co.hidden, co.eps); @@ -260,6 +271,12 @@ pub const Forward = struct { try kern.moePartial(&f.m.k, f.stream, b.ey, b.wts, b.sy, f.slot(R, 2), R, topk, h); } + /// Whether segment `g`'s attention scores and selects index blocks first (more blocks than it attends). + pub fn sparse(f: *const Forward, g: Seg) bool { + const co = f.c(); + return co.blocks(g.st.pos + g.rows) > co.topk_blocks; + } + /// One segment's rows prepared (q, k, v, index pair), its rows from `from` selected and attended into b.o. fn attention(f: *const Forward, a: weights.Attention, j: usize, g: Seg, window: usize, from: usize) !void { const b = f.b; diff --git a/zig/src/families/minimax_m3/cuda_graphs.zig b/zig/src/families/minimax_m3/cuda_graphs.zig new file mode 100644 index 00000000000..6b6abf83785 --- /dev/null +++ b/zig/src/families/minimax_m3/cuda_graphs.zig @@ -0,0 +1,107 @@ +//! TF_MINIMAX_GRAPHS=1: a one-stream decode verify window as a CUDA graph, recorded each round and updated in place. +const std = @import("std"); +const cuda = @import("cuda"); +const fw = @import("cuda_forward.zig"); +const gc = cuda.graph_cache; + +/// The switch; default off. The startup check refused every malformed value already, so a plain default stands here. +pub fn on() bool { + return @import("sys").environment.read(bool, "TF_MINIMAX_GRAPHS", false) catch false; +} + +/// A window's launches, beside the arguments each refresh takes again: rows, sparse attention (index blocks), taps. +pub const Key = struct { rows: u32, sparse: bool, taps: bool }; + +/// A window a graph may hold: one decode segment, no prompt chunk, images, layer hook or tail cut. +pub fn eligible(f: *const fw.Forward, segs: []const fw.Seg) bool { + return segs.len == 1 and !f.b.prefill and f.images == null and f.watch == null and f.tail == null; +} + +pub fn keyOf(f: *const fw.Forward, rows: usize, seg: fw.Seg) Key { + return .{ .rows = @intCast(rows), .sparse = f.sparse(seg), .taps = f.taps != null }; +} + +pub const Graphs = struct { + state: ?*State = null, // set up at the first eligible window with the switch on (the exchange is known by then) + off: bool = false, + + const State = struct { engine: gc.CudaEngine, cache: gc.Cache(Key), agreement: ?Agreement }; + + pub fn deinit(g: *Graphs, gpa: std.mem.Allocator) void { + if (g.state) |s| { + s.cache.deinit(); + if (s.agreement) |*a| a.dev.free(); + gpa.destroy(s); + } + g.* = .{}; + } + + /// `f.run(ids, segs)`: with the switch on and an eligible window, its launches through the graph cache. + pub fn run(g: *Graphs, gpa: std.mem.Allocator, f: *const fw.Forward, ids: []const i32, segs: []const fw.Seg) !void { + if (g.off or !eligible(f, segs)) return f.run(ids, segs); + if (g.state == null and !on()) { // read once, at the first eligible window + g.off = true; + return f.run(ids, segs); + } + const s = g.state orelse try g.setUp(gpa, f); + try f.upload(ids, segs); + var body: Body = .{ .f = f, .rows = ids.len, .segs = segs }; + const fp = gc.fingerprintOf(&.{ f.b.ids, f.b.resid, f.b.logits, @as(u64, f.b.rows) }); + _ = try s.cache.run(keyOf(f, ids.len, segs[0]), f.stream, fp, .{ .ctx = &body, .run = Body.run }); + } + + fn setUp(g: *Graphs, gpa: std.mem.Allocator, f: *const fw.Forward) !*State { + const s = try gpa.create(State); + errdefer gpa.destroy(s); + s.engine = .{ .d = f.d }; + s.agreement = switch (f.exchange) { + .local => null, + .nccl => |n| .{ .lib = n.lib, .comm = n.comm, .stream = f.stream, .dev = try cuda.DeviceBuffer.alloc(f.d, 16) }, + }; + s.cache = gc.Cache(Key).init(gpa, s.engine.refreshing(), .{ .on = true, .max = 48 }); + s.cache.name = "minimax verify"; + if (s.agreement) |*a| s.cache.agree = .{ .ctx = a, .all = Agreement.all }; + g.state = s; + return s; + } +}; + +/// The launches a graph records: the window's whole forward past its ids' upload. +const Body = struct { + f: *const fw.Forward, + rows: usize, + segs: []const fw.Seg, + + fn run(ctx: *anyopaque, _: cuda.Stream) anyerror!void { + const b: *Body = @ptrCast(@alignCast(ctx)); + try b.f.launches(b.rows, b.segs); + } +}; + +/// Every rank's verdict: one int's minimum over the ranks, read back (outside any capture). +const Agreement = struct { + lib: *const cuda.nccl.Library, + comm: cuda.nccl.Comm, + stream: cuda.Stream, + dev: cuda.DeviceBuffer, + + fn all(ctx: *anyopaque, ok: bool) anyerror!bool { + const a: *Agreement = @ptrCast(@alignCast(ctx)); + var v: i32 = @intFromBool(ok); + try a.dev.uploadAsync(0, std.mem.asBytes(&v), a.stream.handle); + try a.lib.check(a.lib.api.ncclAllReduce(a.dev.ptr, a.dev.ptr, 1, .i32, .min, a.comm, a.stream.handle), "ncclAllReduce"); + try a.stream.synchronize(); + try a.dev.download(0, std.mem.asBytes(&v)); + return v == 1; + } +}; + +test "MiniMax graphs: the key separates rows, sparse attention and taps; the same launches share one" { + const t = std.testing; + const keys = [_]Key{ + .{ .rows = 1, .sparse = false, .taps = false }, .{ .rows = 4, .sparse = false, .taps = false }, + .{ .rows = 4, .sparse = true, .taps = false }, .{ .rows = 4, .sparse = true, .taps = true }, + .{ .rows = 8, .sparse = true, .taps = true }, + }; + for (keys, 0..) |a, i| for (keys, 0..) |b, j| try t.expectEqual(i == j, std.meta.eql(a, b)); +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 4b9e39b6df0..f49639869a0 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -166,6 +166,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_WORLD", .scope = .glm, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, .{ .name = "TF_MINIMAX_RANK", .scope = .minimax_m3, .kind = .u32, .forms = "a whole rank from 0", .flag = "--rank", .retire = alias_retire }, .{ .name = "TF_MINIMAX_WORLD", .scope = .minimax_m3, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, + .{ .name = "TF_MINIMAX_GRAPHS", .scope = .minimax_m3, .kind = .flag, .forms = "0 or 1 (1 records one-stream decode verify windows as CUDA graphs; default 0)" }, .{ .name = "TF_NEMOTRON_RANK", .scope = .nemotron, .kind = .u32, .forms = "a whole rank from 0", .flag = "--rank", .retire = alias_retire }, .{ .name = "TF_NEMOTRON_WORLD", .scope = .nemotron, .kind = .u32, .forms = "a whole world size from 1", .flag = "--tp", .retire = alias_retire }, .{ .name = "TF_NEMOTRON_WIDE_ROUNDS", .scope = .nemotron, .kind = .flag, .forms = "0 or 1 (default 0)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 9f4ac21c05c..d96cf50b94a 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -129,6 +129,8 @@ const valid = [_]Case{ .{ .name = "TF_ROCE_GID_INDEX", .raw = "2147483647", .n = 2147483647 }, .{ .name = "TF_MINIMAX_RANK", .raw = "1", .n = 1 }, .{ .name = "TF_MINIMAX_WORLD", .raw = "2", .n = 2 }, + .{ .name = "TF_MINIMAX_GRAPHS", .raw = "0", .n = 0 }, + .{ .name = "TF_MINIMAX_GRAPHS", .raw = "1", .n = 1 }, .{ .name = "TF_NEMOTRON_RANK", .raw = "0", .n = 0 }, .{ .name = "TF_NEMOTRON_WORLD", .raw = "4294967295", .n = 4294967295 }, .{ .name = "TF_NEMOTRON_WIDE_ROUNDS", .raw = "0", .n = 0 }, @@ -310,6 +312,7 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "TF_GEMMA4_ARGMAX_GRAPH", "2" }, .{ "TF_GEMMA4_ARGMAX_GRAPH", "on" }, .{ "TF_Q35_GROUP_PROJ", "2" }, .{ "TF_Q35_GROUP_PROJ", "on" }, .{ "TF_QMMF_HALF_BN", "2" }, .{ "TF_QMMF_HALF_BN", "on" }, + .{ "TF_MINIMAX_GRAPHS", "2" }, .{ "TF_MINIMAX_GRAPHS", "on" }, .{ "TF_MTP_TREES", "yes" }, .{ "TF_MTP_BATCH", "off" }, .{ "TF_QWEN_POOL_LOG", "true" }, .{ "TF_COST_KEY_TRACE", "on" }, .{ "TF_COST_KEY_TRACE", "on" }, .{ "TF_ROCE_HCA", "rocep1s0f0,roceP2p1s0f0,rocep1s0f1" }, From 33bf8c19e037177e966a46a85a2fe705aaeba3cb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:22:17 +0000 Subject: [PATCH 136/361] tests: re-pin cuda/root.zig, whose test block imports graph_cache_refresh_test --- zig/tests/fixtures/gradient-serving.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index ef642c2196b..cc29d84eeb5 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -105,7 +105,7 @@ zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7 zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/qmmf.zig 08acd959abfd7336cded19c67d044590c3497066e6f36381d03ea31b9a733f1a raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fuse_split_n, default 0: main's kernels); threshold owned by Flash Next's lane, other families keep 0; #4533 optional FP4/FP8/FP8G half tiles, default off zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig d4f3c80440208cae60fb2336ac2b2e4837dc7035e34eb3ca6d189765c5422e62 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); #4533 exports qmmf_half +zig/src/cuda/root.zig 5aecc0ffdeb2f22f4a836803d8c81842526aa04a4a0ad4dcbedc1d4aba1f7d4d raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); #4533 exports qmmf_half zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw From e30ee20cde10040fd11c7cbcefb04501833a1d03 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:47:48 +0000 Subject: [PATCH 137/361] changelog: #4610 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e89de008c24..eb8a59824f8 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 +- MiniMax-M3 on CUDA: `TF_MINIMAX_GRAPHS=1` (opt-in) runs the decode verify window from one CUDA graph, re-recorded with each round's arguments and updated in place, so every kernel sees the same arguments as the eager path and tokens are unchanged (#4610). + - Server: `POST /v1/prompt_cache/flush` takes an optional `retain` count that keeps the most recently used prompt states in RAM and on disk; without it the flush is unchanged (#4856). - Flash Next on CUDA: the pass scratch now has room for the MTP head's own rows, so a 128 to 1,023-token prompt with drafts on no longer writes past it (#4801). Thanks @BadAd84. From 5f0de4f4d0b52b5b6deb6bfb780816c65f433269 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:09:49 +0000 Subject: [PATCH 138/361] server: /v1/completions takes echo, the prompt's text and legacy logprobs ahead of an unchanged reply echo: true puts the prompt's decoded ids in front of text and, with logprobs, each prompt token's entry (null for the first) ahead of the reply's, whose entries stay as without echo. max_tokens 0 with echo returns the prompt alone. Engines without prompt_logprobs, streams, messages bodies and non-boolean values are refused by name; prompt_logprobs keeps its own count. --- docs/api.md | 15 ++ zig/build/server.zig | 4 +- zig/src/server/chat.zig | 17 +- zig/src/server/chat_generation.zig | 3 +- zig/src/server/completion_echo.zig | 68 +++++++ zig/src/server/completion_echo_test.zig | 166 ++++++++++++++++++ zig/src/server/logprobs.zig | 23 ++- zig/src/server/logprobs_test.zig | 2 + zig/src/server/openai.zig | 4 +- zig/src/server/root.zig | 1 + zig/tests/server/corpus.py | 2 + zig/tests/server/golden/cases.json | 2 +- .../server/golden/completions/echo-false.json | 20 +++ .../golden/completions/echo-stream.json | 20 +++ .../golden/completions/echo-unsupported.json | 20 +++ .../server/golden/lifecycle/request-log.json | 3 + 16 files changed, 354 insertions(+), 16 deletions(-) create mode 100644 zig/src/server/completion_echo.zig create mode 100644 zig/src/server/completion_echo_test.zig create mode 100644 zig/tests/server/golden/completions/echo-false.json create mode 100644 zig/tests/server/golden/completions/echo-stream.json create mode 100644 zig/tests/server/golden/completions/echo-unsupported.json diff --git a/docs/api.md b/docs/api.md index d92fc600065..2de2033fd71 100644 --- a/docs/api.md +++ b/docs/api.md @@ -520,6 +520,7 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n | `deadline_s` | Seconds, more than 0 and at most 1,000,000, on chat and legacy completions: at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave, usage and token ids. A reply that ends first, or a [cancel](#cancel-a-request) that came first, keeps its own ending; without the field nothing changes | Native | | `return_token_ids` | The reply's token ids in the response's `tensorfold.token_ids`, the tokens its `token_sha256` hashes | Native | | `execution_witness` | Boolean, default false. True binds the reply to the execution witness; see [Reply binding](#reply-binding). A server without `--execution-witness` answers 400, a key with `inference` but not `read` 403 | Both | +| `echo` | `/v1/completions` only: the prompt's text, and with `logprobs` its tokens' entries, ahead of the reply's, described below | Native | `n` takes 1 through 16 choices: each is its own engine request on the one prompt, and later choices resume the prompt the first fills (their `tensorfold.cached_tokens` show it). Choice 0 keeps the request's seed (a request that @@ -571,6 +572,20 @@ and on GLM-5.3-Flash's CUDA engine. `logprob`, `rank` and `decoded_token`. The prompt token's `rank` counts every vocabulary token at or above it, itself included, as vLLM does, and the best tokens are ranked by place. Such a request never resumes from the prompt cache, so its whole prompt is prefilled. Chat, streamed requests and other engines return HTTP 400 with it. + +Nonstreamed `/v1/completions` takes OpenAI's legacy `echo` on the engines that advertise +`capabilities.prompt_logprobs`, so evaluation harnesses can score a prompt's own tokens. With `echo: true`, `text` +starts with the prompt: its token ids decoded, which is the text as sent unless the tokenizer adds or normalizes +something, such as a beginning-of-text token. With `logprobs`, the legacy arrays list each prompt token before the +reply's: `tokens`, `token_logprobs`, `top_logprobs` (the likeliest tokens at that place, as many as `logprobs` asks +for), `null` in both for the first prompt token, and `text_offset` counting each token's own text from 0. The +reply's own entries are the ones the same request gets without `echo`, with their offsets counted on past the +prompt's. `max_tokens: 0` with `echo` +generates nothing: `text` is the prompt alone, `finish_reason` is `length` and `usage.completion_tokens` is 0 +(without `echo`, 0 still means the server's default length). With `logprobs`, the whole prompt is prefilled, as for +`prompt_logprobs`; asked together, each lists its own number of alternatives. A non-boolean `echo`, a streamed +request, a body with `messages` and other engines return HTTP 400 naming `echo`; chat routes ignore the field. + `ignore_eos: true` keeps user-supplied `stop` strings active, including when a stop string spans streamed chunks. Both backends reject a non-boolean `ignore_eos` or a malformed `stop` with HTTP 400 before a stream opens. Both backends reject malformed `temperature`, `top_p`, `top_k` and `seed` values with HTTP 400, whether or not diff --git a/zig/build/server.zig b/zig/build/server.zig index c6886be2bfb..6b156cf77ab 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -126,8 +126,8 @@ pub fn toolHostTests(b: *std.Build, parser: *std.Build.Module, server: *std.Buil b.step("test-responses-background-host", "Background response completion, cancellation and ownership without sockets").dependOn(&background.step); const environment = b.step("test-environment-report-host", "Named environment discovery, new registry rows and startup reporting"); environment.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "capability audit: environment", "stable profile:", "profile line:" } })).step); - const logprobs = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "logprobs_test", "logprob combinations:" } })); - b.step("test-logprob-offers-host", "Logprob refusals before submission, and entries with tools, stops, reasoning and Responses").dependOn(&logprobs.step); + const logprobs = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{ "logprobs_test", "logprob combinations:", "completions echo:" } })); + b.step("test-logprob-offers-host", "Logprob refusals before submission, entries with tools, stops, reasoning and Responses, and echo").dependOn(&logprobs.step); const limits = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"limit pins:"} })); b.step("test-limit-pins-host", "Documented request and flag limits pinned at their bounds").dependOn(&limits.step); const deps = b.addRunArtifact(b.addTest(.{ .root_module = server, .filters = &.{"flag deps:"} })); diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 2bea070c6e3..e8927575f38 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -52,6 +52,10 @@ pub const Input = struct { prompt_logprobs: ?u8 = null, /// The prompt cache's salt (cache_salt.zig): a hash, 0 for none; states kept under one salt serve only that salt. cache_salt: u64 = 0, + /// ``echo: true`` on ``/v1/completions``: the reply's text and legacy logprobs start with the prompt's own. + echo: bool = false, + /// ``echo`` with ``max_tokens: 0``: the engine draws one token the reply drops, so the reply is the prompt alone. + prompt_only: bool = false, /// The client's own name for the grammar field (text.format, output_config.format); null on chat and completions. format: ?[]const u8 = null, /// The encoded image bytes the request may send; chat's limits unless a route (OCR) sets its own. @@ -60,6 +64,13 @@ pub const Input = struct { fill_room: bool = false, /// ``"execution_witness": true``: the reply binds the witness, its prompt, resolved request and tokens. execution_witness: bool = false, + + /// The prompt rows the engine computes: ``prompt_logprobs``' alternatives, or echo's ``logprobs`` when more. + pub fn promptRows(input: Input) ?u8 { + const echoed: ?u8 = if (input.echo) input.logprobs else null; + const asked = input.prompt_logprobs orelse return echoed; + return @max(asked, echoed orelse 0); + } }; /// A streamed piece: content text (a string) or a delta object (reasoning or tool calls). @@ -101,6 +112,8 @@ pub const Reply = struct { decode_tps: f64 = 0, /// ``choices[0].prompt_logprobs`` (vLLM's form) for a request that asked; null otherwise. prompt_logprobs: ?Value = null, + /// The engine's prompt rows, one a prompt token after the first, for a request that asked (completion_echo.zig). + prompt_rows: ?[]const api.LogprobRow = null, loop_stop: ?u32 = null, // the loop period when --loop-guard-stop ended the reply in its reasoning reasoning_recovered: bool = false, // ended at its end token in an unclosed think block: content repeats it execution_witness: ?Value = null, // the reply binding, when the request asked (witness_reply.zig) @@ -244,7 +257,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa if (srv.info.capability(.answer_limit)) @import("thinking_reserve.zig").apply(&request, srv.config.thinking_reserve, if (window > 0) window - n else std.math.maxInt(u32), srv.think_close_end); } request.logprobs = input.logprobs; - request.prompt_logprobs = input.prompt_logprobs; + request.prompt_logprobs = input.promptRows(); if (try engine_refusal.of(srv.engine, cx, &request)) |message| return cx.refuse(message); const deadline: ?i96 = if (f.get("deadline_s")) |v| blk: { const s = (if (v == .bool) null else v.float64()) orelse return cx.refuse("deadline_s must be a number of seconds"); @@ -297,7 +310,7 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an }; srv.release(preparing, null); // a background request waits only while a foreground one prepares preparing = false; - var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .report_seed = input.choices > 1, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .grammar = if (request.structure) |st| (if (st.after) |t| .{ .after = t } else .on) else .none, .max_tokens = request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .required = fields_mod.flag(input.fields, "tool_call_required") orelse false, .recover = input.prompt == null and request.structure == null, .deadline_ns = prepared.deadline_ns }; + var gen: Generation = .{ .srv = srv, .a = a, .box = &box, .id = id, .asked = input.cancel, .reply_id = input.id, .seed = if (request.sampling) |v| v.seed else null, .report_seed = input.choices > 1, .sink = sink, .thinking = prepared.reasoning or (srv.text.vtable.format != .kimi and srv.info.capability(.reasoning) and reply_text.isChannel(srv.markers)), .chat = input.prompt == null, .stops = .{ .strings = stops_opt.strings }, .ignore_eos = stops_opt.ignore_eos, .grammar = if (request.structure) |st| (if (st.after) |t| .{ .after = t } else .on) else .none, .max_tokens = if (input.prompt_only) 0 else request.max_tokens, .tools = input.tools, .token_ids = prepared.token_ids, .lp = if (request.logprobs != null) .{ .positions = if (sink) |s| s.tokens != null else false } else null, .loop_stop = request.loop_stop, .single = fields_mod.flag(input.fields, "tool_call_single") orelse false, .required = fields_mod.flag(input.fields, "tool_call_required") orelse false, .recover = input.prompt == null and request.structure == null, .deadline_ns = prepared.deadline_ns }; gen.call_end = @import("chat_inkling2.zig").callEnd(srv, gen.required, request.structure); defer srv.noteRequest(prepared.prompt_len, cached_tokens.within(box.cached, prepared.prompt_len), gen.collected.items.len, box.stats.drafted, box.stats.accepted, box.stats.rounds, received, gen.first_ns, gen.last_ns, box.stats.prefill_seconds, if (box.stats.prefill_seconds != null) box.stats.queued_seconds else null); errdefer if (!gen.engine_done) gen.cancel(); // the engine writes to the mailbox until it says finished diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 8d4256fa786..77d7615be06 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -123,6 +123,7 @@ pub const Generation = struct { /// Commits a round's tokens as ``LaneStream.commit`` would, then streams what they add. fn commit(g: *Generation, chunk: []const u32) Failure!void { const before = g.grammar; // the stream below judges each token's end at its own phase, as this loop does + if (g.max_tokens == 0) g.reason = "length"; // a prompt-only reply keeps none of the engine's tokens var landed: usize = 0; for (chunk) |t| { if (g.reason != null) break; @@ -462,7 +463,7 @@ pub const Generation = struct { .thinking = thinking, .effort = effort, .probability_rows = if (g.lp) |l| .{ .tokens = content_tokens, .rows = l.rows.items, .thinking = g.thinking, .stops = g.stops, .closer = close, .sent = l.sent, .positions = l.positions } else null, - .prompt_logprobs = if (m.prompt_rows) |r| try @import("logprobs.zig").promptValue(g.srv, a, r) else null, + .prompt_rows = if (m.prompt_rows) |r| try a.dupe(api.LogprobRow, r) else null, .loop_stop = stopped, .reasoning_recovered = recovered, }; diff --git a/zig/src/server/completion_echo.zig b/zig/src/server/completion_echo.zig new file mode 100644 index 00000000000..e6ddae30bc5 --- /dev/null +++ b/zig/src/server/completion_echo.zig @@ -0,0 +1,68 @@ +//! ``echo`` on /v1/completions, beside vLLM's ``prompt_logprobs``: the prompt's own text and rows in a whole reply. +const std = @import("std"); +const json = @import("json"); +const errors = @import("errors.zig"); +const fields = @import("fields.zig"); +const chat = @import("chat.zig"); +const logprobs = @import("logprobs.zig"); +const Server = @import("server.zig").Server; +const Value = json.Value; +const Cx = errors.Cx; + +/// ``prompt_logprobs`` and ``echo`` from a body into `input`, each refused by name where it cannot be served. +pub fn plan(srv: *Server, cx: *Cx, body: Value, input: *chat.Input, completions: bool, streamed: bool) errors.Refused!void { + const rows = srv.info.capability(.prompt_logprobs); + input.prompt_logprobs = try fields.promptLogprobs(cx, body, completions, streamed, rows); + const asked = (if (completions) body.field("echo") else null) orelse return; // chat routes do not read it + if (asked != .bool) return cx.refuse("echo must be a boolean or null"); + if (!asked.bool) return; + if (streamed) return cx.refuse("echo is supported on /v1/completions without streaming only"); + if (input.messages.array.len > 0) return cx.refuse("echo is supported with a prompt, not messages"); + if (!rows) return cx.refuse("echo is not supported by this model or backend"); + input.echo = true; + input.prompt_only = noTokens(body); + if (input.prompt_only) input.max_tokens = 1; // the engine still draws one token, which the reply drops +} + +/// The body asks for no reply tokens: a ``max_tokens`` or ``max_completion_tokens`` of 0, and neither asks for more. +fn noTokens(body: Value) bool { + if (json.truthyField(body, "max_tokens") or json.truthyField(body, "max_completion_tokens")) return false; + return body.field("max_tokens") != null or body.field("max_completion_tokens") != null; +} + +/// ``logprobs.project``, then the prompt's rows where they were asked: vLLM's form, and echo's ahead of the reply. +pub fn project(srv: *Server, cx: *Cx, reply: *chat.Reply, input: chat.Input, calls: ?[]Value) errors.Refused!void { + try logprobs.project(srv, cx, reply, input.tools, calls); + if (input.prompt_logprobs) |n| if (reply.prompt_rows) |rows| { + reply.prompt_logprobs = try logprobs.promptValue(srv, cx.a, rows, n); + }; + if (input.echo) try echo(srv, cx, reply, input); +} + +/// The prompt ahead of the reply: its text, and with ``logprobs`` its tokens' entries, the first with none. +fn echo(srv: *Server, cx: *Cx, reply: *chat.Reply, input: chat.Input) errors.Refused!void { + const a = cx.a; + const ids = (try @import("prompt.zig").prepare(srv, cx, input, false, null)).ids; // the ids the engine read + reply.content = try std.mem.concat(a, u8, &.{ try srv.text.decode(a, ids), reply.content }); + const n = input.logprobs orelse return; + const rows = reply.prompt_rows orelse return cx.other("the engine gave no rows for the echoed prompt"); + const shown = reply.logprobs orelse return cx.other("the reply has no logprob entries to echo the prompt before"); + if (ids.len == 0 or rows.len != ids.len - 1) return cx.other("the engine's prompt rows are out of step with the prompt"); + const after = shown.object.get("content").?.array; + const all = try a.alloc(Value, ids.len + after.len); + const first = try json.newObject(a); + try first.put(a, "token", .{ .string = try srv.text.decode(a, ids[0..1]) }); + try first.put(a, "logprob", .null); + try first.put(a, "top_logprobs", .null); + all[0] = .{ .object = first }; + for (all[1..ids.len], ids[1..], rows) |*slot, id, row| { + var best = row; + best.count = @min(row.count, n); // the engine may hold more for prompt_logprobs' count + slot.* = logprobs.rowValue(srv, a, id, best, &.{}, false) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Failed => cx.other("the engine's prompt rows are out of step with the prompt"), + }; + } + @memcpy(all[ids.len..], after); + try shown.object.put(a, "content", .{ .array = all }); +} diff --git a/zig/src/server/completion_echo_test.zig b/zig/src/server/completion_echo_test.zig new file mode 100644 index 00000000000..a0072ac610a --- /dev/null +++ b/zig/src/server/completion_echo_test.zig @@ -0,0 +1,166 @@ +//! ``echo`` on /v1/completions: the prompt's text and rows ahead of an unchanged reply, prompt-only replies, refusals. +const std = @import("std"); +const server = @import("root.zig"); +const json = server.json; +const openai = @import("openai.zig"); +const fixture = @import("logprobs_test.zig"); +const Conn = @import("http_conn.zig").Conn; +const Allocator = std.mem.Allocator; +const T = std.testing; + +/// The route's reply to `body` over `backend`'s rows; the bytes-as-tokens text, so "abc" is the prompt 97, 98, 99. +fn sendTo(backend: *fixture.Script, chat: bool, body: []const u8) !fixture.Got { + var text: fixture.Text = .{}; + var srv = try server.Server.init(T.allocator, T.io, backend.engine(), text.text(), .{ + .served_name = "test-model", + .model_ids = &.{"test-model"}, + .enable_thinking = false, + .use_drafts = false, + }, null); + defer srv.deinit(); + var arena = std.heap.ArenaAllocator.init(T.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var conn: Conn = .{ .fd = -1, .peer = "", .buf = &.{}, .gpa = a }; + var got: fixture.Got = .{}; + openai.run(srv, a, got.out(), .{ .conn = &conn }, chat, (try json.parse(a, body)).ok); + return got; +} + +/// The whole 200 reply to a completion body, as values in `a`. +fn whole(a: Allocator, reply: []const u32, body: []const u8) !json.Value { + var backend: fixture.Script = .{ .reply = reply }; + var got = try sendTo(&backend, false, body); + defer got.deinit(); + try T.expectEqual(@as(u16, 200), got.status); + return (try json.parse(a, try a.dupe(u8, got.body))).ok; +} + +fn choiceOf(v: json.Value) json.Value { + return v.get("choices").?.array[0]; +} + +fn compact(a: Allocator, v: json.Value) ![]const u8 { + return json.stringify(a, v, .{ .compact = true }); +} + +fn expectList(a: Allocator, choice: json.Value, key: []const u8, want: []const u8) !void { + try T.expectEqualStrings(want, try compact(a, choice.get("logprobs").?.get(key).?)); +} + +test "completions echo: the prompt's tokens and rows come first, then the reply's entries as without echo" { + var arena = std.heap.ArenaAllocator.init(T.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = [_]u32{ 'H', 'i' }; + const head = "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":2,\"logprobs\":1"; + const plain = choiceOf(try whole(a, &reply, head ++ "}")); + const echoed_reply = try whole(a, &reply, head ++ ",\"echo\":true}"); + const echoed = choiceOf(echoed_reply); + try T.expectEqualStrings("Hi", plain.get("text").?.string); + try T.expectEqualStrings("abcHi", echoed.get("text").?.string); + // the first prompt token has no row; "b" is not its row's best token, so the best ('z') is its one alternative + try expectList(a, echoed, "tokens", "[\"a\",\"b\",\"c\",\"H\",\"i\"]"); + try expectList(a, echoed, "token_logprobs", "[null,-0.125,-0.25,-0.25,-0.5]"); + try expectList(a, echoed, "top_logprobs", "[null,{\"z\":-0.0},{\"c\":-0.25},{\"H\":-0.25},{\"i\":-0.5}]"); + try expectList(a, echoed, "text_offset", "[0,1,2,3,4]"); + // the reply's own entries are the ones the request gets without echo; only their offsets move past the prompt + for ([_][]const u8{ "tokens", "token_logprobs", "top_logprobs" }) |key| { + const tail: json.Value = .{ .array = echoed.get("logprobs").?.get(key).?.array[3..] }; + try T.expectEqualStrings(try compact(a, plain.get("logprobs").?.get(key).?), try compact(a, tail)); + } + try expectList(a, plain, "text_offset", "[0,1]"); + try T.expect(echoed.get("prompt_logprobs") == null); + try T.expectEqualStrings("{\"prompt_tokens\":3,\"completion_tokens\":2,\"total_tokens\":5,\"prompt_tokens_details\":{\"cached_tokens\":0},\"completion_tokens_details\":{\"reasoning_tokens\":0}}", try compact(a, echoed_reply.get("usage").?)); + // a prompt of token ids echoes their text; logprobs 0 gives each row no alternatives + const ids = choiceOf(try whole(a, &reply, "{\"model\":\"test-model\",\"prompt\":[97,98,99],\"max_tokens\":2,\"logprobs\":0,\"echo\":true}")); + try T.expectEqualStrings("abcHi", ids.get("text").?.string); + try expectList(a, ids, "top_logprobs", "[null,{},{},{},{}]"); + // without logprobs, echo is the prompt's text alone + const bare = choiceOf(try whole(a, &reply, "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":2,\"echo\":true}")); + try T.expectEqualStrings("abcHi", bare.get("text").?.string); + try T.expect(bare.get("logprobs").? == .null); +} + +test "completions echo: max_tokens 0 returns the prompt alone, and without echo keeps meaning the default length" { + var arena = std.heap.ArenaAllocator.init(T.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = [_]u32{ 'H', 'i' }; // the engine sends its whole reply whatever it is asked: the server keeps none + for ([_][]const u8{ "\"max_tokens\":0", "\"max_completion_tokens\":0", "\"max_tokens\":0,\"max_completion_tokens\":null" }) |limit| { + const body = try std.mem.concat(a, u8, &.{ "{\"model\":\"test-model\",\"prompt\":\"abc\",\"logprobs\":2,\"echo\":true,", limit, "}" }); + const got = try whole(a, &reply, body); + const c = choiceOf(got); + try T.expectEqualStrings("abc", c.get("text").?.string); + try T.expectEqualStrings("length", c.get("finish_reason").?.string); + try expectList(a, c, "tokens", "[\"a\",\"b\",\"c\"]"); + try expectList(a, c, "token_logprobs", "[null,-0.125,-0.25]"); + try expectList(a, c, "text_offset", "[0,1,2]"); + try T.expectEqualStrings("0", got.get("usage").?.get("completion_tokens").?.int); + } + const bare = choiceOf(try whole(a, &reply, "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":0,\"echo\":true}")); + try T.expectEqualStrings("abc", bare.get("text").?.string); + try T.expect(bare.get("logprobs").? == .null); + // the engine is asked for one token, the fewest a submitted reply takes, not for the server's default length + var backend: fixture.Script = .{ .reply = &reply }; + var asked = try sendTo(&backend, false, "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":0,\"logprobs\":1,\"echo\":true}"); + defer asked.deinit(); + try T.expectEqual(@as(u32, 1), backend.max_tokens); + const plain = choiceOf(try whole(a, &reply, "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":0}")); + try T.expectEqualStrings("Hi", plain.get("text").?.string); +} + +test "completions echo: echo false, null or absent leaves the reply as it was" { + var arena = std.heap.ArenaAllocator.init(T.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = [_]u32{ 'H', 'i' }; + const head = "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":2,\"logprobs\":2"; + const want = try whole(a, &reply, head ++ "}"); + for ([_][]const u8{ ",\"echo\":false}", ",\"echo\":null}" }) |tail| { + const got = try whole(a, &reply, try std.mem.concat(a, u8, &.{ head, tail })); + try T.expectEqualStrings(try compact(a, want.get("choices").?), try compact(a, got.get("choices").?)); + try T.expectEqualStrings(try compact(a, want.get("usage").?), try compact(a, got.get("usage").?)); + } +} + +test "completions echo: beside prompt_logprobs each form keeps its own count of alternatives" { + var arena = std.heap.ArenaAllocator.init(T.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const reply = [_]u32{ 'H', 'i' }; + // the engine reads two alternatives a row for echo: prompt_logprobs still lists one + const wide = choiceOf(try whole(a, &reply, "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":2,\"logprobs\":2,\"prompt_logprobs\":1,\"echo\":true}")); + try T.expectEqualStrings("[null,{\"98\":{\"logprob\":-0.125,\"rank\":2,\"decoded_token\":\"b\"},\"122\":{\"logprob\":-0.0,\"rank\":1,\"decoded_token\":\"z\"}},{\"99\":{\"logprob\":-0.25,\"rank\":1,\"decoded_token\":\"c\"}}]", try compact(a, wide.get("prompt_logprobs").?)); + try T.expectEqualStrings("{\"z\":-0.0,\"B\":-0.0625}", try compact(a, wide.get("logprobs").?.get("top_logprobs").?.array[1])); + // and the other way round: echo lists one, prompt_logprobs two + const narrow = choiceOf(try whole(a, &reply, "{\"model\":\"test-model\",\"prompt\":\"abc\",\"max_tokens\":2,\"logprobs\":1,\"prompt_logprobs\":2,\"echo\":true}")); + try T.expectEqualStrings("{\"z\":-0.0}", try compact(a, narrow.get("logprobs").?.get("top_logprobs").?.array[1])); + try T.expectEqual(@as(usize, 3), narrow.get("prompt_logprobs").?.array[1].object.count()); + try T.expectEqual(@as(usize, 2), narrow.get("prompt_logprobs").?.array[2].object.count()); +} + +test "completions echo: refused by name before anything is submitted, while chat routes still ignore the field" { + const reply = [_]u32{ 'H', 'i' }; + const cases = [_]struct { body: []const u8, message: []const u8, rows: bool = true }{ + .{ .body = "{\"prompt\":\"abc\",\"echo\":true,\"stream\":true}", .message = "echo is supported on /v1/completions without streaming only" }, + .{ .body = "{\"prompt\":\"abc\",\"echo\":\"yes\"}", .message = "echo must be a boolean or null" }, + .{ .body = "{\"prompt\":\"abc\",\"echo\":1}", .message = "echo must be a boolean or null" }, + .{ .body = "{\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"echo\":true}", .message = "echo is supported with a prompt, not messages" }, + .{ .body = "{\"prompt\":\"abc\",\"echo\":true}", .message = "echo is not supported by this model or backend", .rows = false }, + .{ .body = "{\"prompt\":\"abc\",\"echo\":true,\"max_tokens\":0,\"logprobs\":1}", .message = "echo is not supported by this model or backend", .rows = false }, + }; + for (cases) |c| { + var backend: fixture.Script = .{ .reply = &reply, .prompt_rows = c.rows }; + var got = try sendTo(&backend, false, c.body); + defer got.deinit(); + try T.expectEqual(@as(u16, 400), got.status); + try T.expect(std.mem.indexOf(u8, got.body, c.message) != null); + try T.expectEqual(@as(usize, 0), backend.submits); + } + var backend: fixture.Script = .{ .reply = &reply, .prompt_rows = false }; + var got = try sendTo(&backend, true, "{\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"max_tokens\":2,\"echo\":true}"); + defer got.deinit(); + try T.expectEqual(@as(u16, 200), got.status); + try T.expect(std.mem.indexOf(u8, got.body, "\"content\": \"Hi\"") != null); +} diff --git a/zig/src/server/logprobs.zig b/zig/src/server/logprobs.zig index b6e260343ee..c217057600b 100644 --- a/zig/src/server/logprobs.zig +++ b/zig/src/server/logprobs.zig @@ -20,12 +20,8 @@ pub fn legacy(a: Allocator, rows: Value, offset: *usize) Allocator.Error!Value { const text = r.object.get("token").?.string; t.* = .{ .string = text }; lp.* = r.object.get("logprob").?; - const alts = try json.newObject(a); - for (r.object.get("top_logprobs").?.array) |alt| { - const got = try alts.getOrPut(a, alt.object.get("token").?.string); - if (!got.found_existing) got.value_ptr.* = alt.object.get("logprob").?; - } - top.* = .{ .object = alts }; + const alts = r.object.get("top_logprobs").?; + top.* = if (alts == .array) try byText(a, alts.array) else .null; // an echoed prompt's first token has no row at.* = try json.intValue(a, offset.*); offset.* += reply_text.charCount(text); } @@ -37,14 +33,25 @@ pub fn legacy(a: Allocator, rows: Value, offset: *usize) Allocator.Error!Value { return .{ .object = out }; } +/// Alternatives as the legacy form keys them, each text to its logprob; of two that decode alike, the first. +fn byText(a: Allocator, alternatives: []const Value) Allocator.Error!Value { + const alts = try json.newObject(a); + for (alternatives) |alt| { + const got = try alts.getOrPut(a, alt.object.get("token").?.string); + if (!got.found_existing) got.value_ptr.* = alt.object.get("logprob").?; + } + return .{ .object = alts }; +} + /// vLLM's ``prompt_logprobs``: null, then ``{id: {logprob, rank, decoded_token}}`` a token, the prompt token first. -pub fn promptValue(srv: *Server, a: Allocator, rows: []const api.LogprobRow) Allocator.Error!Value { +pub fn promptValue(srv: *Server, a: Allocator, rows: []const api.LogprobRow, limit: u8) Allocator.Error!Value { const out = try a.alloc(Value, rows.len + 1); out[0] = .null; for (out[1..], rows) |*slot, r| { const o = try json.newObject(a); try promptEntry(srv, a, o, r.token, r.logprob, r.rank); - for (r.ids[0..r.count], r.logprobs[0..r.count], 1..) |id, lp, rank| if (id != r.token) try promptEntry(srv, a, o, id, lp, rank); + const n = @min(r.count, limit); // the engine may hold more for echo's count + for (r.ids[0..n], r.logprobs[0..n], 1..) |id, lp, rank| if (id != r.token) try promptEntry(srv, a, o, id, lp, rank); slot.* = .{ .object = o }; } return .{ .array = out }; diff --git a/zig/src/server/logprobs_test.zig b/zig/src/server/logprobs_test.zig index f311766ccab..0e356999f8b 100644 --- a/zig/src/server/logprobs_test.zig +++ b/zig/src/server/logprobs_test.zig @@ -77,6 +77,7 @@ pub const Script = struct { prompt_rows: bool = true, logprobs: bool = true, submits: usize = 0, + max_tokens: u32 = 0, // the last request's limit pub fn engine(e: *@This()) api.Engine { return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; @@ -91,6 +92,7 @@ pub const Script = struct { const e: *Script = @ptrCast(@alignCast(ctx)); e.submits += 1; e.asked = r.logprobs; + e.max_tokens = r.max_tokens; var rows: [1024]api.LogprobRow = undefined; for (e.reply, rows[0..e.reply.len], 0..) |t, *row, i| { const lp = -@as(f32, @floatFromInt(i + 1)) / 4; diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index c96c3b68fe8..8e2a65351e7 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -148,9 +148,9 @@ pub fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value, format: ?[]const u input.fields = .{ .object = sampling }; input.explicit_off = client_thinking and !(thinking.enable orelse true); const streamed = if (body.get("stream")) |s| s.truthy() else false; - input.prompt_logprobs = try fields.promptLogprobs(cx, body, !is_chat, streamed, srv.info.capability(.prompt_logprobs)); input.logprobs = logprobs; input.cache_salt = try @import("cache_salt.zig").field(&srv.tool_ids, cx, body); + try @import("completion_echo.zig").plan(srv, cx, body, &input, !is_chat, streamed); var policy: tool_stream.Policy = .{}; if (body.field("parallel_tool_calls")) |p| { if (p != .bool) return cx.refuse("parallel_tool_calls must be a boolean"); @@ -332,7 +332,7 @@ pub const Run = struct { var cx: Cx = .{ .a = a }; var reply = (if (r.turn) |t| cortheon.loop.whole(t, r.srv, &cx, &r.plan.input, gone) else chat.run(r.srv, &cx, r.plan.input, null, gone)) catch |e| return r.unsent(&cx, e, field); const calls = r.attachCalls(&reply) catch return; - @import("logprobs.zig").project(r.srv, &cx, &reply, r.plan.input.tools, calls) catch |e| return r.unsent(&cx, e, field); + @import("completion_echo.zig").project(r.srv, &cx, &reply, r.plan.input, calls) catch |e| return r.unsent(&cx, e, field); const o = json.newObject(a) catch return; r.wholeBody(o, &reply, calls) catch return; r.out.vt.reply(r.out.ctx, 200, .{ .object = o }); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 51bb4a550fe..c6f5add9375 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -177,6 +177,7 @@ test { _ = @import("tool_single_stream_test.zig"); _ = @import("logprobs_test.zig"); _ = @import("logprob_parts_test.zig"); + _ = @import("completion_echo_test.zig"); _ = @import("limit_pins_test.zig"); _ = @import("flag_deps_test.zig"); _ = @import("think_split_test.zig"); diff --git a/zig/tests/server/corpus.py b/zig/tests/server/corpus.py index 8dae5c647df..22077479ef5 100644 --- a/zig/tests/server/corpus.py +++ b/zig/tests/server/corpus.py @@ -125,6 +125,8 @@ def completion_cases(encode: Any) -> list[tuple[str, str, list[Any]]]: out.append(("completions", f"{name}-stream", [post("/v1/completions", {**bodies[name], "stream": True})])) out.append(("completions", "usage-chunk", [post("/v1/completions", {**bodies["text"], "stream": True, "stream_options": {"include_usage": True}})])) out.append(("completions", "think-script", [post("/v1/completions", {"prompt": "x @script=think", "stream": True})])) + for name, extra in (("echo-false", {"echo": False}), ("echo-unsupported", {"echo": True}), ("echo-stream", {"echo": True, "stream": True})): + out.append(("completions", name, [post("/v1/completions", {**bodies["text"], **extra})])) return out diff --git a/zig/tests/server/golden/cases.json b/zig/tests/server/golden/cases.json index 1acfa44e12f..87adc3b6e2d 100644 --- a/zig/tests/server/golden/cases.json +++ b/zig/tests/server/golden/cases.json @@ -1 +1 @@ -{"steps": [{"kind": "serve", "args": [], "env": {"TENSORFOLD_REQUEST_LOG": "@LOG@"}, "cases": [{"group": "chat", "name": "default", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "default-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "plain", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "chat", "name": "plain-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "chat", "name": "think", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "chat", "name": "think-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "chat", "name": "split_utf8", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zcGxpdF91dGY4In1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "split_utf8-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zcGxpdF91dGY4In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "harmony", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "harmony-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "long", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "long-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "no_end", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1ub19lbmQifV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "chat", "name": "no_end-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1ub19lbmQifV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "chat", "name": "json_answer", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1qc29uX2Fuc3dlciJ9XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "chat", "name": "json_answer-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1qc29uX2Fuc3dlciJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "thinking", "name": "think-off", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJlbmFibGVfdGhpbmtpbmciOiBmYWxzZX19"}], "opts": {}}, {"group": "thinking", "name": "think-off-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNTQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0cmVhbSI6IHRydWUsICJjaGF0X3RlbXBsYXRlX2t3YXJncyI6IHsiZW5hYmxlX3RoaW5raW5nIjogZmFsc2V9fQ=="}], "opts": {}}, {"group": "thinking", "name": "harmony-off", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAiY2hhdF90ZW1wbGF0ZV9rd2FyZ3MiOiB7ImVuYWJsZV90aGlua2luZyI6IGZhbHNlfX0="}], "opts": {}}, {"group": "thinking", "name": "harmony-off-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAic3RyZWFtIjogdHJ1ZSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJlbmFibGVfdGhpbmtpbmciOiBmYWxzZX19"}], "opts": {}}, {"group": "thinking", "name": "default-off", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAiY2hhdF90ZW1wbGF0ZV9rd2FyZ3MiOiB7ImVuYWJsZV90aGlua2luZyI6IGZhbHNlfX0="}], "opts": {}}, {"group": "thinking", "name": "default-off-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAic3RyZWFtIjogdHJ1ZSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJlbmFibGVfdGhpbmtpbmciOiBmYWxzZX19"}], "opts": {}}, {"group": "thinking", "name": "effort-none", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibm9uZSJ9"}], "opts": {}}, {"group": "thinking", "name": "effort-low", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibG93In0="}], "opts": {}}, {"group": "thinking", "name": "effort-high", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAiaGlnaCJ9"}], "opts": {}}, {"group": "thinking", "name": "effort-max", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibWF4In0="}], "opts": {}}, {"group": "thinking", "name": "effort-medium", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibWVkaXVtIn0="}], "opts": {}}, {"group": "thinking", "name": "effort-bogus", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAiYm9ndXMifQ=="}], "opts": {}}, {"group": "thinking", "name": "deepseek-switch", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJ0aGlua2luZyI6IHsidHlwZSI6ICJkaXNhYmxlZCJ9fX0="}], "opts": {}}, {"group": "thinking", "name": "kwargs-effort", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJyZWFzb25pbmdfZWZmb3J0IjogImxvdyJ9fQ=="}], "opts": {}}, {"group": "thinking", "name": "length-while-thinking", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGlua19sb25nIn1dLCAibWF4X3Rva2VucyI6IDR9"}], "opts": {}}, {"group": "thinking", "name": "length-while-thinking-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGlua19sb25nIn1dLCAibWF4X3Rva2VucyI6IDQsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-[wor]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29yIl19"}], "opts": {}}, {"group": "stops", "name": "stop-[wor]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29yIl0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-STOP", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6ICJTVE9QIn0="}], "opts": {}}, {"group": "stops", "name": "stop-STOP-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6ICJTVE9QIiwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "stops", "name": "stop-[zzz, STOP]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsienp6IiwgIlNUT1AiXX0="}], "opts": {}}, {"group": "stops", "name": "stop-[zzz, STOP]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsienp6IiwgIlNUT1AiXSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "stops", "name": "stop-[ld STO]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsibGQgU1RPIl19"}], "opts": {}}, {"group": "stops", "name": "stop-[ld STO]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsibGQgU1RPIl0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-[worldx]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29ybGR4Il19"}], "opts": {}}, {"group": "stops", "name": "stop-[worldx]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29ybGR4Il0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-in-reasoning", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0b3AiOiBbInRoaW5rIl19"}], "opts": {}}, {"group": "stops", "name": "ignore-eos", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1lb3NfbWlkIn1dLCAiaWdub3JlX2VvcyI6IHRydWV9"}], "opts": {}}, {"group": "stops", "name": "eos-mid", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1lb3NfbWlkIn1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "usage", "name": "include-usage", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWUsICJzdHJlYW1fb3B0aW9ucyI6IHsiaW5jbHVkZV91c2FnZSI6IHRydWV9fQ=="}], "opts": {}}, {"group": "usage", "name": "max-tokens", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X3Rva2VucyI6IDN9"}], "opts": {}}, {"group": "usage", "name": "max-completion-tokens", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X2NvbXBsZXRpb25fdG9rZW5zIjogMn0="}], "opts": {}}, {"group": "usage", "name": "max-tokens-zero", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X3Rva2VucyI6IDB9"}], "opts": {}}, {"group": "usage", "name": "max-tokens-string", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X3Rva2VucyI6ICI1In0="}], "opts": {}}, {"group": "usage", "name": "sampled", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRlbXBlcmF0dXJlIjogMC43LCAidG9wX2siOiA1fQ=="}], "opts": {}}, {"group": "usage", "name": "seeded", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRlbXBlcmF0dXJlIjogMSwgInNlZWQiOiAtMywgImRyYWZ0IjogZmFsc2V9"}], "opts": {}}, {"group": "usage", "name": "model-alias", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtYWxpYXMiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "usage", "name": "model-unknown", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4MQ0KDQp7Im1vZGVsIjogIm90aGVyIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "usage", "name": "background-title", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTANCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAiV3JpdGUgYSB0aXRsZSJ9LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogInggQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "qwen_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "qwen_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "xml_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "xml_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "xml_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "xml_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "two_tools", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "two_tools-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "two_tools-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "two_tools-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "glm_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "glm_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "glm_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "glm_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "gemma_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "gemma_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "gemma_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "gemma_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "dsml_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "dsml_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "dsml_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "dsml_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "lfm2_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "lfm2_json-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_json-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_json-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_typed", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_typed-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "lfm2_typed-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_typed-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "lfm2_two", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_two-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_two-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "lfm2_two-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "bare_json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "bare_json-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "bare_json-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "bare_json-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "bad_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "bad_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "bad_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "bad_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "plain", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "plain-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "plain-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "plain-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "choice-\"auto\"", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiAiYXV0byJ9"}], "opts": {}}, {"group": "tools", "name": "choice-\"none\"", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiAibm9uZSJ9"}], "opts": {}}, {"group": "tools", "name": "choice-\"required\"", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiAicmVxdWlyZWQifQ=="}], "opts": {}}, {"group": "tools", "name": "choice-{\"type\": \"function\", \"function\": {\"name\": \"lookup\"}}", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIn19fQ=="}], "opts": {}}, {"group": "tools", "name": "choice-{\"type\": \"function\", \"function\": {\"name\": \"nope\"}}", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibm9wZSJ9fX0="}], "opts": {}}, {"group": "tools", "name": "choice-{\"type\": \"function\"}", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiZnVuY3Rpb24ifX0="}], "opts": {}}, {"group": "tools", "name": "required-no-tools", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xfY2hvaWNlIjogInJlcXVpcmVkIn0="}], "opts": {}}, {"group": "tools", "name": "tools-not-list", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogeyJhIjogMX19"}], "opts": {}}, {"group": "tools", "name": "tool-without-name", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHt9fV19"}], "opts": {}}, {"group": "tools", "name": "parallel-not-bool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogInllcyJ9"}], "opts": {}}, {"group": "tools", "name": "history-with-calls", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1MjUNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQgaXQifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogIiIsICJ0b29sX2NhbGxzIjogW3siaWQiOiAiY2FsbF8xIiwgInR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImFyZ3VtZW50cyI6ICJ7XCJxdWVyeVwiOiBcInhcIn0ifX1dfSwgeyJyb2xlIjogInRvb2wiLCAidG9vbF9jYWxsX2lkIjogImNhbGxfMSIsICJjb250ZW50IjogImZvdW5kIn0sIHsicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiZ28gQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV19"}], "opts": {}}, {"group": "tools", "name": "history-bad-arguments", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyNDcNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQgaXQifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogIiIsICJ0b29sX2NhbGxzIjogW3siaWQiOiAiYyIsICJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJhcmd1bWVudHMiOiAibm90IGpzb24ifX1dfSwgeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJnbyBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "errors", "name": "not-json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1DQoNCntub3Bl"}], "opts": {}}, {"group": "errors", "name": "list-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCltd"}], "opts": {}}, {"group": "errors", "name": "null-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA0DQoNCm51bGw="}], "opts": {}}, {"group": "errors", "name": "empty-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAwDQoNCg=="}], "opts": {}}, {"group": "errors", "name": "string-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzDQoNCiJ4Ig=="}], "opts": {}}, {"group": "errors", "name": "bad-utf8", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNw0KDQp7Im1lc3NhZ2VzIjogIv8ifQ=="}], "opts": {}}, {"group": "errors", "name": "trailing-comma", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5DQoNCnsiYSI6IDEsfQ=="}], "opts": {}}, {"group": "errors", "name": "n-seventeen", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5NQ0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAibiI6IDE3fQ=="}], "opts": {}}, {"group": "errors", "name": "logprobs", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImxvZ3Byb2JzIjogdHJ1ZX0="}], "opts": {}}, {"group": "errors", "name": "top-logprobs", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvcF9sb2dwcm9icyI6IDN9"}], "opts": {}}, {"group": "errors", "name": "temperature-text", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRlbXBlcmF0dXJlIjogImFiYyJ9"}], "opts": {}}, {"group": "errors", "name": "min-p", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5OA0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAibWluX3AiOiAyfQ=="}], "opts": {}}, {"group": "errors", "name": "top-k-float", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvcF9rIjogMS41fQ=="}], "opts": {}}, {"group": "errors", "name": "ignore-eos-null", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImlnbm9yZV9lb3MiOiBudWxsfQ=="}], "opts": {}}, {"group": "errors", "name": "stop-empty", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0b3AiOiBbIiJdfQ=="}], "opts": {}}, {"group": "errors", "name": "stop-int", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5Nw0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAic3RvcCI6IDV9"}], "opts": {}}, {"group": "errors", "name": "messages-missing", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNA0KDQp7Im1vZGVsIjogIngifQ=="}], "opts": {}}, {"group": "errors", "name": "messages-empty", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNg0KDQp7Im1lc3NhZ2VzIjogW119"}], "opts": {}}, {"group": "errors", "name": "role-robot", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA0OQ0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJyb2JvdCIsICJjb250ZW50IjogIngifV19"}], "opts": {}}, {"group": "errors", "name": "content-int", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA0Ng0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiA1fV19"}], "opts": {}}, {"group": "errors", "name": "content-image", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5NQ0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogImltYWdlX3VybCIsICJpbWFnZV91cmwiOiB7InVybCI6ICJ4In19XX1dfQ=="}], "opts": {}}, {"group": "errors", "name": "message-not-object", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMA0KDQp7Im1lc3NhZ2VzIjogWyJoaSJdfQ=="}], "opts": {}}, {"group": "errors", "name": "text-part-int", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA3NA0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogInRleHQiLCAidGV4dCI6IDF9XX1dfQ=="}], "opts": {}}, {"group": "errors", "name": "modalities", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgIm1vZGFsaXRpZXMiOiBbInRleHQiLCAiYXVkaW8iXX0="}], "opts": {}}, {"group": "errors", "name": "audio-field", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImF1ZGlvIjogeyJ2b2ljZSI6ICJ4In19"}], "opts": {}}, {"group": "errors", "name": "format-json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1qc29uX2Fuc3dlciJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJqc29uX29iamVjdCJ9fQ=="}], "opts": {}}, {"group": "errors", "name": "format-bogus", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJib2d1cyJ9fQ=="}], "opts": {}}, {"group": "errors", "name": "format-text", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJ0ZXh0In19"}], "opts": {}}, {"group": "errors", "name": "format-string", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6ICJqc29uIn0="}], "opts": {}}, {"group": "errors", "name": "format-no-schema", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJqc29uX3NjaGVtYSIsICJqc29uX3NjaGVtYSI6IHt9fX0="}], "opts": {}}, {"group": "errors", "name": "guided-choice-empty", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImd1aWRlZF9jaG9pY2UiOiBbXX0="}], "opts": {}}, {"group": "errors", "name": "guided-json-bad", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImd1aWRlZF9qc29uIjogIntiYWQifQ=="}], "opts": {}}, {"group": "errors", "name": "structured-other", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cnVjdHVyZWRfb3V0cHV0cyI6IHsieG1sIjogMX19"}], "opts": {}}, {"group": "errors", "name": "format-with-required", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJ0b29sX2Nob2ljZSI6ICJyZXF1aXJlZCIsICJyZXNwb25zZV9mb3JtYXQiOiB7InR5cGUiOiAianNvbl9vYmplY3QifX0="}], "opts": {}}, {"group": "errors", "name": "context-prompt", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTQ3DQoNCnsibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJ4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eCJ9XX0="}], "opts": {}}, {"group": "errors", "name": "context-reply", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgIm1heF90b2tlbnMiOiAyMDAwfQ=="}], "opts": {}}, {"group": "errors", "name": "system-merged", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNzYNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAiQSJ9LCB7InJvbGUiOiAiZGV2ZWxvcGVyIiwgImNvbnRlbnQiOiAiQiJ9LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogInggQHNjcmlwdD1wbGFpbiJ9LCB7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAibGF0ZSJ9XX0="}], "opts": {}}, {"group": "errors", "name": "stream-context", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgIm1heF90b2tlbnMiOiAyMDAwLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "errors", "name": "stream-structured", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJqc29uX29iamVjdCJ9LCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "completions", "name": "text", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMzINCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIn0="}], "opts": {}}, {"group": "completions", "name": "ids", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogOTYNCg0KeyJwcm9tcHQiOiBbNzksIDExMCwgOTksIDEwMSwgMzIsIDY0LCAxMTUsIDk5LCAxMTQsIDEwNSwgMTEyLCAxMTYsIDYxLCAxMTYsIDEwNCwgMTA1LCAxMTAsIDEwN119"}], "opts": {}}, {"group": "completions", "name": "bad-ids", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjINCg0KeyJwcm9tcHQiOiBbNSwgOTk5OTldfQ=="}], "opts": {}}, {"group": "completions", "name": "bool-ids", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjENCg0KeyJwcm9tcHQiOiBbdHJ1ZSwgMV19"}], "opts": {}}, {"group": "completions", "name": "strings", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMzYNCg0KeyJwcm9tcHQiOiBbImEiLCAiYiBAc2NyaXB0PXBsYWluIl19"}], "opts": {}}, {"group": "completions", "name": "null", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTYNCg0KeyJwcm9tcHQiOiBudWxsfQ=="}], "opts": {}}, {"group": "completions", "name": "missing", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMg0KDQp7fQ=="}], "opts": {}}, {"group": "completions", "name": "messages", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjMNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV19"}], "opts": {}}, {"group": "completions", "name": "number", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTQNCg0KeyJwcm9tcHQiOiAxMn0="}], "opts": {}}, {"group": "completions", "name": "nested", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDANCg0KeyJwcm9tcHQiOiBbWyJ4Il0sICJ5IEBzY3JpcHQ9ZGVmYXVsdCJdfQ=="}], "opts": {}}, {"group": "completions", "name": "max-tokens", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDUNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PWxvbmciLCAibWF4X3Rva2VucyI6IDJ9"}], "opts": {}}, {"group": "completions", "name": "text-stream", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDgNCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "completions", "name": "messages-stream", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNzkNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "completions", "name": "usage-chunk", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogOTENCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgInN0cmVhbSI6IHRydWUsICJzdHJlYW1fb3B0aW9ucyI6IHsiaW5jbHVkZV91c2FnZSI6IHRydWV9fQ=="}], "opts": {}}, {"group": "completions", "name": "think-script", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDUNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXRoaW5rIiwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "responses", "name": "input-string", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUyDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJpbnB1dCI6ICJIaSBAc2NyaXB0PXRoaW5rIn0="}], "opts": {}}, {"group": "responses", "name": "input-stream", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ1DQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD10aGluayIsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "responses", "name": "tools", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE5Mw0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cXdlbl90b29sIiwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJuYW1lIjogImxvb2t1cCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fV19"}], "opts": {}}, {"group": "responses", "name": "tools-stream", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDk5DQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCIsICJzdHJlYW0iOiB0cnVlLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAibG9va3VwIn1dfQ=="}], "opts": {}}, {"group": "responses", "name": "incomplete", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUyDQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD1sb25nIiwgIm1heF9vdXRwdXRfdG9rZW5zIjogMn0="}], "opts": {}}, {"group": "responses", "name": "instructions", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE3OQ0KDQp7ImlucHV0IjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogImlucHV0X3RleHQiLCAidGV4dCI6ICJ4IEBzY3JpcHQ9cGxhaW4ifV19XSwgImluc3RydWN0aW9ucyI6ICJCZSBicmllZiIsICJtZXRhZGF0YSI6IHsiayI6ICJ2In0sICJ0ZW1wZXJhdHVyZSI6IDAsICJzdG9yZSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "responses", "name": "items", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDM0NA0KDQp7ImlucHV0IjogW3sidHlwZSI6ICJtZXNzYWdlIiwgInJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQifSwgeyJ0eXBlIjogInJlYXNvbmluZyIsICJjb250ZW50IjogW3sidHlwZSI6ICJyZWFzb25pbmdfdGV4dCIsICJ0ZXh0IjogImhtbSJ9XX0sIHsidHlwZSI6ICJmdW5jdGlvbl9jYWxsIiwgImNhbGxfaWQiOiAiYzEiLCAibmFtZSI6ICJsb29rdXAiLCAiYXJndW1lbnRzIjogInt9In0sIHsidHlwZSI6ICJmdW5jdGlvbl9jYWxsX291dHB1dCIsICJjYWxsX2lkIjogImMxIiwgIm91dHB1dCI6IFt7InR5cGUiOiAiaW5wdXRfdGV4dCIsICJ0ZXh0IjogImRvbmUgQHNjcmlwdD1wbGFpbiJ9XX1dfQ=="}], "opts": {}}, {"group": "responses", "name": "allowed-tools", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDIzMQ0KDQp7ImlucHV0IjogInggQHNjcmlwdD1xd2VuX3Rvb2wiLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAibG9va3VwIn0sIHsidHlwZSI6ICJmdW5jdGlvbiIsICJuYW1lIjogIm90aGVyIn1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiYWxsb3dlZF90b29scyIsICJtb2RlIjogImF1dG8iLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAibG9va3VwIn1dfX0="}], "opts": {}}, {"group": "responses", "name": "stored-chain", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMwDQoNCnsiaW5wdXQiOiAib25lIEBzY3JpcHQ9cGxhaW4ifQ=="}, {"tmpl_b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDY1DQoNCnsiaW5wdXQiOiAidHdvIEBzY3JpcHQ9dGhpbmsiLCAicHJldmlvdXNfcmVzcG9uc2VfaWQiOiAiWlpJRDBaWiJ9", "ids": [0]}, {"tmpl_b64": "R0VUIC92MS9yZXNwb25zZXMvWlpJRDFaWiBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg==", "ids": [1]}, {"tmpl_b64": "REVMRVRFIC92MS9yZXNwb25zZXMvWlpJRDBaWiBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg==", "ids": [0]}, {"tmpl_b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAidGhyZWUiLCAicHJldmlvdXNfcmVzcG9uc2VfaWQiOiAiWlpJRDFaWiJ9", "ids": [1]}], "opts": {}}, {"group": "responses", "name": "get-missing", "raws": [{"b64": "R0VUIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "responses", "name": "delete-missing", "raws": [{"b64": "REVMRVRFIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "responses", "name": "delete-collection", "raws": [{"b64": "REVMRVRFIC92MS9yZXNwb25zZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "responses", "name": "post-with-id", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzL3Jlc3BfeCBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNA0KDQp7ImlucHV0IjogIngifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-include", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ2DQoNCnsiaW5wdXQiOiAieCIsICJpbmNsdWRlIjogWyJyZWFzb25pbmcuYm9ndXMiXX0="}], "opts": {}}, {"group": "responses", "name": "refuse-truncation", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDM2DQoNCnsiaW5wdXQiOiAieCIsICJ0cnVuY2F0aW9uIjogImF1dG8ifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-background", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUwDQoNCnsiaW5wdXQiOiAieCIsICJiYWNrZ3JvdW5kIjogdHJ1ZSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "responses", "name": "refuse-empty-input", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDEzDQoNCnsiaW5wdXQiOiBbXX0="}], "opts": {}}, {"group": "responses", "name": "refuse-item-type", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMwDQoNCnsiaW5wdXQiOiBbeyJ0eXBlIjogImJvZ3VzIn1dfQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-tool-type", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ5DQoNCnsiaW5wdXQiOiAieCIsICJ0b29scyI6IFt7InR5cGUiOiAid2ViX3NlYXJjaCJ9XX0="}], "opts": {}}, {"group": "responses", "name": "refuse-metadata", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDIwNQ0KDQp7ImlucHV0IjogIngiLCAibWV0YWRhdGEiOiB7IjAiOiAidiIsICIxIjogInYiLCAiMiI6ICJ2IiwgIjMiOiAidiIsICI0IjogInYiLCAiNSI6ICJ2IiwgIjYiOiAidiIsICI3IjogInYiLCAiOCI6ICJ2IiwgIjkiOiAidiIsICIxMCI6ICJ2IiwgIjExIjogInYiLCAiMTIiOiAidiIsICIxMyI6ICJ2IiwgIjE0IjogInYiLCAiMTUiOiAidiIsICIxNiI6ICJ2In19"}], "opts": {}}, {"group": "responses", "name": "refuse-not-json", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDENCg0Kew=="}], "opts": {}}, {"group": "responses", "name": "refuse-list-body", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMNCg0KWzFd"}], "opts": {}}, {"group": "responses", "name": "refuse-format", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAieCIsICJ0ZXh0IjogeyJmb3JtYXQiOiB7InR5cGUiOiAiYm9ndXMifX19"}], "opts": {}}, {"group": "responses", "name": "refuse-content-part", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDY2DQoNCnsiaW5wdXQiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6IFt7InR5cGUiOiAiaW5wdXRfZmlsZSJ9XX1dfQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-role", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ2DQoNCnsiaW5wdXQiOiBbeyJyb2xlIjogInJvYm90IiwgImNvbnRlbnQiOiAieCJ9XX0="}], "opts": {}}, {"group": "responses", "name": "refuse-previous-missing", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUxDQoNCnsiaW5wdXQiOiAieCIsICJwcmV2aW91c19yZXNwb25zZV9pZCI6ICJyZXNwX2dvbmUifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-logprobs", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMyDQoNCnsiaW5wdXQiOiAieCIsICJsb2dwcm9icyI6IHRydWV9"}], "opts": {}}, {"group": "responses", "name": "refuse-chat-refusal", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDM2DQoNCnsiaW5wdXQiOiAieCIsICJ0ZW1wZXJhdHVyZSI6ICJob3QifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-image", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDkwDQoNCnsiaW5wdXQiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6IFt7InR5cGUiOiAiaW5wdXRfaW1hZ2UiLCAiaW1hZ2VfdXJsIjogImRhdGE6eCJ9XX1dfQ=="}], "opts": {}}, {"group": "anthropic", "name": "plain", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTA0DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV19"}], "opts": {}}, {"group": "anthropic", "name": "plain-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTIwDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "anthropic", "name": "thinking", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0aGlua2luZyI6IHsidHlwZSI6ICJlbmFibGVkIiwgImJ1ZGdldF90b2tlbnMiOiAzMn19"}], "opts": {}}, {"group": "anthropic", "name": "thinking-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU0DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiB0cnVlLCAidGhpbmtpbmciOiB7InR5cGUiOiAiYWRhcHRpdmUifX0="}], "opts": {}}, {"group": "anthropic", "name": "system", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV0sICJzeXN0ZW0iOiBbeyJ0eXBlIjogInRleHQiLCAidGV4dCI6ICJCZSBraW5kIn1dfQ=="}], "opts": {}}, {"group": "anthropic", "name": "tool-use", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjc1DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cXdlbl90b29sIn1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV19"}], "opts": {}}, {"group": "anthropic", "name": "tool-use-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjkwDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9eG1sX3Rvb2wifV0sICJ0b29scyI6IFt7Im5hbWUiOiAibG9va3VwIiwgImlucHV0X3NjaGVtYSI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fSwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "anthropic", "name": "tool-use-think-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMzUwDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cXdlbl90b29sX3RoaW5rIn1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV0sICJzdHJlYW0iOiB0cnVlLCAidGhpbmtpbmciOiB7InR5cGUiOiAiZW5hYmxlZCIsICJidWRnZXRfdG9rZW5zIjogOH19"}], "opts": {}}, {"group": "anthropic", "name": "stop-sequence", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTM3DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9c3RvcF93b3JkcyJ9XSwgInN0b3Bfc2VxdWVuY2VzIjogWyJTVE9QIl19"}], "opts": {}}, {"group": "anthropic", "name": "stop-sequence-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9c3RvcF93b3JkcyJ9XSwgInN0b3Bfc2VxdWVuY2VzIjogWyJTVE9QIl0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "anthropic", "name": "max-tokens", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTE4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogMiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "anthropic", "name": "tool-result", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjM5DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogW3sidHlwZSI6ICJ0aGlua2luZyIsICJ0aGlua2luZyI6ICJobW0ifSwgeyJ0eXBlIjogInRvb2xfdXNlIiwgImlkIjogInQxIiwgIm5hbWUiOiAibG9va3VwIiwgImlucHV0IjogeyJxdWVyeSI6ICLDqSJ9fV19LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogW3sidHlwZSI6ICJ0b29sX3Jlc3VsdCIsICJ0b29sX3VzZV9pZCI6ICJ0MSIsICJjb250ZW50IjogIm9rIiwgImlzX2Vycm9yIjogdHJ1ZX0sIHsidHlwZSI6ICJ0ZXh0IiwgInRleHQiOiAiZ28gQHNjcmlwdD1wbGFpbiJ9XX1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV0sICJ0b29sX2Nob2ljZSI6IHsidHlwZSI6ICJhbnkiLCAiZGlzYWJsZV9wYXJhbGxlbF90b29sX3VzZSI6IHRydWV9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "count", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMvY291bnRfdG9rZW5zIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDI0NA0KDQp7Im1vZGVsIjogIm0iLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV19"}], "opts": {}}, {"group": "anthropic", "name": "count-query", "raws": [{"b64": "UE9TVCAvbWVzc2FnZXMvY291bnRfdG9rZW5zP2JldGE9dHJ1ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzANCg0KeyJtb2RlbCI6ICJtIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRoaW5raW5nIjogeyJ0eXBlIjogImVuYWJsZWQiLCAiYnVkZ2V0X3Rva2VucyI6IDV9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-no-model", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogODANCg0KeyJtYXhfdG9rZW5zIjogNSwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-no-max", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNzcNCg0KeyJtb2RlbCI6ICJtIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-stream-text", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTIxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiAieWVzIn0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-choice", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTM4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0b29sX2Nob2ljZSI6IHsidHlwZSI6ICJib2d1cyJ9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-redacted", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTM1DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAiYXNzaXN0YW50IiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogInJlZGFjdGVkX3RoaW5raW5nIiwgImRhdGEiOiAieCJ9XX1dfQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-budget", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0aGlua2luZyI6IHsidHlwZSI6ICJlbmFibGVkIiwgImJ1ZGdldF90b2tlbnMiOiA2NH19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-server-tool", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTYxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAid2ViX3NlYXJjaF8yMDI1MDMwNSIsICJuYW1lIjogIncifV19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-mid-system", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTY0DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImEifSwgeyJyb2xlIjogInN5c3RlbSIsICJjb250ZW50IjogImIifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogImMifV19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-bad-system", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTI1DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAiYiJ9LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImEifV19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-context", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJjb250ZXh0X21hbmFnZW1lbnQiOiB7ImVkaXRzIjogW3sidHlwZSI6ICJvdGhlciJ9XX19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-service-tier", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTMyDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzZXJ2aWNlX3RpZXIiOiAicHJpb3JpdHkifQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-not-json", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMg0KDQp7eA=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-image", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogW3sidHlwZSI6ICJpbWFnZSIsICJzb3VyY2UiOiB7InR5cGUiOiAidXJsIiwgInVybCI6ICJodHRwOi8veCJ9fV19XX0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-effort", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTQxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJvdXRwdXRfY29uZmlnIjogeyJlZmZvcnQiOiAiaHVnZSJ9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-format", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTcyDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJvdXRwdXRfY29uZmlnIjogeyJmb3JtYXQiOiB7InR5cGUiOiAianNvbl9zY2hlbWEiLCAic2NoZW1hIjoge319fX0="}], "opts": {}}, {"group": "tokens", "name": "tokenize-prompt", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjgNCg0KeyJwcm9tcHQiOiAiSGVsbG8gd29ybGQgw6kifQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-prompt-special", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNTYNCg0KeyJwcm9tcHQiOiAiPHxpbV9zdGFydHw+eCIsICJhZGRfc3BlY2lhbF90b2tlbnMiOiBmYWxzZX0="}], "opts": {}}, {"group": "tokens", "name": "tokenize-strs", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDgNCg0KeyJwcm9tcHQiOiAiSGVsbG9cbiIsICJyZXR1cm5fdG9rZW5fc3RycyI6IHRydWV9"}], "opts": {}}, {"group": "tokens", "name": "tokenize-messages", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjMNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "tokens", "name": "tokenize-messages-no-gen", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjk0DQoNCnsibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAiYWRkX2dlbmVyYXRpb25fcHJvbXB0IjogZmFsc2UsICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dfQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-messages-effort", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogOTANCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV0sICJyZWFzb25pbmdfZWZmb3J0IjogImxvdyJ9"}], "opts": {}}, {"group": "tokens", "name": "tokenize-prompt-int", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTMNCg0KeyJwcm9tcHQiOiA1fQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-flag-bad", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDMNCg0KeyJwcm9tcHQiOiAieCIsICJyZXR1cm5fdG9rZW5fc3RycyI6ICJ5ZXMifQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-list-body", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMw0KDQpbMV0="}], "opts": {}}, {"group": "tokens", "name": "tokenize-bad-json", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMQ0KDQp7"}], "opts": {}}, {"group": "tokens", "name": "tokenize-tools-bad", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNzUNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV0sICJ0b29scyI6IDN9"}], "opts": {}}, {"group": "tokens", "name": "tokenize-v1", "raws": [{"b64": "UE9TVCAvdjEvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUNCg0KeyJwcm9tcHQiOiAieCJ9"}], "opts": {}}, {"group": "tokens", "name": "detokenize-ids", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMg0KDQp7InRva2VucyI6IFsyODQsIDI4NV19"}], "opts": {}}, {"group": "tokens", "name": "detokenize-nested", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMw0KDQp7InRva2VucyI6IFtbNzIsIDEwNV1dfQ=="}], "opts": {}}, {"group": "tokens", "name": "detokenize-range", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMA0KDQp7InRva2VucyI6IFsxLCA5OTldfQ=="}], "opts": {}}, {"group": "tokens", "name": "detokenize-negative", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNg0KDQp7InRva2VucyI6IFstMV19"}], "opts": {}}, {"group": "tokens", "name": "detokenize-floats", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNw0KDQp7InRva2VucyI6IFsxLjBdfQ=="}], "opts": {}}, {"group": "tokens", "name": "detokenize-missing", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCnt9"}], "opts": {}}, {"group": "tokens", "name": "detokenize-body-list", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCltd"}], "opts": {}}, {"group": "status", "name": "get-health", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-", "raws": [{"b64": "R0VUIC8gSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-health-", "raws": [{"b64": "R0VUIC9oZWFsdGgvIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "status", "name": "get-v1-models", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-models", "raws": [{"b64": "R0VUIC9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-v1-models?x=1", "raws": [{"b64": "R0VUIC92MS9tb2RlbHM/eD0xIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "status", "name": "get-x-models", "raws": [{"b64": "R0VUIC94L21vZGVscyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}], "opts": {}}, {"group": "status", "name": "get-v1-health", "raws": [{"b64": "R0VUIC92MS9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-nope", "raws": [{"b64": "R0VUIC9ub3BlIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "status", "name": "get-v1-responses", "raws": [{"b64": "R0VUIC92MS9yZXNwb25zZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-health?reset_peak=1", "raws": [{"b64": "R0VUIC9oZWFsdGg/cmVzZXRfcGVhaz0xIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "bad-0", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KQ29udGVudC1MZW5ndGg6IDINCg0KMA0KDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-1", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcA0KDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-2", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcCwgY2h1bmtlZA0KDQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-3", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZCwgY2h1bmtlZA0KDQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-4", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogYmFkDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-5", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogLTENCg0K"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-6", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogMg0KQ29udGVudC1MZW5ndGg6IDMNCg0Ke30="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-7", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogMjANCg0Ke30="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-8", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQorMg0Ke30NCjANCg0K"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-9", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoweDINCnt9DQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-10", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyCnt9DQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-11", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyDQp7"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-12", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyDQp7fVhYMA0KDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-13", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQowDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-14", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQowDQpJbnZhbGlkIHRyYWlsZXINCg0K"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-15", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyMDAwMDAxDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-16", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogMiwgMDINCg0Ke30="}], "opts": {"half_close": true}}, {"group": "framing", "name": "chunked-bytes", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NClRyYW5zZmVyLUVuY29kaW5nOiBjaHVua2VkDQoNCjENCnsNCjENCiINCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCmYNCjENCmENCjENCmsNCjENCmUNCjENCi0NCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCiwNCjENCiANCjENCiINCjENCm0NCjENCmUNCjENCnMNCjENCnMNCjENCmENCjENCmcNCjENCmUNCjENCnMNCjENCiINCjENCjoNCjENCiANCjENClsNCjENCnsNCjENCiINCjENCnINCjENCm8NCjENCmwNCjENCmUNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCnUNCjENCnMNCjENCmUNCjENCnINCjENCiINCjENCiwNCjENCiANCjENCiINCjENCmMNCjENCm8NCjENCm4NCjENCnQNCjENCmUNCjENCm4NCjENCnQNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCkgNCjENCmkNCjENCiANCjENCkANCjENCnMNCjENCmMNCjENCnINCjENCmkNCjENCnANCjENCnQNCjENCj0NCjENCnANCjENCmwNCjENCmENCjENCmkNCjENCm4NCjENCiINCjENCn0NCjENCl0NCjENCn0NCjANCg0K"}, {"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "framing", "name": "chunked-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NClRyYW5zZmVyLUVuY29kaW5nOiBjaHVua2VkDQoNCjENCnsNCjENCiINCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCmYNCjENCmENCjENCmsNCjENCmUNCjENCi0NCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCiwNCjENCiANCjENCiINCjENCm0NCjENCmUNCjENCnMNCjENCnMNCjENCmENCjENCmcNCjENCmUNCjENCnMNCjENCiINCjENCjoNCjENCiANCjENClsNCjENCnsNCjENCiINCjENCnINCjENCm8NCjENCmwNCjENCmUNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCnUNCjENCnMNCjENCmUNCjENCnINCjENCiINCjENCiwNCjENCiANCjENCiINCjENCmMNCjENCm8NCjENCm4NCjENCnQNCjENCmUNCjENCm4NCjENCnQNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCkgNCjENCmkNCjENCiANCjENCkANCjENCnMNCjENCmMNCjENCnINCjENCmkNCjENCnANCjENCnQNCjENCj0NCjENCnANCjENCmwNCjENCmENCjENCmkNCjENCm4NCjENCiINCjENCn0NCjENCl0NCjENCiwNCjENCiANCjENCiINCjENCnMNCjENCnQNCjENCnINCjENCmUNCjENCmENCjENCm0NCjENCiINCjENCjoNCjENCiANCjENCnQNCjENCnINCjENCnUNCjENCmUNCjENCn0NCjANCg0K"}], "opts": {}}, {"group": "framing", "name": "extensions-trailers", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQo1NjtuYW1lPSJ4Ig0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0NCjANClgtVGVzdDogaWdub3JlZA0KDQo="}, {"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "framing", "name": "oversized", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogNDAwMDAwMDANCg0K"}], "opts": {}}, {"group": "framing", "name": "unknown-post-keepalive", "raws": [{"b64": "UE9TVCAvdjEvbm90LWEtcm91dGUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTgNCg0KeyJtYXhfdG9rZW5zIjogMTZ9"}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "framing", "name": "keepalive-three", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}, {"b64": "R0VUIC92MS9tb2RlbHM/eD0xIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "pipelined", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQpHRVQgL3YxL21vZGVscyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}, {"b64": ""}], "opts": {}}, {"group": "framing", "name": "http10", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMA0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "framing", "name": "http10-keepalive", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjANCkhvc3Q6IHBhcml0eQ0KQ29ubmVjdGlvbjoga2VlcC1hbGl2ZQ0KDQo="}, {"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "framing", "name": "connection-close", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29ubmVjdGlvbjogY2xvc2UNCg0K"}], "opts": {}}, {"group": "framing", "name": "expect-continue", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpFeHBlY3Q6IDEwMC1jb250aW51ZQ0KQ29udGVudC1MZW5ndGg6IDg2DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "framing", "name": "put", "raws": [{"b64": "UFVUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1MZW5ndGg6IDINCg0Ke30="}], "opts": {}}, {"group": "framing", "name": "options", "raws": [{"b64": "T1BUSU9OUyAvdjEvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "head", "raws": [{"b64": "SEVBRCAvaGVhbHRoIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "bad-version", "raws": [{"b64": "R0VUIC8gSFRUWC8xLjENCg0K"}], "opts": {}}, {"group": "framing", "name": "http09", "raws": [{"b64": "R0VUIC9oZWFsdGgNCg=="}], "opts": {}}, {"group": "framing", "name": "http09-post", "raws": [{"b64": "UE9TVCAvaGVhbHRoDQo="}], "opts": {}}, {"group": "framing", "name": "four-words", "raws": [{"b64": "R0VUIC8geCBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}], "opts": {}}, {"group": "framing", "name": "http2", "raws": [{"b64": "R0VUIC8gSFRUUC8yLjANCg0K"}], "opts": {}}, {"group": "framing", "name": "long-header", "raws": [{"b64": "R0VUIC8gSFRUUC8xLjENClg6IGFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWENCg0K"}], "opts": {}}, {"group": "framing", "name": "many-headers", "raws": [{"b64": "R0VUIC8gSFRUUC8xLjENClgtMDogeQ0KWC0xOiB5DQpYLTI6IHkNClgtMzogeQ0KWC00OiB5DQpYLTU6IHkNClgtNjogeQ0KWC03OiB5DQpYLTg6IHkNClgtOTogeQ0KWC0xMDogeQ0KWC0xMTogeQ0KWC0xMjogeQ0KWC0xMzogeQ0KWC0xNDogeQ0KWC0xNTogeQ0KWC0xNjogeQ0KWC0xNzogeQ0KWC0xODogeQ0KWC0xOTogeQ0KWC0yMDogeQ0KWC0yMTogeQ0KWC0yMjogeQ0KWC0yMzogeQ0KWC0yNDogeQ0KWC0yNTogeQ0KWC0yNjogeQ0KWC0yNzogeQ0KWC0yODogeQ0KWC0yOTogeQ0KWC0zMDogeQ0KWC0zMTogeQ0KWC0zMjogeQ0KWC0zMzogeQ0KWC0zNDogeQ0KWC0zNTogeQ0KWC0zNjogeQ0KWC0zNzogeQ0KWC0zODogeQ0KWC0zOTogeQ0KWC00MDogeQ0KWC00MTogeQ0KWC00MjogeQ0KWC00MzogeQ0KWC00NDogeQ0KWC00NTogeQ0KWC00NjogeQ0KWC00NzogeQ0KWC00ODogeQ0KWC00OTogeQ0KWC01MDogeQ0KWC01MTogeQ0KWC01MjogeQ0KWC01MzogeQ0KWC01NDogeQ0KWC01NTogeQ0KWC01NjogeQ0KWC01NzogeQ0KWC01ODogeQ0KWC01OTogeQ0KWC02MDogeQ0KWC02MTogeQ0KWC02MjogeQ0KWC02MzogeQ0KWC02NDogeQ0KWC02NTogeQ0KWC02NjogeQ0KWC02NzogeQ0KWC02ODogeQ0KWC02OTogeQ0KWC03MDogeQ0KWC03MTogeQ0KWC03MjogeQ0KWC03MzogeQ0KWC03NDogeQ0KWC03NTogeQ0KWC03NjogeQ0KWC03NzogeQ0KWC03ODogeQ0KWC03OTogeQ0KWC04MDogeQ0KWC04MTogeQ0KWC04MjogeQ0KWC04MzogeQ0KWC04NDogeQ0KWC04NTogeQ0KWC04NjogeQ0KWC04NzogeQ0KWC04ODogeQ0KWC04OTogeQ0KWC05MDogeQ0KWC05MTogeQ0KWC05MjogeQ0KWC05MzogeQ0KWC05NDogeQ0KWC05NTogeQ0KWC05NjogeQ0KWC05NzogeQ0KWC05ODogeQ0KWC05OTogeQ0KWC0xMDA6IHkNClgtMTAxOiB5DQpYLTEwMjogeQ0KWC0xMDM6IHkNClgtMTA0OiB5DQoNCg=="}], "opts": {}}, {"group": "framing", "name": "blank-line", "raws": [{"b64": "DQo="}], "opts": {}}, {"group": "framing", "name": "double-slash", "raws": [{"b64": "R0VUIC8vaGVhbHRoIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "latin1-path", "raws": [{"b64": "R0VUIC9jYWbpIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "decisions", "raws": [{"b64": "UE9TVCAvdjEvZGVjaXNpb25zIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE0DQoNCnsiaW5wdXQiOiAieCJ9"}], "opts": {}}], "then": [{"kind": "cases", "cases": [{"group": "cancel", "name": "client-leaves", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zbG93In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {"leave_after_events": 3}}]}, {"kind": "sleep", "seconds": 1.0}, {"kind": "cases", "cases": [{"group": "cancel", "name": "metrics-after", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}]}, {"kind": "sigterm", "expect_exit": 0}, {"kind": "compare_log", "golden": "lifecycle/request-log.json"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli", "--metrics-open"], "env": {}, "cases": [{"group": "metrics-open", "name": "metrics", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "metrics-open", "name": "v1-metrics", "raws": [{"b64": "R0VUIC92MS9tZXRyaWNzLyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}], "opts": {}}, {"group": "metrics-open", "name": "models", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "metrics-open", "name": "health", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli", "--api-key-file", "@KEYFILE@"], "env": {"TENSORFOLD_API_KEY": "sk-env"}, "key_file": "# keys\nclient: sk-file\nsk-bare\n", "cases": [], "then": [{"kind": "cases", "cases": [{"group": "keys", "name": "health", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "models-none", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "models-cli", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLWNsaQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "models-file", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "models-bare", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogYmVhcmVyICAgc2stYmFyZSANCg0K"}], "opts": {}}, {"group": "keys", "name": "models-env", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1lbnYNCg0K"}], "opts": {}}, {"group": "keys", "name": "models-wrong", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLW5vcGUNCg0K"}], "opts": {}}, {"group": "keys", "name": "models-basic", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogQmFzaWMgc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "metrics-none", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "keys", "name": "messages-none", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1MZW5ndGg6IDINCg0Ke30="}], "opts": {}}, {"group": "keys", "name": "tokenize-none", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1MZW5ndGg6IDINCg0Ke30="}], "opts": {}}, {"group": "keys", "name": "alt-models", "raws": [{"b64": "R0VUIC9hbHQvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "keys", "name": "options", "raws": [{"b64": "T1BUSU9OUyAvdjEvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}]}, {"kind": "cases", "cases": [{"group": "keys", "name": "twice-x-api-key", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1jbGkNCngtYXBpLWtleTogc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "chat-with-key", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQp4LWFwaS1rZXk6IHNrLWNsaQ0KQ29udGVudC1MZW5ndGg6IDg2DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "keys", "name": "expect-without-key", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpFeHBlY3Q6IDEwMC1jb250aW51ZQ0KQ29udGVudC1MZW5ndGg6IDg2DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "keys", "name": "pooled-identity", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1jbGkNCg0K"}, {"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}]}, {"kind": "rewrite_key", "content": "next: sk-next\n"}, {"kind": "sleep", "seconds": 0.3}, {"kind": "cases", "cases": [{"group": "keys", "name": "rotated-old", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "rotated-new", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1uZXh0DQoNCg=="}], "opts": {}}, {"group": "keys", "name": "metrics-counted", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCngtYXBpLWtleTogc2stY2xpDQoNCg=="}], "opts": {}}]}, {"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": [{"group": "responses", "name": "namespace-tools", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE3MQ0KDQp7ImlucHV0IjogInggQHNjcmlwdD1uc190b29sIiwgInRvb2xzIjogW3sidHlwZSI6ICJuYW1lc3BhY2UiLCAibmFtZSI6ICJ3ZWF0aGVyIiwgImRlc2NyaXB0aW9uIjogIndlYXRoZXIgdG9vbHMiLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAiZ2V0X3dlYXRoZXIifV19XX0="}], "opts": {}}, {"group": "responses", "name": "namespace-tools-stream", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE4Nw0KDQp7ImlucHV0IjogInggQHNjcmlwdD1uc190b29sIiwgInN0cmVhbSI6IHRydWUsICJ0b29scyI6IFt7InR5cGUiOiAibmFtZXNwYWNlIiwgIm5hbWUiOiAid2VhdGhlciIsICJkZXNjcmlwdGlvbiI6ICJ3ZWF0aGVyIHRvb2xzIiwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJuYW1lIjogImdldF93ZWF0aGVyIn1dfV19"}], "opts": {}}], "then": [{"kind": "terminate"}]}]} +{"steps": [{"kind": "serve", "args": [], "env": {"TENSORFOLD_REQUEST_LOG": "@LOG@"}, "cases": [{"group": "chat", "name": "default", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "default-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "plain", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "chat", "name": "plain-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "chat", "name": "think", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "chat", "name": "think-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "chat", "name": "split_utf8", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zcGxpdF91dGY4In1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "split_utf8-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zcGxpdF91dGY4In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "harmony", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "harmony-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "long", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "chat", "name": "long-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "chat", "name": "no_end", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1ub19lbmQifV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "chat", "name": "no_end-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1ub19lbmQifV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "chat", "name": "json_answer", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1qc29uX2Fuc3dlciJ9XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "chat", "name": "json_answer-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1qc29uX2Fuc3dlciJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "thinking", "name": "think-off", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJlbmFibGVfdGhpbmtpbmciOiBmYWxzZX19"}], "opts": {}}, {"group": "thinking", "name": "think-off-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNTQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0cmVhbSI6IHRydWUsICJjaGF0X3RlbXBsYXRlX2t3YXJncyI6IHsiZW5hYmxlX3RoaW5raW5nIjogZmFsc2V9fQ=="}], "opts": {}}, {"group": "thinking", "name": "harmony-off", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAiY2hhdF90ZW1wbGF0ZV9rd2FyZ3MiOiB7ImVuYWJsZV90aGlua2luZyI6IGZhbHNlfX0="}], "opts": {}}, {"group": "thinking", "name": "harmony-off-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1oYXJtb255In1dLCAic3RyZWFtIjogdHJ1ZSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJlbmFibGVfdGhpbmtpbmciOiBmYWxzZX19"}], "opts": {}}, {"group": "thinking", "name": "default-off", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAiY2hhdF90ZW1wbGF0ZV9rd2FyZ3MiOiB7ImVuYWJsZV90aGlua2luZyI6IGZhbHNlfX0="}], "opts": {}}, {"group": "thinking", "name": "default-off-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kZWZhdWx0In1dLCAic3RyZWFtIjogdHJ1ZSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJlbmFibGVfdGhpbmtpbmciOiBmYWxzZX19"}], "opts": {}}, {"group": "thinking", "name": "effort-none", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibm9uZSJ9"}], "opts": {}}, {"group": "thinking", "name": "effort-low", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibG93In0="}], "opts": {}}, {"group": "thinking", "name": "effort-high", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAiaGlnaCJ9"}], "opts": {}}, {"group": "thinking", "name": "effort-max", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibWF4In0="}], "opts": {}}, {"group": "thinking", "name": "effort-medium", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAibWVkaXVtIn0="}], "opts": {}}, {"group": "thinking", "name": "effort-bogus", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInJlYXNvbmluZ19lZmZvcnQiOiAiYm9ndXMifQ=="}], "opts": {}}, {"group": "thinking", "name": "deepseek-switch", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJ0aGlua2luZyI6IHsidHlwZSI6ICJkaXNhYmxlZCJ9fX0="}], "opts": {}}, {"group": "thinking", "name": "kwargs-effort", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgImNoYXRfdGVtcGxhdGVfa3dhcmdzIjogeyJyZWFzb25pbmdfZWZmb3J0IjogImxvdyJ9fQ=="}], "opts": {}}, {"group": "thinking", "name": "length-while-thinking", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGlua19sb25nIn1dLCAibWF4X3Rva2VucyI6IDR9"}], "opts": {}}, {"group": "thinking", "name": "length-while-thinking-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGlua19sb25nIn1dLCAibWF4X3Rva2VucyI6IDQsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-[wor]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29yIl19"}], "opts": {}}, {"group": "stops", "name": "stop-[wor]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29yIl0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-STOP", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6ICJTVE9QIn0="}], "opts": {}}, {"group": "stops", "name": "stop-STOP-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6ICJTVE9QIiwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "stops", "name": "stop-[zzz, STOP]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsienp6IiwgIlNUT1AiXX0="}], "opts": {}}, {"group": "stops", "name": "stop-[zzz, STOP]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsienp6IiwgIlNUT1AiXSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "stops", "name": "stop-[ld STO]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsibGQgU1RPIl19"}], "opts": {}}, {"group": "stops", "name": "stop-[ld STO]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsibGQgU1RPIl0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-[worldx]", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29ybGR4Il19"}], "opts": {}}, {"group": "stops", "name": "stop-[worldx]-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zdG9wX3dvcmRzIn1dLCAic3RvcCI6IFsid29ybGR4Il0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "stops", "name": "stop-in-reasoning", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10aGluayJ9XSwgInN0b3AiOiBbInRoaW5rIl19"}], "opts": {}}, {"group": "stops", "name": "ignore-eos", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1lb3NfbWlkIn1dLCAiaWdub3JlX2VvcyI6IHRydWV9"}], "opts": {}}, {"group": "stops", "name": "eos-mid", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1lb3NfbWlkIn1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "usage", "name": "include-usage", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cmVhbSI6IHRydWUsICJzdHJlYW1fb3B0aW9ucyI6IHsiaW5jbHVkZV91c2FnZSI6IHRydWV9fQ=="}], "opts": {}}, {"group": "usage", "name": "max-tokens", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X3Rva2VucyI6IDN9"}], "opts": {}}, {"group": "usage", "name": "max-completion-tokens", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X2NvbXBsZXRpb25fdG9rZW5zIjogMn0="}], "opts": {}}, {"group": "usage", "name": "max-tokens-zero", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X3Rva2VucyI6IDB9"}], "opts": {}}, {"group": "usage", "name": "max-tokens-string", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAibWF4X3Rva2VucyI6ICI1In0="}], "opts": {}}, {"group": "usage", "name": "sampled", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRlbXBlcmF0dXJlIjogMC43LCAidG9wX2siOiA1fQ=="}], "opts": {}}, {"group": "usage", "name": "seeded", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRlbXBlcmF0dXJlIjogMSwgInNlZWQiOiAtMywgImRyYWZ0IjogZmFsc2V9"}], "opts": {}}, {"group": "usage", "name": "model-alias", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtYWxpYXMiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "usage", "name": "model-unknown", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4MQ0KDQp7Im1vZGVsIjogIm90aGVyIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "usage", "name": "background-title", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTANCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAiV3JpdGUgYSB0aXRsZSJ9LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogInggQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "qwen_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "qwen_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "qwen_tool_think-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2xfdGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "xml_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "xml_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "xml_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "xml_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "two_tools", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "two_tools-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "two_tools-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "two_tools-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD10d29fdG9vbHMifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "glm_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "glm_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "glm_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "glm_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nbG1fdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "gemma_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "gemma_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "gemma_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "gemma_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1nZW1tYV90b29sIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "dsml_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "dsml_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "dsml_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "dsml_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1kc21sX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "lfm2_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "lfm2_json-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_json-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_json-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_typed", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_typed-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "lfm2_typed-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_typed-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R5cGVkIn1dLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJkZXNjcmlwdGlvbiI6ICJTZWFyY2giLCAicGFyYW1ldGVycyI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fX19XSwgInBhcmFsbGVsX3Rvb2xfY2FsbHMiOiBmYWxzZSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "tools", "name": "lfm2_two", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "lfm2_two-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "lfm2_two-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "lfm2_two-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sZm0yX3R3byJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "bare_json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "bare_json-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "bare_json-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "tools", "name": "bare_json-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYXJlX2pzb24ifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAicGFyYWxsZWxfdG9vbF9jYWxscyI6IGZhbHNlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "tools", "name": "bad_tool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "bad_tool-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "bad_tool-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "bad_tool-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1iYWRfdG9vbCJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "plain", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiBmYWxzZX0="}], "opts": {}}, {"group": "tools", "name": "plain-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "plain-single", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2V9"}], "opts": {}}, {"group": "tools", "name": "plain-single-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMzENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogZmFsc2UsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "tools", "name": "choice-\"auto\"", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiAiYXV0byJ9"}], "opts": {}}, {"group": "tools", "name": "choice-\"none\"", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiAibm9uZSJ9"}], "opts": {}}, {"group": "tools", "name": "choice-\"required\"", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiAicmVxdWlyZWQifQ=="}], "opts": {}}, {"group": "tools", "name": "choice-{\"type\": \"function\", \"function\": {\"name\": \"lookup\"}}", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNTgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIn19fQ=="}], "opts": {}}, {"group": "tools", "name": "choice-{\"type\": \"function\", \"function\": {\"name\": \"nope\"}}", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibm9wZSJ9fX0="}], "opts": {}}, {"group": "tools", "name": "choice-{\"type\": \"function\"}", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMjYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1xd2VuX3Rvb2wifV0sICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiZnVuY3Rpb24ifX0="}], "opts": {}}, {"group": "tools", "name": "required-no-tools", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xfY2hvaWNlIjogInJlcXVpcmVkIn0="}], "opts": {}}, {"group": "tools", "name": "tools-not-list", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogeyJhIjogMX19"}], "opts": {}}, {"group": "tools", "name": "tool-without-name", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHt9fV19"}], "opts": {}}, {"group": "tools", "name": "parallel-not-bool", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzMTUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJwYXJhbGxlbF90b29sX2NhbGxzIjogInllcyJ9"}], "opts": {}}, {"group": "tools", "name": "history-with-calls", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1MjUNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQgaXQifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogIiIsICJ0b29sX2NhbGxzIjogW3siaWQiOiAiY2FsbF8xIiwgInR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImFyZ3VtZW50cyI6ICJ7XCJxdWVyeVwiOiBcInhcIn0ifX1dfSwgeyJyb2xlIjogInRvb2wiLCAidG9vbF9jYWxsX2lkIjogImNhbGxfMSIsICJjb250ZW50IjogImZvdW5kIn0sIHsicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiZ28gQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV19"}], "opts": {}}, {"group": "tools", "name": "history-bad-arguments", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyNDcNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQgaXQifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogIiIsICJ0b29sX2NhbGxzIjogW3siaWQiOiAiYyIsICJ0eXBlIjogImZ1bmN0aW9uIiwgImZ1bmN0aW9uIjogeyJuYW1lIjogImxvb2t1cCIsICJhcmd1bWVudHMiOiAibm90IGpzb24ifX1dfSwgeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJnbyBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "errors", "name": "not-json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA1DQoNCntub3Bl"}], "opts": {}}, {"group": "errors", "name": "list-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCltd"}], "opts": {}}, {"group": "errors", "name": "null-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA0DQoNCm51bGw="}], "opts": {}}, {"group": "errors", "name": "empty-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAwDQoNCg=="}], "opts": {}}, {"group": "errors", "name": "string-body", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzDQoNCiJ4Ig=="}], "opts": {}}, {"group": "errors", "name": "bad-utf8", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNw0KDQp7Im1lc3NhZ2VzIjogIv8ifQ=="}], "opts": {}}, {"group": "errors", "name": "trailing-comma", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5DQoNCnsiYSI6IDEsfQ=="}], "opts": {}}, {"group": "errors", "name": "n-seventeen", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5NQ0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAibiI6IDE3fQ=="}], "opts": {}}, {"group": "errors", "name": "logprobs", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImxvZ3Byb2JzIjogdHJ1ZX0="}], "opts": {}}, {"group": "errors", "name": "top-logprobs", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDUNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvcF9sb2dwcm9icyI6IDN9"}], "opts": {}}, {"group": "errors", "name": "temperature-text", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDgNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRlbXBlcmF0dXJlIjogImFiYyJ9"}], "opts": {}}, {"group": "errors", "name": "min-p", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5OA0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAibWluX3AiOiAyfQ=="}], "opts": {}}, {"group": "errors", "name": "top-k-float", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvcF9rIjogMS41fQ=="}], "opts": {}}, {"group": "errors", "name": "ignore-eos-null", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImlnbm9yZV9lb3MiOiBudWxsfQ=="}], "opts": {}}, {"group": "errors", "name": "stop-empty", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0b3AiOiBbIiJdfQ=="}], "opts": {}}, {"group": "errors", "name": "stop-int", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5Nw0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAic3RvcCI6IDV9"}], "opts": {}}, {"group": "errors", "name": "messages-missing", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNA0KDQp7Im1vZGVsIjogIngifQ=="}], "opts": {}}, {"group": "errors", "name": "messages-empty", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNg0KDQp7Im1lc3NhZ2VzIjogW119"}], "opts": {}}, {"group": "errors", "name": "role-robot", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA0OQ0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJyb2JvdCIsICJjb250ZW50IjogIngifV19"}], "opts": {}}, {"group": "errors", "name": "content-int", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA0Ng0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiA1fV19"}], "opts": {}}, {"group": "errors", "name": "content-image", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA5NQ0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogImltYWdlX3VybCIsICJpbWFnZV91cmwiOiB7InVybCI6ICJ4In19XX1dfQ=="}], "opts": {}}, {"group": "errors", "name": "message-not-object", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMA0KDQp7Im1lc3NhZ2VzIjogWyJoaSJdfQ=="}], "opts": {}}, {"group": "errors", "name": "text-part-int", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA3NA0KDQp7Im1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogInRleHQiLCAidGV4dCI6IDF9XX1dfQ=="}], "opts": {}}, {"group": "errors", "name": "modalities", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgIm1vZGFsaXRpZXMiOiBbInRleHQiLCAiYXVkaW8iXX0="}], "opts": {}}, {"group": "errors", "name": "audio-field", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImF1ZGlvIjogeyJ2b2ljZSI6ICJ4In19"}], "opts": {}}, {"group": "errors", "name": "format-json", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1qc29uX2Fuc3dlciJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJqc29uX29iamVjdCJ9fQ=="}], "opts": {}}, {"group": "errors", "name": "format-bogus", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjQNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJib2d1cyJ9fQ=="}], "opts": {}}, {"group": "errors", "name": "format-text", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJ0ZXh0In19"}], "opts": {}}, {"group": "errors", "name": "format-string", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTMNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6ICJqc29uIn0="}], "opts": {}}, {"group": "errors", "name": "format-no-schema", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJqc29uX3NjaGVtYSIsICJqc29uX3NjaGVtYSI6IHt9fX0="}], "opts": {}}, {"group": "errors", "name": "guided-choice-empty", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDcNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImd1aWRlZF9jaG9pY2UiOiBbXX0="}], "opts": {}}, {"group": "errors", "name": "guided-json-bad", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDkNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgImd1aWRlZF9qc29uIjogIntiYWQifQ=="}], "opts": {}}, {"group": "errors", "name": "structured-other", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjANCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInN0cnVjdHVyZWRfb3V0cHV0cyI6IHsieG1sIjogMX19"}], "opts": {}}, {"group": "errors", "name": "format-with-required", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAzNTYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJmdW5jdGlvbiI6IHsibmFtZSI6ICJsb29rdXAiLCAiZGVzY3JpcHRpb24iOiAiU2VhcmNoIiwgInBhcmFtZXRlcnMiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX19fV0sICJ0b29sX2Nob2ljZSI6ICJyZXF1aXJlZCIsICJyZXNwb25zZV9mb3JtYXQiOiB7InR5cGUiOiAianNvbl9vYmplY3QifX0="}], "opts": {}}, {"group": "errors", "name": "context-prompt", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMTQ3DQoNCnsibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJ4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eCJ9XX0="}], "opts": {}}, {"group": "errors", "name": "context-reply", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgIm1heF90b2tlbnMiOiAyMDAwfQ=="}], "opts": {}}, {"group": "errors", "name": "system-merged", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNzYNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAiQSJ9LCB7InJvbGUiOiAiZGV2ZWxvcGVyIiwgImNvbnRlbnQiOiAiQiJ9LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogInggQHNjcmlwdD1wbGFpbiJ9LCB7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAibGF0ZSJ9XX0="}], "opts": {}}, {"group": "errors", "name": "stream-context", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMjINCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgIm1heF90b2tlbnMiOiAyMDAwLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "errors", "name": "stream-structured", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNDYNCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInJlc3BvbnNlX2Zvcm1hdCI6IHsidHlwZSI6ICJqc29uX29iamVjdCJ9LCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "completions", "name": "text", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMzINCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIn0="}], "opts": {}}, {"group": "completions", "name": "ids", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogOTYNCg0KeyJwcm9tcHQiOiBbNzksIDExMCwgOTksIDEwMSwgMzIsIDY0LCAxMTUsIDk5LCAxMTQsIDEwNSwgMTEyLCAxMTYsIDYxLCAxMTYsIDEwNCwgMTA1LCAxMTAsIDEwN119"}], "opts": {}}, {"group": "completions", "name": "bad-ids", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjINCg0KeyJwcm9tcHQiOiBbNSwgOTk5OTldfQ=="}], "opts": {}}, {"group": "completions", "name": "bool-ids", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjENCg0KeyJwcm9tcHQiOiBbdHJ1ZSwgMV19"}], "opts": {}}, {"group": "completions", "name": "strings", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMzYNCg0KeyJwcm9tcHQiOiBbImEiLCAiYiBAc2NyaXB0PXBsYWluIl19"}], "opts": {}}, {"group": "completions", "name": "null", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTYNCg0KeyJwcm9tcHQiOiBudWxsfQ=="}], "opts": {}}, {"group": "completions", "name": "missing", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMg0KDQp7fQ=="}], "opts": {}}, {"group": "completions", "name": "messages", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjMNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV19"}], "opts": {}}, {"group": "completions", "name": "number", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTQNCg0KeyJwcm9tcHQiOiAxMn0="}], "opts": {}}, {"group": "completions", "name": "nested", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDANCg0KeyJwcm9tcHQiOiBbWyJ4Il0sICJ5IEBzY3JpcHQ9ZGVmYXVsdCJdfQ=="}], "opts": {}}, {"group": "completions", "name": "max-tokens", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDUNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PWxvbmciLCAibWF4X3Rva2VucyI6IDJ9"}], "opts": {}}, {"group": "completions", "name": "text-stream", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDgNCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "completions", "name": "messages-stream", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNzkNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "completions", "name": "usage-chunk", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogOTENCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgInN0cmVhbSI6IHRydWUsICJzdHJlYW1fb3B0aW9ucyI6IHsiaW5jbHVkZV91c2FnZSI6IHRydWV9fQ=="}], "opts": {}}, {"group": "completions", "name": "think-script", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDUNCg0KeyJwcm9tcHQiOiAieCBAc2NyaXB0PXRoaW5rIiwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "completions", "name": "echo-false", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDcNCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgImVjaG8iOiBmYWxzZX0="}], "opts": {}}, {"group": "completions", "name": "echo-unsupported", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDYNCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgImVjaG8iOiB0cnVlfQ=="}], "opts": {}}, {"group": "completions", "name": "echo-stream", "raws": [{"b64": "UE9TVCAvdjEvY29tcGxldGlvbnMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjINCg0KeyJwcm9tcHQiOiAiT25jZSBAc2NyaXB0PXBsYWluIiwgImVjaG8iOiB0cnVlLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "responses", "name": "input-string", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUyDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJpbnB1dCI6ICJIaSBAc2NyaXB0PXRoaW5rIn0="}], "opts": {}}, {"group": "responses", "name": "input-stream", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ1DQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD10aGluayIsICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "responses", "name": "tools", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE5Mw0KDQp7ImlucHV0IjogIkhpIEBzY3JpcHQ9cXdlbl90b29sIiwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJuYW1lIjogImxvb2t1cCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fV19"}], "opts": {}}, {"group": "responses", "name": "tools-stream", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDk5DQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD14bWxfdG9vbCIsICJzdHJlYW0iOiB0cnVlLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAibG9va3VwIn1dfQ=="}], "opts": {}}, {"group": "responses", "name": "incomplete", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUyDQoNCnsiaW5wdXQiOiAiSGkgQHNjcmlwdD1sb25nIiwgIm1heF9vdXRwdXRfdG9rZW5zIjogMn0="}], "opts": {}}, {"group": "responses", "name": "instructions", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE3OQ0KDQp7ImlucHV0IjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogImlucHV0X3RleHQiLCAidGV4dCI6ICJ4IEBzY3JpcHQ9cGxhaW4ifV19XSwgImluc3RydWN0aW9ucyI6ICJCZSBicmllZiIsICJtZXRhZGF0YSI6IHsiayI6ICJ2In0sICJ0ZW1wZXJhdHVyZSI6IDAsICJzdG9yZSI6IGZhbHNlfQ=="}], "opts": {}}, {"group": "responses", "name": "items", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDM0NA0KDQp7ImlucHV0IjogW3sidHlwZSI6ICJtZXNzYWdlIiwgInJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQifSwgeyJ0eXBlIjogInJlYXNvbmluZyIsICJjb250ZW50IjogW3sidHlwZSI6ICJyZWFzb25pbmdfdGV4dCIsICJ0ZXh0IjogImhtbSJ9XX0sIHsidHlwZSI6ICJmdW5jdGlvbl9jYWxsIiwgImNhbGxfaWQiOiAiYzEiLCAibmFtZSI6ICJsb29rdXAiLCAiYXJndW1lbnRzIjogInt9In0sIHsidHlwZSI6ICJmdW5jdGlvbl9jYWxsX291dHB1dCIsICJjYWxsX2lkIjogImMxIiwgIm91dHB1dCI6IFt7InR5cGUiOiAiaW5wdXRfdGV4dCIsICJ0ZXh0IjogImRvbmUgQHNjcmlwdD1wbGFpbiJ9XX1dfQ=="}], "opts": {}}, {"group": "responses", "name": "allowed-tools", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDIzMQ0KDQp7ImlucHV0IjogInggQHNjcmlwdD1xd2VuX3Rvb2wiLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAibG9va3VwIn0sIHsidHlwZSI6ICJmdW5jdGlvbiIsICJuYW1lIjogIm90aGVyIn1dLCAidG9vbF9jaG9pY2UiOiB7InR5cGUiOiAiYWxsb3dlZF90b29scyIsICJtb2RlIjogImF1dG8iLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAibG9va3VwIn1dfX0="}], "opts": {}}, {"group": "responses", "name": "stored-chain", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMwDQoNCnsiaW5wdXQiOiAib25lIEBzY3JpcHQ9cGxhaW4ifQ=="}, {"tmpl_b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDY1DQoNCnsiaW5wdXQiOiAidHdvIEBzY3JpcHQ9dGhpbmsiLCAicHJldmlvdXNfcmVzcG9uc2VfaWQiOiAiWlpJRDBaWiJ9", "ids": [0]}, {"tmpl_b64": "R0VUIC92MS9yZXNwb25zZXMvWlpJRDFaWiBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg==", "ids": [1]}, {"tmpl_b64": "REVMRVRFIC92MS9yZXNwb25zZXMvWlpJRDBaWiBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg==", "ids": [0]}, {"tmpl_b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAidGhyZWUiLCAicHJldmlvdXNfcmVzcG9uc2VfaWQiOiAiWlpJRDFaWiJ9", "ids": [1]}], "opts": {}}, {"group": "responses", "name": "get-missing", "raws": [{"b64": "R0VUIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "responses", "name": "delete-missing", "raws": [{"b64": "REVMRVRFIC92MS9yZXNwb25zZXMvcmVzcF9taXNzaW5nIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "responses", "name": "delete-collection", "raws": [{"b64": "REVMRVRFIC92MS9yZXNwb25zZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "responses", "name": "post-with-id", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzL3Jlc3BfeCBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNA0KDQp7ImlucHV0IjogIngifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-include", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ2DQoNCnsiaW5wdXQiOiAieCIsICJpbmNsdWRlIjogWyJyZWFzb25pbmcuYm9ndXMiXX0="}], "opts": {}}, {"group": "responses", "name": "refuse-truncation", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDM2DQoNCnsiaW5wdXQiOiAieCIsICJ0cnVuY2F0aW9uIjogImF1dG8ifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-background", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUwDQoNCnsiaW5wdXQiOiAieCIsICJiYWNrZ3JvdW5kIjogdHJ1ZSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "responses", "name": "refuse-empty-input", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDEzDQoNCnsiaW5wdXQiOiBbXX0="}], "opts": {}}, {"group": "responses", "name": "refuse-item-type", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMwDQoNCnsiaW5wdXQiOiBbeyJ0eXBlIjogImJvZ3VzIn1dfQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-tool-type", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ5DQoNCnsiaW5wdXQiOiAieCIsICJ0b29scyI6IFt7InR5cGUiOiAid2ViX3NlYXJjaCJ9XX0="}], "opts": {}}, {"group": "responses", "name": "refuse-metadata", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDIwNQ0KDQp7ImlucHV0IjogIngiLCAibWV0YWRhdGEiOiB7IjAiOiAidiIsICIxIjogInYiLCAiMiI6ICJ2IiwgIjMiOiAidiIsICI0IjogInYiLCAiNSI6ICJ2IiwgIjYiOiAidiIsICI3IjogInYiLCAiOCI6ICJ2IiwgIjkiOiAidiIsICIxMCI6ICJ2IiwgIjExIjogInYiLCAiMTIiOiAidiIsICIxMyI6ICJ2IiwgIjE0IjogInYiLCAiMTUiOiAidiIsICIxNiI6ICJ2In19"}], "opts": {}}, {"group": "responses", "name": "refuse-not-json", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDENCg0Kew=="}], "opts": {}}, {"group": "responses", "name": "refuse-list-body", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMNCg0KWzFd"}], "opts": {}}, {"group": "responses", "name": "refuse-format", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUzDQoNCnsiaW5wdXQiOiAieCIsICJ0ZXh0IjogeyJmb3JtYXQiOiB7InR5cGUiOiAiYm9ndXMifX19"}], "opts": {}}, {"group": "responses", "name": "refuse-content-part", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDY2DQoNCnsiaW5wdXQiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6IFt7InR5cGUiOiAiaW5wdXRfZmlsZSJ9XX1dfQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-role", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDQ2DQoNCnsiaW5wdXQiOiBbeyJyb2xlIjogInJvYm90IiwgImNvbnRlbnQiOiAieCJ9XX0="}], "opts": {}}, {"group": "responses", "name": "refuse-previous-missing", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDUxDQoNCnsiaW5wdXQiOiAieCIsICJwcmV2aW91c19yZXNwb25zZV9pZCI6ICJyZXNwX2dvbmUifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-logprobs", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDMyDQoNCnsiaW5wdXQiOiAieCIsICJsb2dwcm9icyI6IHRydWV9"}], "opts": {}}, {"group": "responses", "name": "refuse-chat-refusal", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDM2DQoNCnsiaW5wdXQiOiAieCIsICJ0ZW1wZXJhdHVyZSI6ICJob3QifQ=="}], "opts": {}}, {"group": "responses", "name": "refuse-image", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDkwDQoNCnsiaW5wdXQiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6IFt7InR5cGUiOiAiaW5wdXRfaW1hZ2UiLCAiaW1hZ2VfdXJsIjogImRhdGE6eCJ9XX1dfQ=="}], "opts": {}}, {"group": "anthropic", "name": "plain", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTA0DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV19"}], "opts": {}}, {"group": "anthropic", "name": "plain-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTIwDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "anthropic", "name": "thinking", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0aGlua2luZyI6IHsidHlwZSI6ICJlbmFibGVkIiwgImJ1ZGdldF90b2tlbnMiOiAzMn19"}], "opts": {}}, {"group": "anthropic", "name": "thinking-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU0DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiB0cnVlLCAidGhpbmtpbmciOiB7InR5cGUiOiAiYWRhcHRpdmUifX0="}], "opts": {}}, {"group": "anthropic", "name": "system", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV0sICJzeXN0ZW0iOiBbeyJ0eXBlIjogInRleHQiLCAidGV4dCI6ICJCZSBraW5kIn1dfQ=="}], "opts": {}}, {"group": "anthropic", "name": "tool-use", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjc1DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cXdlbl90b29sIn1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV19"}], "opts": {}}, {"group": "anthropic", "name": "tool-use-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjkwDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9eG1sX3Rvb2wifV0sICJ0b29scyI6IFt7Im5hbWUiOiAibG9va3VwIiwgImlucHV0X3NjaGVtYSI6IHsidHlwZSI6ICJvYmplY3QiLCAicHJvcGVydGllcyI6IHsicXVlcnkiOiB7InR5cGUiOiAic3RyaW5nIn0sICJsaW1pdCI6IHsidHlwZSI6ICJpbnRlZ2VyIn19fSwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCJ9XSwgInN0cmVhbSI6IHRydWV9"}], "opts": {}}, {"group": "anthropic", "name": "tool-use-think-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMzUwDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cXdlbl90b29sX3RoaW5rIn1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV0sICJzdHJlYW0iOiB0cnVlLCAidGhpbmtpbmciOiB7InR5cGUiOiAiZW5hYmxlZCIsICJidWRnZXRfdG9rZW5zIjogOH19"}], "opts": {}}, {"group": "anthropic", "name": "stop-sequence", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTM3DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9c3RvcF93b3JkcyJ9XSwgInN0b3Bfc2VxdWVuY2VzIjogWyJTVE9QIl19"}], "opts": {}}, {"group": "anthropic", "name": "stop-sequence-stream", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUzDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9c3RvcF93b3JkcyJ9XSwgInN0b3Bfc2VxdWVuY2VzIjogWyJTVE9QIl0sICJzdHJlYW0iOiB0cnVlfQ=="}], "opts": {}}, {"group": "anthropic", "name": "max-tokens", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTE4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogMiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1sb25nIn1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {}}, {"group": "anthropic", "name": "tool-result", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjM5DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImZpbmQifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogW3sidHlwZSI6ICJ0aGlua2luZyIsICJ0aGlua2luZyI6ICJobW0ifSwgeyJ0eXBlIjogInRvb2xfdXNlIiwgImlkIjogInQxIiwgIm5hbWUiOiAibG9va3VwIiwgImlucHV0IjogeyJxdWVyeSI6ICLDqSJ9fV19LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogW3sidHlwZSI6ICJ0b29sX3Jlc3VsdCIsICJ0b29sX3VzZV9pZCI6ICJ0MSIsICJjb250ZW50IjogIm9rIiwgImlzX2Vycm9yIjogdHJ1ZX0sIHsidHlwZSI6ICJ0ZXh0IiwgInRleHQiOiAiZ28gQHNjcmlwdD1wbGFpbiJ9XX1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV0sICJ0b29sX2Nob2ljZSI6IHsidHlwZSI6ICJhbnkiLCAiZGlzYWJsZV9wYXJhbGxlbF90b29sX3VzZSI6IHRydWV9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "count", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMvY291bnRfdG9rZW5zIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDI0NA0KDQp7Im1vZGVsIjogIm0iLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAidG9vbHMiOiBbeyJuYW1lIjogImxvb2t1cCIsICJpbnB1dF9zY2hlbWEiOiB7InR5cGUiOiAib2JqZWN0IiwgInByb3BlcnRpZXMiOiB7InF1ZXJ5IjogeyJ0eXBlIjogInN0cmluZyJ9LCAibGltaXQiOiB7InR5cGUiOiAiaW50ZWdlciJ9fX0sICJkZXNjcmlwdGlvbiI6ICJTZWFyY2gifV19"}], "opts": {}}, {"group": "anthropic", "name": "count-query", "raws": [{"b64": "UE9TVCAvbWVzc2FnZXMvY291bnRfdG9rZW5zP2JldGE9dHJ1ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMzANCg0KeyJtb2RlbCI6ICJtIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XSwgInRoaW5raW5nIjogeyJ0eXBlIjogImVuYWJsZWQiLCAiYnVkZ2V0X3Rva2VucyI6IDV9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-no-model", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogODANCg0KeyJtYXhfdG9rZW5zIjogNSwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-no-max", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNzcNCg0KeyJtb2RlbCI6ICJtIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-stream-text", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTIxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzdHJlYW0iOiAieWVzIn0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-choice", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTM4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0b29sX2Nob2ljZSI6IHsidHlwZSI6ICJib2d1cyJ9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-redacted", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTM1DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAiYXNzaXN0YW50IiwgImNvbnRlbnQiOiBbeyJ0eXBlIjogInJlZGFjdGVkX3RoaW5raW5nIiwgImRhdGEiOiAieCJ9XX1dfQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-budget", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0aGlua2luZyI6IHsidHlwZSI6ICJlbmFibGVkIiwgImJ1ZGdldF90b2tlbnMiOiA2NH19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-server-tool", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTYxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJ0b29scyI6IFt7InR5cGUiOiAid2ViX3NlYXJjaF8yMDI1MDMwNSIsICJuYW1lIjogIncifV19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-mid-system", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTY0DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImEifSwgeyJyb2xlIjogInN5c3RlbSIsICJjb250ZW50IjogImIifSwgeyJyb2xlIjogImFzc2lzdGFudCIsICJjb250ZW50IjogImMifV19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-bad-system", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTI1DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAic3lzdGVtIiwgImNvbnRlbnQiOiAiYiJ9LCB7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogImEifV19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-context", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTU4DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJjb250ZXh0X21hbmFnZW1lbnQiOiB7ImVkaXRzIjogW3sidHlwZSI6ICJvdGhlciJ9XX19"}], "opts": {}}, {"group": "anthropic", "name": "refuse-service-tier", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTMyDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJzZXJ2aWNlX3RpZXIiOiAicHJpb3JpdHkifQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-not-json", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMg0KDQp7eA=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-image", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogW3sidHlwZSI6ICJpbWFnZSIsICJzb3VyY2UiOiB7InR5cGUiOiAidXJsIiwgInVybCI6ICJodHRwOi8veCJ9fV19XX0="}], "opts": {}}, {"group": "anthropic", "name": "refuse-effort", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTQxDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJvdXRwdXRfY29uZmlnIjogeyJlZmZvcnQiOiAiaHVnZSJ9fQ=="}], "opts": {}}, {"group": "anthropic", "name": "refuse-format", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTcyDQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtYXhfdG9rZW5zIjogNjQsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9dGhpbmsifV0sICJvdXRwdXRfY29uZmlnIjogeyJmb3JtYXQiOiB7InR5cGUiOiAianNvbl9zY2hlbWEiLCAic2NoZW1hIjoge319fX0="}], "opts": {}}, {"group": "tokens", "name": "tokenize-prompt", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjgNCg0KeyJwcm9tcHQiOiAiSGVsbG8gd29ybGQgw6kifQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-prompt-special", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNTYNCg0KeyJwcm9tcHQiOiAiPHxpbV9zdGFydHw+eCIsICJhZGRfc3BlY2lhbF90b2tlbnMiOiBmYWxzZX0="}], "opts": {}}, {"group": "tokens", "name": "tokenize-strs", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDgNCg0KeyJwcm9tcHQiOiAiSGVsbG9cbiIsICJyZXR1cm5fdG9rZW5fc3RycyI6IHRydWV9"}], "opts": {}}, {"group": "tokens", "name": "tokenize-messages", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNjMNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "tokens", "name": "tokenize-messages-no-gen", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMjk0DQoNCnsibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dLCAiYWRkX2dlbmVyYXRpb25fcHJvbXB0IjogZmFsc2UsICJ0b29scyI6IFt7InR5cGUiOiAiZnVuY3Rpb24iLCAiZnVuY3Rpb24iOiB7Im5hbWUiOiAibG9va3VwIiwgImRlc2NyaXB0aW9uIjogIlNlYXJjaCIsICJwYXJhbWV0ZXJzIjogeyJ0eXBlIjogIm9iamVjdCIsICJwcm9wZXJ0aWVzIjogeyJxdWVyeSI6IHsidHlwZSI6ICJzdHJpbmcifSwgImxpbWl0IjogeyJ0eXBlIjogImludGVnZXIifX19fX1dfQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-messages-effort", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogOTANCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV0sICJyZWFzb25pbmdfZWZmb3J0IjogImxvdyJ9"}], "opts": {}}, {"group": "tokens", "name": "tokenize-prompt-int", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTMNCg0KeyJwcm9tcHQiOiA1fQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-flag-bad", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNDMNCg0KeyJwcm9tcHQiOiAieCIsICJyZXR1cm5fdG9rZW5fc3RycyI6ICJ5ZXMifQ=="}], "opts": {}}, {"group": "tokens", "name": "tokenize-list-body", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMw0KDQpbMV0="}], "opts": {}}, {"group": "tokens", "name": "tokenize-bad-json", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMQ0KDQp7"}], "opts": {}}, {"group": "tokens", "name": "tokenize-tools-bad", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogNzUNCg0KeyJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV0sICJ0b29scyI6IDN9"}], "opts": {}}, {"group": "tokens", "name": "tokenize-v1", "raws": [{"b64": "UE9TVCAvdjEvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTUNCg0KeyJwcm9tcHQiOiAieCJ9"}], "opts": {}}, {"group": "tokens", "name": "detokenize-ids", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMg0KDQp7InRva2VucyI6IFsyODQsIDI4NV19"}], "opts": {}}, {"group": "tokens", "name": "detokenize-nested", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMw0KDQp7InRva2VucyI6IFtbNzIsIDEwNV1dfQ=="}], "opts": {}}, {"group": "tokens", "name": "detokenize-range", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyMA0KDQp7InRva2VucyI6IFsxLCA5OTldfQ=="}], "opts": {}}, {"group": "tokens", "name": "detokenize-negative", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNg0KDQp7InRva2VucyI6IFstMV19"}], "opts": {}}, {"group": "tokens", "name": "detokenize-floats", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxNw0KDQp7InRva2VucyI6IFsxLjBdfQ=="}], "opts": {}}, {"group": "tokens", "name": "detokenize-missing", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCnt9"}], "opts": {}}, {"group": "tokens", "name": "detokenize-body-list", "raws": [{"b64": "UE9TVCAvdjEvZGV0b2tlbml6ZSBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAyDQoNCltd"}], "opts": {}}, {"group": "status", "name": "get-health", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-", "raws": [{"b64": "R0VUIC8gSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-health-", "raws": [{"b64": "R0VUIC9oZWFsdGgvIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "status", "name": "get-v1-models", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-models", "raws": [{"b64": "R0VUIC9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-v1-models?x=1", "raws": [{"b64": "R0VUIC92MS9tb2RlbHM/eD0xIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "status", "name": "get-x-models", "raws": [{"b64": "R0VUIC94L21vZGVscyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}], "opts": {}}, {"group": "status", "name": "get-v1-health", "raws": [{"b64": "R0VUIC92MS9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-nope", "raws": [{"b64": "R0VUIC9ub3BlIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "status", "name": "get-v1-responses", "raws": [{"b64": "R0VUIC92MS9yZXNwb25zZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "status", "name": "get-health?reset_peak=1", "raws": [{"b64": "R0VUIC9oZWFsdGg/cmVzZXRfcGVhaz0xIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "bad-0", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KQ29udGVudC1MZW5ndGg6IDINCg0KMA0KDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-1", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcA0KDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-2", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogZ3ppcCwgY2h1bmtlZA0KDQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-3", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZCwgY2h1bmtlZA0KDQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-4", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogYmFkDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-5", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogLTENCg0K"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-6", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogMg0KQ29udGVudC1MZW5ndGg6IDMNCg0Ke30="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-7", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogMjANCg0Ke30="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-8", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQorMg0Ke30NCjANCg0K"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-9", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoweDINCnt9DQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-10", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyCnt9DQowDQoNCg=="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-11", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyDQp7"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-12", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyDQp7fVhYMA0KDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-13", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQowDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-14", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQowDQpJbnZhbGlkIHRyYWlsZXINCg0K"}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-15", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQoyMDAwMDAxDQo="}], "opts": {"half_close": true}}, {"group": "framing", "name": "bad-16", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogMiwgMDINCg0Ke30="}], "opts": {"half_close": true}}, {"group": "framing", "name": "chunked-bytes", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NClRyYW5zZmVyLUVuY29kaW5nOiBjaHVua2VkDQoNCjENCnsNCjENCiINCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCmYNCjENCmENCjENCmsNCjENCmUNCjENCi0NCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCiwNCjENCiANCjENCiINCjENCm0NCjENCmUNCjENCnMNCjENCnMNCjENCmENCjENCmcNCjENCmUNCjENCnMNCjENCiINCjENCjoNCjENCiANCjENClsNCjENCnsNCjENCiINCjENCnINCjENCm8NCjENCmwNCjENCmUNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCnUNCjENCnMNCjENCmUNCjENCnINCjENCiINCjENCiwNCjENCiANCjENCiINCjENCmMNCjENCm8NCjENCm4NCjENCnQNCjENCmUNCjENCm4NCjENCnQNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCkgNCjENCmkNCjENCiANCjENCkANCjENCnMNCjENCmMNCjENCnINCjENCmkNCjENCnANCjENCnQNCjENCj0NCjENCnANCjENCmwNCjENCmENCjENCmkNCjENCm4NCjENCiINCjENCn0NCjENCl0NCjENCn0NCjANCg0K"}, {"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "framing", "name": "chunked-stream", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NClRyYW5zZmVyLUVuY29kaW5nOiBjaHVua2VkDQoNCjENCnsNCjENCiINCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCmYNCjENCmENCjENCmsNCjENCmUNCjENCi0NCjENCm0NCjENCm8NCjENCmQNCjENCmUNCjENCmwNCjENCiINCjENCiwNCjENCiANCjENCiINCjENCm0NCjENCmUNCjENCnMNCjENCnMNCjENCmENCjENCmcNCjENCmUNCjENCnMNCjENCiINCjENCjoNCjENCiANCjENClsNCjENCnsNCjENCiINCjENCnINCjENCm8NCjENCmwNCjENCmUNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCnUNCjENCnMNCjENCmUNCjENCnINCjENCiINCjENCiwNCjENCiANCjENCiINCjENCmMNCjENCm8NCjENCm4NCjENCnQNCjENCmUNCjENCm4NCjENCnQNCjENCiINCjENCjoNCjENCiANCjENCiINCjENCkgNCjENCmkNCjENCiANCjENCkANCjENCnMNCjENCmMNCjENCnINCjENCmkNCjENCnANCjENCnQNCjENCj0NCjENCnANCjENCmwNCjENCmENCjENCmkNCjENCm4NCjENCiINCjENCn0NCjENCl0NCjENCiwNCjENCiANCjENCiINCjENCnMNCjENCnQNCjENCnINCjENCmUNCjENCmENCjENCm0NCjENCiINCjENCjoNCjENCiANCjENCnQNCjENCnINCjENCnUNCjENCmUNCjENCn0NCjANCg0K"}], "opts": {}}, {"group": "framing", "name": "extensions-trailers", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpUcmFuc2Zlci1FbmNvZGluZzogY2h1bmtlZA0KDQo1NjtuYW1lPSJ4Ig0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1wbGFpbiJ9XX0NCjANClgtVGVzdDogaWdub3JlZA0KDQo="}, {"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "framing", "name": "oversized", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LUxlbmd0aDogNDAwMDAwMDANCg0K"}], "opts": {}}, {"group": "framing", "name": "unknown-post-keepalive", "raws": [{"b64": "UE9TVCAvdjEvbm90LWEtcm91dGUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9qc29uDQpDb250ZW50LUxlbmd0aDogMTgNCg0KeyJtYXhfdG9rZW5zIjogMTZ9"}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "framing", "name": "keepalive-three", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}, {"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}, {"b64": "R0VUIC92MS9tb2RlbHM/eD0xIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "pipelined", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQpHRVQgL3YxL21vZGVscyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}, {"b64": ""}], "opts": {}}, {"group": "framing", "name": "http10", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMA0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiA4Ng0KDQp7Im1vZGVsIjogImZha2UtbW9kZWwiLCAibWVzc2FnZXMiOiBbeyJyb2xlIjogInVzZXIiLCAiY29udGVudCI6ICJIaSBAc2NyaXB0PXBsYWluIn1dfQ=="}], "opts": {}}, {"group": "framing", "name": "http10-keepalive", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjANCkhvc3Q6IHBhcml0eQ0KQ29ubmVjdGlvbjoga2VlcC1hbGl2ZQ0KDQo="}, {"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "framing", "name": "connection-close", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29ubmVjdGlvbjogY2xvc2UNCg0K"}], "opts": {}}, {"group": "framing", "name": "expect-continue", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpFeHBlY3Q6IDEwMC1jb250aW51ZQ0KQ29udGVudC1MZW5ndGg6IDg2DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "framing", "name": "put", "raws": [{"b64": "UFVUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1MZW5ndGg6IDINCg0Ke30="}], "opts": {}}, {"group": "framing", "name": "options", "raws": [{"b64": "T1BUSU9OUyAvdjEvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "head", "raws": [{"b64": "SEVBRCAvaGVhbHRoIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "bad-version", "raws": [{"b64": "R0VUIC8gSFRUWC8xLjENCg0K"}], "opts": {}}, {"group": "framing", "name": "http09", "raws": [{"b64": "R0VUIC9oZWFsdGgNCg=="}], "opts": {}}, {"group": "framing", "name": "http09-post", "raws": [{"b64": "UE9TVCAvaGVhbHRoDQo="}], "opts": {}}, {"group": "framing", "name": "four-words", "raws": [{"b64": "R0VUIC8geCBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}], "opts": {}}, {"group": "framing", "name": "http2", "raws": [{"b64": "R0VUIC8gSFRUUC8yLjANCg0K"}], "opts": {}}, {"group": "framing", "name": "long-header", "raws": [{"b64": "R0VUIC8gSFRUUC8xLjENClg6IGFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWENCg0K"}], "opts": {}}, {"group": "framing", "name": "many-headers", "raws": [{"b64": "R0VUIC8gSFRUUC8xLjENClgtMDogeQ0KWC0xOiB5DQpYLTI6IHkNClgtMzogeQ0KWC00OiB5DQpYLTU6IHkNClgtNjogeQ0KWC03OiB5DQpYLTg6IHkNClgtOTogeQ0KWC0xMDogeQ0KWC0xMTogeQ0KWC0xMjogeQ0KWC0xMzogeQ0KWC0xNDogeQ0KWC0xNTogeQ0KWC0xNjogeQ0KWC0xNzogeQ0KWC0xODogeQ0KWC0xOTogeQ0KWC0yMDogeQ0KWC0yMTogeQ0KWC0yMjogeQ0KWC0yMzogeQ0KWC0yNDogeQ0KWC0yNTogeQ0KWC0yNjogeQ0KWC0yNzogeQ0KWC0yODogeQ0KWC0yOTogeQ0KWC0zMDogeQ0KWC0zMTogeQ0KWC0zMjogeQ0KWC0zMzogeQ0KWC0zNDogeQ0KWC0zNTogeQ0KWC0zNjogeQ0KWC0zNzogeQ0KWC0zODogeQ0KWC0zOTogeQ0KWC00MDogeQ0KWC00MTogeQ0KWC00MjogeQ0KWC00MzogeQ0KWC00NDogeQ0KWC00NTogeQ0KWC00NjogeQ0KWC00NzogeQ0KWC00ODogeQ0KWC00OTogeQ0KWC01MDogeQ0KWC01MTogeQ0KWC01MjogeQ0KWC01MzogeQ0KWC01NDogeQ0KWC01NTogeQ0KWC01NjogeQ0KWC01NzogeQ0KWC01ODogeQ0KWC01OTogeQ0KWC02MDogeQ0KWC02MTogeQ0KWC02MjogeQ0KWC02MzogeQ0KWC02NDogeQ0KWC02NTogeQ0KWC02NjogeQ0KWC02NzogeQ0KWC02ODogeQ0KWC02OTogeQ0KWC03MDogeQ0KWC03MTogeQ0KWC03MjogeQ0KWC03MzogeQ0KWC03NDogeQ0KWC03NTogeQ0KWC03NjogeQ0KWC03NzogeQ0KWC03ODogeQ0KWC03OTogeQ0KWC04MDogeQ0KWC04MTogeQ0KWC04MjogeQ0KWC04MzogeQ0KWC04NDogeQ0KWC04NTogeQ0KWC04NjogeQ0KWC04NzogeQ0KWC04ODogeQ0KWC04OTogeQ0KWC05MDogeQ0KWC05MTogeQ0KWC05MjogeQ0KWC05MzogeQ0KWC05NDogeQ0KWC05NTogeQ0KWC05NjogeQ0KWC05NzogeQ0KWC05ODogeQ0KWC05OTogeQ0KWC0xMDA6IHkNClgtMTAxOiB5DQpYLTEwMjogeQ0KWC0xMDM6IHkNClgtMTA0OiB5DQoNCg=="}], "opts": {}}, {"group": "framing", "name": "blank-line", "raws": [{"b64": "DQo="}], "opts": {}}, {"group": "framing", "name": "double-slash", "raws": [{"b64": "R0VUIC8vaGVhbHRoIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "latin1-path", "raws": [{"b64": "R0VUIC9jYWbpIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "framing", "name": "decisions", "raws": [{"b64": "UE9TVCAvdjEvZGVjaXNpb25zIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE0DQoNCnsiaW5wdXQiOiAieCJ9"}], "opts": {}}], "then": [{"kind": "cases", "cases": [{"group": "cancel", "name": "client-leaves", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpDb250ZW50LVR5cGU6IGFwcGxpY2F0aW9uL2pzb24NCkNvbnRlbnQtTGVuZ3RoOiAxMDENCg0KeyJtb2RlbCI6ICJmYWtlLW1vZGVsIiwgIm1lc3NhZ2VzIjogW3sicm9sZSI6ICJ1c2VyIiwgImNvbnRlbnQiOiAiSGkgQHNjcmlwdD1zbG93In1dLCAic3RyZWFtIjogdHJ1ZX0="}], "opts": {"leave_after_events": 3}}]}, {"kind": "sleep", "seconds": 1.0}, {"kind": "cases", "cases": [{"group": "cancel", "name": "metrics-after", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}]}, {"kind": "sigterm", "expect_exit": 0}, {"kind": "compare_log", "golden": "lifecycle/request-log.json"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli", "--metrics-open"], "env": {}, "cases": [{"group": "metrics-open", "name": "metrics", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "metrics-open", "name": "v1-metrics", "raws": [{"b64": "R0VUIC92MS9tZXRyaWNzLyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQoNCg=="}], "opts": {}}, {"group": "metrics-open", "name": "models", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "metrics-open", "name": "health", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}], "then": [{"kind": "terminate"}]}, {"kind": "serve", "args": ["--api-key", "sk-cli", "--api-key-file", "@KEYFILE@"], "env": {"TENSORFOLD_API_KEY": "sk-env"}, "key_file": "# keys\nclient: sk-file\nsk-bare\n", "cases": [], "then": [{"kind": "cases", "cases": [{"group": "keys", "name": "health", "raws": [{"b64": "R0VUIC9oZWFsdGggSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "models-none", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "models-cli", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLWNsaQ0KDQo="}], "opts": {}}, {"group": "keys", "name": "models-file", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "models-bare", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogYmVhcmVyICAgc2stYmFyZSANCg0K"}], "opts": {}}, {"group": "keys", "name": "models-env", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1lbnYNCg0K"}], "opts": {}}, {"group": "keys", "name": "models-wrong", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogQmVhcmVyIHNrLW5vcGUNCg0K"}], "opts": {}}, {"group": "keys", "name": "models-basic", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQXV0aG9yaXphdGlvbjogQmFzaWMgc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "metrics-none", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "keys", "name": "messages-none", "raws": [{"b64": "UE9TVCAvdjEvbWVzc2FnZXMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1MZW5ndGg6IDINCg0Ke30="}], "opts": {}}, {"group": "keys", "name": "tokenize-none", "raws": [{"b64": "UE9TVCAvdG9rZW5pemUgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KQ29udGVudC1MZW5ndGg6IDINCg0Ke30="}], "opts": {}}, {"group": "keys", "name": "alt-models", "raws": [{"b64": "R0VUIC9hbHQvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}, {"group": "keys", "name": "options", "raws": [{"b64": "T1BUSU9OUyAvdjEvbW9kZWxzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCg0K"}], "opts": {}}]}, {"kind": "cases", "cases": [{"group": "keys", "name": "twice-x-api-key", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1jbGkNCngtYXBpLWtleTogc2stY2xpDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "chat-with-key", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQp4LWFwaS1rZXk6IHNrLWNsaQ0KQ29udGVudC1MZW5ndGg6IDg2DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "keys", "name": "expect-without-key", "raws": [{"b64": "UE9TVCAvdjEvY2hhdC9jb21wbGV0aW9ucyBIVFRQLzEuMQ0KSG9zdDogcGFyaXR5DQpFeHBlY3Q6IDEwMC1jb250aW51ZQ0KQ29udGVudC1MZW5ndGg6IDg2DQoNCnsibW9kZWwiOiAiZmFrZS1tb2RlbCIsICJtZXNzYWdlcyI6IFt7InJvbGUiOiAidXNlciIsICJjb250ZW50IjogIkhpIEBzY3JpcHQ9cGxhaW4ifV19"}], "opts": {}}, {"group": "keys", "name": "pooled-identity", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1jbGkNCg0K"}, {"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KDQo="}], "opts": {}}]}, {"kind": "rewrite_key", "content": "next: sk-next\n"}, {"kind": "sleep", "seconds": 0.3}, {"kind": "cases", "cases": [{"group": "keys", "name": "rotated-old", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1maWxlDQoNCg=="}], "opts": {}}, {"group": "keys", "name": "rotated-new", "raws": [{"b64": "R0VUIC92MS9tb2RlbHMgSFRUUC8xLjENCkhvc3Q6IHBhcml0eQ0KeC1hcGkta2V5OiBzay1uZXh0DQoNCg=="}], "opts": {}}, {"group": "keys", "name": "metrics-counted", "raws": [{"b64": "R0VUIC9tZXRyaWNzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCngtYXBpLWtleTogc2stY2xpDQoNCg=="}], "opts": {}}]}, {"kind": "terminate"}]}, {"kind": "serve", "args": [], "env": {}, "cases": [{"group": "responses", "name": "namespace-tools", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE3MQ0KDQp7ImlucHV0IjogInggQHNjcmlwdD1uc190b29sIiwgInRvb2xzIjogW3sidHlwZSI6ICJuYW1lc3BhY2UiLCAibmFtZSI6ICJ3ZWF0aGVyIiwgImRlc2NyaXB0aW9uIjogIndlYXRoZXIgdG9vbHMiLCAidG9vbHMiOiBbeyJ0eXBlIjogImZ1bmN0aW9uIiwgIm5hbWUiOiAiZ2V0X3dlYXRoZXIifV19XX0="}], "opts": {}}, {"group": "responses", "name": "namespace-tools-stream", "raws": [{"b64": "UE9TVCAvdjEvcmVzcG9uc2VzIEhUVFAvMS4xDQpIb3N0OiBwYXJpdHkNCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vanNvbg0KQ29udGVudC1MZW5ndGg6IDE4Nw0KDQp7ImlucHV0IjogInggQHNjcmlwdD1uc190b29sIiwgInN0cmVhbSI6IHRydWUsICJ0b29scyI6IFt7InR5cGUiOiAibmFtZXNwYWNlIiwgIm5hbWUiOiAid2VhdGhlciIsICJkZXNjcmlwdGlvbiI6ICJ3ZWF0aGVyIHRvb2xzIiwgInRvb2xzIjogW3sidHlwZSI6ICJmdW5jdGlvbiIsICJuYW1lIjogImdldF93ZWF0aGVyIn1dfV19"}], "opts": {}}], "then": [{"kind": "terminate"}]}]} \ No newline at end of file diff --git a/zig/tests/server/golden/completions/echo-false.json b/zig/tests/server/golden/completions/echo-false.json new file mode 100644 index 00000000000..c12381ab2c9 --- /dev/null +++ b/zig/tests/server/golden/completions/echo-false.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 200 OK", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "" + ] + ], + "body": "{\"id\": \"\", \"object\": \"text_completion\", \"created\": , \"model\": \"fake-model\", \"choices\": [{\"index\": 0, \"text\": \"Hello world!\", \"finish_reason\": \"stop\", \"logprobs\": null}], \"usage\": {\"prompt_tokens\": 18, \"completion_tokens\": 4, \"total_tokens\": 22, \"prompt_tokens_details\": {\"cached_tokens\": 0}, \"completion_tokens_details\": {\"reasoning_tokens\": 0}}, \"exact_mode\": \"exact\", \"tensorfold\": {\"enable_thinking\": false, \"reasoning_effort\": \"none\", \"engine\": \"lanes\", \"tokens_per_second\": , \"seconds\": , \"prefill_seconds\": , \"prefill_widths\": [], \"prefill_raised\": [], \"time_to_first_token\": , \"sampling\": \"greedy\", \"drafts\": true, \"token_sha\": \"ab74875c663e\", \"min_rows\": 1}, \"speculative\": {\"rounds\": 3, \"drafted\": 1, \"accepted\": 1, \"acceptance_rate\": 1.0, \"tokens_per_round\": 1.3333333333333333}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/completions/echo-stream.json b/zig/tests/server/golden/completions/echo-stream.json new file mode 100644 index 00000000000..1ef62be6d86 --- /dev/null +++ b/zig/tests/server/golden/completions/echo-stream.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 400 Bad Request", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "118" + ] + ], + "body": "{\"error\": {\"message\": \"echo is supported on /v1/completions without streaming only\", \"type\": \"invalid_request_error\"}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/completions/echo-unsupported.json b/zig/tests/server/golden/completions/echo-unsupported.json new file mode 100644 index 00000000000..200ae1ad440 --- /dev/null +++ b/zig/tests/server/golden/completions/echo-unsupported.json @@ -0,0 +1,20 @@ +{ + "closed": "open", + "replies": [ + { + "status": "HTTP/1.1 400 Bad Request", + "headers": [ + [ + "Content-Type", + "application/json" + ], + [ + "Content-Length", + "105" + ] + ], + "body": "{\"error\": {\"message\": \"echo is not supported by this model or backend\", \"type\": \"invalid_request_error\"}}", + "interim": "" + } + ] +} diff --git a/zig/tests/server/golden/lifecycle/request-log.json b/zig/tests/server/golden/lifecycle/request-log.json index d08dc23f282..4b61a0b9b1c 100644 --- a/zig/tests/server/golden/lifecycle/request-log.json +++ b/zig/tests/server/golden/lifecycle/request-log.json @@ -158,6 +158,9 @@ {"messages": [{"role": "user", "content": "Hi @script=think"}], "stream": true} {"prompt": "Once @script=plain", "stream": true, "stream_options": {"include_usage": true}} {"prompt": "x @script=think", "stream": true} +{"prompt": "Once @script=plain", "echo": false} +{"prompt": "Once @script=plain", "echo": true} +{"prompt": "Once @script=plain", "echo": true, "stream": true} {"model": "fake-model", "messages": [{"role": "user", "content": "Hi @script=think"}]} {"stream": true, "messages": [{"role": "user", "content": "Hi @script=think"}]} {"messages": [{"role": "user", "content": "Hi @script=qwen_tool"}], "tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "limit": {"type": "integer"}}}}}]} From 1867fc7b15aca7fcc027b01d2c3e85d816c7a05c Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:45:40 +0000 Subject: [PATCH 139/361] test: reject completions echo with an empty messages array --- zig/src/server/completion_echo_test.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/server/completion_echo_test.zig b/zig/src/server/completion_echo_test.zig index a0072ac610a..b5981066d0e 100644 --- a/zig/src/server/completion_echo_test.zig +++ b/zig/src/server/completion_echo_test.zig @@ -147,6 +147,7 @@ test "completions echo: refused by name before anything is submitted, while chat .{ .body = "{\"prompt\":\"abc\",\"echo\":\"yes\"}", .message = "echo must be a boolean or null" }, .{ .body = "{\"prompt\":\"abc\",\"echo\":1}", .message = "echo must be a boolean or null" }, .{ .body = "{\"messages\":[{\"role\":\"user\",\"content\":\"x\"}],\"echo\":true}", .message = "echo is supported with a prompt, not messages" }, + .{ .body = "{\"model\":\"test-model\",\"prompt\":\"abc\",\"messages\":[],\"echo\":true}", .message = "echo is supported with a prompt, not messages" }, .{ .body = "{\"prompt\":\"abc\",\"echo\":true}", .message = "echo is not supported by this model or backend", .rows = false }, .{ .body = "{\"prompt\":\"abc\",\"echo\":true,\"max_tokens\":0,\"logprobs\":1}", .message = "echo is not supported by this model or backend", .rows = false }, }; From 220cbd50a22d605f6276176919c929adb1f95139 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:45:42 +0000 Subject: [PATCH 140/361] server: refuse completions echo whenever messages is present --- zig/src/server/completion_echo.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/server/completion_echo.zig b/zig/src/server/completion_echo.zig index e6ddae30bc5..04b6fbc9d77 100644 --- a/zig/src/server/completion_echo.zig +++ b/zig/src/server/completion_echo.zig @@ -17,7 +17,7 @@ pub fn plan(srv: *Server, cx: *Cx, body: Value, input: *chat.Input, completions: if (asked != .bool) return cx.refuse("echo must be a boolean or null"); if (!asked.bool) return; if (streamed) return cx.refuse("echo is supported on /v1/completions without streaming only"); - if (input.messages.array.len > 0) return cx.refuse("echo is supported with a prompt, not messages"); + if (body.get("messages") != null) return cx.refuse("echo is supported with a prompt, not messages"); if (!rows) return cx.refuse("echo is not supported by this model or backend"); input.echo = true; input.prompt_only = noTokens(body); From 7ab4e93c69dcac823277803d68788a7c2b76d350 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:08:59 +0000 Subject: [PATCH 141/361] changelog: #3526 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb8a59824f8..5ff4f87f99d 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 +- 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). + - MiniMax-M3 on CUDA: `TF_MINIMAX_GRAPHS=1` (opt-in) runs the decode verify window from one CUDA graph, re-recorded with each round's arguments and updated in place, so every kernel sees the same arguments as the eager path and tokens are unchanged (#4610). - Server: `POST /v1/prompt_cache/flush` takes an optional `retain` count that keeps the most recently used prompt states in RAM and on disk; without it the flush is unchanged (#4856). From 4b541ef95b39c92ce7e5eb3cf96ed0df2b7da7f9 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:58:11 +0100 Subject: [PATCH 142/361] glm metal: GLM_ROUND_PROF per-round host and GPU summary GLM_ROUND_PROF=1 logs verify window GPU time, idle gap, ahead span, host phases, and partial accepts when streams end. Unset, blank, or 0 stays off; invalid values fail startup by name via environment.read. Refs #3152. --- docs/environment.md | 1 + zig/src/families/glm/backend.zig | 10 + zig/src/families/glm/glm.zig | 1 + zig/src/families/glm/round_prof.zig | 270 ++++++++++++++++++++++++++ zig/src/families/glm/slots.zig | 12 +- zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 4 +- 7 files changed, 297 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/glm/round_prof.zig diff --git a/docs/environment.md b/docs/environment.md index 684543619c6..7c21e763c9b 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -112,6 +112,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_QWEN27_TIED_HEAD` | Dense Qwen on Metal: exactly `0` or `1`; `1` lets a checkpoint with a tied head load on the 27B engine, its head read from the embedding (one Mac, no draft head, qualified shapes only); unset or blank is `0` | | `TF_QWEN35_METAL_KV_PAGES` | Qwen 3.5 on Metal: exactly `0` or `1`; `1` puts the streams' keys and values in core-pool pages; unset or blank is `0` | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | +| `GLM_ROUND_PROF` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `1` has the server log a summary of its verify windows when streams end (window GPU time, idle gap, drafts span and host phases by rows, streams and drafted or plain; partial accepts); default off | | `TF_DSV41_SMALL` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` reads the checkpoint's config at its own small shapes (the served smoke test's tiny model); default 0 | | `TF_DSV41_ASSETS` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the Engram token map; unset or blank reads it beside the checkpoint | | `TF_DSV41_ENGRAM_DIR` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the packed Engram tables; unset or blank takes the checkpoint's `engram_table_dir` | diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 9c3429cc602..209f8a5ad40 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lanes = @import("lanes"); const st = @import("state.zig"); const slots_mod = @import("slots.zig"); +const rp = @import("round_prof.zig"); const slot_images = @import("slot_images.zig"); const pool = @import("pool.zig"); const mirror = @import("mirror.zig"); @@ -404,6 +405,7 @@ pub const Backend = struct { try mirror.windowWords(&b.words, b.gpa, b.sl.digest, b.wins.items); try mirror.send(b.sl.e, .window, b.words.items); try b.sl.window(b.wins.items, &draws); + const t_picks = rp.tick(b.sl.prof); const picks = Engine.u32s(b.sl.e.sc.picks, total); var row: usize = 0; for (windows, out, b.wins.items) |w, o, win| { @@ -413,10 +415,15 @@ pub const Backend = struct { if (b.rounds) |r| r.sawWindow(win.slot, @intCast(w.held + w.tokens.len)); row += w.rows(); } + rp.since(b.sl.prof, .picks, t_picks); + rp.verified(b.sl.prof); } fn keep(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { const b = self(ptr); + rp.laneEnd(b.sl.prof); + const t_keeps = rp.tick(b.sl.prof); + defer rp.since(b.sl.prof, .keeps, t_keeps); for (windows, paths) |w, path| { for (path, 0..) |r, k| if (r != k) return error.TreeWindowsUnsupported; const i = try b.slotOf(w.stream); @@ -429,6 +436,9 @@ pub const Backend = struct { fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { const b = self(ptr); + rp.laneEnd(b.sl.prof); + const t_drafts = rp.tick(b.sl.prof); + defer rp.since(b.sl.prof, .drafts, t_drafts); if (b.rounds) |r| return dflash.draft(b, r, requests); var ones: [st.max_rows]u32 = undefined; // a prompt's first token, the one its head absorbs with b.drafts.clearRetainingCapacity(); diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index e96251d261a..381635e8c22 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -60,6 +60,7 @@ test { _ = @import("page_cache.zig"); _ = pool; _ = @import("kept.zig"); + _ = @import("round_prof.zig"); _ = @import("draw_test.zig"); _ = mirror; _ = timing; diff --git a/zig/src/families/glm/round_prof.zig b/zig/src/families/glm/round_prof.zig new file mode 100644 index 00000000000..7a7eb2f72c4 --- /dev/null +++ b/zig/src/families/glm/round_prof.zig @@ -0,0 +1,270 @@ +//! GLM Metal verify windows: GPU time, idle gaps and host phases by window shape, summarized when streams end. +const std = @import("std"); +const platform = @import("sys"); + +const ticks_per_ms = 24e3; +const bin_ms = 0.05; +const n_bins = 400; + +/// What a round measures: the window's own times, then the host phases between one window and the next. +pub const Metric = enum { gpu, gap, ahead, encode, wait, picks, lane, keeps, drafts }; +const n_metrics = std.enums.values(Metric).len; +const row_buckets = [_][]const u8{ "1", "2", "3-4", "5-8", "9-16" }; +const n_groups = row_buckets.len * 3 * 2; + +/// A window's shape and the clock readings its times come from. +pub const Window = struct { + rows: u32, + streams: u32, + drafted: u32, + t_in: u64, + committed: u64, + ret: u64, + gpu: [2]f64, + ahead: [2]f64, + last_end: f64, +}; + +const Stat = struct { + sum: f64 = 0, + max: f64 = 0, + bins: [n_bins + 1]u32 = @splat(0), + + fn add(s: *Stat, ms: f64) void { + s.sum += ms; + s.max = @max(s.max, ms); + const at: usize = @intFromFloat(@min(@max(ms, 0) / bin_ms, n_bins)); + s.bins[at] += 1; + } + + /// The bin edge at or above fraction `q` of `n` values; the overflow bin answers with the largest value. + fn quantile(s: *const Stat, n: u64, q: f64) f64 { + const want: u64 = @max(1, @as(u64, @intFromFloat(@ceil(q * @as(f64, @floatFromInt(n)))))); + var seen: u64 = 0; + for (s.bins, 0..) |c, i| { + seen += c; + if (seen >= want) return if (i == n_bins) s.max else @min(@as(f64, @floatFromInt(i + 1)) * bin_ms, s.max); + } + return s.max; + } +}; + +const Group = struct { n: u64 = 0, stats: [n_metrics]Stat = @splat(.{}) }; + +/// Every field is valid all zero: `create` clears the whole record. +pub const Prof = struct { + groups: [n_groups]Group, + pend: [n_metrics]f64, // the round in progress: its window's times, then the host phases as they finish + pend_group: usize, + pend_live: bool, + verify_end: u64, + lane_open: bool, + windows: u64, + reported: u64, + queued: u64, // one-row rounds queued ahead, which run no window + keeps: u64, + partial: u64, // keeps that rejected rows: each replays the KDA states + kept_rows: u64, + window_rows: u64, + drafted_rows: u64, + + /// The round in progress joins its group's histograms. + fn finish(p: *Prof) void { + if (!p.pend_live) return; + const g = &p.groups[p.pend_group]; + g.n += 1; + for (&g.stats, p.pend) |*s, ms| s.add(ms); + p.pend_live = false; + } +}; + +fn rowBucket(rows: u32) usize { + return if (rows <= 2) (if (rows == 0) 0 else rows - 1) else if (rows <= 4) 2 else if (rows <= 8) 3 else 4; +} + +/// The group of a window's rows, streams and whether any draft rows rode in it. +pub fn group(rows: u32, streams: u32, drafted: bool) usize { + return (rowBucket(rows) * 3 + @min(@max(streams, 1), 3) - 1) * 2 + @intFromBool(drafted); +} + +fn alloc(gpa: std.mem.Allocator) !*Prof { + const p = try gpa.create(Prof); + @memset(std.mem.asBytes(p), 0); + return p; +} + +/// GLM_ROUND_PROF on: the record, else null (every hook then costs one branch and no clock read). +pub fn create(gpa: std.mem.Allocator, raw: ?[]const u8) !?*Prof { + if (!try platform.environment.value(bool, "GLM_ROUND_PROF", raw, false)) return null; + return try alloc(gpa); +} + +pub fn fromEnvironment(gpa: std.mem.Allocator) !?*Prof { + if (!try platform.environment.read(bool, "GLM_ROUND_PROF", false)) return null; + return try alloc(gpa); +} + +pub fn destroy(p: ?*Prof, gpa: std.mem.Allocator) void { + if (p) |q| gpa.destroy(q); +} + +/// A clock reading for `since`, or 0 with the profile off. +pub fn tick(p: ?*Prof) u64 { + return if (p != null) platform.c.mach_absolute_time() else 0; +} + +/// The host time from `t0` added to this round's `which` phase. +pub fn since(p: ?*Prof, which: Metric, t0: u64) void { + const q = p orelse return; + q.pend[@backingInt(which)] += millis(platform.c.mach_absolute_time() -| t0); +} + +fn millis(ticks: u64) f64 { + return @as(f64, @floatFromInt(ticks)) / ticks_per_ms; +} + +/// A window ran: the previous round is complete, this one's times are taken. +pub fn window(p: *Prof, w: Window) void { + p.finish(); + const first = if (w.ahead[1] > 0) w.ahead[0] else w.gpu[0]; + p.pend = @splat(0); + p.pend[@backingInt(Metric.gpu)] = (w.gpu[1] - w.gpu[0]) * 1e3; + p.pend[@backingInt(Metric.gap)] = if (w.last_end > 0) @max(first - w.last_end, 0) * 1e3 else 0; + p.pend[@backingInt(Metric.ahead)] = (w.ahead[1] - w.ahead[0]) * 1e3; + p.pend[@backingInt(Metric.encode)] = millis(w.committed -| w.t_in); + p.pend[@backingInt(Metric.wait)] = millis(w.ret -| w.committed); + p.pend_group = group(w.rows, w.streams, w.drafted > 0); + p.pend_live = true; + p.windows += 1; + p.window_rows += w.rows; + p.drafted_rows += w.drafted; +} + +/// The window's picks are on the host: the lane core's accept time starts. +pub fn verified(p: ?*Prof) void { + const q = p orelse return; + q.verify_end = platform.c.mach_absolute_time(); + q.lane_open = true; +} + +/// The lane core finished accepting: its time since `verified`, once a round. +pub fn laneEnd(p: ?*Prof) void { + const q = p orelse return; + if (!q.lane_open) return; + q.lane_open = false; + q.pend[@backingInt(Metric.lane)] += millis(platform.c.mach_absolute_time() -| q.verify_end); +} + +/// One stream's keep: `kept` of the window's `rows` stay. +pub fn kept(p: *Prof, n: u32, rows: u32) void { + p.keeps += 1; + p.partial += @intFromBool(n < rows); + p.kept_rows += n; +} + +/// The summary, once there is a window since the last one. +pub fn report(p: ?*Prof) void { + const q = p orelse return; + q.finish(); + if (q.windows == q.reported) return; + q.reported = q.windows; + std.log.info("glm round prof: {d} windows, {d} queued one-row rounds, {d} keeps ({d} partial), {d} rows kept of {d} ({d} drafted)", .{ q.windows, q.queued, q.keeps, q.partial, q.kept_rows, q.window_rows, q.drafted_rows }); + var buf: [160]u8 = undefined; + for (&q.groups, 0..) |*g, i| if (g.n > 0) { + std.log.info("glm round prof: rows {s}, streams {d}{s}, {s}: {d} windows (ms: mean p50 p90 max)", .{ row_buckets[i / 6], (i / 2) % 3 + 1, if ((i / 2) % 3 == 2) "+" else "", if (i % 2 == 1) "drafted" else "plain", g.n }); + for (&g.stats, 0..) |*s, m| std.log.info("{s}", .{line(&buf, @tagName(@as(Metric, @fromBackingInt(@intCast(m)))), s, g.n)}); + }; +} + +fn line(buf: []u8, name: []const u8, s: *const Stat, n: u64) []const u8 { + return std.fmt.bufPrint(buf, " {s:<7} {d:8.2} {d:8.2} {d:8.2} {d:8.2}", .{ name, s.sum / @as(f64, @floatFromInt(n)), s.quantile(n, 0.5), s.quantile(n, 0.9), s.max }) catch ""; +} + +/// Draft rows (held and host drafts) in `wins`. +pub fn draftedRows(wins: anytype) u32 { + var n: u32 = 0; + for (wins) |w| n += w.held + @as(u32, @intCast(w.tokens.len)); + return n; +} + +test "round profile: rows and streams bucket into thirty distinct groups" { + var seen: [n_groups]bool = @splat(false); + for ([_]u32{ 1, 2, 3, 4, 5, 8, 9, 16 }) |rows| for ([_]u32{ 1, 2, 3, 7 }) |streams| for ([_]bool{ false, true }) |d| { + const g = group(rows, streams, d); + try std.testing.expect(g < n_groups); + seen[g] = true; + }; + for (seen) |s| try std.testing.expect(s); + try std.testing.expectEqual(group(3, 1, false), group(4, 1, false)); + try std.testing.expect(group(8, 2, true) != group(9, 2, true)); + try std.testing.expectEqual(group(1, 3, false), group(1, 9, false)); +} + +test "round profile: GLM_ROUND_PROF unset, blank or 0 is off and 1 on; text is refused by name" { + const gpa = std.testing.allocator; + for ([_]?[]const u8{ null, "", " ", "0" }) |raw| try std.testing.expect((try create(gpa, raw)) == null); + const p = (try create(gpa, "1")).?; + defer destroy(p, gpa); + try std.testing.expect(!p.pend_live and p.windows == 0 and p.groups[0].n == 0); + try std.testing.expectError(error.InvalidEnvironment, create(gpa, "yes")); + try std.testing.expectError(error.InvalidEnvironment, create(gpa, "2")); + const why = try platform.environment.describe(gpa, "GLM_ROUND_PROF", "yes"); + defer gpa.free(why); + try std.testing.expect(std.mem.startsWith(u8, why, "GLM_ROUND_PROF=\"yes\":")); + defer _ = platform.env.unsetenv("GLM_ROUND_PROF"); + _ = platform.env.unsetenv("GLM_ROUND_PROF"); + try std.testing.expect((try fromEnvironment(gpa)) == null); + _ = platform.env.setenv("GLM_ROUND_PROF", " ", 1); + try std.testing.expect((try fromEnvironment(gpa)) == null); + _ = platform.env.setenv("GLM_ROUND_PROF", "1", 1); + const env_p = (try fromEnvironment(gpa)).?; + destroy(env_p, gpa); + _ = platform.env.setenv("GLM_ROUND_PROF", "yes", 1); + try std.testing.expectError(error.InvalidEnvironment, fromEnvironment(gpa)); +} + +test "round profile: off hooks read no clock and change nothing" { + try std.testing.expectEqual(@as(u64, 0), tick(null)); + since(null, .picks, 5); + verified(null); + laneEnd(null); + report(null); +} + +test "round profile: histograms give mean, p50, p90 and max per group" { + const gpa = std.testing.allocator; + const p = (try create(gpa, "1")).?; + defer destroy(p, gpa); + for (1..11) |k| { + const x: f64 = @floatFromInt(k); + window(p, .{ .rows = 4, .streams = 2, .drafted = 2, .t_in = 0, .committed = 24000, .ret = 72000, .gpu = .{ 1.0, 1.0 + x * 1e-3 }, .ahead = .{ 0, 0 }, .last_end = 0 }); + } + p.finish(); + const g = &p.groups[group(4, 2, true)]; + try std.testing.expectEqual(@as(u64, 10), g.n); + const gpu = &g.stats[@backingInt(Metric.gpu)]; + try std.testing.expectApproxEqAbs(@as(f64, 5.5), gpu.sum / 10, 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 5), gpu.quantile(10, 0.5), bin_ms); + try std.testing.expectApproxEqAbs(@as(f64, 9), gpu.quantile(10, 0.9), bin_ms); + try std.testing.expectApproxEqAbs(@as(f64, 10), gpu.max, 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 1), g.stats[@backingInt(Metric.encode)].max, 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 2), g.stats[@backingInt(Metric.wait)].max, 1e-9); + try std.testing.expectEqual(@as(u64, 10), p.windows); + try std.testing.expectEqual(@as(u64, 20), p.drafted_rows); + var buf: [160]u8 = undefined; + try std.testing.expect(std.mem.startsWith(u8, line(&buf, "gpu", gpu, g.n), " gpu 5.50 ")); +} + +test "round profile: keeps count partial accepts and the overflow bin reports the largest value" { + const gpa = std.testing.allocator; + const p = (try create(gpa, "1")).?; + defer destroy(p, gpa); + kept(p, 3, 5); + kept(p, 5, 5); + try std.testing.expectEqual(@as(u64, 2), p.keeps); + try std.testing.expectEqual(@as(u64, 1), p.partial); + try std.testing.expectEqual(@as(u64, 8), p.kept_rows); + var s: Stat = .{}; + s.add(500); + try std.testing.expectEqual(@as(f64, 500), s.quantile(1, 0.9)); +} diff --git a/zig/src/families/glm/slots.zig b/zig/src/families/glm/slots.zig index 498894344c2..703e60360ae 100644 --- a/zig/src/families/glm/slots.zig +++ b/zig/src/families/glm/slots.zig @@ -13,6 +13,7 @@ const Engine = @import("engine.zig").Engine; const Ref = @import("weights.zig").Ref; const Fence = @import("../../core/fence.zig").Fence; const lanes = @import("lanes"); +const rp = @import("round_prof.zig"); /// Handles of tokens on the GPU: queued rounds' picks and the host tokens they read, a slot each. const ring_len = 64; @@ -61,6 +62,7 @@ pub const Slots = struct { open: ?Open = null, // keeps and drafts encode here; the next window commits them with its forward windows: u64 = 0, follow: ?Follow = null, // the drafter's same-buffer pass behind each verify window + prof: ?*rp.Prof = null, // GLM_ROUND_PROF=1: windows and host phases by shape, summarized when streams end log: bool = false, // GLM_WINDOWS=1: each window's streams, rows, GPU time and the GPU's idle gap before it last_end: f64 = 0, last_ret: u64 = 0, // when the last window's wait returned (host clock ticks) @@ -87,8 +89,10 @@ pub const Slots = struct { .held = try e.arena.buffer(st.max_rows * 4), .last = try e.arena.buffer(@as(usize, e.c.hidden) * 2), }; + const prof = try rp.fromEnvironment(gpa); + errdefer rp.destroy(prof, gpa); const plane = @as(usize, st.max_rows) * e.c.hidden * 2; - var sl: Slots = .{ .gpa = gpa, .e = e, .slots = slots, .log = platform.c.getenv("GLM_WINDOWS") != null, .rows = try e.arena.buffer(plane), .ids = try e.arena.buffer(st.max_rows * 4), .lasts = try e.arena.buffer(plane), .picks = try e.arena.buffer(st.max_rows * 4), .ring = try e.arena.buffer(ring_len * 4) }; + var sl: Slots = .{ .gpa = gpa, .e = e, .slots = slots, .prof = prof, .log = platform.c.getenv("GLM_WINDOWS") != null, .rows = try e.arena.buffer(plane), .ids = try e.arena.buffer(st.max_rows * 4), .lasts = try e.arena.buffer(plane), .picks = try e.arena.buffer(st.max_rows * 4), .ring = try e.arena.buffer(ring_len * 4) }; if (pool_mod.on(e)) pool_mod.setUp(&sl); return sl; } @@ -96,6 +100,8 @@ pub const Slots = struct { pub fn deinit(sl: *Slots, gpa: std.mem.Allocator) void { sl.land() catch {}; sl.e.sync(); + rp.report(sl.prof); + rp.destroy(sl.prof, gpa); sl.dropRing(); if (sl.fence) |f| f.deinit(); var it = sl.snaps.valueIterator(); @@ -325,6 +331,7 @@ pub const Slots = struct { const s_of = @as(f64, @floatFromInt(e.committed)) / 24e6; std.log.info("glm window: streams {d} rows {d} gpu {d:.2} ms gap {d:.2} ms ahead {d:.2} join {d:.3} host {d:.2} encode {d:.2} ms start {d:.3} seen {d:.3} ms", .{ wins.len, total, (e.gpu[1] - e.gpu[0]) * 1e3, (first - sl.last_end) * 1e3, (sl.ahead[1] - sl.ahead[0]) * 1e3, if (sl.ahead[1] > 0) (e.gpu[0] - sl.ahead[1]) * 1e3 else 0, @as(f64, @floatFromInt(t_in -| sl.last_ret)) / 24e3, @as(f64, @floatFromInt(e.committed - t_in)) / 24e3, (e.gpu[0] - s_of) * 1e3, (@as(f64, @floatFromInt(ret)) / 24e6 - e.gpu[1]) * 1e3 }); } + if (sl.prof) |p| rp.window(p, .{ .rows = total, .streams = @intCast(wins.len), .drafted = rp.draftedRows(wins), .t_in = t_in, .committed = e.committed, .ret = ret, .gpu = e.gpu, .ahead = sl.ahead, .last_end = sl.last_end }); sl.last_ret = ret; sl.last_end = e.gpu[1]; sl.windows += 1; @@ -399,6 +406,7 @@ pub const Slots = struct { slot.row0 = 0; slot.rows = 1; slot.width = 1; + if (sl.prof) |p| p.queued += 1; sl.windows += 1; slot.seen = sl.windows; return to; @@ -408,6 +416,7 @@ pub const Slots = struct { pub fn keep(sl: *Slots, i: u32, kept: u32) !void { const slot = try sl.slotAt(i); if (slot.rows == 0 or kept == 0 or kept > slot.rows) return error.KeepOutOfStep; + if (sl.prof) |p| rp.kept(p, kept, slot.rows); sl.settle(slot, kept); } @@ -522,6 +531,7 @@ pub const Slots = struct { slot.held_n = 0; if (sl.pool != null) pool_mod.leave(sl, i); for (sl.slots) |s| if (s.used) return; + rp.report(sl.prof); sl.flush() catch |err| std.log.err("glm: the slots' last command buffer failed: {s}", .{@errorName(err)}); } }; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index f49639869a0..66963f8826f 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -114,6 +114,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSV41_ROUND_PROF", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 logs DeepSeek-V4.1 Metal decode rounds' host and GPU milliseconds by rows)" }, .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0: Flash Next's 4-bit expert kernels read the stored scales and biases, not their 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, + .{ .name = "GLM_ROUND_PROF", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: GLM-5.3-Flash's server logs a window and host-phase summary when streams end)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, .{ .name = "TF_FN_GX_GATEUP_MB2", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's grouped gate/up decodes an expert's weights once for two rows; same output bits)" }, .{ .name = "TF_FN_GX_SHARED", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next shared rounds use eligible grouped experts with the per-row kernels' bits)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index d96cf50b94a..8b1fe873c5f 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -174,6 +174,8 @@ const valid = [_]Case{ .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .raw = "1", .n = 1 }, .{ .name = "GLM_EHPROJ_NAX", .raw = "0", .n = 0 }, .{ .name = "GLM_EHPROJ_NAX", .raw = "1", .n = 1 }, + .{ .name = "GLM_ROUND_PROF", .raw = "0", .n = 0 }, + .{ .name = "GLM_ROUND_PROF", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_SHARED_PREFIX", .raw = "0", .n = 0 }, @@ -478,7 +480,7 @@ test "environment: a legacy alias is checked only while its canonical name is un } test "environment: the Metal Qwen and slide-learning switches take their forms, read blank as unset and name a refusal" { - const flags = [_][:0]const u8{ "TF_Q27_MTP_GPU_PICK", "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_SHARED_PREFIX", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN27_JOIN", "TF_QWEN27_TIED_HEAD", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; + const flags = [_][:0]const u8{ "GLM_ROUND_PROF", "TF_Q27_MTP_GPU_PICK", "TF_QWEN27_SLOT_RESUME", "TF_QWEN27_SHARED_PREFIX", "TF_QWEN27_METAL_KV_PAGES", "TF_QWEN27_JOIN", "TF_QWEN27_TIED_HEAD", "TF_QWEN35_METAL_KV_PAGES", "TF_SLIDE_TAKE_OUT_CHECK", "TF_SLIDE_TAP_CHECK" }; for (flags) |name| { try t.expectEqual(@as(?u64, 0), try e.parse(name, "0")); try t.expectEqual(@as(?u64, 1), try e.parse(name, "1")); From 00e0e98784aeede96f765f4f0f3fd6d4ef75cba6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:28:56 +0000 Subject: [PATCH 143/361] changelog: #3894 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ff4f87f99d..8c6771be3e6 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 +- 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). - MiniMax-M3 on CUDA: `TF_MINIMAX_GRAPHS=1` (opt-in) runs the decode verify window from one CUDA graph, re-recorded with each round's arguments and updated in place, so every kernel sees the same arguments as the eager path and tokens are unchanged (#4610). From 475c2b61457885fe84ab54d9b1aaff70eda6c291 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:16:56 +0100 Subject: [PATCH 144/361] glm metal: shortest-remaining-first prompt order by default on one Mac A reply that would end well before a long prompt goes first, as for Qwen3.8-27B. A decode share, a prompt share below 1, the two-Mac pair or a TENSORFOLD_PREFILL_ORDER other than srpt keeps the old order. Refs #3152. --- docs/api.md | 2 +- zig/build/glm_expiry.zig | 2 +- zig/src/glm_order_tests.zig | 38 ++++++++++++++++++++++++++++++++++ zig/src/glm_schedule_tests.zig | 4 ++++ zig/src/native/glm_host.zig | 3 +++ zig/src/native/glm_order.zig | 6 ++++++ 6 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 zig/src/glm_order_tests.zig create mode 100644 zig/src/native/glm_order.zig diff --git a/docs/api.md b/docs/api.md index 2de2033fd71..fda7c9f6c34 100644 --- a/docs/api.md +++ b/docs/api.md @@ -692,7 +692,7 @@ are the exception: absent both, replies take 0.8 of that time and a filling prom from 32 to 512 rows after eight, while `--decode-share 0` keeps the 32-row steps with the prompt first. `TENSORFOLD_PREFILL_ORDER=srpt` lets a running reply that would end within a quarter of a filling long prompt's estimated time left take rounds first, the prompt keeping at least 10% of the time and lending at most a quarter of its own. It's the default for Qwen3.8-27B -on Metal when neither `--decode-share` nor `TENSORFOLD_PREFILL_SHARE` is set; any other value of the variable turns it off. With `--thinking-reserve`, a reply that is still reasoning counts as its answer quota plus the reasoning still expected, from the think blocks this server has seen close; before the first has closed it counts as its limit left (its `max_tokens` plus the reserve, less what it has emitted). With `--decode-share` it keeps that share when the prompt goes first and takes at most 10% when a reply does, and `--decode-share 0` still prefills each prompt whole. The CUDA, qwen27 Metal, DeepSeek-V4.1 Metal and +and for GLM-5.3-Flash on one Mac (not the two-Mac pair) on Metal when neither `--decode-share` nor a `TENSORFOLD_PREFILL_SHARE` below 1 is set; any other value of the variable turns it off. With `--thinking-reserve`, a reply that is still reasoning counts as its answer quota plus the reasoning still expected, from the think blocks this server has seen close; before the first has closed it counts as its limit left (its `max_tokens` plus the reserve, less what it has emitted). With `--decode-share` it keeps that share when the prompt goes first and takes at most 10% when a reply does, and `--decode-share 0` still prefills each prompt whole. The CUDA, qwen27 Metal, DeepSeek-V4.1 Metal and hip_serve servers pass the flag to their lane host and take its time share (DeepSeek-V4.1 on Metal also runs prompts in steps with it, replies taking 0.25 when it is absent and steps are on; `TF_DSV41_PREFILL_PIECES`); the DeepSeek CUDA, Spark-X on Metal, Qwen4 and XPU servers do not parse or apply the flag. `--decode-share 0` prefills each prompt diff --git a/zig/build/glm_expiry.zig b/zig/build/glm_expiry.zig index 25e71ec4643..9fbc177c59d 100644 --- a/zig/build/glm_expiry.zig +++ b/zig/build/glm_expiry.zig @@ -47,7 +47,7 @@ pub fn steps(b: *std.Build, test_step: *std.Build.Step, lanes: *std.Build.Module b.step("check-glm-gather-gpu-host", "Compile the GPU gather equality gate without compiling or running shaders").dependOn(&gpu_check.step); const core = sharedHostCore(b, metal); const sched_mod = hostMod(b, "zig/src/glm_schedule_tests.zig", metal, lanes, fabric, sources, core); - const schedule = b.addTest(.{ .filters = &.{ "glm prefill:", "fill aging:" }, .root_module = sched_mod }); + const schedule = b.addTest(.{ .filters = &.{ "glm prefill:", "fill aging:", "glm order:" }, .root_module = sched_mod }); if (b.graph.host.result.os.tag == .macos) schedule.root_module.linkSystemLibrary("objc", .{}); const schedule_run = b.addRunArtifact(schedule); b.step("test-glm-scheduling-host", "Actual GLM prefill chunks and lane-host decode fairness using a fake engine").dependOn(&schedule_run.step); diff --git a/zig/src/glm_order_tests.zig b/zig/src/glm_order_tests.zig new file mode 100644 index 00000000000..954ad2bc635 --- /dev/null +++ b/zig/src/glm_order_tests.zig @@ -0,0 +1,38 @@ +//! GLM Metal's prompt order on the lane host's Srpt: the default, the env's say, and the cases that keep main's order. +const std = @import("std"); +const Srpt = @import("core/lane_host_srpt.zig").Srpt; +const order = @import("native/glm_order.zig"); +const env = @import("sys").env; + +const name = "TENSORFOLD_PREFILL_ORDER"; + +fn started(pair: bool, share: ?f64, prompt_share: f64) Srpt { + return if (order.srptByDefault(pair, share, prompt_share)) Srpt.withDefault(true) else Srpt.fromEnv(); +} + +test "glm order: one Mac with no share starts with shortest-remaining-first" { + _ = env.unsetenv(name); + try std.testing.expect(started(false, null, 1).on); +} + +test "glm order: an explicit order wins over the default, either way" { + defer _ = env.unsetenv(name); + _ = env.setenv(name, "fifo", 1); + try std.testing.expect(!started(false, null, 1).on); + _ = env.setenv(name, "srpt", 1); + try std.testing.expect(started(false, null, 1).on); + try std.testing.expect(started(true, null, 1).on); // opt-in still works on the pair and beside a share + try std.testing.expect(started(false, 0.5, 1).on); +} + +test "glm order: the pair, a decode share and a prompt share below 1 keep main's order" { + _ = env.unsetenv(name); + try std.testing.expect(!started(true, null, 1).on); + try std.testing.expect(!started(false, 0.25, 1).on); + try std.testing.expect(!started(false, null, 0.5).on); +} + +test "glm order: a host nobody gave a default starts off, as every other family's" { + _ = env.unsetenv(name); + try std.testing.expect(!Srpt.fromEnv().on); +} diff --git a/zig/src/glm_schedule_tests.zig b/zig/src/glm_schedule_tests.zig index 46b9131e1b9..c7a4a1233b0 100644 --- a/zig/src/glm_schedule_tests.zig +++ b/zig/src/glm_schedule_tests.zig @@ -22,3 +22,7 @@ test { test { _ = @import("core/lane_host_fill_aging_test.zig"); } + +test { + _ = @import("glm_order_tests.zig"); +} diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index ddee2bb22e6..9088b6c5dfd 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -8,6 +8,7 @@ const glm = tf.glm; const ge = glm.engine; const glm_disk = @import("glm_disk.zig"); const cache_fit = @import("cache_fit.zig"); +const order = @import("glm_order.zig"); const Allocator = std.mem.Allocator; /// The warm-up reply's draft depth: every rank of a pair pays a process's first-round costs at the same step. @@ -141,6 +142,8 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: // sampled draws on one Mac (the pair refuses them per request) h.host = api.LaneHost.init(gpa, io, &h.core, .{ .benchmark_ranks = if (eng.ep != null) 2 else 1, .benchmark_group = if (eng.ep) |p| p.benchmark_group else null, .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .decode_share = decode_share, .greedy_only = eng.ep != null, .draft_sources = .{ .drafter = if (drafter) |d| .{ .kind = "DFlash2", .name = drafter_name orelse d } else null }, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null, .vision = offer }); h.host.memory = .{ .ctx = h, .read = readMemory }; + // a reply that ends soon goes first beside a long prompt; the pair and a share someone set keep main's order + if (order.srptByDefault(eng.ep != null, decode_share, h.host.share.p)) h.host.srpt = @TypeOf(h.host.srpt).withDefault(true); h.cache = null; const budget = cacheBudget(eng, cache_gib); if (!eng.followsPeer() and budget > 0) { diff --git a/zig/src/native/glm_order.zig b/zig/src/native/glm_order.zig new file mode 100644 index 00000000000..4da248c528b --- /dev/null +++ b/zig/src/native/glm_order.zig @@ -0,0 +1,6 @@ +//! GLM's default prompt order on the lane host: shortest-remaining-first on one Mac, as Qwen3.8-27B does. + +/// Whether the host starts with shortest-remaining-first: one Mac, no decode share, no prompt share below 1. +pub fn srptByDefault(pair: bool, decode_share: ?f64, prompt_share: f64) bool { + return !pair and decode_share == null and prompt_share >= 1; +} From 99df7d33d882ae4f676f0e435ed9e9ce5d0b0b20 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:50:18 +0000 Subject: [PATCH 145/361] changelog: #3903 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c6771be3e6..1e125de0c9d 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 +- 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). From 7035016b1405499ed1f9acebacb1f4c5318481a7 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:50:18 +0000 Subject: [PATCH 146/361] changelog: #3903 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e125de0c9d..3fa05d3677a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - 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). From 67e686e0c639fc9f72743f3b7c8d874bee97898e Mon Sep 17 00:00:00 2001 From: GrgaPalcic <26028466+GrgaPalcic@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:08:16 +0100 Subject: [PATCH 147/361] tools: add model-agnostic bench_prose.py (8-novel decode, KV loss, distinct long) --- tools/bench_prose.py | 373 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 373 insertions(+) create mode 100755 tools/bench_prose.py diff --git a/tools/bench_prose.py b/tools/bench_prose.py new file mode 100755 index 00000000000..e0d22fb78af --- /dev/null +++ b/tools/bench_prose.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +"""Realistic natural-prose benchmark for OpenAI-compatible LLM servers: +1. 8-stream distinct literary/prose generation (drafted vs plain, zero shared prefixes, cached_tokens=0). +2. BF16 vs FP8 KV cache loss on genuine classic prose (1K..32K chapters + 48-step teacher-forced Moby-Dick NLL/KL). +3. Nx >500,000-token (4.0M+ total) completely distinct uncached classic novels (cached_tokens=0 on all streams, 3 unique markers per stream). +""" +import argparse, concurrent.futures, json, math, os, re, statistics, time, urllib.request + +def strip_gutenberg(raw: str) -> str: + # Strip Project Gutenberg header and footer so zero boilerplate is shared across books! + m_start = re.search(r"\*\*\*\s*START OF (?:THE|THIS) PROJECT GUTENBERG.*?\*\*\*", raw, flags=re.I | re.S) + if m_start: + raw = raw[m_start.end():] + else: + raw = raw[4000:] + m_end = re.search(r"\*\*\*\s*END OF (?:THE|THIS) PROJECT GUTENBERG", raw, flags=re.I) + if m_end: + raw = raw[:m_end.start()] + return raw.strip() + +def load_book(prose_dir: str, name: str) -> str: + with open(os.path.join(prose_dir, f"{name}.txt"), "r", encoding="utf-8", errors="ignore") as f: + return strip_gutenberg(f.read()) + +def post_json(url: str, payload: dict, timeout: int = 3600) -> dict: + req = urllib.request.Request( + url, + data=json.dumps(payload).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read().decode("utf-8")) + +DISTINCT_PROSE_8 = [ + ("war_and_peace", 12000, 9500, "Analyze how Tolstoy contrasts salon artifice with genuine human emotion in this opening scene, then continue the narrative tone for two paragraphs."), + ("monte_cristo", 15000, 9500, "Examine Edmond Dantes' character and relationship with shipboard authority in this passage, and write a detailed critical commentary."), + ("les_miserables", 18000, 9500, "Discuss Victor Hugo's portrait of Bishop Myriel's moral philosophy in this excerpt and trace its narrative consequences."), + ("don_quixote", 14000, 9500, "Analyze Cervantes' use of irony and chivalric obsession in this passage and explain how the prose rhythm builds comedic tension."), + ("moby_dick", 22000, 9500, "Examine Ishmael's reflections on the sea and solitude in this excerpt, focusing on Melville's imagery and philosophical undertones."), + ("anna_karenina", 16000, 9500, "Analyze how Tolstoy establishes domestic conflict and psychological realism in the Oblonsky household in this scene."), + ("crime_and_punishment", 14000, 9500, "Examine how Dostoevsky conveys Raskolnikov's feverish alienation through sensory detail in St. Petersburg."), + ("ulysses", 14000, 9500, "Analyze Joyce's shifts between external action and interior monologue on the Martello tower in this opening passage."), +] + +def stream_chat(url: str, body: dict, timeout: int = 600): + body = dict(body, stream=True, stream_options={"include_usage": True}) + req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), headers={"Content-Type": "application/json"}) + t0 = time.time() + t_first = None + t_last = None + usage = {} + with urllib.request.urlopen(req, timeout=timeout) as resp: + for raw in resp: + ln = raw.decode("utf-8", errors="ignore").strip() + if not ln.startswith("data: "): + continue + payload = ln[6:] + if payload == "[DONE]": + break + obj = json.loads(payload) + if obj.get("usage"): + usage = obj["usage"] + ch = obj.get("choices") or [] + if ch and (ch[0].get("delta", {}).get("content") or ""): + now = time.time() + if t_first is None: + t_first = now + t_last = now + t_end = time.time() + if t_first is None: + t_first = t_end + if t_last is None or t_last <= t_first: + t_last = t_end + return usage, t0, t_first, t_last + +def run_prose_decode(base_url: str, prose_dir: str, model: str = "model", levels=(1, 4, 8), gen_tokens: int = 256): + print("\n=== REALISTIC DISTINCT-PROSE MULTI-STREAM DECODE BENCHMARK (SSE TTFT + PURE DECODE) ===", flush=True) + for tag, excerpt_chars in [("350tok_prose", 1400), ("2.5Ktok_chapter", 9500)]: + prompts = [] + for i, (book, off, _, question) in enumerate(DISTINCT_PROSE_8): + txt = load_book(prose_dir, book)[off : off + excerpt_chars] + prompts.append((book, f"[Excerpt {i+1} — {book}]\n\n{txt}\n\nTask: {question}")) + print(f" --- Workload: {tag} (8 distinct classic novels, cached=0) ---", flush=True) + for n in levels: + for draft_on in (True, False): + nonce = f"[Run {tag} n={n} draft={'on' if draft_on else 'plain'} ts={time.time():.3f}]\n" + def one(idx): + book, p = prompts[idx] + body = { + "model": model, + "messages": [{"role": "user", "content": nonce + p}], + "chat_template_kwargs": {"enable_thinking": False}, + "temperature": 0, + "max_tokens": gen_tokens, + } + if not draft_on: + body["draft"] = False + u, t0, t_first, t_last = stream_chat(f"{base_url}/v1/chat/completions", body) + cached = u.get("prompt_tokens_details", {}).get("cached_tokens", 0) + return book, u["prompt_tokens"], cached, u["completion_tokens"], t0, t_first, t_last + + with concurrent.futures.ThreadPoolExecutor(max_workers=n) as ex: + futs = [ex.submit(one, i) for i in range(n)] + rows = [f.result() for f in futs] + tot_prompt = sum(r[1] for r in rows) + tot_cached = sum(r[2] for r in rows) + tot_gen = sum(r[3] for r in rows) + first_tok_t = min(r[5] for r in rows) + last_tok_t = max(r[6] for r in rows) + start_t = min(r[4] for r in rows) + dec_tps = sum((r[3] - 1) / max(r[6] - r[5], 1e-3) for r in rows) + ttft_med = statistics.median(r[5] - r[4] for r in rows) + mode_s = "DFly2" if draft_on else "Plain" + print( + f" [{n}s {mode_s:5s}] prompt={tot_prompt:,} (cached={tot_cached}) | " + f"decode={dec_tps:6.2f} tok/s | e2e={tot_gen/(last_tok_t - start_t):6.2f} tok/s | " + f"median_TTFT={ttft_med:.2f}s", + flush=True, + ) +def dump_prose_loss(base_url: str, prose_dir: str, out_json: str, model: str = "model"): + print("\n=== REAL-PROSE KV LOSS PROBE (1K..32K NOVEL CHAPTERS + 48-STEP MOBY-DICK NLL) ===") + cases = [ + ("war_peace_2k", "war_and_peace", 25000, 10500, "Provide a concise literary analysis of the character dynamics in this scene."), + ("monte_cristo_4k", "monte_cristo", 30000, 21000, "Trace the chain of events and motives revealed in this chapter."), + ("les_mis_8k", "les_miserables", 40000, 44000, "Examine how Hugo develops the tension between law and mercy across these chapters."), + ("don_quixote_16k", "don_quixote", 35000, 88000, "Synthesize the major episodes in this section and how Sancho Panza's perspective evolves."), + ("anna_karenina_24k", "anna_karenina", 30000, 132000, "Analyze the parallel narrative threads in these chapters and their emotional turning points."), + ("david_copperfield_32k", "david_copperfield", 25000, 174000, "Summarize the key characters introduced across these chapters and Dickens' narrative voice."), + ] + records = {} + for label, book, off, chars, q in cases: + excerpt = load_book(prose_dir, book)[off : off + chars] + t0 = time.time() + res = post_json(f"{base_url}/v1/chat/completions", { + "model": model, + "messages": [{"role": "user", "content": f"{excerpt}\n\nQuestion: {q}"}], + "chat_template_kwargs": {"enable_thinking": False}, + "temperature": 0, + "max_tokens": 64, + "logprobs": True, + "top_logprobs": 20, + }) + dt = time.time() - t0 + ch = res["choices"][0] + steps = [ + {"token": it["token"], "logprob": it["logprob"], "top": {e["token"]: e["logprob"] for e in it["top_logprobs"]}} + for it in ch["logprobs"]["content"] + ] + records[label] = { + "prompt_tokens": res["usage"]["prompt_tokens"], + "steps": steps, + "text": ch["message"]["content"], + } + print(f" [{label:22s}] prompt={res['usage']['prompt_tokens']:6,d} tok ({dt:.2f}s) -> {ch['message']['content'][:85]!r}") + + # 48-step teacher-forced natural prose continuation on 16K-token Moby-Dick chapter! + md_full = load_book(prose_dir, "moby_dick") + md_prefix = "Continue the following Melville passage verbatim:\n\n" + md_full[50000:136000] + md_cont_words = md_full[136000:136450].split()[:48] + tf_steps = [] + cur = md_prefix + t_tf = time.time() + for w in md_cont_words: + res = post_json(f"{base_url}/v1/chat/completions", { + "model": model, + "messages": [{"role": "user", "content": cur}], + "chat_template_kwargs": {"enable_thinking": False}, + "temperature": 0, + "max_tokens": 1, + "logprobs": True, + "top_logprobs": 20, + }) + it = res["choices"][0]["logprobs"]["content"][0] + tf_steps.append({ + "gt_word": w, + "pred": it["token"], + "pred_lp": it["logprob"], + "top": {e["token"]: e["logprob"] for e in it["top_logprobs"]}, + }) + cur = cur + " " + w + print(f" [moby_dick_16k_tf48 ] {len(tf_steps)} teacher-forced natural prose steps in {time.time()-t_tf:.2f}s") + records["_tf_moby_dick_16k"] = tf_steps + json.dump(records, open(out_json, "w")) + print(f"Saved real-prose KV probe to {out_json}") + +def compare_prose_loss(bf16_json: str, fp8_json: str): + b16 = json.load(open(bf16_json)) + f8 = json.load(open(fp8_json)) + print("\n=== REAL-PROSE BF16 vs FP8 KV CACHE LOSS REPORT ===") + kls, tvds, dlps = [], [], [] + matched, agree = 0, 0 + for name, r16 in b16.items(): + if name.startswith("_"): + continue + s16, s8 = r16["steps"], f8[name]["steps"] + step0_kl = 0.0 + for i in range(min(len(s16), len(s8))): + if not all(s16[j]["token"] == s8[j]["token"] for j in range(i)): + break + matched += 1 + if s16[i]["token"] == s8[i]["token"]: + agree += 1 + t16, t8 = s16[i]["top"], s8[i]["top"] + common = set(t16) & set(t8) + z16 = sum(math.exp(t16[k]) for k in common) + z8 = sum(math.exp(t8[k]) for k in common) + if z16 > 0.5 and z8 > 0.5: + kl = max(0.0, sum((math.exp(t16[k])/z16) * math.log((math.exp(t16[k])/z16) / (math.exp(t8[k])/z8)) for k in common)) + tvd = 0.5 * sum(abs(math.exp(t16[k])/z16 - math.exp(t8[k])/z8) for k in common) + kls.append(kl) + tvds.append(tvd) + if i == 0: + step0_kl = kl + if s16[i]["token"] in t8: + dlps.append(abs(s16[i]["logprob"] - t8[s16[i]["token"]])) + div = next((i for i in range(min(len(s16), len(s8))) if s16[i]["token"] != s8[i]["token"]), "IDENTICAL") + print(f" {name:22s} ({r16['prompt_tokens']:6,d} tok): step0_KL={step0_kl:.6f} nats, first_diff_step={div}") + + print(f" OVERALL MATCHED-PREFIX PROSE ({matched} steps across 6 chapters, 2K..32K):") + print(f" Top-1 Greedy Agreement : {agree}/{matched} ({100*agree/max(matched,1):.2f}%)") + print(f" Mean KL(BF16 || FP8) : {statistics.mean(kls):.6f} nats (PPL mult: {math.exp(statistics.mean(kls)):.5f}x = +{(math.exp(statistics.mean(kls))-1)*100:.3f}%), median={statistics.median(kls):.6f}") + print(f" Mean Total Variation : {100*statistics.mean(tvds):.3f}% (median={100*statistics.median(tvds):.3f}%)") + print(f" Mean Top-1 |Δlogprob| : {statistics.mean(dlps):.5f} (median={statistics.median(dlps):.5f}, max={max(dlps):.5f})") + + tf16, tf8 = b16["_tf_moby_dick_16k"], f8["_tf_moby_dick_16k"] + tkls, ttvds, tdlps, tagree = [], [], [], 0 + for x16, x8 in zip(tf16, tf8): + if x16["pred"] == x8["pred"]: + tagree += 1 + t16, t8 = x16["top"], x8["top"] + common = set(t16) & set(t8) + z16 = sum(math.exp(t16[k]) for k in common) + z8 = sum(math.exp(t8[k]) for k in common) + if z16 > 0.5 and z8 > 0.5: + tkls.append(max(0.0, sum((math.exp(t16[k])/z16) * math.log((math.exp(t16[k])/z16) / (math.exp(t8[k])/z8)) for k in common))) + ttvds.append(0.5 * sum(abs(math.exp(t16[k])/z16 - math.exp(t8[k])/z8) for k in common)) + if x16["pred"] in t8: + tdlps.append(abs(x16["pred_lp"] - t8[x16["pred"]])) + print(f"\n 16K MOBY-DICK TEACHER-FORCED CONTINUATION ({len(tf16)} steps, zero trajectory drift):") + print(f" Top-1 Greedy Agreement : {tagree}/{len(tf16)} ({100*tagree/len(tf16):.2f}%)") + print(f" Mean KL(BF16 || FP8) : {statistics.mean(tkls):.6f} nats (PPL mult: {math.exp(statistics.mean(tkls)):.5f}x = +{(math.exp(statistics.mean(tkls))-1)*100:.3f}%), median={statistics.median(tkls):.6f}") + print(f" Mean Total Variation : {100*statistics.mean(ttvds):.3f}%") + print(f" Mean Top-1 |Δlogprob| : {statistics.mean(tdlps):.5f} (max={max(tdlps):.5f})") + +STREAM_SOURCES_500K = [ + ("Stream0_WarAndPeace", ["war_and_peace"], ("FOLIO-WP-1812", "FOLIO-WP-4409", "FOLIO-WP-8831"), "Summarize the closing philosophical reflections in the manuscript"), + ("Stream1_LesMiserables", ["les_miserables"], ("FOLIO-LM-1832", "FOLIO-LM-5510", "FOLIO-LM-9047"), "Describe how the narrative resolves Jean Valjean's journey"), + ("Stream2_MonteCristo", ["monte_cristo"], ("FOLIO-MC-1815", "FOLIO-MC-6128", "FOLIO-MC-9723"), "Explain how Edmond Dantes' final philosophy is presented"), + ("Stream3_DonQuixote", ["don_quixote", "vanity_fair"], ("FOLIO-DQ-1605", "FOLIO-DQ-3384", "FOLIO-DQ-7762"), "Describe the contrast in prose style near the end of this volume"), + ("Stream4_Karenina_Crime", ["anna_karenina", "crime_and_punishment"], ("FOLIO-AK-1877", "FOLIO-AK-4920", "FOLIO-AK-8156"), "Identify the central moral dilemma in the final chapters above"), + ("Stream5_Copperfield_Moby", ["david_copperfield", "moby_dick"], ("FOLIO-DC-1850", "FOLIO-DC-5291", "FOLIO-DC-9408"), "Characterize the narrator's voice in the concluding section"), + ("Stream6_Dorrit_Ulysses", ["little_dorrit", "ulysses"], ("FOLIO-LD-1857", "FOLIO-LD-6634", "FOLIO-LD-8519"), "Analyze the stylistic shift in the final portion of this manuscript"), + ("Stream7_Dickens_Trilogy", ["our_mutual_friend", "nicholas_nickleby", "martin_chuzzlewit"], ("FOLIO-MF-1865", "FOLIO-MF-4073", "FOLIO-MF-7295"), "Summarize the social critique running through the closing chapters"), +] + +def build_stream_manuscript(prose_dir: str, idx: int, target_tokens: int, chars_per_tok: float) -> tuple[str, tuple[str, str, str], str]: + name, books, codes, lit_q = STREAM_SOURCES_500K[idx] + joined = "\n\n".join(load_book(prose_dir, b) for b in books) + # Distinct opening header so token 0 is unique on every stream (cached_tokens == 0 guaranteed!) + target_chars = int(target_tokens * chars_per_tok) + body = joined[:target_chars] + p10 = int(len(body) * 0.10) + p50 = int(len(body) * 0.50) + p90 = int(len(body) * 0.90) + manuscript = ( + f"Archival Volume #{idx + 1} ({name}):\n\n" + + body[:p10] + + f"\n\n[Archival Margin Note Alpha for {name}: Early catalog marker is {codes[0]}.]\n\n" + + body[p10:p50] + + f"\n\n[Archival Margin Note Beta for {name}: Mid-volume catalog marker is {codes[1]}.]\n\n" + + body[p50:p90] + + f"\n\n[Archival Margin Note Gamma for {name}: Late catalog marker is {codes[2]}.]\n\n" + + body[p90:] + + f"\n\nFinal Instructions for {name}: First list the three exact catalog markers (Alpha, Beta, Gamma) recorded in this volume, then in two sentences: {lit_q}." + ) + return name, codes, manuscript + +def calibrate_stream_cpts(base_url: str, prose_dir: str, n_streams: int, model: str = "model") -> list[float]: + cpts = [] + for idx in range(n_streams): + name, books, _, _ = STREAM_SOURCES_500K[idx] + joined = "\n\n".join(load_book(prose_dir, b) for b in books) + n = min(len(joined), 2_300_000) + sample = joined[n // 6 : n // 6 + 20000] + "\n" + joined[n // 2 : n // 2 + 20000] + "\n" + joined[(5 * n) // 6 : (5 * n) // 6 + 20000] + res = post_json(f"{base_url}/v1/chat/completions", { + "model": model, + "messages": [{"role": "user", "content": sample}], + "chat_template_kwargs": {"enable_thinking": False}, + "temperature": 0, + "max_tokens": 1, + }) + ptok = res["usage"]["prompt_tokens"] + cpt = len(sample) / ptok + cpts.append(cpt) + print(f" Calibrated {name:24s}: {cpt:.4f} chars/tok (available={int(len(joined)/cpt):,} tok)", flush=True) + return cpts + +def run_distinct_long(base_url: str, prose_dir: str, target_tokens: int, n_streams: int, model: str = "model"): + print(f"\n=== {n_streams}x ~{target_tokens:,}-TOKEN 100% DISTINCT REAL-PROSE CONCURRENT BENCHMARK ===", flush=True) + cpts = calibrate_stream_cpts(base_url, prose_dir, n_streams, model=model) + try: + urllib.request.urlopen(f"{base_url}/health?reset_peak=1", timeout=10).read() + except Exception: + pass + + payloads = [build_stream_manuscript(prose_dir, i, target_tokens, cpts[i]) for i in range(n_streams)] + for i, (name, codes, ms) in enumerate(payloads): + print(f" Prepared {name:24s}: {len(ms):,} chars (~{int(len(ms)/cpts[i]):,} est tokens), unique markers={codes}", flush=True) + def run_one(i): + name, codes, ms = payloads[i] + t0 = time.time() + res = post_json(f"{base_url}/v1/chat/completions", { + "model": model, + "messages": [{"role": "user", "content": ms}], + "chat_template_kwargs": {"enable_thinking": False}, + "temperature": 0, + "max_tokens": 96, + }, timeout=7200) + el = time.time() - t0 + u = res["usage"] + ptok = u["prompt_tokens"] + cached = u.get("prompt_tokens_details", {}).get("cached_tokens", 0) + gtok = u["completion_tokens"] + txt = res["choices"][0]["message"]["content"] + hits = sum(1 for c in codes if c in txt) + print(f" [Done {name:24s}] prompt={ptok:,} (cached={cached}), gen={gtok}, {el:.1f}s, markers={hits}/3 -> {txt[:105]!r}", flush=True) + return name, ptok, cached, gtok, el, hits, txt + + print(f"\nLaunching all {n_streams} distinct real-prose streams concurrently (`cached_tokens == 0` on all {n_streams})...", flush=True) + t_all = time.time() + with concurrent.futures.ThreadPoolExecutor(max_workers=n_streams) as ex: + futs = [ex.submit(run_one, i) for i in range(n_streams)] + results = [f.result() for f in futs] + wall = time.time() - t_all + + tot_prompt = sum(r[1] for r in results) + tot_cached = sum(r[2] for r in results) + tot_gen = sum(r[3] for r in results) + tot_kv = tot_prompt + tot_gen + tot_hits = sum(r[5] for r in results) + print(f"\n=== {n_streams}x DISTINCT REAL-PROSE SUMMARY ===") + print(f" Streams completed : {len(results)}/{n_streams} (total cached_tokens = {tot_cached})") + print(f" Distinct cold prompt tokens : {tot_prompt:,} tokens ({tot_prompt/1e6:.3f}M)") + print(f" Total simultaneous KV tokens : {tot_kv:,} tokens ({tot_kv/1e6:.3f}M)") + print(f" Wall clock (prefill+decode) : {wall:.1f}s (effective cold throughput: {(tot_prompt+tot_gen)/wall:.1f} tok/s)") + print(f" Unique marker recall (24) : {tot_hits}/{3 * n_streams} ({sum(1 for r in results if r[5]==3)}/{n_streams} streams 3/3)") + try: + h = json.loads(urllib.request.urlopen(f"{base_url}/health", timeout=10).read().decode("utf-8")) + mem = h.get("memory", {}) + print(f" GPU Memory (rank 0) : active={mem.get('active',0)/(1024**3):.2f} GiB, peak={mem.get('peak',0)/(1024**3):.2f} GiB, cache={mem.get('cache',0)/(1024**3):.2f} GiB") + except Exception as e: + print(f" Health note: {e}") + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--url", default="http://127.0.0.1:8888") + ap.add_argument("--model", default="model") + ap.add_argument("--prose-dir", default="/tmp/prose_8") + ap.add_argument("--mode", choices=["prose-decode", "prose-loss-dump", "prose-loss-compare", "distinct-long"], required=True) + ap.add_argument("--out", default="") + ap.add_argument("--bf16", default="") + ap.add_argument("--fp8", default="") + ap.add_argument("--tokens", type=int, default=502000) + ap.add_argument("--streams", type=int, default=8) + a = ap.parse_args() + if a.mode == "prose-decode": + run_prose_decode(a.url, a.prose_dir, model=a.model) + elif a.mode == "prose-loss-dump": + dump_prose_loss(a.url, a.prose_dir, a.out, model=a.model) + elif a.mode == "prose-loss-compare": + compare_prose_loss(a.bf16, a.fp8) + elif a.mode == "distinct-long": + run_distinct_long(a.url, a.prose_dir, a.tokens, a.streams, model=a.model) From e1e2e50c3da17276aa5b19abc4b4956ffc23a8d7 Mon Sep 17 00:00:00 2001 From: GrgaPalcic <26028466+GrgaPalcic@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:05:52 +0100 Subject: [PATCH 148/361] tools: harden bench_prose evidence, logprobs, and mock-server tests Address PR #4797 review feedback: - Require explicit valid cached_tokens == 0 <= prompt_tokens for cold work. - Send identical model-visible prompts and seeds across drafted/plain pairs and keep complete token IDs / full 64-hex hashes for equality checks. - Accept streams only after clean completion with no error and actual content or reasoning output using monotonic perf_counter timing. - Label top-k intersection metrics as conditional intersection-only diagnostics with missing support, report unavailable metrics as unavailable, and compare complete sequences and lengths before reporting IDENTICAL. - Score one immutable tokenized ground-truth continuation via /v1/tokenize and /v1/completions prompt_logprobs with exact per-token ground-truth probability and token count. - Report submitted vs completed token totals separately in distinct-long, preserve actual prompt lengths, reject/label undersized cells, and omit simultaneous KV claims unless engine residency is observed. - Add mock-server unit tests in tools/tests/test_bench_prose.py. --- tools/bench_prose.py | 698 ++++++++++++++++++-------------- tools/bench_prose_loss.py | 383 ++++++++++++++++++ tools/tests/test_bench_prose.py | 408 +++++++++++++++++++ 3 files changed, 1192 insertions(+), 297 deletions(-) create mode 100644 tools/bench_prose_loss.py create mode 100644 tools/tests/test_bench_prose.py diff --git a/tools/bench_prose.py b/tools/bench_prose.py index e0d22fb78af..9fb2974b08a 100755 --- a/tools/bench_prose.py +++ b/tools/bench_prose.py @@ -1,28 +1,68 @@ #!/usr/bin/env python3 -"""Realistic natural-prose benchmark for OpenAI-compatible LLM servers: -1. 8-stream distinct literary/prose generation (drafted vs plain, zero shared prefixes, cached_tokens=0). -2. BF16 vs FP8 KV cache loss on genuine classic prose (1K..32K chapters + 48-step teacher-forced Moby-Dick NLL/KL). -3. Nx >500,000-token (4.0M+ total) completely distinct uncached classic novels (cached_tokens=0 on all streams, 3 unique markers per stream). -""" -import argparse, concurrent.futures, json, math, os, re, statistics, time, urllib.request +"""Model-agnostic natural-prose benchmark client with verified cold-cache, equality, logprob and long-context checks.""" +import argparse +import concurrent.futures +import hashlib +import json +import math +import os +import re +import statistics +import sys +import time +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import bench_prose_loss +import bench_stream +from bench_evidence import count as valid_count, token_equal +from bench_prose_loss import CLEAN_FINISH, LOSS_CASES, compare_prose_loss, sha256_token_ids, valid_token_ids + +DISTINCT_PROSE_8 = [ + ("war_and_peace", 12000, 9500, "Analyze how Tolstoy contrasts salon artifice with genuine human emotion in this opening scene, then continue the narrative tone for two paragraphs."), + ("monte_cristo", 15000, 9500, "Examine Edmond Dantes' character and relationship with shipboard authority in this passage, and write a detailed critical commentary."), + ("les_miserables", 18000, 9500, "Discuss Victor Hugo's portrait of Bishop Myriel's moral philosophy in this excerpt and trace its narrative consequences."), + ("don_quixote", 14000, 9500, "Analyze Cervantes' use of irony and chivalric obsession in this passage and explain how the prose rhythm builds comedic tension."), + ("moby_dick", 22000, 9500, "Examine Ishmael's reflections on the sea and solitude in this excerpt, focusing on Melville's imagery and philosophical undertones."), + ("anna_karenina", 16000, 9500, "Analyze how Tolstoy establishes domestic conflict and psychological realism in the Oblonsky household in this scene."), + ("crime_and_punishment", 14000, 9500, "Examine how Dostoevsky conveys Raskolnikov's feverish alienation through sensory detail in St. Petersburg."), + ("ulysses", 14000, 9500, "Analyze Joyce's shifts between external action and interior monologue on the Martello tower in this opening passage."), +] + +STREAM_SOURCES_500K = [ + ("Stream0_WarAndPeace", ["war_and_peace"], ("FOLIO-WP-1812", "FOLIO-WP-4409", "FOLIO-WP-8831"), "Summarize the closing philosophical reflections in the manuscript"), + ("Stream1_LesMiserables", ["les_miserables"], ("FOLIO-LM-1832", "FOLIO-LM-5510", "FOLIO-LM-9047"), "Describe how the narrative resolves Jean Valjean's journey"), + ("Stream2_MonteCristo", ["monte_cristo"], ("FOLIO-MC-1815", "FOLIO-MC-6128", "FOLIO-MC-9723"), "Explain how Edmond Dantes' final philosophy is presented"), + ("Stream3_DonQuixote", ["don_quixote", "vanity_fair"], ("FOLIO-DQ-1605", "FOLIO-DQ-3384", "FOLIO-DQ-7762"), "Describe the contrast in prose style near the end of this volume"), + ("Stream4_Karenina_Crime", ["anna_karenina", "crime_and_punishment"], ("FOLIO-AK-1877", "FOLIO-AK-4920", "FOLIO-AK-8156"), "Identify the central moral dilemma in the final chapters above"), + ("Stream5_Copperfield_Moby", ["david_copperfield", "moby_dick"], ("FOLIO-DC-1850", "FOLIO-DC-5291", "FOLIO-DC-9408"), "Characterize the narrator's voice in the concluding section"), + ("Stream6_Dorrit_Ulysses", ["little_dorrit", "ulysses"], ("FOLIO-LD-1857", "FOLIO-LD-6634", "FOLIO-LD-8519"), "Analyze the stylistic shift in the final portion of this manuscript"), + ("Stream7_Dickens_Trilogy", ["our_mutual_friend", "nicholas_nickleby", "martin_chuzzlewit"], ("FOLIO-MF-1865", "FOLIO-MF-4073", "FOLIO-MF-7295"), "Summarize the social critique running through the closing chapters"), +] + def strip_gutenberg(raw: str) -> str: - # Strip Project Gutenberg header and footer so zero boilerplate is shared across books! + """Strip Project Gutenberg header and footer so books share no boilerplate prefix.""" m_start = re.search(r"\*\*\*\s*START OF (?:THE|THIS) PROJECT GUTENBERG.*?\*\*\*", raw, flags=re.I | re.S) if m_start: raw = raw[m_start.end():] - else: + elif "PROJECT GUTENBERG" in raw[:4000].upper(): raw = raw[4000:] m_end = re.search(r"\*\*\*\s*END OF (?:THE|THIS) PROJECT GUTENBERG", raw, flags=re.I) if m_end: raw = raw[:m_end.start()] return raw.strip() + def load_book(prose_dir: str, name: str) -> str: + """Read one plain-text book from prose_dir and strip any Gutenberg wrapper.""" with open(os.path.join(prose_dir, f"{name}.txt"), "r", encoding="utf-8", errors="ignore") as f: return strip_gutenberg(f.read()) + def post_json(url: str, payload: dict, timeout: int = 3600) -> dict: + """POST JSON payload and return the decoded JSON object.""" req = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), @@ -31,343 +71,407 @@ def post_json(url: str, payload: dict, timeout: int = 3600) -> dict: with urllib.request.urlopen(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) -DISTINCT_PROSE_8 = [ - ("war_and_peace", 12000, 9500, "Analyze how Tolstoy contrasts salon artifice with genuine human emotion in this opening scene, then continue the narrative tone for two paragraphs."), - ("monte_cristo", 15000, 9500, "Examine Edmond Dantes' character and relationship with shipboard authority in this passage, and write a detailed critical commentary."), - ("les_miserables", 18000, 9500, "Discuss Victor Hugo's portrait of Bishop Myriel's moral philosophy in this excerpt and trace its narrative consequences."), - ("don_quixote", 14000, 9500, "Analyze Cervantes' use of irony and chivalric obsession in this passage and explain how the prose rhythm builds comedic tension."), - ("moby_dick", 22000, 9500, "Examine Ishmael's reflections on the sea and solitude in this excerpt, focusing on Melville's imagery and philosophical undertones."), - ("anna_karenina", 16000, 9500, "Analyze how Tolstoy establishes domestic conflict and psychological realism in the Oblonsky household in this scene."), - ("crime_and_punishment", 14000, 9500, "Examine how Dostoevsky conveys Raskolnikov's feverish alienation through sensory detail in St. Petersburg."), - ("ulysses", 14000, 9500, "Analyze Joyce's shifts between external action and interior monologue on the Martello tower in this opening passage."), -] -def stream_chat(url: str, body: dict, timeout: int = 600): - body = dict(body, stream=True, stream_options={"include_usage": True}) - req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), headers={"Content-Type": "application/json"}) - t0 = time.time() - t_first = None - t_last = None - usage = {} - with urllib.request.urlopen(req, timeout=timeout) as resp: +def sha256_text(text: str) -> str: + """Return lowercase 64-hex SHA-256 of UTF-8 text.""" + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def parse_usage(usage, complete: bool) -> dict: + """Validate usage counters; only explicit cached_tokens == 0 <= prompt_tokens qualifies as cold.""" + u = usage if isinstance(usage, dict) else {} + details = u.get("prompt_tokens_details") + details = details if isinstance(details, dict) else {} + prompt = valid_count(u.get("prompt_tokens")) + cached = valid_count(details.get("cached_tokens")) + tokens = valid_count(u.get("completion_tokens")) + valid_cache = prompt is not None and cached is not None and cached <= prompt + if not complete or not valid_cache: + state = "unverified" + elif cached == 0: + state = "cold" + else: + state = "reused" + return {"prompt_tokens": prompt, "cached_tokens": cached, "tokens": tokens, "cache_state": state} + + +def pair_token_equal(left: dict, right: dict) -> bool | None: + """Compare complete token IDs when both sides have them, else full 64-hex token_sha256.""" + if not left.get("accepted") or not right.get("accepted"): + return None + l_ids, r_ids = left.get("token_ids"), right.get("token_ids") + if isinstance(l_ids, list) and isinstance(r_ids, list): + return l_ids == r_ids + return token_equal(left, right) + + +def pair_output_equal(left: dict, right: dict) -> bool | None: + """Compare full 64-hex output_sha256 across two accepted replies.""" + if not left.get("accepted") or not right.get("accepted"): + return None + a, b = left.get("output_sha256"), right.get("output_sha256") + return None if not a or not b else (a == b) + + +def stream_chat(url: str, body: dict, timeout: int = 600) -> dict: + """Stream one SSE chat completion using monotonic timing and strict completion/output validation.""" + payload = dict(body, stream=True, stream_options={"include_usage": True}) + req = urllib.request.Request( + url, data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json"} + ) + sent = time.perf_counter() + reply = bench_stream.Collector(sent) + chunk_token_ids: list[int] = [] + error = None + + def tap_lines(resp): for raw in resp: - ln = raw.decode("utf-8", errors="ignore").strip() - if not ln.startswith("data: "): - continue - payload = ln[6:] - if payload == "[DONE]": - break - obj = json.loads(payload) - if obj.get("usage"): - usage = obj["usage"] - ch = obj.get("choices") or [] - if ch and (ch[0].get("delta", {}).get("content") or ""): - now = time.time() - if t_first is None: - t_first = now - t_last = now - t_end = time.time() - if t_first is None: - t_first = t_end - if t_last is None or t_last <= t_first: - t_last = t_end - return usage, t0, t_first, t_last - -def run_prose_decode(base_url: str, prose_dir: str, model: str = "model", levels=(1, 4, 8), gen_tokens: int = 256): + if b"token_ids" in raw: + line = raw.decode("utf-8", errors="ignore").strip() + if line.startswith("data:"): + try: + chunk = json.loads(line[5:]) + except ValueError: + chunk = None + if isinstance(chunk, dict): + for ch in chunk.get("choices") or []: + ids = ch.get("token_ids") or (ch.get("delta") or {}).get("token_ids") + if isinstance(ids, list) and all(type(x) is int and x >= 0 for x in ids): + chunk_token_ids.extend(ids) + yield raw + + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + reply.read(tap_lines(resp)) + except Exception as exc: # noqa: BLE001 - stream failures are reported in the receipt, not hidden + error = type(exc).__name__ + + if error is None and reply.end == "error": + error = "server_stream_error" + complete = error is None and reply.end == "done" + if error is None and not complete: + error = "incomplete_stream" + observed = reply.evidence.finish(reply.usage, reply.runtime, complete) + has_output = reply.evidence.observed_output and bool(reply.pieces) + tokens, prompt_tokens = observed["tokens"], observed["prompt_tokens"] + accepted = complete and has_output and prompt_tokens is not None and tokens is not None and tokens > 0 + if error is None and not has_output: + error = "no_output" + elif error is None and not accepted: + error = "invalid_usage" + + raw_ids = reply.runtime.get("token_ids") if isinstance(reply.runtime, dict) else None + if raw_ids is None and chunk_token_ids: + raw_ids = chunk_token_ids + token_ids = valid_token_ids(raw_ids, tokens) if accepted else None + token_sha256 = observed["token_sha256"] or (sha256_token_ids(token_ids) if token_ids is not None else None) + first = reply.pieces[0][0] if (accepted and reply.pieces) else None + last = reply.pieces[-1][0] if (accepted and reply.pieces) else None + ttft_s = (first - sent) if first is not None else None + decode_tps = ((tokens - 1) / (last - first)) if (accepted and tokens > 1 and last > first) else None + + return { + "accepted": accepted, "complete": complete, "completion": reply.completion(), "error": error, + "prompt_tokens": prompt_tokens, "cached_tokens": observed["cached_tokens"], + "cache_state": observed["cache_state"], "tokens": tokens, "sent": sent, "first": first, "last": last, + "ttft_s": ttft_s, "decode_tps": decode_tps, "token_ids": token_ids, + "token_sha256": token_sha256 if accepted else None, + "output_sha256": observed["output_sha256"] if accepted else None, + } + + +def run_prose_decode( + base_url: str, + prose_dir: str, + model: str = "model", + levels=(1, 4, 8), + gen_tokens: int = 256, + seed: int = 1234, + excerpt_specs=(("350tok_prose", 1400), ("2.5Ktok_chapter", 9500)), + sources=None, +) -> dict: + """Run paired drafted/plain distinct-prose decode with identical prompts, seeds, and cold-cache verification.""" + pool = sources if sources is not None else DISTINCT_PROSE_8 print("\n=== REALISTIC DISTINCT-PROSE MULTI-STREAM DECODE BENCHMARK (SSE TTFT + PURE DECODE) ===", flush=True) - for tag, excerpt_chars in [("350tok_prose", 1400), ("2.5Ktok_chapter", 9500)]: + report = {"mode": "prose-decode", "seed": seed, "gen_tokens": gen_tokens, "pairs": [], "qualified": True} + + for tag, excerpt_chars in excerpt_specs: prompts = [] - for i, (book, off, _, question) in enumerate(DISTINCT_PROSE_8): - txt = load_book(prose_dir, book)[off : off + excerpt_chars] - prompts.append((book, f"[Excerpt {i+1} — {book}]\n\n{txt}\n\nTask: {question}")) - print(f" --- Workload: {tag} (8 distinct classic novels, cached=0) ---", flush=True) + for i, (book, off, _, question) in enumerate(pool): + raw_book = load_book(prose_dir, book) + txt = raw_book[off : off + excerpt_chars] if len(raw_book) > off else raw_book[:excerpt_chars] + prompt_text = f"[Excerpt {i + 1} — {book}]\n\n{txt}\n\nTask: {question}" + prompts.append((book, prompt_text, seed + i, sha256_text(prompt_text))) + print(f" --- Workload: {tag} ({len(prompts)} distinct novels) ---", flush=True) + for n in levels: + arms = {} for draft_on in (True, False): - nonce = f"[Run {tag} n={n} draft={'on' if draft_on else 'plain'} ts={time.time():.3f}]\n" - def one(idx): - book, p = prompts[idx] + def one(idx, _draft=draft_on): + book, prompt_text, req_seed, prompt_sha = prompts[idx] body = { "model": model, - "messages": [{"role": "user", "content": nonce + p}], + "messages": [{"role": "user", "content": prompt_text}], "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, + "seed": req_seed, "max_tokens": gen_tokens, } - if not draft_on: + if not _draft: body["draft"] = False - u, t0, t_first, t_last = stream_chat(f"{base_url}/v1/chat/completions", body) - cached = u.get("prompt_tokens_details", {}).get("cached_tokens", 0) - return book, u["prompt_tokens"], cached, u["completion_tokens"], t0, t_first, t_last + row = stream_chat(f"{base_url}/v1/chat/completions", body) + row.update(book=book, seed=req_seed, prompt_sha256=prompt_sha) + return row with concurrent.futures.ThreadPoolExecutor(max_workers=n) as ex: - futs = [ex.submit(one, i) for i in range(n)] - rows = [f.result() for f in futs] - tot_prompt = sum(r[1] for r in rows) - tot_cached = sum(r[2] for r in rows) - tot_gen = sum(r[3] for r in rows) - first_tok_t = min(r[5] for r in rows) - last_tok_t = max(r[6] for r in rows) - start_t = min(r[4] for r in rows) - dec_tps = sum((r[3] - 1) / max(r[6] - r[5], 1e-3) for r in rows) - ttft_med = statistics.median(r[5] - r[4] for r in rows) - mode_s = "DFly2" if draft_on else "Plain" - print( - f" [{n}s {mode_s:5s}] prompt={tot_prompt:,} (cached={tot_cached}) | " - f"decode={dec_tps:6.2f} tok/s | e2e={tot_gen/(last_tok_t - start_t):6.2f} tok/s | " - f"median_TTFT={ttft_med:.2f}s", - flush=True, - ) -def dump_prose_loss(base_url: str, prose_dir: str, out_json: str, model: str = "model"): - print("\n=== REAL-PROSE KV LOSS PROBE (1K..32K NOVEL CHAPTERS + 48-STEP MOBY-DICK NLL) ===") - cases = [ - ("war_peace_2k", "war_and_peace", 25000, 10500, "Provide a concise literary analysis of the character dynamics in this scene."), - ("monte_cristo_4k", "monte_cristo", 30000, 21000, "Trace the chain of events and motives revealed in this chapter."), - ("les_mis_8k", "les_miserables", 40000, 44000, "Examine how Hugo develops the tension between law and mercy across these chapters."), - ("don_quixote_16k", "don_quixote", 35000, 88000, "Synthesize the major episodes in this section and how Sancho Panza's perspective evolves."), - ("anna_karenina_24k", "anna_karenina", 30000, 132000, "Analyze the parallel narrative threads in these chapters and their emotional turning points."), - ("david_copperfield_32k", "david_copperfield", 25000, 174000, "Summarize the key characters introduced across these chapters and Dickens' narrative voice."), - ] - records = {} - for label, book, off, chars, q in cases: - excerpt = load_book(prose_dir, book)[off : off + chars] - t0 = time.time() - res = post_json(f"{base_url}/v1/chat/completions", { - "model": model, - "messages": [{"role": "user", "content": f"{excerpt}\n\nQuestion: {q}"}], - "chat_template_kwargs": {"enable_thinking": False}, - "temperature": 0, - "max_tokens": 64, - "logprobs": True, - "top_logprobs": 20, - }) - dt = time.time() - t0 - ch = res["choices"][0] - steps = [ - {"token": it["token"], "logprob": it["logprob"], "top": {e["token"]: e["logprob"] for e in it["top_logprobs"]}} - for it in ch["logprobs"]["content"] - ] - records[label] = { - "prompt_tokens": res["usage"]["prompt_tokens"], - "steps": steps, - "text": ch["message"]["content"], - } - print(f" [{label:22s}] prompt={res['usage']['prompt_tokens']:6,d} tok ({dt:.2f}s) -> {ch['message']['content'][:85]!r}") - - # 48-step teacher-forced natural prose continuation on 16K-token Moby-Dick chapter! - md_full = load_book(prose_dir, "moby_dick") - md_prefix = "Continue the following Melville passage verbatim:\n\n" + md_full[50000:136000] - md_cont_words = md_full[136000:136450].split()[:48] - tf_steps = [] - cur = md_prefix - t_tf = time.time() - for w in md_cont_words: - res = post_json(f"{base_url}/v1/chat/completions", { - "model": model, - "messages": [{"role": "user", "content": cur}], - "chat_template_kwargs": {"enable_thinking": False}, - "temperature": 0, - "max_tokens": 1, - "logprobs": True, - "top_logprobs": 20, - }) - it = res["choices"][0]["logprobs"]["content"][0] - tf_steps.append({ - "gt_word": w, - "pred": it["token"], - "pred_lp": it["logprob"], - "top": {e["token"]: e["logprob"] for e in it["top_logprobs"]}, - }) - cur = cur + " " + w - print(f" [moby_dick_16k_tf48 ] {len(tf_steps)} teacher-forced natural prose steps in {time.time()-t_tf:.2f}s") - records["_tf_moby_dick_16k"] = tf_steps - json.dump(records, open(out_json, "w")) - print(f"Saved real-prose KV probe to {out_json}") - -def compare_prose_loss(bf16_json: str, fp8_json: str): - b16 = json.load(open(bf16_json)) - f8 = json.load(open(fp8_json)) - print("\n=== REAL-PROSE BF16 vs FP8 KV CACHE LOSS REPORT ===") - kls, tvds, dlps = [], [], [] - matched, agree = 0, 0 - for name, r16 in b16.items(): - if name.startswith("_"): - continue - s16, s8 = r16["steps"], f8[name]["steps"] - step0_kl = 0.0 - for i in range(min(len(s16), len(s8))): - if not all(s16[j]["token"] == s8[j]["token"] for j in range(i)): - break - matched += 1 - if s16[i]["token"] == s8[i]["token"]: - agree += 1 - t16, t8 = s16[i]["top"], s8[i]["top"] - common = set(t16) & set(t8) - z16 = sum(math.exp(t16[k]) for k in common) - z8 = sum(math.exp(t8[k]) for k in common) - if z16 > 0.5 and z8 > 0.5: - kl = max(0.0, sum((math.exp(t16[k])/z16) * math.log((math.exp(t16[k])/z16) / (math.exp(t8[k])/z8)) for k in common)) - tvd = 0.5 * sum(abs(math.exp(t16[k])/z16 - math.exp(t8[k])/z8) for k in common) - kls.append(kl) - tvds.append(tvd) - if i == 0: - step0_kl = kl - if s16[i]["token"] in t8: - dlps.append(abs(s16[i]["logprob"] - t8[s16[i]["token"]])) - div = next((i for i in range(min(len(s16), len(s8))) if s16[i]["token"] != s8[i]["token"]), "IDENTICAL") - print(f" {name:22s} ({r16['prompt_tokens']:6,d} tok): step0_KL={step0_kl:.6f} nats, first_diff_step={div}") - - print(f" OVERALL MATCHED-PREFIX PROSE ({matched} steps across 6 chapters, 2K..32K):") - print(f" Top-1 Greedy Agreement : {agree}/{matched} ({100*agree/max(matched,1):.2f}%)") - print(f" Mean KL(BF16 || FP8) : {statistics.mean(kls):.6f} nats (PPL mult: {math.exp(statistics.mean(kls)):.5f}x = +{(math.exp(statistics.mean(kls))-1)*100:.3f}%), median={statistics.median(kls):.6f}") - print(f" Mean Total Variation : {100*statistics.mean(tvds):.3f}% (median={100*statistics.median(tvds):.3f}%)") - print(f" Mean Top-1 |Δlogprob| : {statistics.mean(dlps):.5f} (median={statistics.median(dlps):.5f}, max={max(dlps):.5f})") - - tf16, tf8 = b16["_tf_moby_dick_16k"], f8["_tf_moby_dick_16k"] - tkls, ttvds, tdlps, tagree = [], [], [], 0 - for x16, x8 in zip(tf16, tf8): - if x16["pred"] == x8["pred"]: - tagree += 1 - t16, t8 = x16["top"], x8["top"] - common = set(t16) & set(t8) - z16 = sum(math.exp(t16[k]) for k in common) - z8 = sum(math.exp(t8[k]) for k in common) - if z16 > 0.5 and z8 > 0.5: - tkls.append(max(0.0, sum((math.exp(t16[k])/z16) * math.log((math.exp(t16[k])/z16) / (math.exp(t8[k])/z8)) for k in common))) - ttvds.append(0.5 * sum(abs(math.exp(t16[k])/z16 - math.exp(t8[k])/z8) for k in common)) - if x16["pred"] in t8: - tdlps.append(abs(x16["pred_lp"] - t8[x16["pred"]])) - print(f"\n 16K MOBY-DICK TEACHER-FORCED CONTINUATION ({len(tf16)} steps, zero trajectory drift):") - print(f" Top-1 Greedy Agreement : {tagree}/{len(tf16)} ({100*tagree/len(tf16):.2f}%)") - print(f" Mean KL(BF16 || FP8) : {statistics.mean(tkls):.6f} nats (PPL mult: {math.exp(statistics.mean(tkls)):.5f}x = +{(math.exp(statistics.mean(tkls))-1)*100:.3f}%), median={statistics.median(tkls):.6f}") - print(f" Mean Total Variation : {100*statistics.mean(ttvds):.3f}%") - print(f" Mean Top-1 |Δlogprob| : {statistics.mean(tdlps):.5f} (max={max(tdlps):.5f})") + rows = [f.result() for f in [ex.submit(one, i) for i in range(n)]] + + all_accepted = all(r["accepted"] for r in rows) + all_cold = all(r["cache_state"] == "cold" for r in rows) + all_timed = all_accepted and all(r["decode_tps"] is not None for r in rows) + timing_row = None + if all_accepted and all_cold: + tot_prompt = sum(r["prompt_tokens"] for r in rows) + tot_gen = sum(r["tokens"] for r in rows) + start_t, last_tok_t = min(r["sent"] for r in rows), max(r["last"] for r in rows) + timing_row = { + "prompt_tokens": tot_prompt, "cached_tokens": 0, "completion_tokens": tot_gen, + "decode_tps": sum(r["decode_tps"] for r in rows) if all_timed else None, + "e2e_tps": (tot_gen / (last_tok_t - start_t)) if last_tok_t > start_t else None, + "median_ttft_s": statistics.median(r["ttft_s"] for r in rows), + } + mode_key, mode_s = ("draft", "DFly2") if draft_on else ("plain", "Plain") + arms[mode_key] = {"rows": rows, "all_accepted": all_accepted, + "cold_verified": all_accepted and all_cold, "timing": timing_row} + if timing_row is not None: + dec_s = f"{timing_row['decode_tps']:6.2f}" if timing_row["decode_tps"] is not None else " n/a " + e2e_s = f"{timing_row['e2e_tps']:6.2f}" if timing_row["e2e_tps"] is not None else " n/a " + print(f" [{n}s {mode_s:5s}] prompt={timing_row['prompt_tokens']:,} (cached=0, cold) | " + f"decode={dec_s} tok/s | e2e={e2e_s} tok/s | median_TTFT={timing_row['median_ttft_s']:.2f}s", flush=True) + else: + reasons = sorted({r["error"] or f"cache_{r['cache_state']}" for r in rows if not r["accepted"] or r["cache_state"] != "cold"}) + print(f" [{n}s {mode_s:5s}] REJECTED (no timing row): {', '.join(reasons)}", flush=True) + + d_rows, p_rows = arms["draft"]["rows"], arms["plain"]["rows"] + prompts_identical = all(d["prompt_sha256"] == p["prompt_sha256"] for d, p in zip(d_rows, p_rows)) + seeds_identical = all(d["seed"] == p["seed"] for d, p in zip(d_rows, p_rows)) + tok_eq = [pair_token_equal(d, p) for d, p in zip(d_rows, p_rows)] + out_eq = [pair_output_equal(d, p) for d, p in zip(d_rows, p_rows)] + pair_qualified = (arms["draft"]["cold_verified"] and arms["plain"]["cold_verified"] + and prompts_identical and seeds_identical and False not in tok_eq and False not in out_eq) + if not pair_qualified: + report["qualified"] = False + report["pairs"].append({ + "workload": tag, "streams": n, "prompts_identical": prompts_identical, + "seeds_identical": seeds_identical, "token_equal": tok_eq, "output_equal": out_eq, + "draft": arms["draft"], "plain": arms["plain"], "qualified": pair_qualified, + }) + return report + + +def dump_prose_loss(base_url: str, prose_dir: str, out_json: str, model: str = "model", + cases=None, tf_tokens: int = 48, tf_file: str = "") -> dict: + """Delegate prose KV loss dumping to bench_prose_loss.""" + return bench_prose_loss.dump_prose_loss( + post_json, load_book, parse_usage, base_url, prose_dir, out_json, + model=model, cases=cases, tf_tokens=tf_tokens, tf_file=tf_file, + ) -STREAM_SOURCES_500K = [ - ("Stream0_WarAndPeace", ["war_and_peace"], ("FOLIO-WP-1812", "FOLIO-WP-4409", "FOLIO-WP-8831"), "Summarize the closing philosophical reflections in the manuscript"), - ("Stream1_LesMiserables", ["les_miserables"], ("FOLIO-LM-1832", "FOLIO-LM-5510", "FOLIO-LM-9047"), "Describe how the narrative resolves Jean Valjean's journey"), - ("Stream2_MonteCristo", ["monte_cristo"], ("FOLIO-MC-1815", "FOLIO-MC-6128", "FOLIO-MC-9723"), "Explain how Edmond Dantes' final philosophy is presented"), - ("Stream3_DonQuixote", ["don_quixote", "vanity_fair"], ("FOLIO-DQ-1605", "FOLIO-DQ-3384", "FOLIO-DQ-7762"), "Describe the contrast in prose style near the end of this volume"), - ("Stream4_Karenina_Crime", ["anna_karenina", "crime_and_punishment"], ("FOLIO-AK-1877", "FOLIO-AK-4920", "FOLIO-AK-8156"), "Identify the central moral dilemma in the final chapters above"), - ("Stream5_Copperfield_Moby", ["david_copperfield", "moby_dick"], ("FOLIO-DC-1850", "FOLIO-DC-5291", "FOLIO-DC-9408"), "Characterize the narrator's voice in the concluding section"), - ("Stream6_Dorrit_Ulysses", ["little_dorrit", "ulysses"], ("FOLIO-LD-1857", "FOLIO-LD-6634", "FOLIO-LD-8519"), "Analyze the stylistic shift in the final portion of this manuscript"), - ("Stream7_Dickens_Trilogy", ["our_mutual_friend", "nicholas_nickleby", "martin_chuzzlewit"], ("FOLIO-MF-1865", "FOLIO-MF-4073", "FOLIO-MF-7295"), "Summarize the social critique running through the closing chapters"), -] -def build_stream_manuscript(prose_dir: str, idx: int, target_tokens: int, chars_per_tok: float) -> tuple[str, tuple[str, str, str], str]: - name, books, codes, lit_q = STREAM_SOURCES_500K[idx] +def build_stream_manuscript(prose_dir: str, idx: int, target_tokens: int, chars_per_tok: float, sources=None) -> tuple[str, tuple[str, str, str], str, bool]: + """Assemble one distinct archival manuscript and flag whether source text fell short of target_chars.""" + pool = sources if sources is not None else STREAM_SOURCES_500K + name, books, codes, lit_q = pool[idx] joined = "\n\n".join(load_book(prose_dir, b) for b in books) - # Distinct opening header so token 0 is unique on every stream (cached_tokens == 0 guaranteed!) target_chars = int(target_tokens * chars_per_tok) + source_undersized = len(joined) < target_chars body = joined[:target_chars] - p10 = int(len(body) * 0.10) - p50 = int(len(body) * 0.50) - p90 = int(len(body) * 0.90) + p10, p50, p90 = int(len(body) * 0.10), int(len(body) * 0.50), int(len(body) * 0.90) manuscript = ( - f"Archival Volume #{idx + 1} ({name}):\n\n" - + body[:p10] - + f"\n\n[Archival Margin Note Alpha for {name}: Early catalog marker is {codes[0]}.]\n\n" - + body[p10:p50] - + f"\n\n[Archival Margin Note Beta for {name}: Mid-volume catalog marker is {codes[1]}.]\n\n" - + body[p50:p90] - + f"\n\n[Archival Margin Note Gamma for {name}: Late catalog marker is {codes[2]}.]\n\n" - + body[p90:] + f"Archival Volume #{idx + 1} ({name}):\n\n" + body[:p10] + + f"\n\n[Archival Margin Note Alpha for {name}: Early catalog marker is {codes[0]}.]\n\n" + body[p10:p50] + + f"\n\n[Archival Margin Note Beta for {name}: Mid-volume catalog marker is {codes[1]}.]\n\n" + body[p50:p90] + + f"\n\n[Archival Margin Note Gamma for {name}: Late catalog marker is {codes[2]}.]\n\n" + body[p90:] + f"\n\nFinal Instructions for {name}: First list the three exact catalog markers (Alpha, Beta, Gamma) recorded in this volume, then in two sentences: {lit_q}." ) - return name, codes, manuscript + return name, codes, manuscript, source_undersized -def calibrate_stream_cpts(base_url: str, prose_dir: str, n_streams: int, model: str = "model") -> list[float]: + +def calibrate_stream_cpts(base_url: str, prose_dir: str, n_streams: int, model: str = "model", sources=None) -> list[float]: + """Estimate characters per token for each stream's source corpus.""" + pool = sources if sources is not None else STREAM_SOURCES_500K cpts = [] for idx in range(n_streams): - name, books, _, _ = STREAM_SOURCES_500K[idx] + name, books, _, _ = pool[idx] joined = "\n\n".join(load_book(prose_dir, b) for b in books) n = min(len(joined), 2_300_000) - sample = joined[n // 6 : n // 6 + 20000] + "\n" + joined[n // 2 : n // 2 + 20000] + "\n" + joined[(5 * n) // 6 : (5 * n) // 6 + 20000] + if n > 60000: + sample = joined[n // 6 : n // 6 + 20000] + "\n" + joined[n // 2 : n // 2 + 20000] + "\n" + joined[(5 * n) // 6 : (5 * n) // 6 + 20000] + else: + sample = joined[: max(1, min(n, 4000))] res = post_json(f"{base_url}/v1/chat/completions", { - "model": model, - "messages": [{"role": "user", "content": sample}], - "chat_template_kwargs": {"enable_thinking": False}, - "temperature": 0, - "max_tokens": 1, + "model": model, "messages": [{"role": "user", "content": sample}], + "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, "max_tokens": 1, }) - ptok = res["usage"]["prompt_tokens"] + ptok = valid_count((res.get("usage") or {}).get("prompt_tokens")) + if not ptok: + raise ValueError(f"calibration failed for {name}: invalid prompt_tokens") cpt = len(sample) / ptok cpts.append(cpt) - print(f" Calibrated {name:24s}: {cpt:.4f} chars/tok (available={int(len(joined)/cpt):,} tok)", flush=True) + print(f" Calibrated {name:24s}: {cpt:.4f} chars/tok (available={int(len(joined) / cpt):,} tok)", flush=True) return cpts -def run_distinct_long(base_url: str, prose_dir: str, target_tokens: int, n_streams: int, model: str = "model"): - print(f"\n=== {n_streams}x ~{target_tokens:,}-TOKEN 100% DISTINCT REAL-PROSE CONCURRENT BENCHMARK ===", flush=True) - cpts = calibrate_stream_cpts(base_url, prose_dir, n_streams, model=model) - try: - urllib.request.urlopen(f"{base_url}/health?reset_peak=1", timeout=10).read() - except Exception: - pass - payloads = [build_stream_manuscript(prose_dir, i, target_tokens, cpts[i]) for i in range(n_streams)] - for i, (name, codes, ms) in enumerate(payloads): - print(f" Prepared {name:24s}: {len(ms):,} chars (~{int(len(ms)/cpts[i]):,} est tokens), unique markers={codes}", flush=True) +def _observed_kv_residency(health: dict) -> int | None: + """Return observed engine KV token residency from /health only when explicitly reported.""" + if not isinstance(health, dict): + return None + kv = health.get("kv_cache") if isinstance(health.get("kv_cache"), dict) else {} + for candidate in (health.get("kv_resident_tokens"), kv.get("used_tokens"), kv.get("resident_tokens")): + val = valid_count(candidate) + if val is not None: + return val + return None + + +def run_distinct_long(base_url: str, prose_dir: str, target_tokens: int, n_streams: int, model: str = "model", + min_prompt_ratio: float = 0.95, sources=None) -> dict: + """Run N distinct long-context prose streams with separate submitted/completed totals and undersized-cell checks.""" + print(f"\n=== {n_streams}x TARGET {target_tokens:,}-TOKEN DISTINCT REAL-PROSE CONCURRENT BENCHMARK ===", flush=True) + cpts = calibrate_stream_cpts(base_url, prose_dir, n_streams, model=model, sources=sources) + min_prompt_tokens = math.ceil(target_tokens * min_prompt_ratio) + payloads = [build_stream_manuscript(prose_dir, i, target_tokens, cpts[i], sources=sources) for i in range(n_streams)] + est_tokens = [int(len(ms) / cpts[i]) for i, (_, _, ms, _) in enumerate(payloads)] + + for i, (name, codes, ms, src_short) in enumerate(payloads): + tag = " [UNDERSIZED SOURCE]" if src_short else "" + print(f" Prepared {name:24s}: {len(ms):,} chars (~{est_tokens[i]:,} est tok), markers={codes}{tag}", flush=True) + def run_one(i): - name, codes, ms = payloads[i] - t0 = time.time() - res = post_json(f"{base_url}/v1/chat/completions", { - "model": model, - "messages": [{"role": "user", "content": ms}], - "chat_template_kwargs": {"enable_thinking": False}, - "temperature": 0, - "max_tokens": 96, - }, timeout=7200) - el = time.time() - t0 - u = res["usage"] - ptok = u["prompt_tokens"] - cached = u.get("prompt_tokens_details", {}).get("cached_tokens", 0) - gtok = u["completion_tokens"] - txt = res["choices"][0]["message"]["content"] - hits = sum(1 for c in codes if c in txt) - print(f" [Done {name:24s}] prompt={ptok:,} (cached={cached}), gen={gtok}, {el:.1f}s, markers={hits}/3 -> {txt[:105]!r}", flush=True) - return name, ptok, cached, gtok, el, hits, txt - - print(f"\nLaunching all {n_streams} distinct real-prose streams concurrently (`cached_tokens == 0` on all {n_streams})...", flush=True) - t_all = time.time() + name, codes, ms, src_short = payloads[i] + t0 = time.perf_counter() + try: + res = post_json(f"{base_url}/v1/chat/completions", { + "model": model, "messages": [{"role": "user", "content": ms}], + "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, "seed": 1234 + i, "max_tokens": 96, + }, timeout=7200) + except Exception as exc: # noqa: BLE001 - capture per-stream failures without losing submitted totals + return {"name": name, "accepted": False, "error": type(exc).__name__, "est_prompt_tokens": est_tokens[i], + "prompt_tokens": None, "cached_tokens": None, "cache_state": "unverified", "tokens": None, + "elapsed_s": time.perf_counter() - t0, "hits": 0, "undersized": True, "source_undersized": src_short} + el = time.perf_counter() - t0 + if res.get("error"): + return {"name": name, "accepted": False, "error": "server_error", "est_prompt_tokens": est_tokens[i], + "prompt_tokens": None, "cached_tokens": None, "cache_state": "unverified", "tokens": None, + "elapsed_s": el, "hits": 0, "undersized": True, "source_undersized": src_short} + choices = res.get("choices") or [] + ch = choices[0] if choices else {} + msg = ch.get("message") or {} + txt, reasoning = msg.get("content") or "", msg.get("reasoning_content") or "" + complete = ch.get("finish_reason") in CLEAN_FINISH and bool(txt or reasoning) + usage = parse_usage(res.get("usage"), complete=complete) + accepted = complete and usage["prompt_tokens"] is not None and usage["tokens"] is not None and usage["tokens"] > 0 + ptok = usage["prompt_tokens"] + undersized = src_short or ptok is None or ptok < min_prompt_tokens + hits = sum(1 for c in codes if c in txt or c in reasoning) if accepted else 0 + status = "OK" if accepted else f"FAILED({ch.get('finish_reason') or 'no_output'})" + print(f" [{status:12s} {name:24s}] prompt={ptok} (cached={usage['cached_tokens']}, {usage['cache_state']}), gen={usage['tokens']}, {el:.1f}s, markers={hits}/3", flush=True) + return { + "name": name, "accepted": accepted, "error": None if accepted else (ch.get("finish_reason") or "incomplete_or_empty"), + "est_prompt_tokens": est_tokens[i], "prompt_tokens": ptok, "cached_tokens": usage["cached_tokens"], + "cache_state": usage["cache_state"], "tokens": usage["tokens"], "elapsed_s": el, + "hits": hits, "undersized": undersized, "source_undersized": src_short, + } + + t_all = time.perf_counter() with concurrent.futures.ThreadPoolExecutor(max_workers=n_streams) as ex: - futs = [ex.submit(run_one, i) for i in range(n_streams)] - results = [f.result() for f in futs] - wall = time.time() - t_all - - tot_prompt = sum(r[1] for r in results) - tot_cached = sum(r[2] for r in results) - tot_gen = sum(r[3] for r in results) - tot_kv = tot_prompt + tot_gen - tot_hits = sum(r[5] for r in results) - print(f"\n=== {n_streams}x DISTINCT REAL-PROSE SUMMARY ===") - print(f" Streams completed : {len(results)}/{n_streams} (total cached_tokens = {tot_cached})") - print(f" Distinct cold prompt tokens : {tot_prompt:,} tokens ({tot_prompt/1e6:.3f}M)") - print(f" Total simultaneous KV tokens : {tot_kv:,} tokens ({tot_kv/1e6:.3f}M)") - print(f" Wall clock (prefill+decode) : {wall:.1f}s (effective cold throughput: {(tot_prompt+tot_gen)/wall:.1f} tok/s)") - print(f" Unique marker recall (24) : {tot_hits}/{3 * n_streams} ({sum(1 for r in results if r[5]==3)}/{n_streams} streams 3/3)") + results = [f.result() for f in [ex.submit(run_one, i) for i in range(n_streams)]] + wall = time.perf_counter() - t_all + + completed = [r for r in results if r["accepted"]] + cold_completed = [r for r in completed if r["cache_state"] == "cold"] + undersized_names = [r["name"] for r in results if r["undersized"]] + submitted_est = sum(r["est_prompt_tokens"] for r in results) + reported_prompt = sum(r["prompt_tokens"] for r in results if r["prompt_tokens"] is not None) + completed_prompt = sum(r["prompt_tokens"] for r in completed) + completed_gen = sum(r["tokens"] for r in completed) + cold_prompt = sum(r["prompt_tokens"] for r in cold_completed) + tot_hits = sum(r["hits"] for r in completed) + + observed_kv = None try: - h = json.loads(urllib.request.urlopen(f"{base_url}/health", timeout=10).read().decode("utf-8")) - mem = h.get("memory", {}) - print(f" GPU Memory (rank 0) : active={mem.get('active',0)/(1024**3):.2f} GiB, peak={mem.get('peak',0)/(1024**3):.2f} GiB, cache={mem.get('cache',0)/(1024**3):.2f} GiB") - except Exception as e: - print(f" Health note: {e}") + health = json.loads(urllib.request.urlopen(f"{base_url}/health", timeout=10).read().decode("utf-8")) + observed_kv = _observed_kv_residency(health) + except Exception: + pass -if __name__ == "__main__": - ap = argparse.ArgumentParser() + cell_status = "ok" + if undersized_names: + cell_status = "undersized" + elif len(completed) != n_streams: + cell_status = "incomplete" + elif len(cold_completed) != n_streams: + cell_status = "cache_not_cold" + qualified = cell_status == "ok" + + print(f"\n=== {n_streams}x DISTINCT REAL-PROSE SUMMARY (status={cell_status}) ===") + print(f" Submitted streams : {n_streams} (est_prompt={submitted_est:,}, reported_prompt={reported_prompt:,})") + print(f" Completed streams : {len(completed)}/{n_streams} (prompt={completed_prompt:,}, completion={completed_gen:,})") + print(f" Verified cold streams : {len(cold_completed)}/{n_streams} (cold_completed_prompt={cold_prompt:,})") + if undersized_names: + print(f" Undersized cells (<{min_prompt_tokens:,} tok): {', '.join(undersized_names)}") + if observed_kv is not None: + print(f" Observed engine KV residency : {observed_kv:,} tokens") + print(f" Wall clock : {wall:.1f}s") + print(f" Unique marker recall : {tot_hits}/{3 * n_streams}") + + return { + "mode": "distinct-long", "target_tokens": target_tokens, "min_prompt_tokens": min_prompt_tokens, + "cell_status": cell_status, "qualified": qualified, "submitted_streams": n_streams, + "completed_streams": len(completed), "cold_verified_streams": len(cold_completed), + "submitted_est_prompt_tokens": submitted_est, "reported_prompt_tokens": reported_prompt, + "completed_prompt_tokens": completed_prompt, "completed_completion_tokens": completed_gen, + "cold_completed_prompt_tokens": cold_prompt, "undersized_streams": undersized_names, + "observed_kv_resident_tokens": observed_kv, "wall_s": wall, "marker_hits": tot_hits, "streams": results, + } + + +def main(argv=None) -> int: + """CLI entry point returning 0 on qualified/valid runs and 1 when verification fails.""" + ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--url", default="http://127.0.0.1:8888") ap.add_argument("--model", default="model") ap.add_argument("--prose-dir", default="/tmp/prose_8") ap.add_argument("--mode", choices=["prose-decode", "prose-loss-dump", "prose-loss-compare", "distinct-long"], required=True) ap.add_argument("--out", default="") + ap.add_argument("--output", default="") ap.add_argument("--bf16", default="") ap.add_argument("--fp8", default="") ap.add_argument("--tokens", type=int, default=502000) ap.add_argument("--streams", type=int, default=8) - a = ap.parse_args() + ap.add_argument("--levels", default="1,4,8") + ap.add_argument("--gen-tokens", type=int, default=256) + ap.add_argument("--seed", type=int, default=1234) + ap.add_argument("--tf-tokens", type=int, default=48) + ap.add_argument("--tf-file", default="") + ap.add_argument("--min-prompt-ratio", type=float, default=0.95) + a = ap.parse_args(argv) + if a.mode == "prose-decode": - run_prose_decode(a.url, a.prose_dir, model=a.model) + levels = tuple(int(x) for x in a.levels.split(",")) + report = run_prose_decode(a.url, a.prose_dir, model=a.model, levels=levels, gen_tokens=a.gen_tokens, seed=a.seed) elif a.mode == "prose-loss-dump": - dump_prose_loss(a.url, a.prose_dir, a.out, model=a.model) + report = dump_prose_loss(a.url, a.prose_dir, a.out, model=a.model, tf_tokens=a.tf_tokens, tf_file=a.tf_file) elif a.mode == "prose-loss-compare": - compare_prose_loss(a.bf16, a.fp8) - elif a.mode == "distinct-long": - run_distinct_long(a.url, a.prose_dir, a.tokens, a.streams, model=a.model) + report = compare_prose_loss(a.bf16, a.fp8) + else: + report = run_distinct_long(a.url, a.prose_dir, a.tokens, a.streams, model=a.model, min_prompt_ratio=a.min_prompt_ratio) + + if a.output: + with open(a.output, "w", encoding="utf-8") as f: + json.dump(report, f, indent=2) + return 0 if report.get("qualified", True) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/bench_prose_loss.py b/tools/bench_prose_loss.py new file mode 100644 index 00000000000..01f55a2601f --- /dev/null +++ b/tools/bench_prose_loss.py @@ -0,0 +1,383 @@ +"""Prose KV loss probe: chapter logprob dumps, immutable ground-truth continuation scoring, and comparison.""" +import hashlib +import json +import math +import statistics +import time + +CLEAN_FINISH = {"stop", "length"} + +LOSS_CASES = [ + ("war_peace_2k", "war_and_peace", 25000, 10500, "Provide a concise literary analysis of the character dynamics in this scene."), + ("monte_cristo_4k", "monte_cristo", 30000, 21000, "Trace the chain of events and motives revealed in this chapter."), + ("les_mis_8k", "les_miserables", 40000, 44000, "Examine how Hugo develops the tension between law and mercy across these chapters."), + ("don_quixote_16k", "don_quixote", 35000, 88000, "Synthesize the major episodes in this section and how Sancho Panza's perspective evolves."), + ("anna_karenina_24k", "anna_karenina", 30000, 132000, "Analyze the parallel narrative threads in these chapters and their emotional turning points."), + ("david_copperfield_32k", "david_copperfield", 25000, 174000, "Summarize the key characters introduced across these chapters and Dickens' narrative voice."), +] + + +def finite_num(value) -> float | None: + """Return finite float for int/float (excluding bool), else None.""" + if type(value) in (int, float) and math.isfinite(value): + return float(value) + return None + + +def sha256_token_ids(ids: list[int]) -> str: + """Return lowercase 64-hex SHA-256 of comma-joined decimal token IDs.""" + return hashlib.sha256(",".join(str(i) for i in ids).encode("ascii")).hexdigest() + + +def valid_token_ids(value, expected_len: int | None = None) -> list[int] | None: + """Validate a complete list of non-negative integer token IDs.""" + if not isinstance(value, list) or not value: + return None + if not all(type(x) is int and x >= 0 for x in value): + return None + if expected_len is not None and len(value) != expected_len: + return None + return list(value) + + +def _fmt(val, fmt_s: str = ".6f") -> str: + """Format a numeric value or report unavailable when None.""" + return "unavailable" if val is None else format(val, fmt_s) + + +def _tokenize_text(post_json, base_url: str, text: str, add_special_tokens: bool) -> list[int]: + """Tokenize text via /v1/tokenize and validate the integer token ID list.""" + res = post_json(f"{base_url}/v1/tokenize", {"prompt": text, "add_special_tokens": add_special_tokens}) + ids = valid_token_ids(res.get("tokens")) + if ids is None: + raise ValueError("invalid /v1/tokenize response: missing non-empty integer token list") + return ids + + +def score_teacher_forced_continuation(post_json, base_url: str, model: str, prefix_ids: list[int], cont_ids: list[int]) -> dict: + """Score one immutable tokenized ground-truth continuation via /v1/completions prompt_logprobs.""" + full_ids = prefix_ids + cont_ids + t0 = time.perf_counter() + res = post_json(f"{base_url}/v1/completions", { + "model": model, + "prompt": full_ids, + "max_tokens": 1, + "temperature": 0, + "prompt_logprobs": 20, + }) + dt = time.perf_counter() - t0 + if res.get("error"): + raise ValueError(f"teacher-forced request error: {res['error']}") + choices = res.get("choices") or [] + prompt_lps = (choices[0].get("prompt_logprobs") if choices else None) or res.get("prompt_logprobs") + if not isinstance(prompt_lps, list) or len(prompt_lps) != len(full_ids): + raise ValueError("prompt_logprobs missing or length mismatch") + + steps = [] + for offset, gt_id in enumerate(cont_ids): + row = prompt_lps[len(prefix_ids) + offset] + if not isinstance(row, dict) or str(gt_id) not in row: + raise ValueError(f"missing ground-truth token {gt_id} in prompt_logprobs[{len(prefix_ids) + offset}]") + gt_entry = row[str(gt_id)] + gt_lp = finite_num(gt_entry.get("logprob") if isinstance(gt_entry, dict) else None) + if gt_lp is None: + raise ValueError(f"invalid ground-truth logprob for token {gt_id}") + top = {} + top1_id = None + top1_lp = -math.inf + for tid_s, entry in row.items(): + lp = finite_num(entry.get("logprob") if isinstance(entry, dict) else None) + if lp is None: + continue + top[str(tid_s)] = lp + if entry.get("rank") == 1: + top1_id, top1_lp = str(tid_s), lp + elif top1_id is None or lp > top1_lp: + top1_id, top1_lp = str(tid_s), lp + steps.append({ + "gt_token_id": gt_id, + "gt_token": gt_entry.get("decoded_token", ""), + "gt_logprob": gt_lp, + "gt_prob": math.exp(gt_lp), + "gt_rank": gt_entry.get("rank"), + "top1_token_id": top1_id, + "top": top, + }) + + mean_nll = statistics.mean(-s["gt_logprob"] for s in steps) + return { + "prefix_token_count": len(prefix_ids), + "continuation_token_count": len(cont_ids), + "continuation_token_ids": cont_ids, + "continuation_sha256": sha256_token_ids(cont_ids), + "mean_gt_nll": mean_nll, + "gt_perplexity": math.exp(mean_nll), + "elapsed_s": dt, + "steps": steps, + } + + +def dump_prose_loss( + post_json, + load_book, + parse_usage, + base_url: str, + prose_dir: str, + out_json: str, + model: str = "model", + cases=None, + tf_tokens: int = 48, + tf_file: str = "", +) -> dict: + """Dump chapter top-logprobs and immutable tokenized ground-truth continuation scores to JSON.""" + case_list = cases if cases is not None else LOSS_CASES + print("\n=== REAL-PROSE KV LOSS PROBE (CHAPTER LOGPROBS + IMMUTABLE GROUND-TRUTH CONTINUATION) ===") + records: dict = {} + for label, book, off, chars, q in case_list: + raw_book = load_book(prose_dir, book) + excerpt = raw_book[off : off + chars] if len(raw_book) > off else raw_book[:chars] + t0 = time.perf_counter() + res = post_json(f"{base_url}/v1/chat/completions", { + "model": model, + "messages": [{"role": "user", "content": f"{excerpt}\n\nQuestion: {q}"}], + "chat_template_kwargs": {"enable_thinking": False}, + "temperature": 0, + "seed": 1234, + "max_tokens": 64, + "logprobs": True, + "top_logprobs": 20, + }) + dt = time.perf_counter() - t0 + if res.get("error"): + raise ValueError(f"{label}: server error {res['error']}") + ch = res["choices"][0] + msg = ch.get("message") or {} + text = msg.get("content") or "" + reasoning = msg.get("reasoning_content") or "" + if ch.get("finish_reason") not in CLEAN_FINISH or not (text or reasoning): + raise ValueError(f"{label}: incomplete or empty response") + usage = parse_usage(res.get("usage"), complete=True) + lp_items = (ch.get("logprobs") or {}).get("content") or [] + steps = [ + { + "token": it["token"], + "token_id": it.get("token_id"), + "logprob": finite_num(it.get("logprob")), + "top": {e["token"]: lp for e in it.get("top_logprobs") or [] if (lp := finite_num(e.get("logprob"))) is not None}, + } + for it in lp_items + ] + tf_meta = res.get("tensorfold") if isinstance(res.get("tensorfold"), dict) else {} + tids = valid_token_ids(tf_meta.get("token_ids") or ch.get("token_ids"), usage["tokens"]) + records[label] = { + "prompt_tokens": usage["prompt_tokens"], + "cached_tokens": usage["cached_tokens"], + "cache_state": usage["cache_state"], + "completion_tokens": usage["tokens"], + "finish_reason": ch.get("finish_reason"), + "token_ids": tids, + "token_sha256": tf_meta.get("token_sha256") or (sha256_token_ids(tids) if tids else None), + "steps": steps, + "text": text, + "reasoning": reasoning, + } + print(f" [{label:22s}] prompt={usage['prompt_tokens']} tok ({dt:.2f}s) -> {text[:85]!r}") + + if tf_file: + with open(tf_file, "r", encoding="utf-8") as f: + tf_spec = json.load(f) + prefix_ids = valid_token_ids(tf_spec.get("prefix_ids")) + cont_ids = valid_token_ids(tf_spec.get("continuation_ids")) + if prefix_ids is None or cont_ids is None: + raise ValueError("--tf-file must contain non-empty integer prefix_ids and continuation_ids") + else: + md_full = load_book(prose_dir, "moby_dick") + prefix_text = "Continue the following Melville passage verbatim:\n\n" + ( + md_full[50000:136000] if len(md_full) > 50000 else md_full[: max(1, len(md_full) // 2)] + ) + cont_text = md_full[136000:137500] if len(md_full) > 136000 else md_full[max(1, len(md_full) // 2) :] + prefix_ids = _tokenize_text(post_json, base_url, prefix_text, add_special_tokens=True) + cont_ids = _tokenize_text(post_json, base_url, cont_text, add_special_tokens=False)[:tf_tokens] + + tf_record = score_teacher_forced_continuation(post_json, base_url, model, prefix_ids, cont_ids) + records["_tf_moby_dick_16k"] = tf_record + print( + f" [moby_dick_16k_tf ] {tf_record['continuation_token_count']} gt tokens, " + f"NLL={tf_record['mean_gt_nll']:.5f}, PPL={tf_record['gt_perplexity']:.4f} ({tf_record['elapsed_s']:.2f}s)" + ) + with open(out_json, "w", encoding="utf-8") as f: + json.dump(records, f, indent=2) + print(f"Saved real-prose KV probe to {out_json}") + return records + + +def _cond_intersection_step(t16: dict, t8: dict) -> dict: + """Compute conditional intersection-only KL/TVD and unobserved probability mass outside the shared top-k.""" + common = [k for k in (set(t16) & set(t8)) if finite_num(t16[k]) is not None and finite_num(t8[k]) is not None] + z16 = sum(math.exp(t16[k]) for k in common) + z8 = sum(math.exp(t8[k]) for k in common) + missing_ref, missing_cand = max(0.0, 1.0 - z16), max(0.0, 1.0 - z8) + if not common or z16 <= 0.5 or z8 <= 0.5: + return {"kl": None, "tvd": None, "common_mass_ref": z16, "common_mass_cand": z8, + "missing_support_ref": missing_ref, "missing_support_cand": missing_cand} + kl = max(0.0, sum((math.exp(t16[k]) / z16) * math.log((math.exp(t16[k]) / z16) / (math.exp(t8[k]) / z8)) for k in common)) + tvd = 0.5 * sum(abs(math.exp(t16[k]) / z16 - math.exp(t8[k]) / z8) for k in common) + return {"kl": kl, "tvd": tvd, "common_mass_ref": z16, "common_mass_cand": z8, + "missing_support_ref": missing_ref, "missing_support_cand": missing_cand} + + +def _compare_sequences(r16: dict, r8: dict) -> dict: + """Compare complete token sequences, token IDs, and lengths before declaring IDENTICAL.""" + s16, s8 = r16.get("steps") or [], r8.get("steps") or [] + ids16, ids8 = r16.get("token_ids"), r8.get("token_ids") + if not s16 or not s8: + return {"identical": False, "first_diff_step": None, "status": "unavailable (empty sequence)", + "len_ref": len(s16), "len_cand": len(s8)} + for rec, steps in ((r16, s16), (r8, s8)): + ctok = rec.get("completion_tokens") + if type(ctok) is int and ctok != len(steps): + return {"identical": False, "first_diff_step": None, "status": "incomplete_steps", + "len_ref": len(s16), "len_cand": len(s8)} + shared = min(len(s16), len(s8)) + for i in range(shared): + tok_diff = s16[i].get("token") != s8[i].get("token") + id_diff = isinstance(ids16, list) and isinstance(ids8, list) and i < len(ids16) and i < len(ids8) and ids16[i] != ids8[i] + if tok_diff or id_diff: + return {"identical": False, "first_diff_step": i, "status": f"step {i}", + "len_ref": len(s16), "len_cand": len(s8)} + if len(s16) != len(s8): + return {"identical": False, "first_diff_step": shared, + "status": f"length_mismatch ({len(s16)} vs {len(s8)})", "len_ref": len(s16), "len_cand": len(s8)} + if (ids16 is not None or ids8 is not None) and ids16 != ids8: + return {"identical": False, "first_diff_step": None, "status": "token_ids_mismatch", + "len_ref": len(s16), "len_cand": len(s8)} + if r16.get("text") != r8.get("text") or r16.get("reasoning", "") != r8.get("reasoning", ""): + return {"identical": False, "first_diff_step": None, "status": "text_mismatch", + "len_ref": len(s16), "len_cand": len(s8)} + return {"identical": True, "first_diff_step": None, "status": "IDENTICAL", + "len_ref": len(s16), "len_cand": len(s8)} + + +def compare_prose_loss(bf16_json: str, fp8_json: str) -> dict: + """Compare two prose-loss dumps using conditional intersection-only diagnostics and exact ground-truth NLL.""" + with open(bf16_json, "r", encoding="utf-8") as f: + b16 = json.load(f) + with open(fp8_json, "r", encoding="utf-8") as f: + f8 = json.load(f) + + print("\n=== REAL-PROSE KV DIAGNOSTIC REPORT (CONDITIONAL INTERSECTION-ONLY + GROUND-TRUTH NLL) ===") + kls, tvds, dlps, miss_ref, miss_cand = [], [], [], [], [] + matched, agree = 0, 0 + cases_out = {} + + for name, r16 in b16.items(): + if name.startswith("_"): + continue + r8 = f8.get(name) + if not isinstance(r8, dict): + cases_out[name] = {"status": "unavailable (missing candidate)", "identical": False, "step0_cond_kl": None} + print(f" {name:22s}: unavailable (missing in candidate)") + continue + seq = _compare_sequences(r16, r8) + s16, s8 = r16.get("steps") or [], r8.get("steps") or [] + step0_kl = None + for i in range(min(len(s16), len(s8))): + if i > 0 and s16[i - 1].get("token") != s8[i - 1].get("token"): + break + matched += 1 + if s16[i].get("token") == s8[i].get("token"): + agree += 1 + diag = _cond_intersection_step(s16[i].get("top") or {}, s8[i].get("top") or {}) + miss_ref.append(diag["missing_support_ref"]) + miss_cand.append(diag["missing_support_cand"]) + if diag["kl"] is not None: + kls.append(diag["kl"]) + tvds.append(diag["tvd"]) + if i == 0: + step0_kl = diag["kl"] + t8 = s8[i].get("top") or {} + lp16 = finite_num(s16[i].get("logprob")) + lp8 = finite_num(t8.get(s16[i].get("token"))) + if lp16 is not None and lp8 is not None: + dlps.append(abs(lp16 - lp8)) + cases_out[name] = {**seq, "prompt_tokens": r16.get("prompt_tokens"), "step0_cond_kl": step0_kl} + print(f" {name:22s} ({r16.get('prompt_tokens')} tok): step0_cond_KL={_fmt(step0_kl)}, seq={seq['status']}") + + chapter_summary = { + "matched_steps": matched, + "top1_agree": agree, + "top1_agree_pct": (100.0 * agree / matched) if matched else None, + "conditional_intersection_kl_mean": statistics.mean(kls) if kls else None, + "conditional_intersection_kl_median": statistics.median(kls) if kls else None, + "conditional_intersection_tvd_mean": statistics.mean(tvds) if tvds else None, + "conditional_intersection_tvd_median": statistics.median(tvds) if tvds else None, + "missing_support_ref_mean": statistics.mean(miss_ref) if miss_ref else None, + "missing_support_cand_mean": statistics.mean(miss_cand) if miss_cand else None, + "top1_abs_dlogprob_mean": statistics.mean(dlps) if dlps else None, + "top1_abs_dlogprob_max": max(dlps) if dlps else None, + "metric_scope": "conditional_intersection_only_not_full_distribution_kl_or_ppl", + } + print(f" MATCHED-PREFIX CHAPTERS ({matched} steps; conditional intersection-only diagnostics, not full KL/PPL):") + print(f" Top-1 Greedy Agreement : {agree}/{matched} ({_fmt(chapter_summary['top1_agree_pct'], '.2f')}%)") + print(f" Conditional Intersection KL : mean={_fmt(chapter_summary['conditional_intersection_kl_mean'])}, median={_fmt(chapter_summary['conditional_intersection_kl_median'])}") + print(f" Conditional Intersection TVD : mean={_fmt(chapter_summary['conditional_intersection_tvd_mean'])}, median={_fmt(chapter_summary['conditional_intersection_tvd_median'])}") + print(f" Missing Support Outside Intersect: ref={_fmt(chapter_summary['missing_support_ref_mean'])}, cand={_fmt(chapter_summary['missing_support_cand_mean'])}") + print(f" Top-1 |Δlogprob| : mean={_fmt(chapter_summary['top1_abs_dlogprob_mean'], '.5f')}, max={_fmt(chapter_summary['top1_abs_dlogprob_max'], '.5f')}") + + tf_summary: dict = {"available": False} + tf16, tf8 = b16.get("_tf_moby_dick_16k"), f8.get("_tf_moby_dick_16k") + if ( + isinstance(tf16, dict) + and isinstance(tf8, dict) + and tf16.get("continuation_token_ids") + and tf16.get("continuation_token_ids") == tf8.get("continuation_token_ids") + and len(tf16.get("steps") or []) == len(tf16["continuation_token_ids"]) == len(tf8.get("steps") or []) + ): + s16, s8 = tf16["steps"], tf8["steps"] + gt_lps16 = [finite_num(x.get("gt_logprob")) for x in s16] + gt_lps8 = [finite_num(x.get("gt_logprob")) for x in s8] + if all(v is not None for v in gt_lps16) and all(v is not None for v in gt_lps8): + tkls, ttvds, tmiss_r, tmiss_c = [], [], [], [] + tagree = 0 + for x16, x8 in zip(s16, s8): + if x16.get("top1_token_id") is not None and x16.get("top1_token_id") == x8.get("top1_token_id"): + tagree += 1 + diag = _cond_intersection_step(x16.get("top") or {}, x8.get("top") or {}) + tmiss_r.append(diag["missing_support_ref"]) + tmiss_c.append(diag["missing_support_cand"]) + if diag["kl"] is not None: + tkls.append(diag["kl"]) + ttvds.append(diag["tvd"]) + n_tok = len(s16) + nll16 = statistics.mean(-v for v in gt_lps16) + nll8 = statistics.mean(-v for v in gt_lps8) + ppl16, ppl8 = math.exp(nll16), math.exp(nll8) + gt_diffs = [abs(a - b) for a, b in zip(gt_lps16, gt_lps8)] + tf_summary = { + "available": True, + "continuation_token_count": n_tok, + "continuation_sha256": tf16.get("continuation_sha256"), + "gt_nll_ref": nll16, + "gt_nll_cand": nll8, + "gt_nll_delta": nll8 - nll16, + "gt_ppl_ref": ppl16, + "gt_ppl_cand": ppl8, + "gt_ppl_ratio": ppl8 / ppl16, + "gt_abs_dlogprob_mean": statistics.mean(gt_diffs), + "gt_abs_dlogprob_max": max(gt_diffs), + "top1_agree": tagree, + "top1_agree_pct": 100.0 * tagree / n_tok, + "conditional_intersection_kl_mean": statistics.mean(tkls) if tkls else None, + "conditional_intersection_tvd_mean": statistics.mean(ttvds) if ttvds else None, + "missing_support_ref_mean": statistics.mean(tmiss_r) if tmiss_r else None, + "missing_support_cand_mean": statistics.mean(tmiss_c) if tmiss_c else None, + } + print(f"\n IMMUTABLE GROUND-TRUTH CONTINUATION ({n_tok} tokens, sha256={tf_summary['continuation_sha256']}):") + print(f" Ground-Truth NLL / PPL : ref={nll16:.5f} ({ppl16:.4f}), cand={nll8:.5f} ({ppl8:.4f}), ratio={ppl8/ppl16:.5f}x") + print(f" Ground-Truth |Δlogprob| : mean={tf_summary['gt_abs_dlogprob_mean']:.5f}, max={tf_summary['gt_abs_dlogprob_max']:.5f}") + print(f" Top-1 Greedy Token Agreement : {tagree}/{n_tok} ({tf_summary['top1_agree_pct']:.2f}%)") + print(f" Conditional Intersection KL/TVD : kl={_fmt(tf_summary['conditional_intersection_kl_mean'])}, tvd={_fmt(tf_summary['conditional_intersection_tvd_mean'])}") + else: + print("\n IMMUTABLE GROUND-TRUTH CONTINUATION: unavailable (missing or mismatched continuation)") + + return {"mode": "prose-loss-compare", "cases": cases_out, "chapters": chapter_summary, "teacher_forced": tf_summary} diff --git a/tools/tests/test_bench_prose.py b/tools/tests/test_bench_prose.py new file mode 100644 index 00000000000..2b29b1e335c --- /dev/null +++ b/tools/tests/test_bench_prose.py @@ -0,0 +1,408 @@ +"""Mock-server tests for tools/bench_prose.py evidence, equality, logprob, and long-context receipts.""" +import contextlib +import http.server +import io +import json +import math +from pathlib import Path +import sys +import tempfile +import threading +import time +import types +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import bench_prose +import bench_stream + + +def sse_bytes(events: list[dict], done: bool = True) -> bytes: + """Encode SSE JSON chunks with an optional [DONE] terminator.""" + body = b"".join(b"data: " + json.dumps(ev).encode("utf-8") + b"\n\n" for ev in events) + return body + (b"data: [DONE]\n\n" if done else b"") + + +def start_server(handler_fn): + """Run a local ThreadingHTTPServer backed by handler_fn(path, body) -> (status, ctype, bytes).""" + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + status, ctype, data = handler_fn(self.path, None) + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + raw = self.rfile.read(length) if length else b"{}" + status, ctype, data = handler_fn(self.path, json.loads(raw.decode("utf-8"))) + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + return srv, th, f"http://127.0.0.1:{srv.server_port}" + + +def write_books(directory: str, names: list[str], body: str = "") -> None: + """Populate a temporary prose directory with synthetic book files.""" + text = body or ("Alpha beta gamma delta epsilon zeta eta theta. " * 120) + for idx, name in enumerate(names): + (Path(directory) / f"{name}.txt").write_text(f"Book {idx}: {text}", encoding="utf-8") + + +class BenchProseTests(unittest.TestCase): + def test_cached_tokens_must_be_explicit_zero_for_cold_work(self): + cases = [ + ("missing_details", {"prompt_tokens": 32, "completion_tokens": 4}, "unverified", False), + ("missing_cached", {"prompt_tokens": 32, "completion_tokens": 4, "prompt_tokens_details": {}}, "unverified", False), + ("positive_cached", {"prompt_tokens": 32, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 8}}, "reused", False), + ("bool_cached", {"prompt_tokens": 32, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": False}}, "unverified", False), + ("exceeds_prompt", {"prompt_tokens": 4, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 8}}, "unverified", False), + ("explicit_zero", {"prompt_tokens": 32, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, "cold", True), + ] + for label, usage, expected_state, expected_ok in cases: + with self.subTest(case=label): + def handler(_path, _body, _u=usage): + events = [ + {"choices": [{"index": 0, "delta": {"content": "hello "}}]}, + {"choices": [{"index": 0, "delta": {"content": "world"}}]}, + {"choices": [], "usage": _u, "tensorfold": {"token_sha256": "a" * 64}}, + ] + return 200, "text/event-stream", sse_bytes(events, done=True) + + srv, th, url = start_server(handler) + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace"]) + with contextlib.redirect_stdout(io.StringIO()): + report = bench_prose.run_prose_decode( + url, td, levels=(1,), gen_tokens=4, + excerpt_specs=(("short", 120),), sources=bench_prose.DISTINCT_PROSE_8[:1], + ) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + pair = report["pairs"][0] + self.assertEqual(pair["draft"]["rows"][0]["cache_state"], expected_state) + self.assertEqual(pair["draft"]["cold_verified"], expected_ok) + self.assertEqual(pair["draft"]["timing"] is not None, expected_ok) + self.assertEqual(report["qualified"], expected_ok) + + def test_drafted_and_plain_pairs_share_prompt_seed_and_full_token_ids(self): + seen = [] + + def handler(_path, body): + seen.append(body) + ids = [10, 20, 30, 40] + events = [ + {"choices": [{"index": 0, "delta": {"content": "part1 "}}]}, + {"choices": [{"index": 0, "delta": {"content": "part2"}}]}, + { + "choices": [], + "usage": {"prompt_tokens": 40, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, + "tensorfold": {"token_ids": ids, "token_sha256": bench_prose.sha256_token_ids(ids)}, + }, + ] + return 200, "text/event-stream", sse_bytes(events, done=True) + + srv, th, url = start_server(handler) + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace", "monte_cristo"]) + with contextlib.redirect_stdout(io.StringIO()): + report = bench_prose.run_prose_decode( + url, td, levels=(2,), gen_tokens=4, seed=777, + excerpt_specs=(("short", 120),), sources=bench_prose.DISTINCT_PROSE_8[:2], + ) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + + self.assertEqual(len(seen), 4) + draft_reqs = sorted([b for b in seen if b.get("draft") is not False], key=lambda x: x["seed"]) + plain_reqs = sorted([b for b in seen if b.get("draft") is False], key=lambda x: x["seed"]) + for d, p in zip(draft_reqs, plain_reqs): + self.assertEqual(d["messages"], p["messages"]) + self.assertEqual(d["seed"], p["seed"]) + pair = report["pairs"][0] + self.assertTrue(pair["prompts_identical"]) + self.assertTrue(pair["seeds_identical"]) + self.assertEqual(pair["token_equal"], [True, True]) + self.assertEqual(pair["draft"]["rows"][0]["token_ids"], [10, 20, 30, 40]) + self.assertTrue(report["qualified"]) + + def test_token_id_mismatch_marks_pair_unequal(self): + def handler(_path, body): + ids = [1, 2, 3, 9] if body.get("draft") is False else [1, 2, 3, 4] + events = [ + {"choices": [{"index": 0, "delta": {"content": "same "}}]}, + {"choices": [{"index": 0, "delta": {"content": "text"}}]}, + { + "choices": [], + "usage": {"prompt_tokens": 20, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, + "tensorfold": {"token_ids": ids, "token_sha256": bench_prose.sha256_token_ids(ids)}, + }, + ] + return 200, "text/event-stream", sse_bytes(events, done=True) + + srv, th, url = start_server(handler) + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace"]) + with contextlib.redirect_stdout(io.StringIO()): + report = bench_prose.run_prose_decode( + url, td, levels=(1,), gen_tokens=4, + excerpt_specs=(("short", 100),), sources=bench_prose.DISTINCT_PROSE_8[:1], + ) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + self.assertEqual(report["pairs"][0]["token_equal"], [False]) + self.assertFalse(report["qualified"]) + + def test_incomplete_error_empty_rejected_and_reasoning_accepted_with_monotonic_clock(self): + usage = {"prompt_tokens": 16, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}} + h = {"token_sha256": "b" * 64} + cases = [ + ("missing_done", [{"choices": [{"index": 0, "delta": {"content": "hi"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], False, False), + ("stream_error", [{"choices": [{"index": 0, "delta": {"content": "hi"}}]}, {"error": {"message": "boom"}}], True, False), + ("empty_output", [{"choices": [{"index": 0, "delta": {"role": "assistant"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, False), + ("reasoning_only", [{"choices": [{"index": 0, "delta": {"reasoning_content": "step1"}}]}, {"choices": [{"index": 0, "delta": {"reasoning_content": " step2"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, True), + ] + + def fail_wall(): + raise AssertionError("must use monotonic perf_counter") + + monotonic_only = types.SimpleNamespace(perf_counter=time.perf_counter, time=fail_wall) + for label, events, done, expect_accept in cases: + with self.subTest(case=label): + def handler(_path, _body, _e=events, _d=done): + return 200, "text/event-stream", sse_bytes(_e, done=_d) + + srv, th, url = start_server(handler) + try: + with patch.object(bench_prose, "time", monotonic_only), patch.object(bench_stream, "time", monotonic_only): + row = bench_prose.stream_chat(f"{url}/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}]}) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + self.assertEqual(row["accepted"], expect_accept) + if expect_accept: + self.assertIsNotNone(row["ttft_s"]) + self.assertGreaterEqual(row["ttft_s"], 0.0) + self.assertIsNotNone(row["output_sha256"]) + else: + self.assertIsNone(row["ttft_s"]) + self.assertIsNone(row["decode_tps"]) + + def test_compare_prose_loss_length_mismatch_identical_unavailable_and_conditional_labels(self): + with tempfile.TemporaryDirectory() as td: + p16, p8 = Path(td) / "bf16.json", Path(td) / "fp8.json" + bf16 = { + "len_case": { + "prompt_tokens": 100, "completion_tokens": 3, "text": "abc", "token_ids": [1, 2, 3], + "steps": [ + {"token": "a", "logprob": -0.1, "top": {"a": -0.1, "x": -2.5}}, + {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, + {"token": "c", "logprob": -0.1, "top": {"c": -0.1}}, + ], + }, + "same_case": { + "prompt_tokens": 100, "completion_tokens": 2, "text": "ab", "token_ids": [1, 2], + "steps": [ + {"token": "a", "logprob": -0.1, "top": {"a": -0.1}}, + {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, + ], + }, + "disjoint_case": { + "prompt_tokens": 100, "completion_tokens": 1, "text": "a", "token_ids": [1], + "steps": [{"token": "a", "logprob": -0.2, "top": {"a": -0.2}}], + }, + } + fp8 = { + "len_case": { + "prompt_tokens": 100, "completion_tokens": 2, "text": "ab", "token_ids": [1, 2], + "steps": [ + {"token": "a", "logprob": -0.1, "top": {"a": -0.1, "y": -2.5}}, + {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, + ], + }, + "same_case": { + "prompt_tokens": 100, "completion_tokens": 2, "text": "ab", "token_ids": [1, 2], + "steps": [ + {"token": "a", "logprob": -0.1, "top": {"a": -0.1}}, + {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, + ], + }, + "disjoint_case": { + "prompt_tokens": 100, "completion_tokens": 1, "text": "a", "token_ids": [1], + "steps": [{"token": "a", "logprob": -0.2, "top": {"z": -0.2}}], + }, + } + p16.write_text(json.dumps(bf16), encoding="utf-8") + p8.write_text(json.dumps(fp8), encoding="utf-8") + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rep = bench_prose.compare_prose_loss(str(p16), str(p8)) + out = buf.getvalue() + self.assertFalse(rep["cases"]["len_case"]["identical"]) + self.assertIn("length_mismatch", rep["cases"]["len_case"]["status"]) + self.assertTrue(rep["cases"]["same_case"]["identical"]) + self.assertEqual(rep["cases"]["same_case"]["status"], "IDENTICAL") + self.assertIsNone(rep["cases"]["disjoint_case"]["step0_cond_kl"]) + self.assertIn("step0_cond_KL=unavailable", out) + self.assertIn("conditional intersection-only diagnostics", out) + self.assertNotIn("PPL mult", out) + self.assertIsNotNone(rep["chapters"]["missing_support_ref_mean"]) + self.assertFalse(rep["teacher_forced"]["available"]) + + def test_teacher_forced_scores_immutable_tokenized_continuation_and_compares_gt_nll(self): + requests_seen = [] + + def make_handler(gt_202_lp: float): + def handler(path, body): + requests_seen.append((path, body)) + if path == "/v1/tokenize": + if body.get("add_special_tokens"): + return 200, "application/json", json.dumps({"tokens": [101, 102, 103]}).encode() + return 200, "application/json", json.dumps({"tokens": [201, 202, 203, 204]}).encode() + if path == "/v1/completions": + prompt = body["prompt"] + plps = [None] + for tid in prompt[1:]: + if tid == 202: + row = { + "202": {"logprob": gt_202_lp, "rank": 25, "decoded_token": "whale"}, + "999": {"logprob": -0.1, "rank": 1, "decoded_token": "ship"}, + } + else: + row = {str(tid): {"logprob": -0.2, "rank": 1, "decoded_token": f"tok{tid}"}} + plps.append(row) + return 200, "application/json", json.dumps({"choices": [{"text": "x", "finish_reason": "length", "prompt_logprobs": plps}]}).encode() + if path == "/v1/chat/completions": + return 200, "application/json", json.dumps({ + "choices": [{ + "finish_reason": "stop", "message": {"content": "ok"}, + "logprobs": {"content": [{"token": "ok", "logprob": -0.1, "top_logprobs": [{"token": "ok", "logprob": -0.1}]}]}, + }], + "usage": {"prompt_tokens": 10, "completion_tokens": 1, "prompt_tokens_details": {"cached_tokens": 0}}, + }).encode() + return 404, "application/json", b"{}" + return handler + + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace", "moby_dick"]) + p16, p8 = Path(td) / "bf16.json", Path(td) / "fp8.json" + for lp, path in ((-3.0, p16), (-3.2, p8)): + srv, th, url = start_server(make_handler(lp)) + try: + with contextlib.redirect_stdout(io.StringIO()): + rec = bench_prose.dump_prose_loss(url, td, str(path), cases=bench_prose.LOSS_CASES[:1], tf_tokens=4) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + if path == p16: + tf = rec["_tf_moby_dick_16k"] + self.assertEqual(tf["continuation_token_ids"], [201, 202, 203, 204]) + self.assertEqual(tf["continuation_token_count"], 4) + self.assertAlmostEqual(tf["steps"][1]["gt_logprob"], -3.0) + self.assertAlmostEqual(tf["steps"][1]["gt_prob"], math.exp(-3.0)) + self.assertEqual(tf["steps"][1]["top1_token_id"], "999") + with contextlib.redirect_stdout(io.StringIO()): + cmp = bench_prose.compare_prose_loss(str(p16), str(p8)) + self.assertTrue(cmp["teacher_forced"]["available"]) + self.assertEqual(cmp["teacher_forced"]["continuation_token_count"], 4) + self.assertAlmostEqual(cmp["teacher_forced"]["gt_nll_delta"], 0.05) + self.assertEqual(sum(1 for p, _ in requests_seen if p == "/v1/completions"), 2) + + def test_distinct_long_separates_submitted_completed_rejects_undersized_and_omits_kv_claim(self): + def handler(path, body): + if path.startswith("/health"): + return 200, "application/json", json.dumps({"memory": {"active": 1024}}).encode() + text = body["messages"][0]["content"] + if body.get("max_tokens") == 1: + return 200, "application/json", json.dumps({ + "choices": [{"finish_reason": "length", "message": {"content": "x"}}], + "usage": {"prompt_tokens": max(1, len(text) // 4), "completion_tokens": 1, "prompt_tokens_details": {"cached_tokens": 0}}, + }).encode() + if "Stream1_LesMiserables" in text: + return 200, "application/json", json.dumps({"error": {"message": "oom"}}).encode() + actual_ptok = max(1, len(text) // 4) + return 200, "application/json", json.dumps({ + "choices": [{"finish_reason": "stop", "message": {"content": "FOLIO-WP-1812 FOLIO-WP-4409 FOLIO-WP-8831"}}], + "usage": {"prompt_tokens": actual_ptok, "completion_tokens": 12, "prompt_tokens_details": {"cached_tokens": 0}}, + }).encode() + + srv, th, url = start_server(handler) + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace"], body="Short prose text. " * 20) + write_books(td, ["les_miserables"], body="Longer prose text. " * 400) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rep = bench_prose.run_distinct_long(url, td, target_tokens=500, n_streams=2) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + + out = buf.getvalue() + self.assertNotIn("simultaneous KV", out) + self.assertIsNone(rep["observed_kv_resident_tokens"]) + self.assertEqual(rep["submitted_streams"], 2) + self.assertEqual(rep["completed_streams"], 1) + self.assertEqual(rep["completed_completion_tokens"], 12) + self.assertFalse(rep["qualified"]) + self.assertEqual(rep["cell_status"], "undersized") + self.assertIn("Stream0_WarAndPeace", rep["undersized_streams"]) + s0 = next(s for s in rep["streams"] if s["name"] == "Stream0_WarAndPeace") + self.assertLess(s0["prompt_tokens"], 500) + + def test_distinct_long_reports_observed_kv_and_rejects_non_cold_cache(self): + for cached_val, expect_ok, expect_status in ((0, True, "ok"), (12, False, "cache_not_cold"), (None, False, "cache_not_cold")): + with self.subTest(cached=cached_val): + def handler(path, body, _c=cached_val): + if path.startswith("/health"): + return 200, "application/json", json.dumps({"kv_cache": {"used_tokens": 1024}}).encode() + text = body["messages"][0]["content"] + ptok = max(1, len(text) // 4) + details = {} if _c is None else {"cached_tokens": _c} + return 200, "application/json", json.dumps({ + "choices": [{"finish_reason": "stop", "message": {"content": "FOLIO-WP-1812 FOLIO-WP-4409 FOLIO-WP-8831"}}], + "usage": {"prompt_tokens": ptok, "completion_tokens": 10, "prompt_tokens_details": details}, + }).encode() + + srv, th, url = start_server(handler) + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace", "les_miserables"], body="Longer prose text. " * 400) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = bench_prose.main(["--url", url, "--prose-dir", td, "--mode", "distinct-long", "--tokens", "500", "--streams", "2"]) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + self.assertEqual(code, 0 if expect_ok else 1) + self.assertIn(f"status={expect_status}", buf.getvalue()) + self.assertIn("Observed engine KV residency : 1,024 tokens", buf.getvalue()) + + +if __name__ == "__main__": + unittest.main() From 2e269bb5a33208268e3f459e73144eca5f991dfe Mon Sep 17 00:00:00 2001 From: GrgaPalcic <26028466+GrgaPalcic@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:11:40 +0100 Subject: [PATCH 149/361] tools: tighten bench_prose qualification, EOS/hash/prefix guards, and input checks Address PR #4797 follow-up review feedback: - Require affirmative token_equal and output_equal (missing token hashes/IDs never qualify). - Require clean finish_reason (stop/length) on every streamed choice before accepting a stream or emitting timing. - Allow normal EOS slack (completion_tokens == len(steps) + 1) for finish_reason == stop in loss sequence comparison while keeping strict checks for length. - Compare full 64-hex token_sha256 in loss sequence comparison before declaring IDENTICAL. - Record prefix_sha256 in teacher-forced dumps and require matching prefix count/hash, continuation IDs, and per-step gt_token_id/gt_token before comparing teacher-forced runs. - Separate failed long-context streams from undersized cells so failed full-length streams are never labeled undersized. - Validate levels, token counts, stream counts, min_prompt_ratio, and empty sources before network calls or calibration division. - Add mock-server regression controls for each case in tools/tests/test_bench_prose.py. --- tools/bench_prose.py | 101 ++++++++++++---- tools/bench_prose_loss.py | 81 +++++++++++-- tools/tests/test_bench_prose.py | 207 +++++++++++++++++++++----------- 3 files changed, 283 insertions(+), 106 deletions(-) diff --git a/tools/bench_prose.py b/tools/bench_prose.py index 9fb2974b08a..2470be3d421 100755 --- a/tools/bench_prose.py +++ b/tools/bench_prose.py @@ -151,11 +151,15 @@ def tap_lines(resp): complete = error is None and reply.end == "done" if error is None and not complete: error = "incomplete_stream" - observed = reply.evidence.finish(reply.usage, reply.runtime, complete) + finish_reasons = [reply.finish[i] for i in sorted(reply.finish)] + clean_finish = bool(finish_reasons) and all(r in CLEAN_FINISH for r in finish_reasons) + observed = reply.evidence.finish(reply.usage, reply.runtime, complete and clean_finish) has_output = reply.evidence.observed_output and bool(reply.pieces) tokens, prompt_tokens = observed["tokens"], observed["prompt_tokens"] - accepted = complete and has_output and prompt_tokens is not None and tokens is not None and tokens > 0 - if error is None and not has_output: + accepted = complete and clean_finish and has_output and prompt_tokens is not None and tokens is not None and tokens > 0 + if error is None and not clean_finish: + error = "unclean_finish_reason" + elif error is None and not has_output: error = "no_output" elif error is None and not accepted: error = "invalid_usage" @@ -171,7 +175,8 @@ def tap_lines(resp): decode_tps = ((tokens - 1) / (last - first)) if (accepted and tokens > 1 and last > first) else None return { - "accepted": accepted, "complete": complete, "completion": reply.completion(), "error": error, + "accepted": accepted, "complete": complete and clean_finish, "completion": reply.completion(), + "finish_reasons": finish_reasons, "error": error, "prompt_tokens": prompt_tokens, "cached_tokens": observed["cached_tokens"], "cache_state": observed["cache_state"], "tokens": tokens, "sent": sent, "first": first, "last": last, "ttft_s": ttft_s, "decode_tps": decode_tps, "token_ids": token_ids, @@ -180,6 +185,16 @@ def tap_lines(resp): } +def _validate_decode_args(levels, gen_tokens: int, pool_len: int) -> list[int]: + """Validate prose-decode counts before issuing any HTTP requests.""" + if type(gen_tokens) is not int or gen_tokens < 1: + raise ValueError("gen_tokens must be a positive integer") + vals = list(levels) + if not vals or any(type(n) is not int or n < 1 or n > pool_len for n in vals): + raise ValueError(f"levels must be integers between 1 and {pool_len}") + return vals + + def run_prose_decode( base_url: str, prose_dir: str, @@ -192,6 +207,7 @@ def run_prose_decode( ) -> dict: """Run paired drafted/plain distinct-prose decode with identical prompts, seeds, and cold-cache verification.""" pool = sources if sources is not None else DISTINCT_PROSE_8 + checked_levels = _validate_decode_args(levels, gen_tokens, len(pool)) print("\n=== REALISTIC DISTINCT-PROSE MULTI-STREAM DECODE BENCHMARK (SSE TTFT + PURE DECODE) ===", flush=True) report = {"mode": "prose-decode", "seed": seed, "gen_tokens": gen_tokens, "pairs": [], "qualified": True} @@ -199,12 +215,14 @@ def run_prose_decode( prompts = [] for i, (book, off, _, question) in enumerate(pool): raw_book = load_book(prose_dir, book) + if not raw_book.strip(): + raise ValueError(f"empty source book for {book}") txt = raw_book[off : off + excerpt_chars] if len(raw_book) > off else raw_book[:excerpt_chars] prompt_text = f"[Excerpt {i + 1} — {book}]\n\n{txt}\n\nTask: {question}" prompts.append((book, prompt_text, seed + i, sha256_text(prompt_text))) print(f" --- Workload: {tag} ({len(prompts)} distinct novels) ---", flush=True) - for n in levels: + for n in checked_levels: arms = {} for draft_on in (True, False): def one(idx, _draft=draft_on): @@ -258,7 +276,8 @@ def one(idx, _draft=draft_on): tok_eq = [pair_token_equal(d, p) for d, p in zip(d_rows, p_rows)] out_eq = [pair_output_equal(d, p) for d, p in zip(d_rows, p_rows)] pair_qualified = (arms["draft"]["cold_verified"] and arms["plain"]["cold_verified"] - and prompts_identical and seeds_identical and False not in tok_eq and False not in out_eq) + and prompts_identical and seeds_identical + and all(v is True for v in tok_eq) and all(v is True for v in out_eq)) if not pair_qualified: report["qualified"] = False report["pairs"].append({ @@ -298,17 +317,23 @@ def build_stream_manuscript(prose_dir: str, idx: int, target_tokens: int, chars_ def calibrate_stream_cpts(base_url: str, prose_dir: str, n_streams: int, model: str = "model", sources=None) -> list[float]: - """Estimate characters per token for each stream's source corpus.""" + """Estimate characters per token for each stream's source corpus; reject empty sources cleanly.""" pool = sources if sources is not None else STREAM_SOURCES_500K + if type(n_streams) is not int or n_streams < 1 or n_streams > len(pool): + raise ValueError(f"n_streams must be between 1 and {len(pool)}") cpts = [] for idx in range(n_streams): name, books, _, _ = pool[idx] joined = "\n\n".join(load_book(prose_dir, b) for b in books) + if not joined.strip(): + raise ValueError(f"calibration failed for {name}: empty source text") n = min(len(joined), 2_300_000) if n > 60000: sample = joined[n // 6 : n // 6 + 20000] + "\n" + joined[n // 2 : n // 2 + 20000] + "\n" + joined[(5 * n) // 6 : (5 * n) // 6 + 20000] else: - sample = joined[: max(1, min(n, 4000))] + sample = joined[: min(n, 4000)] + if not sample: + raise ValueError(f"calibration failed for {name}: empty sample") res = post_json(f"{base_url}/v1/chat/completions", { "model": model, "messages": [{"role": "user", "content": sample}], "chat_template_kwargs": {"enable_thinking": False}, "temperature": 0, "max_tokens": 1, @@ -317,6 +342,8 @@ def calibrate_stream_cpts(base_url: str, prose_dir: str, n_streams: int, model: if not ptok: raise ValueError(f"calibration failed for {name}: invalid prompt_tokens") cpt = len(sample) / ptok + if cpt <= 0.0: + raise ValueError(f"calibration failed for {name}: non-positive chars/tok") cpts.append(cpt) print(f" Calibrated {name:24s}: {cpt:.4f} chars/tok (available={int(len(joined) / cpt):,} tok)", flush=True) return cpts @@ -337,10 +364,17 @@ def _observed_kv_residency(health: dict) -> int | None: def run_distinct_long(base_url: str, prose_dir: str, target_tokens: int, n_streams: int, model: str = "model", min_prompt_ratio: float = 0.95, sources=None) -> dict: """Run N distinct long-context prose streams with separate submitted/completed totals and undersized-cell checks.""" + pool = sources if sources is not None else STREAM_SOURCES_500K + if type(target_tokens) is not int or target_tokens < 1: + raise ValueError("target_tokens must be a positive integer") + if type(n_streams) is not int or n_streams < 1 or n_streams > len(pool): + raise ValueError(f"n_streams must be between 1 and {len(pool)}") + if type(min_prompt_ratio) not in (int, float) or not math.isfinite(min_prompt_ratio) or not (0.0 < min_prompt_ratio <= 1.0): + raise ValueError("min_prompt_ratio must be finite and in (0, 1]") print(f"\n=== {n_streams}x TARGET {target_tokens:,}-TOKEN DISTINCT REAL-PROSE CONCURRENT BENCHMARK ===", flush=True) - cpts = calibrate_stream_cpts(base_url, prose_dir, n_streams, model=model, sources=sources) + cpts = calibrate_stream_cpts(base_url, prose_dir, n_streams, model=model, sources=pool) min_prompt_tokens = math.ceil(target_tokens * min_prompt_ratio) - payloads = [build_stream_manuscript(prose_dir, i, target_tokens, cpts[i], sources=sources) for i in range(n_streams)] + payloads = [build_stream_manuscript(prose_dir, i, target_tokens, cpts[i], sources=pool) for i in range(n_streams)] est_tokens = [int(len(ms) / cpts[i]) for i, (_, _, ms, _) in enumerate(payloads)] for i, (name, codes, ms, src_short) in enumerate(payloads): @@ -358,12 +392,12 @@ def run_one(i): except Exception as exc: # noqa: BLE001 - capture per-stream failures without losing submitted totals return {"name": name, "accepted": False, "error": type(exc).__name__, "est_prompt_tokens": est_tokens[i], "prompt_tokens": None, "cached_tokens": None, "cache_state": "unverified", "tokens": None, - "elapsed_s": time.perf_counter() - t0, "hits": 0, "undersized": True, "source_undersized": src_short} + "elapsed_s": time.perf_counter() - t0, "hits": 0, "undersized": src_short, "source_undersized": src_short} el = time.perf_counter() - t0 if res.get("error"): return {"name": name, "accepted": False, "error": "server_error", "est_prompt_tokens": est_tokens[i], "prompt_tokens": None, "cached_tokens": None, "cache_state": "unverified", "tokens": None, - "elapsed_s": el, "hits": 0, "undersized": True, "source_undersized": src_short} + "elapsed_s": el, "hits": 0, "undersized": src_short, "source_undersized": src_short} choices = res.get("choices") or [] ch = choices[0] if choices else {} msg = ch.get("message") or {} @@ -372,7 +406,7 @@ def run_one(i): usage = parse_usage(res.get("usage"), complete=complete) accepted = complete and usage["prompt_tokens"] is not None and usage["tokens"] is not None and usage["tokens"] > 0 ptok = usage["prompt_tokens"] - undersized = src_short or ptok is None or ptok < min_prompt_tokens + undersized = src_short or (ptok is not None and ptok < min_prompt_tokens) hits = sum(1 for c in codes if c in txt or c in reasoning) if accepted else 0 status = "OK" if accepted else f"FAILED({ch.get('finish_reason') or 'no_output'})" print(f" [{status:12s} {name:24s}] prompt={ptok} (cached={usage['cached_tokens']}, {usage['cache_state']}), gen={usage['tokens']}, {el:.1f}s, markers={hits}/3", flush=True) @@ -390,6 +424,7 @@ def run_one(i): completed = [r for r in results if r["accepted"]] cold_completed = [r for r in completed if r["cache_state"] == "cold"] + failed_names = [r["name"] for r in results if not r["accepted"]] undersized_names = [r["name"] for r in results if r["undersized"]] submitted_est = sum(r["est_prompt_tokens"] for r in results) reported_prompt = sum(r["prompt_tokens"] for r in results if r["prompt_tokens"] is not None) @@ -405,19 +440,24 @@ def run_one(i): except Exception: pass - cell_status = "ok" - if undersized_names: - cell_status = "undersized" - elif len(completed) != n_streams: + if failed_names and undersized_names: + cell_status = "incomplete_and_undersized" + elif failed_names: cell_status = "incomplete" + elif undersized_names: + cell_status = "undersized" elif len(cold_completed) != n_streams: cell_status = "cache_not_cold" + else: + cell_status = "ok" qualified = cell_status == "ok" print(f"\n=== {n_streams}x DISTINCT REAL-PROSE SUMMARY (status={cell_status}) ===") print(f" Submitted streams : {n_streams} (est_prompt={submitted_est:,}, reported_prompt={reported_prompt:,})") print(f" Completed streams : {len(completed)}/{n_streams} (prompt={completed_prompt:,}, completion={completed_gen:,})") print(f" Verified cold streams : {len(cold_completed)}/{n_streams} (cold_completed_prompt={cold_prompt:,})") + if failed_names: + print(f" Failed streams : {', '.join(failed_names)}") if undersized_names: print(f" Undersized cells (<{min_prompt_tokens:,} tok): {', '.join(undersized_names)}") if observed_kv is not None: @@ -429,10 +469,11 @@ def run_one(i): "mode": "distinct-long", "target_tokens": target_tokens, "min_prompt_tokens": min_prompt_tokens, "cell_status": cell_status, "qualified": qualified, "submitted_streams": n_streams, "completed_streams": len(completed), "cold_verified_streams": len(cold_completed), - "submitted_est_prompt_tokens": submitted_est, "reported_prompt_tokens": reported_prompt, - "completed_prompt_tokens": completed_prompt, "completed_completion_tokens": completed_gen, - "cold_completed_prompt_tokens": cold_prompt, "undersized_streams": undersized_names, - "observed_kv_resident_tokens": observed_kv, "wall_s": wall, "marker_hits": tot_hits, "streams": results, + "failed_streams": failed_names, "submitted_est_prompt_tokens": submitted_est, + "reported_prompt_tokens": reported_prompt, "completed_prompt_tokens": completed_prompt, + "completed_completion_tokens": completed_gen, "cold_completed_prompt_tokens": cold_prompt, + "undersized_streams": undersized_names, "observed_kv_resident_tokens": observed_kv, + "wall_s": wall, "marker_hits": tot_hits, "streams": results, } @@ -458,13 +499,29 @@ def main(argv=None) -> int: a = ap.parse_args(argv) if a.mode == "prose-decode": - levels = tuple(int(x) for x in a.levels.split(",")) + try: + levels = tuple(int(x) for x in a.levels.split(",")) + _validate_decode_args(levels, a.gen_tokens, len(DISTINCT_PROSE_8)) + except ValueError as exc: + ap.error(str(exc)) report = run_prose_decode(a.url, a.prose_dir, model=a.model, levels=levels, gen_tokens=a.gen_tokens, seed=a.seed) elif a.mode == "prose-loss-dump": + if a.tf_tokens < 1: + ap.error("--tf-tokens must be positive") + if not a.out: + ap.error("--out is required for prose-loss-dump") report = dump_prose_loss(a.url, a.prose_dir, a.out, model=a.model, tf_tokens=a.tf_tokens, tf_file=a.tf_file) elif a.mode == "prose-loss-compare": + if not a.bf16 or not a.fp8: + ap.error("--bf16 and --fp8 are required for prose-loss-compare") report = compare_prose_loss(a.bf16, a.fp8) else: + if a.tokens < 1: + ap.error("--tokens must be positive") + if a.streams < 1 or a.streams > len(STREAM_SOURCES_500K): + ap.error(f"--streams must be between 1 and {len(STREAM_SOURCES_500K)}") + if not math.isfinite(a.min_prompt_ratio) or not (0.0 < a.min_prompt_ratio <= 1.0): + ap.error("--min-prompt-ratio must be finite and in (0, 1]") report = run_distinct_long(a.url, a.prose_dir, a.tokens, a.streams, model=a.model, min_prompt_ratio=a.min_prompt_ratio) if a.output: diff --git a/tools/bench_prose_loss.py b/tools/bench_prose_loss.py index 01f55a2601f..04e073f8d51 100644 --- a/tools/bench_prose_loss.py +++ b/tools/bench_prose_loss.py @@ -2,10 +2,12 @@ import hashlib import json import math +import re import statistics import time CLEAN_FINISH = {"stop", "length"} +SHA256_RE = re.compile(r"^[0-9a-f]{64}$") LOSS_CASES = [ ("war_peace_2k", "war_and_peace", 25000, 10500, "Provide a concise literary analysis of the character dynamics in this scene."), @@ -107,6 +109,7 @@ def score_teacher_forced_continuation(post_json, base_url: str, model: str, pref mean_nll = statistics.mean(-s["gt_logprob"] for s in steps) return { "prefix_token_count": len(prefix_ids), + "prefix_sha256": sha256_token_ids(prefix_ids), "continuation_token_count": len(cont_ids), "continuation_token_ids": cont_ids, "continuation_sha256": sha256_token_ids(cont_ids), @@ -130,6 +133,10 @@ def dump_prose_loss( tf_file: str = "", ) -> dict: """Dump chapter top-logprobs and immutable tokenized ground-truth continuation scores to JSON.""" + if type(tf_tokens) is not int or tf_tokens < 1: + raise ValueError("tf_tokens must be a positive integer") + if not out_json: + raise ValueError("out_json path is required") case_list = cases if cases is not None else LOSS_CASES print("\n=== REAL-PROSE KV LOSS PROBE (CHAPTER LOGPROBS + IMMUTABLE GROUND-TRUTH CONTINUATION) ===") records: dict = {} @@ -226,8 +233,13 @@ def _cond_intersection_step(t16: dict, t8: dict) -> dict: "missing_support_ref": missing_ref, "missing_support_cand": missing_cand} +def _valid_sha256(value) -> str | None: + """Return lowercase 64-hex SHA-256 string if valid, else None.""" + return value if isinstance(value, str) and SHA256_RE.match(value) else None + + def _compare_sequences(r16: dict, r8: dict) -> dict: - """Compare complete token sequences, token IDs, and lengths before declaring IDENTICAL.""" + """Compare complete token sequences, EOS-aware lengths, token IDs, and full hashes before declaring IDENTICAL.""" s16, s8 = r16.get("steps") or [], r8.get("steps") or [] ids16, ids8 = r16.get("token_ids"), r8.get("token_ids") if not s16 or not s8: @@ -235,9 +247,11 @@ def _compare_sequences(r16: dict, r8: dict) -> dict: "len_ref": len(s16), "len_cand": len(s8)} for rec, steps in ((r16, s16), (r8, s8)): ctok = rec.get("completion_tokens") - if type(ctok) is int and ctok != len(steps): - return {"identical": False, "first_diff_step": None, "status": "incomplete_steps", - "len_ref": len(s16), "len_cand": len(s8)} + if type(ctok) is int: + eos_slack = 1 if rec.get("finish_reason") == "stop" else 0 + if len(steps) > ctok or len(steps) + eos_slack < ctok: + return {"identical": False, "first_diff_step": None, "status": "incomplete_steps", + "len_ref": len(s16), "len_cand": len(s8)} shared = min(len(s16), len(s8)) for i in range(shared): tok_diff = s16[i].get("token") != s8[i].get("token") @@ -248,9 +262,22 @@ def _compare_sequences(r16: dict, r8: dict) -> dict: if len(s16) != len(s8): return {"identical": False, "first_diff_step": shared, "status": f"length_mismatch ({len(s16)} vs {len(s8)})", "len_ref": len(s16), "len_cand": len(s8)} + c16, c8 = r16.get("completion_tokens"), r8.get("completion_tokens") + if type(c16) is int and type(c8) is int and c16 != c8: + return {"identical": False, "first_diff_step": shared, + "status": f"completion_tokens_mismatch ({c16} vs {c8})", "len_ref": len(s16), "len_cand": len(s8)} + if r16.get("finish_reason") != r8.get("finish_reason") and (r16.get("finish_reason") is not None or r8.get("finish_reason") is not None): + return {"identical": False, "first_diff_step": None, "status": "finish_reason_mismatch", + "len_ref": len(s16), "len_cand": len(s8)} if (ids16 is not None or ids8 is not None) and ids16 != ids8: return {"identical": False, "first_diff_step": None, "status": "token_ids_mismatch", "len_ref": len(s16), "len_cand": len(s8)} + sha16, sha8 = r16.get("token_sha256"), r8.get("token_sha256") + if sha16 is not None or sha8 is not None: + v16, v8 = _valid_sha256(sha16), _valid_sha256(sha8) + if v16 is None or v8 is None or v16 != v8: + return {"identical": False, "first_diff_step": None, "status": "token_sha256_mismatch", + "len_ref": len(s16), "len_cand": len(s8)} if r16.get("text") != r8.get("text") or r16.get("reasoning", "") != r8.get("reasoning", ""): return {"identical": False, "first_diff_step": None, "status": "text_mismatch", "len_ref": len(s16), "len_cand": len(s8)} @@ -258,6 +285,35 @@ def _compare_sequences(r16: dict, r8: dict) -> dict: "len_ref": len(s16), "len_cand": len(s8)} +def _valid_tf_pair(tf16, tf8) -> tuple[bool, str | None]: + """Verify both teacher-forced dumps share identical prefix, continuation IDs, and per-step GT identity.""" + if not isinstance(tf16, dict) or not isinstance(tf8, dict): + return False, "missing_teacher_forced" + p_cnt16, p_cnt8 = tf16.get("prefix_token_count"), tf8.get("prefix_token_count") + p_sha16, p_sha8 = _valid_sha256(tf16.get("prefix_sha256")), _valid_sha256(tf8.get("prefix_sha256")) + if type(p_cnt16) is not int or p_cnt16 < 1 or p_cnt16 != p_cnt8 or p_sha16 is None or p_sha16 != p_sha8: + return False, "prefix_mismatch" + cont16 = valid_token_ids(tf16.get("continuation_token_ids")) + cont8 = valid_token_ids(tf8.get("continuation_token_ids")) + if cont16 is None or cont8 is None or cont16 != cont8: + return False, "continuation_mismatch" + expected_sha = sha256_token_ids(cont16) + for tf in (tf16, tf8): + if tf.get("continuation_sha256") is not None and tf.get("continuation_sha256") != expected_sha: + return False, "continuation_sha_mismatch" + s16, s8 = tf16.get("steps") or [], tf8.get("steps") or [] + if len(s16) != len(cont16) or len(s8) != len(cont16): + return False, "step_count_mismatch" + for tid, x16, x8 in zip(cont16, s16, s8): + if not isinstance(x16, dict) or not isinstance(x8, dict): + return False, "invalid_step" + if x16.get("gt_token_id") != tid or x8.get("gt_token_id") != tid: + return False, "gt_token_id_mismatch" + if x16.get("gt_token") != x8.get("gt_token"): + return False, "gt_token_text_mismatch" + return True, None + + def compare_prose_loss(bf16_json: str, fp8_json: str) -> dict: """Compare two prose-loss dumps using conditional intersection-only diagnostics and exact ground-truth NLL.""" with open(bf16_json, "r", encoding="utf-8") as f: @@ -326,13 +382,8 @@ def compare_prose_loss(bf16_json: str, fp8_json: str) -> dict: tf_summary: dict = {"available": False} tf16, tf8 = b16.get("_tf_moby_dick_16k"), f8.get("_tf_moby_dick_16k") - if ( - isinstance(tf16, dict) - and isinstance(tf8, dict) - and tf16.get("continuation_token_ids") - and tf16.get("continuation_token_ids") == tf8.get("continuation_token_ids") - and len(tf16.get("steps") or []) == len(tf16["continuation_token_ids"]) == len(tf8.get("steps") or []) - ): + tf_ok, tf_reason = _valid_tf_pair(tf16, tf8) + if tf_ok: s16, s8 = tf16["steps"], tf8["steps"] gt_lps16 = [finite_num(x.get("gt_logprob")) for x in s16] gt_lps8 = [finite_num(x.get("gt_logprob")) for x in s8] @@ -355,6 +406,8 @@ def compare_prose_loss(bf16_json: str, fp8_json: str) -> dict: gt_diffs = [abs(a - b) for a, b in zip(gt_lps16, gt_lps8)] tf_summary = { "available": True, + "prefix_token_count": tf16["prefix_token_count"], + "prefix_sha256": tf16["prefix_sha256"], "continuation_token_count": n_tok, "continuation_sha256": tf16.get("continuation_sha256"), "gt_nll_ref": nll16, @@ -377,7 +430,11 @@ def compare_prose_loss(bf16_json: str, fp8_json: str) -> dict: print(f" Ground-Truth |Δlogprob| : mean={tf_summary['gt_abs_dlogprob_mean']:.5f}, max={tf_summary['gt_abs_dlogprob_max']:.5f}") print(f" Top-1 Greedy Token Agreement : {tagree}/{n_tok} ({tf_summary['top1_agree_pct']:.2f}%)") print(f" Conditional Intersection KL/TVD : kl={_fmt(tf_summary['conditional_intersection_kl_mean'])}, tvd={_fmt(tf_summary['conditional_intersection_tvd_mean'])}") + else: + tf_summary = {"available": False, "reason": "invalid_gt_logprob"} + print("\n IMMUTABLE GROUND-TRUTH CONTINUATION: unavailable (invalid_gt_logprob)") else: - print("\n IMMUTABLE GROUND-TRUTH CONTINUATION: unavailable (missing or mismatched continuation)") + tf_summary = {"available": False, "reason": tf_reason} + print(f"\n IMMUTABLE GROUND-TRUTH CONTINUATION: unavailable ({tf_reason})") return {"mode": "prose-loss-compare", "cases": cases_out, "chapters": chapter_summary, "teacher_forced": tf_summary} diff --git a/tools/tests/test_bench_prose.py b/tools/tests/test_bench_prose.py index 2b29b1e335c..49fd96953a6 100644 --- a/tools/tests/test_bench_prose.py +++ b/tools/tests/test_bench_prose.py @@ -56,9 +56,10 @@ def do_POST(self): def write_books(directory: str, names: list[str], body: str = "") -> None: """Populate a temporary prose directory with synthetic book files.""" - text = body or ("Alpha beta gamma delta epsilon zeta eta theta. " * 120) + text = body if body is not None else ("Alpha beta gamma delta epsilon zeta eta theta. " * 120) for idx, name in enumerate(names): - (Path(directory) / f"{name}.txt").write_text(f"Book {idx}: {text}", encoding="utf-8") + content = f"Book {idx}: {text}" if text else "" + (Path(directory) / f"{name}.txt").write_text(content, encoding="utf-8") class BenchProseTests(unittest.TestCase): @@ -76,7 +77,7 @@ def test_cached_tokens_must_be_explicit_zero_for_cold_work(self): def handler(_path, _body, _u=usage): events = [ {"choices": [{"index": 0, "delta": {"content": "hello "}}]}, - {"choices": [{"index": 0, "delta": {"content": "world"}}]}, + {"choices": [{"index": 0, "delta": {"content": "world"}, "finish_reason": "stop"}]}, {"choices": [], "usage": _u, "tensorfold": {"token_sha256": "a" * 64}}, ] return 200, "text/event-stream", sse_bytes(events, done=True) @@ -84,7 +85,7 @@ def handler(_path, _body, _u=usage): srv, th, url = start_server(handler) try: with tempfile.TemporaryDirectory() as td: - write_books(td, ["war_and_peace"]) + write_books(td, ["war_and_peace"], body=None) with contextlib.redirect_stdout(io.StringIO()): report = bench_prose.run_prose_decode( url, td, levels=(1,), gen_tokens=4, @@ -100,7 +101,7 @@ def handler(_path, _body, _u=usage): self.assertEqual(pair["draft"]["timing"] is not None, expected_ok) self.assertEqual(report["qualified"], expected_ok) - def test_drafted_and_plain_pairs_share_prompt_seed_and_full_token_ids(self): + def test_drafted_and_plain_pairs_share_prompt_seed_and_require_token_evidence(self): seen = [] def handler(_path, body): @@ -108,7 +109,7 @@ def handler(_path, body): ids = [10, 20, 30, 40] events = [ {"choices": [{"index": 0, "delta": {"content": "part1 "}}]}, - {"choices": [{"index": 0, "delta": {"content": "part2"}}]}, + {"choices": [{"index": 0, "delta": {"content": "part2"}, "finish_reason": "stop"}]}, { "choices": [], "usage": {"prompt_tokens": 40, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, @@ -120,7 +121,7 @@ def handler(_path, body): srv, th, url = start_server(handler) try: with tempfile.TemporaryDirectory() as td: - write_books(td, ["war_and_peace", "monte_cristo"]) + write_books(td, ["war_and_peace", "monte_cristo"], body=None) with contextlib.redirect_stdout(io.StringIO()): report = bench_prose.run_prose_decode( url, td, levels=(2,), gen_tokens=4, seed=777, @@ -144,12 +145,37 @@ def handler(_path, body): self.assertEqual(pair["draft"]["rows"][0]["token_ids"], [10, 20, 30, 40]) self.assertTrue(report["qualified"]) + # Missing token_ids and token_sha256 must NOT qualify even when text matches. + def no_hash_handler(_path, _body): + events = [ + {"choices": [{"index": 0, "delta": {"content": "same "}}]}, + {"choices": [{"index": 0, "delta": {"content": "text"}, "finish_reason": "stop"}]}, + {"choices": [], "usage": {"prompt_tokens": 20, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}}, + ] + return 200, "text/event-stream", sse_bytes(events, done=True) + + srv, th, url = start_server(no_hash_handler) + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace"], body=None) + with contextlib.redirect_stdout(io.StringIO()): + missing_rep = bench_prose.run_prose_decode( + url, td, levels=(1,), gen_tokens=4, + excerpt_specs=(("short", 100),), sources=bench_prose.DISTINCT_PROSE_8[:1], + ) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + self.assertEqual(missing_rep["pairs"][0]["token_equal"], [None]) + self.assertFalse(missing_rep["qualified"]) + def test_token_id_mismatch_marks_pair_unequal(self): def handler(_path, body): ids = [1, 2, 3, 9] if body.get("draft") is False else [1, 2, 3, 4] events = [ {"choices": [{"index": 0, "delta": {"content": "same "}}]}, - {"choices": [{"index": 0, "delta": {"content": "text"}}]}, + {"choices": [{"index": 0, "delta": {"content": "text"}, "finish_reason": "stop"}]}, { "choices": [], "usage": {"prompt_tokens": 20, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, @@ -161,7 +187,7 @@ def handler(_path, body): srv, th, url = start_server(handler) try: with tempfile.TemporaryDirectory() as td: - write_books(td, ["war_and_peace"]) + write_books(td, ["war_and_peace"], body=None) with contextlib.redirect_stdout(io.StringIO()): report = bench_prose.run_prose_decode( url, td, levels=(1,), gen_tokens=4, @@ -174,14 +200,16 @@ def handler(_path, body): self.assertEqual(report["pairs"][0]["token_equal"], [False]) self.assertFalse(report["qualified"]) - def test_incomplete_error_empty_rejected_and_reasoning_accepted_with_monotonic_clock(self): + def test_finish_reason_incomplete_error_empty_and_reasoning_with_monotonic_clock(self): usage = {"prompt_tokens": 16, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}} h = {"token_sha256": "b" * 64} cases = [ - ("missing_done", [{"choices": [{"index": 0, "delta": {"content": "hi"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], False, False), + ("missing_done", [{"choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": "stop"}]}, {"choices": [], "usage": usage, "tensorfold": h}], False, False), + ("missing_finish", [{"choices": [{"index": 0, "delta": {"content": "hi"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, False), + ("unclean_finish", [{"choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": "content_filter"}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, False), ("stream_error", [{"choices": [{"index": 0, "delta": {"content": "hi"}}]}, {"error": {"message": "boom"}}], True, False), - ("empty_output", [{"choices": [{"index": 0, "delta": {"role": "assistant"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, False), - ("reasoning_only", [{"choices": [{"index": 0, "delta": {"reasoning_content": "step1"}}]}, {"choices": [{"index": 0, "delta": {"reasoning_content": " step2"}}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, True), + ("empty_output", [{"choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": "stop"}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, False), + ("reasoning_only", [{"choices": [{"index": 0, "delta": {"reasoning_content": "step1"}}]}, {"choices": [{"index": 0, "delta": {"reasoning_content": " step2"}, "finish_reason": "length"}]}, {"choices": [], "usage": usage, "tensorfold": h}], True, True), ] def fail_wall(): @@ -210,48 +238,53 @@ def handler(_path, _body, _e=events, _d=done): self.assertIsNone(row["ttft_s"]) self.assertIsNone(row["decode_tps"]) - def test_compare_prose_loss_length_mismatch_identical_unavailable_and_conditional_labels(self): + def test_compare_prose_loss_eos_counts_token_sha256_length_and_conditional_labels(self): with tempfile.TemporaryDirectory() as td: p16, p8 = Path(td) / "bf16.json", Path(td) / "fp8.json" + steps2 = [ + {"token": "a", "logprob": -0.1, "top": {"a": -0.1}}, + {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, + ] bf16 = { "len_case": { - "prompt_tokens": 100, "completion_tokens": 3, "text": "abc", "token_ids": [1, 2, 3], - "steps": [ - {"token": "a", "logprob": -0.1, "top": {"a": -0.1, "x": -2.5}}, - {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, - {"token": "c", "logprob": -0.1, "top": {"c": -0.1}}, - ], + "prompt_tokens": 100, "completion_tokens": 3, "finish_reason": "length", "text": "abc", "token_ids": [1, 2, 3], + "steps": steps2 + [{"token": "c", "logprob": -0.1, "top": {"c": -0.1}}], }, - "same_case": { - "prompt_tokens": 100, "completion_tokens": 2, "text": "ab", "token_ids": [1, 2], - "steps": [ - {"token": "a", "logprob": -0.1, "top": {"a": -0.1}}, - {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, - ], + "eos_stop_case": { + "prompt_tokens": 100, "completion_tokens": 3, "finish_reason": "stop", "text": "ab", + "token_sha256": "c" * 64, "steps": steps2, + }, + "length_missing_step": { + "prompt_tokens": 100, "completion_tokens": 3, "finish_reason": "length", "text": "ab", "steps": steps2, + }, + "sha_diff_case": { + "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "stop", "text": "ab", + "token_sha256": "a" * 64, "steps": steps2, }, "disjoint_case": { - "prompt_tokens": 100, "completion_tokens": 1, "text": "a", "token_ids": [1], - "steps": [{"token": "a", "logprob": -0.2, "top": {"a": -0.2}}], + "prompt_tokens": 100, "completion_tokens": 1, "finish_reason": "stop", "text": "a", + "token_ids": [1], "steps": [{"token": "a", "logprob": -0.2, "top": {"a": -0.2}}], }, } fp8 = { "len_case": { - "prompt_tokens": 100, "completion_tokens": 2, "text": "ab", "token_ids": [1, 2], - "steps": [ - {"token": "a", "logprob": -0.1, "top": {"a": -0.1, "y": -2.5}}, - {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, - ], + "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "length", "text": "ab", "token_ids": [1, 2], + "steps": steps2, + }, + "eos_stop_case": { + "prompt_tokens": 100, "completion_tokens": 3, "finish_reason": "stop", "text": "ab", + "token_sha256": "c" * 64, "steps": steps2, }, - "same_case": { - "prompt_tokens": 100, "completion_tokens": 2, "text": "ab", "token_ids": [1, 2], - "steps": [ - {"token": "a", "logprob": -0.1, "top": {"a": -0.1}}, - {"token": "b", "logprob": -0.1, "top": {"b": -0.1}}, - ], + "length_missing_step": { + "prompt_tokens": 100, "completion_tokens": 3, "finish_reason": "length", "text": "ab", "steps": steps2, + }, + "sha_diff_case": { + "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "stop", "text": "ab", + "token_sha256": "d" * 64, "steps": steps2, }, "disjoint_case": { - "prompt_tokens": 100, "completion_tokens": 1, "text": "a", "token_ids": [1], - "steps": [{"token": "a", "logprob": -0.2, "top": {"z": -0.2}}], + "prompt_tokens": 100, "completion_tokens": 1, "finish_reason": "stop", "text": "a", + "token_ids": [1], "steps": [{"token": "a", "logprob": -0.2, "top": {"z": -0.2}}], }, } p16.write_text(json.dumps(bf16), encoding="utf-8") @@ -262,24 +295,26 @@ def test_compare_prose_loss_length_mismatch_identical_unavailable_and_conditiona out = buf.getvalue() self.assertFalse(rep["cases"]["len_case"]["identical"]) self.assertIn("length_mismatch", rep["cases"]["len_case"]["status"]) - self.assertTrue(rep["cases"]["same_case"]["identical"]) - self.assertEqual(rep["cases"]["same_case"]["status"], "IDENTICAL") + self.assertTrue(rep["cases"]["eos_stop_case"]["identical"]) + self.assertEqual(rep["cases"]["eos_stop_case"]["status"], "IDENTICAL") + self.assertFalse(rep["cases"]["length_missing_step"]["identical"]) + self.assertEqual(rep["cases"]["length_missing_step"]["status"], "incomplete_steps") + self.assertFalse(rep["cases"]["sha_diff_case"]["identical"]) + self.assertEqual(rep["cases"]["sha_diff_case"]["status"], "token_sha256_mismatch") self.assertIsNone(rep["cases"]["disjoint_case"]["step0_cond_kl"]) self.assertIn("step0_cond_KL=unavailable", out) self.assertIn("conditional intersection-only diagnostics", out) self.assertNotIn("PPL mult", out) - self.assertIsNotNone(rep["chapters"]["missing_support_ref_mean"]) - self.assertFalse(rep["teacher_forced"]["available"]) - def test_teacher_forced_scores_immutable_tokenized_continuation_and_compares_gt_nll(self): + def test_teacher_forced_checks_prefix_and_per_step_gt_identity(self): requests_seen = [] - def make_handler(gt_202_lp: float): + def make_handler(gt_202_lp: float, prefix_tokens: list[int]): def handler(path, body): requests_seen.append((path, body)) if path == "/v1/tokenize": if body.get("add_special_tokens"): - return 200, "application/json", json.dumps({"tokens": [101, 102, 103]}).encode() + return 200, "application/json", json.dumps({"tokens": prefix_tokens}).encode() return 200, "application/json", json.dumps({"tokens": [201, 202, 203, 204]}).encode() if path == "/v1/completions": prompt = body["prompt"] @@ -306,32 +341,36 @@ def handler(path, body): return handler with tempfile.TemporaryDirectory() as td: - write_books(td, ["war_and_peace", "moby_dick"]) - p16, p8 = Path(td) / "bf16.json", Path(td) / "fp8.json" - for lp, path in ((-3.0, p16), (-3.2, p8)): - srv, th, url = start_server(make_handler(lp)) + write_books(td, ["war_and_peace", "moby_dick"], body=None) + p16, p8, p_bad_prefix = Path(td) / "bf16.json", Path(td) / "fp8.json", Path(td) / "bad_prefix.json" + for lp, pfx, path in ((-3.0, [101, 102, 103], p16), (-3.2, [101, 102, 103], p8), (-3.2, [101, 102, 999], p_bad_prefix)): + srv, th, url = start_server(make_handler(lp, pfx)) try: with contextlib.redirect_stdout(io.StringIO()): - rec = bench_prose.dump_prose_loss(url, td, str(path), cases=bench_prose.LOSS_CASES[:1], tf_tokens=4) + bench_prose.dump_prose_loss(url, td, str(path), cases=bench_prose.LOSS_CASES[:1], tf_tokens=4) finally: srv.shutdown() srv.server_close() th.join(timeout=5) - if path == p16: - tf = rec["_tf_moby_dick_16k"] - self.assertEqual(tf["continuation_token_ids"], [201, 202, 203, 204]) - self.assertEqual(tf["continuation_token_count"], 4) - self.assertAlmostEqual(tf["steps"][1]["gt_logprob"], -3.0) - self.assertAlmostEqual(tf["steps"][1]["gt_prob"], math.exp(-3.0)) - self.assertEqual(tf["steps"][1]["top1_token_id"], "999") with contextlib.redirect_stdout(io.StringIO()): - cmp = bench_prose.compare_prose_loss(str(p16), str(p8)) - self.assertTrue(cmp["teacher_forced"]["available"]) - self.assertEqual(cmp["teacher_forced"]["continuation_token_count"], 4) - self.assertAlmostEqual(cmp["teacher_forced"]["gt_nll_delta"], 0.05) - self.assertEqual(sum(1 for p, _ in requests_seen if p == "/v1/completions"), 2) + ok_cmp = bench_prose.compare_prose_loss(str(p16), str(p8)) + bad_pfx_cmp = bench_prose.compare_prose_loss(str(p16), str(p_bad_prefix)) + tampered = json.loads(p8.read_text(encoding="utf-8")) + tampered["_tf_moby_dick_16k"]["steps"][1]["gt_token_id"] = 999 + p_bad_gt = Path(td) / "bad_gt.json" + p_bad_gt.write_text(json.dumps(tampered), encoding="utf-8") + with contextlib.redirect_stdout(io.StringIO()): + bad_gt_cmp = bench_prose.compare_prose_loss(str(p16), str(p_bad_gt)) - def test_distinct_long_separates_submitted_completed_rejects_undersized_and_omits_kv_claim(self): + self.assertTrue(ok_cmp["teacher_forced"]["available"]) + self.assertEqual(ok_cmp["teacher_forced"]["continuation_token_count"], 4) + self.assertAlmostEqual(ok_cmp["teacher_forced"]["gt_nll_delta"], 0.05) + self.assertFalse(bad_pfx_cmp["teacher_forced"]["available"]) + self.assertEqual(bad_pfx_cmp["teacher_forced"]["reason"], "prefix_mismatch") + self.assertFalse(bad_gt_cmp["teacher_forced"]["available"]) + self.assertEqual(bad_gt_cmp["teacher_forced"]["reason"], "gt_token_id_mismatch") + + def test_distinct_long_failed_stream_not_undersized_and_omits_kv_claim(self): def handler(path, body): if path.startswith("/health"): return 200, "application/json", json.dumps({"memory": {"active": 1024}}).encode() @@ -367,12 +406,11 @@ def handler(path, body): self.assertIsNone(rep["observed_kv_resident_tokens"]) self.assertEqual(rep["submitted_streams"], 2) self.assertEqual(rep["completed_streams"], 1) - self.assertEqual(rep["completed_completion_tokens"], 12) - self.assertFalse(rep["qualified"]) - self.assertEqual(rep["cell_status"], "undersized") - self.assertIn("Stream0_WarAndPeace", rep["undersized_streams"]) - s0 = next(s for s in rep["streams"] if s["name"] == "Stream0_WarAndPeace") - self.assertLess(s0["prompt_tokens"], 500) + self.assertEqual(rep["failed_streams"], ["Stream1_LesMiserables"]) + self.assertEqual(rep["undersized_streams"], ["Stream0_WarAndPeace"]) + self.assertEqual(rep["cell_status"], "incomplete_and_undersized") + s1 = next(s for s in rep["streams"] if s["name"] == "Stream1_LesMiserables") + self.assertFalse(s1["undersized"]) def test_distinct_long_reports_observed_kv_and_rejects_non_cold_cache(self): for cached_val, expect_ok, expect_status in ((0, True, "ok"), (12, False, "cache_not_cold"), (None, False, "cache_not_cold")): @@ -403,6 +441,31 @@ def handler(path, body, _c=cached_val): self.assertIn(f"status={expect_status}", buf.getvalue()) self.assertIn("Observed engine KV residency : 1,024 tokens", buf.getvalue()) + def test_invalid_counts_and_empty_source_rejected_before_network_or_division(self): + with patch.object(bench_prose.urllib.request, "urlopen", side_effect=AssertionError("must not call server")): + with self.assertRaises(ValueError): + bench_prose.run_prose_decode("http://127.0.0.1:1", "/nonexistent", levels=(0,)) + with self.assertRaises(ValueError): + bench_prose.run_prose_decode("http://127.0.0.1:1", "/nonexistent", levels=(9,)) + with self.assertRaises(ValueError): + bench_prose.run_prose_decode("http://127.0.0.1:1", "/nonexistent", gen_tokens=0) + with self.assertRaises(ValueError): + bench_prose.run_distinct_long("http://127.0.0.1:1", "/nonexistent", target_tokens=0, n_streams=1) + with self.assertRaises(ValueError): + bench_prose.run_distinct_long("http://127.0.0.1:1", "/nonexistent", target_tokens=100, n_streams=9) + with self.assertRaises(ValueError): + bench_prose.run_distinct_long("http://127.0.0.1:1", "/nonexistent", target_tokens=100, n_streams=1, min_prompt_ratio=0.0) + with self.assertRaises(ValueError): + bench_prose.dump_prose_loss("http://127.0.0.1:1", "/nonexistent", "out.json", tf_tokens=0) + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace"], body="") + with self.assertRaises(ValueError): + bench_prose.calibrate_stream_cpts("http://127.0.0.1:1", td, 1) + with contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as cm: + bench_prose.main(["--mode", "distinct-long", "--streams", "0"]) + self.assertNotEqual(cm.exception.code, 0) + if __name__ == "__main__": unittest.main() From 26fac6b661453ac64666c25a186009c79b24f58e Mon Sep 17 00:00:00 2001 From: GrgaPalcic <26028466+GrgaPalcic@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:40:08 +0100 Subject: [PATCH 150/361] tools: require affirmative loss token evidence and shared-interval decode concurrency Address final PR #4797 review items: - Require affirmative complete token_ids or full 64-hex token_sha256 in compare_prose_loss before declaring IDENTICAL (add both-missing control). - Measure multi-stream decode throughput over the shared [min(first), max(last)] interval instead of summing per-request rates, detect serialized/queued streams via interval overlap, and add a serialized-stream control. --- tools/bench_prose.py | 39 +++++++++-- tools/bench_prose_loss.py | 21 ++++-- tools/tests/test_bench_prose.py | 110 +++++++++++++++++++++++++++----- 3 files changed, 142 insertions(+), 28 deletions(-) diff --git a/tools/bench_prose.py b/tools/bench_prose.py index 2470be3d421..74dee219fc0 100755 --- a/tools/bench_prose.py +++ b/tools/bench_prose.py @@ -195,6 +195,23 @@ def _validate_decode_args(levels, gen_tokens: int, pool_len: int) -> list[int]: return vals +def _decode_overlap(rows: list[dict]) -> tuple[bool | None, int]: + """Return (overlapped, max_concurrent) across accepted streams' [first, last] decode intervals.""" + spans = sorted((r["first"], r["last"]) for r in rows if r.get("first") is not None and r.get("last") is not None) + if len(spans) < 2: + return None, len(spans) + overlapped = any(b[0] < a[1] for a, b in zip(spans, spans[1:])) + events = [(lo, 1) for lo, _ in spans] + [(hi, -1) for _, hi in spans] + # Process end (-1) before start (+1) at equal timestamps so abutting intervals do not count as concurrent. + events.sort(key=lambda e: (e[0], e[1])) + cur = peak = 0 + for _, delta in events: + cur += delta + if cur > peak: + peak = cur + return overlapped, peak + + def run_prose_decode( base_url: str, prose_dir: str, @@ -247,25 +264,38 @@ def one(idx, _draft=draft_on): all_accepted = all(r["accepted"] for r in rows) all_cold = all(r["cache_state"] == "cold" for r in rows) all_timed = all_accepted and all(r["decode_tps"] is not None for r in rows) + overlapped, max_concurrent = _decode_overlap(rows) if all_accepted else (None, 0) + serialized = (n > 1) and (overlapped is False) timing_row = None if all_accepted and all_cold: tot_prompt = sum(r["prompt_tokens"] for r in rows) tot_gen = sum(r["tokens"] for r in rows) - start_t, last_tok_t = min(r["sent"] for r in rows), max(r["last"] for r in rows) + start_t = min(r["sent"] for r in rows) + first_tok_t = min(r["first"] for r in rows) + last_tok_t = max(r["last"] for r in rows) + shared_span = last_tok_t - first_tok_t + agg_dec_tps = (sum(r["tokens"] - 1 for r in rows) / shared_span) if (all_timed and shared_span > 0) else None + per_med_tps = statistics.median(r["decode_tps"] for r in rows) if all_timed else None timing_row = { "prompt_tokens": tot_prompt, "cached_tokens": 0, "completion_tokens": tot_gen, - "decode_tps": sum(r["decode_tps"] for r in rows) if all_timed else None, + "decode_tps": agg_dec_tps, "per_stream_median_tps": per_med_tps, + "shared_decode_s": shared_span if shared_span > 0 else None, + "overlapped": overlapped, "max_concurrent_decoding": max_concurrent, + "serialized": serialized, "e2e_tps": (tot_gen / (last_tok_t - start_t)) if last_tok_t > start_t else None, "median_ttft_s": statistics.median(r["ttft_s"] for r in rows), } mode_key, mode_s = ("draft", "DFly2") if draft_on else ("plain", "Plain") arms[mode_key] = {"rows": rows, "all_accepted": all_accepted, - "cold_verified": all_accepted and all_cold, "timing": timing_row} + "cold_verified": all_accepted and all_cold, + "concurrent_verified": (n == 1) or (overlapped is True), + "overlapped": overlapped, "serialized": serialized, "timing": timing_row} if timing_row is not None: dec_s = f"{timing_row['decode_tps']:6.2f}" if timing_row["decode_tps"] is not None else " n/a " e2e_s = f"{timing_row['e2e_tps']:6.2f}" if timing_row["e2e_tps"] is not None else " n/a " + queue_note = " [SERIALIZED/QUEUED]" if serialized else "" print(f" [{n}s {mode_s:5s}] prompt={timing_row['prompt_tokens']:,} (cached=0, cold) | " - f"decode={dec_s} tok/s | e2e={e2e_s} tok/s | median_TTFT={timing_row['median_ttft_s']:.2f}s", flush=True) + f"decode={dec_s} tok/s | e2e={e2e_s} tok/s | median_TTFT={timing_row['median_ttft_s']:.2f}s{queue_note}", flush=True) else: reasons = sorted({r["error"] or f"cache_{r['cache_state']}" for r in rows if not r["accepted"] or r["cache_state"] != "cold"}) print(f" [{n}s {mode_s:5s}] REJECTED (no timing row): {', '.join(reasons)}", flush=True) @@ -276,6 +306,7 @@ def one(idx, _draft=draft_on): tok_eq = [pair_token_equal(d, p) for d, p in zip(d_rows, p_rows)] out_eq = [pair_output_equal(d, p) for d, p in zip(d_rows, p_rows)] pair_qualified = (arms["draft"]["cold_verified"] and arms["plain"]["cold_verified"] + and arms["draft"]["concurrent_verified"] and arms["plain"]["concurrent_verified"] and prompts_identical and seeds_identical and all(v is True for v in tok_eq) and all(v is True for v in out_eq)) if not pair_qualified: diff --git a/tools/bench_prose_loss.py b/tools/bench_prose_loss.py index 04e073f8d51..a0b2c837db8 100644 --- a/tools/bench_prose_loss.py +++ b/tools/bench_prose_loss.py @@ -269,15 +269,22 @@ def _compare_sequences(r16: dict, r8: dict) -> dict: if r16.get("finish_reason") != r8.get("finish_reason") and (r16.get("finish_reason") is not None or r8.get("finish_reason") is not None): return {"identical": False, "first_diff_step": None, "status": "finish_reason_mismatch", "len_ref": len(s16), "len_cand": len(s8)} - if (ids16 is not None or ids8 is not None) and ids16 != ids8: + sha16, sha8 = r16.get("token_sha256"), r8.get("token_sha256") + has_ids = isinstance(ids16, list) and len(ids16) > 0 and isinstance(ids8, list) and len(ids8) > 0 + v16, v8 = _valid_sha256(sha16), _valid_sha256(sha8) + has_sha = v16 is not None and v8 is not None + if (ids16 is not None or ids8 is not None) and (not has_ids or ids16 != ids8): return {"identical": False, "first_diff_step": None, "status": "token_ids_mismatch", "len_ref": len(s16), "len_cand": len(s8)} - sha16, sha8 = r16.get("token_sha256"), r8.get("token_sha256") - if sha16 is not None or sha8 is not None: - v16, v8 = _valid_sha256(sha16), _valid_sha256(sha8) - if v16 is None or v8 is None or v16 != v8: - return {"identical": False, "first_diff_step": None, "status": "token_sha256_mismatch", - "len_ref": len(s16), "len_cand": len(s8)} + if (sha16 is not None or sha8 is not None) and (not has_sha or v16 != v8): + return {"identical": False, "first_diff_step": None, "status": "token_sha256_mismatch", + "len_ref": len(s16), "len_cand": len(s8)} + if has_ids and has_sha and (sha256_token_ids(ids16) != v16 or sha256_token_ids(ids8) != v8): + return {"identical": False, "first_diff_step": None, "status": "token_hash_id_inconsistent", + "len_ref": len(s16), "len_cand": len(s8)} + if not has_ids and not has_sha: + return {"identical": False, "first_diff_step": None, "status": "unverified (missing token_ids and token_sha256)", + "len_ref": len(s16), "len_cand": len(s8)} if r16.get("text") != r8.get("text") or r16.get("reasoning", "") != r8.get("reasoning", ""): return {"identical": False, "first_diff_step": None, "status": "text_mismatch", "len_ref": len(s16), "len_cand": len(s8)} diff --git a/tools/tests/test_bench_prose.py b/tools/tests/test_bench_prose.py index 49fd96953a6..29c10966c38 100644 --- a/tools/tests/test_bench_prose.py +++ b/tools/tests/test_bench_prose.py @@ -103,28 +103,39 @@ def handler(_path, _body, _u=usage): def test_drafted_and_plain_pairs_share_prompt_seed_and_require_token_evidence(self): seen = [] - - def handler(_path, body): - seen.append(body) - ids = [10, 20, 30, 40] - events = [ - {"choices": [{"index": 0, "delta": {"content": "part1 "}}]}, - {"choices": [{"index": 0, "delta": {"content": "part2"}, "finish_reason": "stop"}]}, - { - "choices": [], - "usage": {"prompt_tokens": 40, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, - "tensorfold": {"token_ids": ids, "token_sha256": bench_prose.sha256_token_ids(ids)}, - }, - ] - return 200, "text/event-stream", sse_bytes(events, done=True) - - srv, th, url = start_server(handler) + ids = [10, 20, 30, 40] + sha = bench_prose.sha256_token_ids(ids) + barrier = threading.Barrier(2) + + class OverlapHandler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + seen.append(json.loads(raw.decode("utf-8"))) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + self.wfile.write(sse_bytes([{"choices": [{"index": 0, "delta": {"content": "part1 "}}]}], done=False)) + self.wfile.flush() + barrier.wait(timeout=5) + self.wfile.write(sse_bytes([ + {"choices": [{"index": 0, "delta": {"content": "part2"}, "finish_reason": "stop"}]}, + {"choices": [], "usage": {"prompt_tokens": 40, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, + "tensorfold": {"token_ids": ids, "token_sha256": sha}}, + ], done=True)) + self.wfile.flush() + + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), OverlapHandler) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() try: with tempfile.TemporaryDirectory() as td: write_books(td, ["war_and_peace", "monte_cristo"], body=None) with contextlib.redirect_stdout(io.StringIO()): report = bench_prose.run_prose_decode( - url, td, levels=(2,), gen_tokens=4, seed=777, + f"http://127.0.0.1:{srv.server_port}", td, levels=(2,), gen_tokens=4, seed=777, excerpt_specs=(("short", 120),), sources=bench_prose.DISTINCT_PROSE_8[:2], ) finally: @@ -261,6 +272,10 @@ def test_compare_prose_loss_eos_counts_token_sha256_length_and_conditional_label "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "stop", "text": "ab", "token_sha256": "a" * 64, "steps": steps2, }, + "both_missing_evidence": { + "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "stop", "text": "ab", + "steps": steps2, + }, "disjoint_case": { "prompt_tokens": 100, "completion_tokens": 1, "finish_reason": "stop", "text": "a", "token_ids": [1], "steps": [{"token": "a", "logprob": -0.2, "top": {"a": -0.2}}], @@ -282,6 +297,10 @@ def test_compare_prose_loss_eos_counts_token_sha256_length_and_conditional_label "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "stop", "text": "ab", "token_sha256": "d" * 64, "steps": steps2, }, + "both_missing_evidence": { + "prompt_tokens": 100, "completion_tokens": 2, "finish_reason": "stop", "text": "ab", + "steps": steps2, + }, "disjoint_case": { "prompt_tokens": 100, "completion_tokens": 1, "finish_reason": "stop", "text": "a", "token_ids": [1], "steps": [{"token": "a", "logprob": -0.2, "top": {"z": -0.2}}], @@ -301,11 +320,68 @@ def test_compare_prose_loss_eos_counts_token_sha256_length_and_conditional_label self.assertEqual(rep["cases"]["length_missing_step"]["status"], "incomplete_steps") self.assertFalse(rep["cases"]["sha_diff_case"]["identical"]) self.assertEqual(rep["cases"]["sha_diff_case"]["status"], "token_sha256_mismatch") + self.assertFalse(rep["cases"]["both_missing_evidence"]["identical"]) + self.assertIn("unverified", rep["cases"]["both_missing_evidence"]["status"]) self.assertIsNone(rep["cases"]["disjoint_case"]["step0_cond_kl"]) self.assertIn("step0_cond_KL=unavailable", out) self.assertIn("conditional intersection-only diagnostics", out) self.assertNotIn("PPL mult", out) + def test_serialized_streams_measure_shared_interval_and_do_not_qualify_as_concurrent(self): + serial_lock = threading.Lock() + ids = [10, 20, 30, 40] + sha = bench_prose.sha256_token_ids(ids) + + class SerialHandler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + with serial_lock: + c1 = sse_bytes([{"choices": [{"index": 0, "delta": {"content": "tok1 "}}]}], done=False) + self.wfile.write(c1) + self.wfile.flush() + time.sleep(0.05) + c2 = sse_bytes([ + {"choices": [{"index": 0, "delta": {"content": "tok2"}, "finish_reason": "stop"}]}, + {"choices": [], "usage": {"prompt_tokens": 20, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, + "tensorfold": {"token_ids": ids, "token_sha256": sha}}, + ], done=True) + self.wfile.write(c2) + self.wfile.flush() + + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SerialHandler) + th = threading.Thread(target=srv.serve_forever, daemon=True) + th.start() + try: + with tempfile.TemporaryDirectory() as td: + write_books(td, ["war_and_peace", "monte_cristo", "les_miserables", "don_quixote"], body=None) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rep = bench_prose.run_prose_decode( + f"http://127.0.0.1:{srv.server_port}", td, levels=(4,), gen_tokens=4, + excerpt_specs=(("short", 100),), sources=bench_prose.DISTINCT_PROSE_8[:4], + ) + finally: + srv.shutdown() + srv.server_close() + th.join(timeout=5) + + pair = rep["pairs"][0] + draft_arm = pair["draft"] + self.assertFalse(draft_arm["overlapped"]) + self.assertTrue(draft_arm["serialized"]) + self.assertFalse(draft_arm["concurrent_verified"]) + self.assertFalse(pair["qualified"]) + self.assertFalse(rep["qualified"]) + self.assertIn("[SERIALIZED/QUEUED]", buf.getvalue()) + per_sum = sum(r["decode_tps"] for r in draft_arm["rows"]) + self.assertLess(draft_arm["timing"]["decode_tps"], per_sum * 0.4) + def test_teacher_forced_checks_prefix_and_per_step_gt_identity(self): requests_seen = [] From 1acf0a225e22eb348a47fdbd45676957064d7b6b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:50:22 +0000 Subject: [PATCH 151/361] changelog: #4797 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fa05d3677a..bbcc33fd435 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 +- 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 4166db3ed0c98df7078af2659c80ef95c2e7b2e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:41:26 +0100 Subject: [PATCH 152/361] inkling2 cuda: split Mini's loop gate into a down half a rank pair a block and an up half a column a thread tf_ink2_loop_gate ran one block a gate row: one block read the 590 KB down matrix and the 590 KB forget/gain pair for each of the 96 gates a token. tf_ink2_loop_gate_down runs a block a row and rank pair, each with the one-block kernel's norms, 256-thread chains and reduction tree, and writes the BF16 zeta to a [rows][64] scratch; tf_ink2_loop_gate_up runs a thread a column with the same ascending rank chains, tanh and four rounding steps. tf_ink2_loop_gate stays in the image, unserved, as the contract's baseline: the halves are gated bit-equal to it. --- zig/kernels/cuda/inkling2/loop_math.cu | 85 ++++++++++++++++++- .../contract/inkling2_experts_records.zig | 2 + zig/src/families/inkling2/loop_engine.zig | 6 +- zig/src/families/inkling2/loop_math_cuda.zig | 32 +++++-- .../cuda/contract_inkling2_loop_math.zig | 43 ++++++++-- .../contract_inkling2_loop_math_extra.zig | 4 +- 6 files changed, 155 insertions(+), 17 deletions(-) diff --git a/zig/kernels/cuda/inkling2/loop_math.cu b/zig/kernels/cuda/inkling2/loop_math.cu index 824ec095042..141e558daa8 100644 --- a/zig/kernels/cuda/inkling2/loop_math.cu +++ b/zig/kernels/cuda/inkling2/loop_math.cu @@ -165,7 +165,7 @@ __device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __r } } -// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)). +// One gate a block: the frozen baseline the down/up halves are gated bit-equal against in the contract (not served). __device__ void gate(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* __restrict__ out, @@ -225,6 +225,76 @@ __device__ void gate(const float* __restrict__ h, const float* __restrict__ m, } } +// A gate's down half, a block a row and rank pair: the one-block kernel's 256-thread chains and tree, so zeta is equal. +__device__ void gateDown(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, + uint16_t* __restrict__ zeta, int c, float eps) { + __shared__ float sh[2 * 32]; + __shared__ float inv_h, inv_m; + const size_t row = blockIdx.x; + const int r = 2 * static_cast(blockIdx.y); + const float* hr = h + row * c; + const float* mr = m + row * c; + float ss[2] = {0.0f, 0.0f}; + for (int i = threadIdx.x; i < c; i += blockDim.x) { + ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]); + ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]); + } + blockSums<2>(ss, sh); + if (threadIdx.x == 0) { + inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast(c)), eps)); + inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast(c)), eps)); + } + __syncthreads(); + float acc[2] = {0.0f, 0.0f}; + const uint16_t* d0 = down + static_cast(r) * (2 * c); + const uint16_t* d1 = d0 + 2 * c; + for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) { + const bool message = i >= c; + const float x = message ? mr[i - c] : hr[i]; + const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h)); + acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]); + acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]); + } + blockSums<2>(acc, sh); + if (threadIdx.x == 0) { + zeta[row * kRank + r] = tobf(acc[0]); + zeta[row * kRank + r + 1] = tobf(acc[1]); + } +} + +// A gate's up half: a thread an output column, forget/gain FP32 through tanh (A7(a)), the same ascending rank chains. +__device__ void gateUp(const float* h, const float* __restrict__ m, const uint16_t* __restrict__ zeta, + const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* out, int c) { + __shared__ float z[kRank]; + const size_t row = blockIdx.x; + if (threadIdx.x < kRank) z[threadIdx.x] = bf(zeta[row * kRank + threadIdx.x]); + __syncthreads(); + const int i = static_cast(blockIdx.y) * blockDim.x + threadIdx.x; + if (i >= c) return; + const uint4* f = reinterpret_cast(forget + static_cast(i) * kRank); + const uint4* g = reinterpret_cast(gain + static_cast(i) * kRank); + float sf = 0.0f, sg = 0.0f; +#pragma unroll + for (int q = 0; q < kRank / 8; ++q) { + const uint4 fq = __ldg(f + q), gq = __ldg(g + q); + const uint32_t fw[4] = {fq.x, fq.y, fq.z, fq.w}, gw[4] = {gq.x, gq.y, gq.z, gq.w}; +#pragma unroll + for (int t = 0; t < 8; ++t) { + const float zr = z[8 * q + t]; + const uint16_t fb = static_cast(fw[t >> 1] >> (16 * (t & 1))); + const uint16_t gb = static_cast(gw[t >> 1] >> (16 * (t & 1))); + sf = __fmaf_rn(bf(fb), zr, sf); + sg = __fmaf_rn(bf(gb), zr, sg); + } + } + const float fg = tanhf(sf), gg = tanhf(sg); + // The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them. + const float keep = __fsub_rn(1.0f, fg); + const float old = __fmul_rn(keep, h[row * c + i]); + const float added = __fmul_rn(gg, m[row * c + i]); + out[row * c + i] = __fadd_rn(old, added); +} + } // namespace ink2l extern "C" __global__ void __launch_bounds__(256) @@ -242,6 +312,19 @@ extern "C" __global__ void __launch_bounds__(256) ink2l::gate(h, m, down, forget, gain, out, c, eps); } +// Gate down: grid (rows, 32 rank pairs). Gate up: grid (rows, c / 64); it may write `out` in place of h. +extern "C" __global__ void __launch_bounds__(256) + tf_ink2_loop_gate_down(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down, + uint16_t* __restrict__ zeta, int c, float eps) { + ink2l::gateDown(h, m, down, zeta, c, eps); +} + +extern "C" __global__ void __launch_bounds__(64) + tf_ink2_loop_gate_up(const float* h, const float* __restrict__ m, const uint16_t* __restrict__ zeta, + const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* out, int c) { + ink2l::gateUp(h, m, zeta, forget, gain, out, c); +} + // Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged. extern "C" __global__ void __launch_bounds__(256) tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk, diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 20b0945515a..4e7ce7fe127 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -18,6 +18,8 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 32, .static = 272, .bound = 256 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 31, .static = 264, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_up", .symbol = "tf_ink2_loop_gate_up", .image = "inkling2_loop_math", .threads = 64, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 256, .bound = 64 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, }; diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig index c04446872e6..18f86678002 100644 --- a/zig/src/families/inkling2/loop_engine.zig +++ b/zig/src/families/inkling2/loop_engine.zig @@ -66,6 +66,7 @@ const Scratch = struct { bank0: u64, bank1: u64, raw: u64, // three FP32 AR/gate rows per token + zeta: u64, // a gate's 64 BF16 bottleneck values per token, between its down and up halves messages: u64, // four FP32 message rows per token normalized: u64, // three BF16 rows per token t: u64, @@ -245,6 +246,7 @@ pub const Model = struct { .bank0 = try m.alloc(rows * h * 2), .bank1 = try m.alloc(rows * h * 2), .raw = try m.alloc(3 * rows * h * 4), + .zeta = try m.alloc(rows * loop_math.rank * 2), .messages = try m.alloc(4 * rows * h * 4), .normalized = try m.alloc(3 * rows * h * 2), .t = try m.alloc(rows * h * 4), @@ -389,7 +391,7 @@ pub const Model = struct { } for (0..3) |role| { const ctl = lw.controllers[role]; - try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps); + try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.zeta, m.s.raw + role * raw_stride, rows, h, c.eps); const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] }; try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows)); } @@ -474,7 +476,7 @@ pub const Model = struct { if (messages) { try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows)); const ctl = lw.controllers[3]; - try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps); + try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.zeta, m.s.raw, rows, h, c.eps); try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); } else { try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows)); diff --git a/zig/src/families/inkling2/loop_math_cuda.zig b/zig/src/families/inkling2/loop_math_cuda.zig index 9a0d4cc4b63..7e63149a608 100644 --- a/zig/src/families/inkling2/loop_math_cuda.zig +++ b/zig/src/families/inkling2/loop_math_cuda.zig @@ -24,7 +24,8 @@ pub const Kernels = struct { mod: cuda.Module, ar_fn: cuda.Function, messages_fn: cuda.Function, - gate_fn: cuda.Function, + gate_down_fn: cuda.Function, + gate_up_fn: cuda.Function, project_qkv_fn: cuda.Function, round_bf16_fn: cuda.Function, @@ -36,7 +37,8 @@ pub const Kernels = struct { .mod = mod, .ar_fn = try mod.function("tf_ink2_loop_ar"), .messages_fn = try mod.function("tf_ink2_loop_messages"), - .gate_fn = try mod.function("tf_ink2_loop_gate"), + .gate_down_fn = try mod.function("tf_ink2_loop_gate_down"), + .gate_up_fn = try mod.function("tf_ink2_loop_gate_up"), .project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"), .round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"), }; @@ -87,7 +89,7 @@ pub fn messages( try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a); } -/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch. +/// Controller: BF16 D/F/G, FP32 F/G dots/tanh/four-step output; zeta [rows][64] BF16 scratch; out may alias state. pub fn gate( k: *const Kernels, s: cuda.Stream, @@ -96,17 +98,33 @@ pub fn gate( down_bf16: u64, forget_bf16: u64, gain_bf16: u64, + zeta_bf16: u64, out_f32: u64, rows: usize, c: usize, eps: f32, ) !void { - if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; + try gateDown(k, s, state_f32, message_f32, down_bf16, zeta_bf16, rows, rank / 2, c, eps); + try gateUp(k, s, state_f32, message_f32, zeta_bf16, forget_bf16, gain_bf16, out_f32, rows, c); +} + +/// The down half alone: `pairs` rank pairs from the first (all 32 in `gate`; fewer only for a contract control). +pub fn gateDown(k: *const Kernels, s: cuda.Stream, state_f32: u64, message_f32: u64, down_bf16: u64, zeta_bf16: u64, rows: usize, pairs: usize, c: usize, eps: f32) !void { + if (rows == 0 or c == 0 or pairs == 0 or pairs > rank / 2) return error.Inkling2LoopGateShape; var a: cuda.Args = .{}; - for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); - for ([_]i32{ int(rows), int(c) }) |v| a.add(v); + for ([_]u64{ state_f32, message_f32, down_bf16, zeta_bf16 }) |v| a.add(v); + a.add(int(c)); a.add(eps); - try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a); + try go(k.gate_down_fn, s, .{ .x = @intCast(rows), .y = @intCast(pairs) }, 256, &a); +} + +/// The up half: forget/gain from zeta and the four-step output, 64 columns a block. +pub fn gateUp(k: *const Kernels, s: cuda.Stream, state_f32: u64, message_f32: u64, zeta_bf16: u64, forget_bf16: u64, gain_bf16: u64, out_f32: u64, rows: usize, c: usize) !void { + if (rows == 0 or c == 0) return error.Inkling2LoopGateShape; + var a: cuda.Args = .{}; + for ([_]u64{ state_f32, message_f32, zeta_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v); + a.add(int(c)); + try go(k.gate_up_fn, s, .{ .x = @intCast(rows), .y = @intCast((c + 63) / 64) }, 64, &a); } /// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history. diff --git a/zig/tests/cuda/contract_inkling2_loop_math.zig b/zig/tests/cuda/contract_inkling2_loop_math.zig index bef2f7d69ef..ab7c93a0830 100644 --- a/zig/tests/cuda/contract_inkling2_loop_math.zig +++ b/zig/tests/cuda/contract_inkling2_loop_math.zig @@ -1,5 +1,6 @@ //! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls. const std = @import("std"); +const cuda = @import("cuda"); const core = @import("core"); const ink = @import("inkling2"); const rig_ = @import("contract_rig.zig"); @@ -54,6 +55,10 @@ pub fn Checked(comptime T: type) type { try self.inner.simulate(acc, order, out); } + pub fn replaced(self: *Self) ![]const u8 { + return self.inner.replaced(); + } + pub fn check(self: *Self, _: g.Gate) !?[]const u8 { const a = self.rig.gpu.gpa; const got = try a.dupe(u8, try self.rig.outputBytes()); @@ -317,10 +322,13 @@ const gate_shapes = [_]c.Shape{ .{ .rows = 2048, .n = 128, .k = 256 }, }; -/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain. +/// The served gate, or a control: forget weights again for gain (up half), or zeta from half the rank pairs (down). +pub const GateFault = enum { none, wrong_gain, half_ranks }; + +/// Host reference preserves BF16 n/zeta and all four FP32 output steps through both halves' launches. pub const Gate = struct { kern: *const lm.Kernels, - wrong_gain: bool = false, + fault: GateFault = .none, shape: c.Shape = undefined, h: []f32 = &.{}, m: []f32 = &.{}, @@ -328,10 +336,18 @@ pub const Gate = struct { f: []u16 = &.{}, gain: []u16 = &.{}, dev: [5]u64 = @splat(0), + zeta: u64 = 0, out: u64 = 0, + base: u64 = 0, pub fn spec(self: *const Gate) c.Spec { - return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes }; + const name = switch (self.fault) { + .none => "inkling2 loop tf_ink2_loop_gate_down + _up (BF16 down input/zeta, FP32 F/G tanh and four output steps)", + .wrong_gain => "control: inkling2 loop rank-64 gate up half with forget weights again instead of gain", + .half_ranks => "control: inkling2 loop rank-64 gate down half launched for 16 of its 32 rank pairs", + }; + const served = if (self.fault != .none) gate_shapes[0..2] else &gate_shapes; + return .{ .name = name, .accum = .f32, .depth = depth, .out = .f32, .served = served, .replaces = "tf_ink2_loop_gate" }; } fn depth(s: c.Shape) usize { @@ -339,7 +355,7 @@ pub const Gate = struct { } pub fn control(self: *const Gate) ?g.Gate { - return if (self.wrong_gain) .shapes else null; + return if (self.fault != .none) .shapes else null; } pub fn free(self: *Gate, a: std.mem.Allocator) void { @@ -377,12 +393,29 @@ pub const Gate = struct { ref.plant(f32, self.m, shape.rows, cols, ref.asF32); } self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) }; + self.zeta = try rig.scratch(shape.rows * lm.rank * 2); + self.base = try rig.scratch(shape.rows * cols * 4); self.out = try rig.output(shape.rows * cols * 4); return true; } pub fn run(self: *Gate, rig: *rig_.Rig) !void { - try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps); + const d = self.dev; + const rows = self.shape.rows; + const pairs: usize = if (self.fault == .half_ranks) lm.rank / 4 else lm.rank / 2; + try lm.gateDown(self.kern, rig.s, d[0], d[1], d[2], self.zeta, rows, pairs, self.shape.n, eps); + try lm.gateUp(self.kern, rig.s, d[0], d[1], self.zeta, d[3], if (self.fault == .wrong_gain) d[3] else d[4], self.out, rows, self.shape.n); + } + + /// The one-block tf_ink2_loop_gate the served halves replace, on the same inputs: gate 3 wants its bytes. + pub fn replaced(self: *Gate, rig: *rig_.Rig) ![]const u8 { + const f = try self.kern.mod.function("tf_ink2_loop_gate"); + var a: cuda.Args = .{}; + for ([_]u64{ self.dev[0], self.dev[1], self.dev[2], self.dev[3], self.dev[4], self.base }) |v| a.add(v); + for ([_]i32{ @intCast(self.shape.rows), @intCast(self.shape.n) }) |v| a.add(v); + a.add(@as(f32, eps)); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(self.shape.rows) }, .block = .{ .x = 256 } }, rig.s, &a); + return rig.bytes(self.base, self.shape.rows * self.shape.n * 4); } pub fn count(self: *const Gate) usize { diff --git a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig index 49bd3ae650e..8eae8b64cce 100644 --- a/zig/tests/cuda/contract_inkling2_loop_math_extra.zig +++ b/zig/tests/cuda/contract_inkling2_loop_math_extra.zig @@ -399,7 +399,7 @@ pub const Set = struct { k: lm.Kernels = undefined, loaded: bool = false, messages: [2]K(Messages) = undefined, - gates: [2]K(Gate) = undefined, + gates: [3]K(Gate) = undefined, qkvs: [2]K(ProjectQkv) = undefined, ars: [3]K(Ar) = undefined, rounds: [2]K(RoundBf16) = undefined, @@ -410,7 +410,7 @@ pub const Set = struct { const k = &set.k; const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; for (&set.messages, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .aliased = i == 1 } } }; - for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .wrong_gain = i == 1 } } }; + for (&set.gates, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .fault = @fromBackingInt(@intCast(i)) } } }; for (&set.qkvs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .shared_input = i == 1 } } }; for (&set.ars, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .partial_bf16 = i == 1, .short = i == 2 } } }; for (&set.rounds, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } } }; From de85eef741a1bb5bd25a1fad349b93bf34811f81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:17:45 +0100 Subject: [PATCH 153/361] inkling2 cuda: the gate halves' compiled usage on sm_80, 86, 89 and 120 too nvcc 13.0 -cubin -O3 --resource-usage per SM, as the image builds them: tf_ink2_loop_gate_down 22/24/24/32 registers, tf_ink2_loop_gate_up 38/70/46/46, static shared bytes and launch bounds as on sm_121, no stack or spills. The two launches admit sm_80 onward, so the registry check now has their numbers on every pinned SM. --- zig/src/core/contract/inkling2_experts_records.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 4e7ce7fe127..092e5b4e30a 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -18,8 +18,8 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 32, .static = 272, .bound = 256 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 31, .static = 264, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_up", .symbol = "tf_ink2_loop_gate_up", .image = "inkling2_loop_math", .threads = 64, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 46, .static = 256, .bound = 64 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 22, .static = 264, .bound = 256 }, .{ .regs = 24, .static = 264, .bound = 256 }, .{ .regs = 24, .static = 264, .bound = 256 }, .{ .regs = 32, .static = 264, .bound = 256 }, .{ .regs = 31, .static = 264, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_up", .symbol = "tf_ink2_loop_gate_up", .image = "inkling2_loop_math", .threads = 64, .min_sm = 80 }, .usage = .{ .{ .regs = 38, .static = 256, .bound = 64 }, .{ .regs = 70, .static = 256, .bound = 64 }, .{ .regs = 46, .static = 256, .bound = 64 }, .{ .regs = 46, .static = 256, .bound = 64 }, .{ .regs = 46, .static = 256, .bound = 64 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true }, }; From eeeee2488c03238bec470473529c2e17d2704494 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:16:43 +0000 Subject: [PATCH 154/361] changelog: #4697 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbcc33fd435..18da2d1d366 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 +- Inkling 2 Mini on CUDA: the loop gate runs as a down half and an up half, so one-stream decode is about 28% faster on GB10 with identical tokens (#4697). Thanks @jschmied. + - 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 41cb783b27a3d2285e6feda09f72551cbf3c8689 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:16:43 +0000 Subject: [PATCH 155/361] changelog: #4697 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18da2d1d366..61861a74e37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on CUDA: the loop gate runs as a down half and an up half, so one-stream decode is about 28% faster on GB10 with identical tokens (#4697). Thanks @jschmied. + + - 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 eea0560bb47a8ab9006d6d6fc6b1dd59ca875c43 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:31:21 +0000 Subject: [PATCH 156/361] server inkling2: thinking off reaches the template as reasoning_effort "none" Inkling 2's chat template has no enable_thinking. Its only thinking control is reasoning_effort, a level from "none" (0) to "max", 0.9 when unset. The server passed enable_thinking: false through as the template's enable_thinking, which the template never reads, and no reasoning_effort, so a thinking-off request rendered "Thinking effort level: 0.9", byte for byte the prompt of a thinking-on request. With the native Inkling 2 template, the server's thinking-off effort is now "none", the template's own off: a thinking-off chat renders "Thinking effort level: 0", and a request that names an effort keeps that level. Every other template's thinking-off effort is unchanged. --- zig/src/server/inkling2_chat_test.zig | 10 ++-- zig/src/server/inkling2_required_test.zig | 1 + zig/src/server/inkling2_thinking_test.zig | 56 +++++++++++++++++++++++ zig/src/server/server.zig | 4 +- 4 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 zig/src/server/inkling2_thinking_test.zig diff --git a/zig/src/server/inkling2_chat_test.zig b/zig/src/server/inkling2_chat_test.zig index 8f1998eaf8c..9c12a5133b3 100644 --- a/zig/src/server/inkling2_chat_test.zig +++ b/zig/src/server/inkling2_chat_test.zig @@ -11,12 +11,12 @@ const sample = "<|message_model|><|content_thinking|>The user asks: ... 340 + 51 const thought = "The user asks: ... 340 + 51 = 391. ... "; /// The committed release tokenizer and template, with only the served model type changed by a case. -const Fixture = struct { +pub const Fixture = struct { tmp: std.testing.TmpDir, path: [:0]u8, /// `kind` "release": the Mini checkpoint's own config.json, tokenizer_config.json and chat template. - fn init(a: std.mem.Allocator, kind: []const u8) !Fixture { + pub fn init(a: std.mem.Allocator, kind: []const u8) !Fixture { var tmp = std.testing.tmpDir(.{}); errdefer tmp.cleanup(); const release = std.mem.eql(u8, kind, "release"); @@ -43,20 +43,20 @@ const Fixture = struct { return .{ .tmp = tmp, .path = try tmp.dir.realPathFileAlloc(t.io, ".", a) }; } - fn deinit(f: *Fixture) void { + pub fn deinit(f: *Fixture) void { f.tmp.cleanup(); } }; /// Answers `reply` in chunks of `stride` tokens. -const Script = struct { +pub const Script = struct { a: std.mem.Allocator, reply: []const u32, stride: usize, lane: bool = false, eos_len: usize = 0, // the request's end ids, as the engine got them - fn engine(s: *@This()) api.Engine { + pub fn engine(s: *@This()) api.Engine { return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; } fn info(_: *anyopaque) api.Info { diff --git a/zig/src/server/inkling2_required_test.zig b/zig/src/server/inkling2_required_test.zig index b8ff1efe5b8..29a6437457c 100644 --- a/zig/src/server/inkling2_required_test.zig +++ b/zig/src/server/inkling2_required_test.zig @@ -177,4 +177,5 @@ test "Inkling 2 reply: a json_schema reply ends on the same token ids as before test { _ = @import("inkling2_stop_test.zig"); + _ = @import("inkling2_thinking_test.zig"); } diff --git a/zig/src/server/inkling2_thinking_test.zig b/zig/src/server/inkling2_thinking_test.zig new file mode 100644 index 00000000000..9aec1d86661 --- /dev/null +++ b/zig/src/server/inkling2_thinking_test.zig @@ -0,0 +1,56 @@ +//! Inkling 2's thinking off reaches its template as reasoning_effort "none": effort level 0, not its default 0.9. +const std = @import("std"); +const json = @import("json"); +const h = @import("inkling2_chat_test.zig"); +const HfText = @import("hf_text.zig").HfText; +const Server = @import("server.zig").Server; +const prompt_mod = @import("prompt.zig"); +const errors = @import("errors.zig"); +const t = std.testing; + +const talk = "[{\"role\":\"user\",\"content\":\"Hi\"}]"; + +/// The prompt a chat renders to on the `kind` fixture, decoded, and the server's thinking-off effort. +fn rendered(a: std.mem.Allocator, kind: []const u8, thinking: bool, named: ?[]const u8) !struct { text: []const u8, off: ?[]const u8 } { + var fx = try h.Fixture.init(a, kind); + defer fx.deinit(); + var problem: []const u8 = ""; + const hf = try HfText.load(a, t.io, fx.path, null, a, &problem); + defer hf.deinit(); + var script: h.Script = .{ .a = a, .reply = &.{}, .stride = 1 }; + const srv = try Server.init(a, t.io, script.engine(), hf.text(), .{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }, null); + defer srv.deinit(); + var cx: errors.Cx = .{ .a = a }; + cx.named_effort = named; // chat.zig's: the request's named effort, none of it for "none" + const r = try prompt_mod.prepare(srv, &cx, .{ .messages = (try json.parse(a, talk)).ok, .fields = .null }, thinking, null); + return .{ .text = try srv.text.decode(a, r.ids), .off = srv.off_effort }; +} + +test "Inkling 2 reply: thinking off renders the template's effort level 0, thinking on its default 0.9" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const off = try rendered(a, "release", false, null); + const on = try rendered(a, "release", true, null); + try t.expect(std.mem.indexOf(u8, off.text, "Thinking effort level: 0<|end_message|>") != null); + try t.expect(std.mem.indexOf(u8, on.text, "Thinking effort level: 0.9<|end_message|>") != null); + // the two prompts differ only in that level + const same = try std.mem.replaceOwned(u8, a, on.text, "level: 0.9<", "level: 0<"); + try t.expectEqualStrings(off.text, same); +} + +test "Inkling 2 reply: thinking off with a named effort keeps that level" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const low = try rendered(a, "release", false, "low"); + try t.expect(std.mem.indexOf(u8, low.text, "Thinking effort level: 0.2<|end_message|>") != null); +} + +test "Inkling 2 reply: another model type keeps no thinking-off effort" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try t.expectEqualStrings("none", (try rendered(a, "release", false, null)).off.?); + try t.expect((try rendered(a, "llama", false, null)).off == null); +} diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 547b3b26dfd..84f0bab330e 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -70,7 +70,7 @@ pub const Server = struct { close_id: ?u32 = null, // the close marker's own token, when the marker is one token chunks: chunk_plan.Plan = .{}, effort_levels: []const []const u8 = &.{}, - /// The effort a recipient template hears with thinking off: it has no switch, so its lowest level, not its default. + /// The effort a template with no thinking switch hears with thinking off: its lowest level, not its default. off_effort: ?[]const u8 = null, thinking_switch: bool = false, video_decoder: bool = false, // libtfvideo loaded in `init`: with the video offer it decides video input (#3004) @@ -158,6 +158,8 @@ pub const Server = struct { const source = text.templateSource(); srv.effort_levels = try fields.effortLevels(a, source); if (srv.recipients and srv.effort_levels.len > 0) srv.off_effort = fields.coerceEffort("minimal", srv.effort_levels); + // Inkling 2's template has no enable_thinking: its off is reasoning_effort "none" (effort level 0) + if (@import("chat_inkling2.zig").enabled(srv)) srv.off_effort = "none"; // MiniMax-M3's template decides on its own; thinking off closes the block in the prompt (prompt.zig) srv.thinking_switch = minimax or std.mem.indexOf(u8, source, "enable_thinking") != null or std.mem.indexOf(u8, source, "thinking_mode") != null; From e3c6f79bacef0a50bdc8ca9a9c1e9abf300f7a27 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:16:44 +0000 Subject: [PATCH 157/361] changelog: #4876 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61861a74e37..7e4ae3e8913 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 +- Inkling 2 Mini: `enable_thinking: false` and `reasoning_effort: "none"` now reach the chat template as thinking effort 0 instead of the default 0.9; thinking-on replies are unchanged (#4876). + - Inkling 2 Mini on CUDA: the loop gate runs as a down half and an up half, so one-stream decode is about 28% faster on GB10 with identical tokens (#4697). Thanks @jschmied. From b4779ced0ebf51abddd10f4370cca6c51baa9aff Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:07:22 -0600 Subject: [PATCH 158/361] ricursive: the publisher's DFlash2 drafter --- THIRD_PARTY_NOTICES.md | 1 + docs/recipes/ripple-65b-metal.md | 73 ++- zig/kernels/metal/ricursive/dflash2.metal | 273 +++++++++ zig/kernels/metal/sources.zig | 2 + zig/src/core/contract/ricursive_records.zig | 14 +- zig/src/families/ricursive/backend.zig | 111 +++- zig/src/families/ricursive/contracts.zig | 21 +- zig/src/families/ricursive/dflash2.zig | 440 ++++++++++++++ zig/src/families/ricursive/dflash2_config.zig | 255 +++++++++ .../ricursive/fixtures/dflash2_config.json | 65 +++ zig/src/families/ricursive/forward.zig | 72 ++- zig/src/families/ricursive/model.zig | 25 + zig/src/families/ricursive/ricursive.zig | 3 + zig/src/families/ricursive/state.zig | 9 + zig/src/families/ricursive/weights.zig | 4 +- zig/src/native/metal.zig | 2 +- zig/src/native/ricursive.zig | 67 ++- zig/tests/contract/metal_ricursive_all.zig | 65 ++- .../contract/metal_ricursive_controls.zig | 43 ++ .../contract/metal_ricursive_dflash2.zig | 534 +++++++++++++++++ .../contract/metal_ricursive_dflash2_act.zig | 230 ++++++++ .../contract/metal_ricursive_dflash2_attn.zig | 539 ++++++++++++++++++ .../contract/metal_ricursive_dflash2_pick.zig | 385 +++++++++++++ 23 files changed, 3173 insertions(+), 60 deletions(-) create mode 100644 zig/kernels/metal/ricursive/dflash2.metal create mode 100644 zig/src/families/ricursive/dflash2.zig create mode 100644 zig/src/families/ricursive/dflash2_config.zig create mode 100644 zig/src/families/ricursive/fixtures/dflash2_config.json create mode 100644 zig/tests/contract/metal_ricursive_dflash2.zig create mode 100644 zig/tests/contract/metal_ricursive_dflash2_act.zig create mode 100644 zig/tests/contract/metal_ricursive_dflash2_attn.zig create mode 100644 zig/tests/contract/metal_ricursive_dflash2_pick.zig diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index f1d1cade953..bb3efe49a8f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -333,6 +333,7 @@ These follow a model's release code or a library's model code for their math, ro - `tools/lfm3/ref64.py` and `zig/kernels/xpu/lfm3.cl`: `modeling_lfm3.py` in [LiquidAI/LFM3-1.7B](https://huggingface.co/LiquidAI/LFM3-1.7B). Copyright Liquid AI, LFM Open License v1.0; see [the license text](LICENSES/LFM-Open-1.0.txt). - `zig/kernels/metal/minimax_m3/glue.metal`: the rounding points of `modeling_minimax_m3_vl.py` in [transformers](https://github.com/huggingface/transformers). - `zig/src/families/ricursive/` (its layer order and rounding points), `zig/kernels/metal/ricursive/glue.metal`, `zig/kernels/cuda/ricursive.cu`, `ricursive.cuh`, `ricursive_prep.cu`, `ricursive_prep.cuh` and `tools/zig/ricursive_reference.py`: `modeling_ricursive.py` in [ricursiveAI/Ripple-65B-Preview](https://huggingface.co/ricursiveAI/Ripple-65B-Preview) at revision `240d5966cbe00f0627c699e59ef58560b60303cf`: the scaled embedding, the value residual, the per-head q/k norms, RoPE on sliding layers only, the fp32 sigmoid gate, the clamped SwiGLU and the four norms a layer. The release's SGLang model `inference/server/model.py` computes the same layers; what is in it alone is its serving (the W4A4 kernels, the capture of hidden states for a drafter), which this family does not take. Copyright ricursiveAI, Apache License 2.0; see [the license text](LICENSES/Apache-2.0.txt). The reference's `--release` and `--release-f64` modes import the release's own `modeling_ricursive.py` from the checkpoint at run time; TensorFold does not include it. +- `zig/src/families/ricursive/dflash2.zig` and `zig/kernels/metal/ricursive/dflash2.metal` (the DFlash2 drafter for ricursiveAI/Ripple-65B-Preview-DFlash2): `DFlash2DraftModel`, `GroupedDynamicCausalConv` and `CandidateSelector` in `dflash/model.py` of [z-lab/dflash](https://github.com/z-lab/dflash) at revision `07ebd93db9f472af339b644bb70221ad8428328a`, MIT License, Copyright © 2026 Z Lab, with its `apply_rotary_pos_emb`'s rounding points; the RMSNorm, rotary cos and sin, and SiLU MLP of the release's `modeling_ricursive.py` above (`RicursiveRMSNorm`, `RicursiveRotaryEmbedding`, `RicursiveMLP`), at the drafter's config. The target's taps are the hidden states `extract_context_feature` in that `model.py` takes (`hidden_states[layer_id + 1]`), here of `modeling_ricursive.py`'s `output_hidden_states`: a tapped layer's output, before the final norm. The NoPE layer is `no_rope_layers` in the drafter's `config.json` ([ricursiveAI/Ripple-65B-Preview-DFlash2](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-DFlash2) at revision `35609b3be3dd08a822b3ba1257c1ea5dd6f87632`, Apache License 2.0); `zig/src/families/ricursive/fixtures/dflash2_config.json` is that `config.json`, unchanged. The 16,384-token draft window is from `inference/server/README.md` in the release above. - `zig/src/vision/qwen_cuda.zig`: `Qwen3_5VisionModel` in transformers. - `zig/src/core/picture/patches_test.zig`: recorded image-processor output data from `Lfm3VlImageProcessor` and `Qwen2VLImageProcessor` in transformers; the processing implementation is described below. - `zig/src/families/flashnext/rotary_config.zig`: `_compute_yarn_parameters` in transformers, for the 64 rotary dims. diff --git a/docs/recipes/ripple-65b-metal.md b/docs/recipes/ripple-65b-metal.md index 038d7d0f8a8..fc21a3e533e 100644 --- a/docs/recipes/ripple-65b-metal.md +++ b/docs/recipes/ripple-65b-metal.md @@ -11,6 +11,11 @@ converted: - [`ricursiveAI/Ripple-65B-Preview`](https://huggingface.co/ricursiveAI/Ripple-65B-Preview) (revision `240d5966cbe00f0627c699e59ef58560b60303cf`, 121 GiB): the bf16 release, the exact model. +The publisher's DFlash2 drafter, +[`ricursiveAI/Ripple-65B-Preview-DFlash2`](https://huggingface.co/ricursiveAI/Ripple-65B-Preview-DFlash2) (revision +`35609b3be3dd08a822b3ba1257c1ea5dd6f87632`, 7.5 GiB, bf16), drafts for either release with `--drafter`; a drafted +reply equals the plain one bit for bit. + It was brought up on an M5 Ultra (256 GB); other Macs are untested. Prompts run on Metal 4 tensor units, so it needs an M5 or later: M1 to M4 Macs are refused by name at load. Other `ricursive` checkpoints, and either release quantized any other way, are refused by name. @@ -26,6 +31,13 @@ zig-out/native/bin/tensorfold-native serve models/ripple-65b-nvfp4 --name ripple --context 262144 --parallel 2 ``` +With the drafter (`hf download ricursiveAI/Ripple-65B-Preview-DFlash2 --revision +35609b3be3dd08a822b3ba1257c1ea5dd6f87632 --local-dir models/ripple-65b-dflash2`), add `--drafter +models/ripple-65b-dflash2`. It takes 7.7 GiB (its weights and its rings). With the drafter the server opens two +streams when `--parallel` is not named and refuses a named `--parallel` above 2 by name: each stream's block is its +own pass through the drafter, so at four streams drafted ties plain except on lists, and at seven it is slower on +every kind (the table under the drafter's speed below). + The bf16 release serves the same way from its own directory. A stream's caches take 16.75 GiB at 262,144 tokens: 64 of the 80 layers slide over 1,024 keys and keep a 3,072-slot ring each (the window and a 2,048-row prompt chunk); every fifth layer is global and keeps every key, in bf16. Under the default load limit (75% of RAM) a 256 GB @@ -55,6 +67,16 @@ model computes the same layers): - **Attention.** Prompt chunks on the tensor units over the sliding ring or every key (`attention_nax.metal`); decode rows over key blocks at absolute positions, so a row's bits never depend on the rows beside it. - **Serving.** The lane host's shared rounds, greedy or `tf_sample_full` draws, copy drafts, the prompt cache. +- **DFlash2 drafter** (`dflash2.zig`, `kernels/metal/ricursive/dflash2.metal`), as z-lab's `DFlash2DraftModel` + (`dflash/model.py`) defines it, with the release's own RMSNorm, rotary and SiLU MLP (`modeling_ricursive.py`), the + NoPE layer of the drafter's `config.json` (`no_rope_layers: [4]`) and the draft window of ricursiveAI's + `inference/server/README.md`. The target writes the residual after layers 1, 20, 39, 58 and 77; the drafter folds + the five into one row (`fc`, then a norm) and keeps its five layers' keys and values from it, in bf16 rings: four + layers slide over 4,096 keys, the fifth (NoPE) over the release's 16,384-key draft window. A round runs a 16-row block + (the pending token and 15 masks) through its layers, each with its causal convolutions (4 taps, per-row kernels) + around attention and the MLP, reads the target's head on the 15 mask rows, keeps each row's 32 best tokens, and walks + them with the selector's codebooks (rank 256) to the draft. The lane core verifies each draft in one target window, so + a reply equals the plain one; the drafter only changes how many tokens a round keeps. **Activations stay bf16.** The publisher serves the NVFP4 release with SGLang's `flashinfer_cutlass`, which also quantizes activations to fp4 (W4A4). TensorFold does not run reduced-precision activations, so the engine serves the @@ -156,14 +178,61 @@ against 7.5 s cold, with the same reply as on a restarted server. back exactly; the cold prompts take 273 s and 790 s to the first token. The bf16 release found it too, at 120k and 258k tokens. +With the DFlash2 drafter (5 Nov 2026, the NVFP4 release, the same settings plus `--drafter`; speed run with no other +model busy; a local build of `a869c4f32`): + +| streams | prose | code | structured | list | first token | a round | +|---:|---:|---:|---:|---:|---:|---:| +| 1 | 15.5 | 27.5 | 17.8 | 19.8 | 0.53-0.65 s | 131.2 ms | +| 2 | 22.5 | 37.7 | 26.6 | 40.6 | 0.82-0.98 s | 166.2 ms | + +1.5 to 2.7 times one plain stream, 1.2 to 2.16 times two. A round keeps 2.65 tokens on average with one stream (48% of +its drafted tokens accepted) and 2.65 with two (56%). The drafted serving checks equal the plain ones: drafted == plain +12/12 in the drafts suite and 12/12 under structured output, seeded sampling 9/9, the soak 60/60, concurrent 12/12, +structured 18/18, tools 5/5, and a resumed turn equal to the cold one (0.59 s against 7.8 s). + +Past two streams the drafter gains little (6 Nov 2026, the NVFP4 release, `--context 262144 --parallel 7`, one local +build of `e1d719275` with and without `--drafter`, no other model busy; tokens a second, all streams together): + +| streams | prose | code | structured | list | a round | +|---:|---:|---:|---:|---:|---:| +| 4, plain | 32.6 | 31.8 | 31.1 | 32.5 | 126.2 ms | +| 4, drafted | 30.3 | 32.0 | 31.3 | 43.1 | 277.6 ms | +| 7, plain | 43.2 | 42.9 | 41.6 | 43.4 | 165.5 ms | +| 7, drafted | 40.2 | 34.7 | 22.9 | 34.1 | 406.4 ms | + +Each stream's block is its own pass through the drafter, so a round grows with the streams while the tokens it keeps +fall (2.35 tokens a round at four, 1.89 at seven). At four it ties plain except on lists; at seven it is slower on +every kind. With `--drafter`, the server opens two streams unless `--parallel` is named, and refuses a named +`--parallel` above 2 by name. + +With the bf16 release (6 Nov 2026, `--context 262144 --parallel 2`, greedy 256-token replies, no other model busy; one +local build of `b7ff7854f` with and without `--drafter`): + +| streams | prose | code | structured | list | first token | a round | +|---:|---:|---:|---:|---:|---:|---:| +| 1, plain | 6.4 | 6.4 | 6.4 | 6.4 | 0.52-1.20 s | 157.2 ms | +| 1, drafted | 13.4 | 30.7 | 13.3 | 18.7 | 0.39-1.06 s | 154.0 ms | + +2.1 to 4.8 times plain with one stream; a round keeps 2.93 tokens. Drafted == plain 12/12 beside the bf16 release. + +Two drafted streams beside the bf16 release do not decode together on a 256 GB M5 Ultra. With the drafter the server +keeps 129.5 GiB wired beside 60.5 GiB of caches, and macOS reports memory pressure as soon as it has loaded (22% free, +against 27% for the plain server); the engine then admits a stream only when none runs. A second request waits for the +first reply (queued 5.4 to 14.0 s in the server's log), so the two-stream ruler cells measured one stream at a time, +with first tokens of 3.24 to 7.98 s; they are left out of the table. Plain, two bf16 streams decode together (13.4 to +13.7 tokens a second in all, 0.79 to 1.78 s to the first token). + ## Not done No quality suite was run. Contexts past 258,039 tokens were not run, so `--context` stops at 262,144 and refuses the card's 1M by name. Ripple's think markers are spelled from several tokens, not one each, so a thinking budget (which forces a close) and logprobs (which cut the reply at its close token) are refused by name, and a reply's -`reasoning_tokens` reads 0. The family has no draft head: drafts come only from the lane core's copies. No images: +`reasoning_tokens` reads 0. No images: Ripple has no vision tower. Only the M5's tensor units were checked; M1 to M4 Macs are refused at load, and smaller -RAM is untested. The publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) is not served yet. +RAM is untested. Beside the bf16 release the drafter was checked for drafted == plain and one stream's speed only (two +drafted streams run one at a time there, see above); its structured output, seeded sampling, soak and resumed turns were +run beside the NVFP4 release. ## Licence diff --git a/zig/kernels/metal/ricursive/dflash2.metal b/zig/kernels/metal/ricursive/dflash2.metal new file mode 100644 index 00000000000..2229ae299f6 --- /dev/null +++ b/zig/kernels/metal/ricursive/dflash2.metal @@ -0,0 +1,273 @@ +// Ripple's DFlash2 drafter (z-lab's DFlash2DraftModel) and the target's taps: 16-row blocks over 5 tapped layers. +#include +using namespace metal; + +#define TF_UNROLL_4 _Pragma("clang loop unroll(full)") + +// The target's residual after a tapped layer, every row, into the features: row r's tap `at` of `taps`. +struct rc_tap_args { uint rows, width, taps, at; }; + +[[kernel]] void rc_tap(const device bfloat* R [[buffer(0)]], constant rc_tap_args& a [[buffer(1)]], + device bfloat* F [[buffer(2)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + F[((size_t)p.y * a.taps + a.at) * a.width + p.x] = R[(size_t)p.y * a.width + p.x]; +} + +struct rc_df_norm_args { uint rows, width; float eps; uint add; }; + +// RicursiveRMSNorm at rms_norm_eps, bf16(w * bf16(x * rsqrt(mean(x^2) + eps))); a.add first takes bf16(R + X). +inline void rc_df_norm_row(device float* x, const device bfloat* w, uint width, float eps, device bfloat* out, + uint t, uint n, threadgroup float* part) { + float sum = 0.0f; + for (uint i = t; i < width; i += n) sum = fma(x[i], x[i], sum); + sum = simd_sum(sum); + if (t % 32 == 0) part[t / 32] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (uint s = 0; s < n / 32; ++s) total += part[s]; + const float inv = precise::rsqrt(total / float(width) + eps); + for (uint i = t; i < width; i += n) out[i] = bfloat(float(w[i]) * float(bfloat(x[i] * inv))); +} + +[[kernel]] void rc_df_norm(device float* R [[buffer(0)]], const device bfloat* X [[buffer(1)]], + const device bfloat* w [[buffer(2)]], constant rc_df_norm_args& a [[buffer(3)]], device bfloat* out [[buffer(4)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]], + uint n [[threads_per_threadgroup]]) { + threadgroup float part[32]; + device float* x = R + (size_t)row * a.width; + if (a.add) + for (uint i = t; i < a.width; i += n) x[i] = float(bfloat(x[i] + float(X[(size_t)row * a.width + i]))); + threadgroup_barrier(mem_flags::mem_device); + rc_df_norm_row(x, w, a.width, a.eps, out + (size_t)row * a.width, t, n, part); +} + +// The embedded block into the fp32 residual: R row r = E[ids[r]] (the target's table, unscaled, as z-lab embeds). +[[kernel]] void rc_df_embed(const device uint* ids [[buffer(0)]], const device bfloat* E [[buffer(1)]], + constant rc_df_norm_args& a [[buffer(2)]], device float* R [[buffer(3)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + R[(size_t)p.y * a.width + p.x] = float(E[(size_t)ids[p.y] * a.width + p.x]); +} + +// The same norm of bf16 rows (fc's output into the context's hidden_norm). +[[kernel]] void rc_df_norm16(const device bfloat* X [[buffer(0)]], const device bfloat* w [[buffer(1)]], + constant rc_df_norm_args& a [[buffer(2)]], device bfloat* out [[buffer(3)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]]) { + threadgroup float part[32]; + const device bfloat* x = X + (size_t)row * a.width; + float sum = 0.0f; + for (uint i = t; i < a.width; i += n) sum = fma(float(x[i]), float(x[i]), sum); + sum = simd_sum(sum); + if (t % 32 == 0) part[t / 32] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (uint s = 0; s < n / 32; ++s) total += part[s]; + const float inv = precise::rsqrt(total / float(a.width) + a.eps); + for (uint i = t; i < a.width; i += n) out[(size_t)row * a.width + i] = bfloat(float(w[i]) * float(bfloat(float(x[i]) * inv))); +} + +struct rc_df_prep_args { uint rows, heads, kv_heads, pos0, stride, q_off, k_off, v_off, ring, rope; float eps, theta; }; + +// Per-head RicursiveRMSNorm, RicursiveRotaryEmbedding's bf16 tables unless a.rope is 0, z-lab's rotation points. +[[kernel]] void rc_df_prep(const device bfloat* X [[buffer(0)]], const device bfloat* qw [[buffer(1)]], + const device bfloat* kw [[buffer(2)]], constant rc_df_prep_args& a [[buffer(3)]], device bfloat* Q [[buffer(4)]], + device bfloat* K [[buffer(5)]], device bfloat* V [[buffer(6)]], uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint unit = tg.x, row = tg.y; + if (unit >= a.heads + a.kv_heads || row >= a.rows) return; + const bool is_q = unit < a.heads; + const uint head = is_q ? unit : unit - a.heads; + const device bfloat* src = X + (size_t)row * a.stride + (is_q ? a.q_off : a.k_off) + (size_t)head * 128; + const device bfloat* w = is_q ? qw : kw; + const uint p = a.pos0 + row; + const size_t slot = p % a.ring; + device bfloat* y = is_q ? Q + ((size_t)row * a.heads + head) * 128 : K + (slot * a.kv_heads + head) * 128; + float v[4]; + float sum = 0.0f; + for (uint j = 0; j < 4; ++j) { + v[j] = float(src[lane + 32 * j]); + sum = fma(v[j], v[j], sum); + } + const float inv = precise::rsqrt(simd_sum(sum) / 128.0f + a.eps); + threadgroup float nrm[128]; + for (uint j = 0; j < 4; ++j) nrm[lane + 32 * j] = float(bfloat(float(w[lane + 32 * j]) * float(bfloat(v[j] * inv)))); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = 0; j < 4; ++j) { + const uint d = lane + 32 * j; + if (a.rope == 0) { + y[d] = bfloat(nrm[d]); + continue; + } + const uint i = d % 64; + const float angle = float(p) * (1.0f / precise::pow(a.theta, float(2 * i) / 128.0f)); + const float c = float(bfloat(precise::cos(angle))), s = float(bfloat(precise::sin(angle))); + const float rot = d < 64 ? -nrm[d + 64] : nrm[d - 64]; + y[d] = bfloat(float(bfloat(nrm[d] * c)) + float(bfloat(rot * s))); + } + if (is_q) return; + const device bfloat* vs = X + (size_t)row * a.stride + a.v_off + (size_t)head * 128; + device bfloat* vd = V + (slot * a.kv_heads + head) * 128; + for (uint j = 0; j < 4; ++j) vd[lane + 32 * j] = vs[lane + 32 * j]; +} + +struct rc_df_conv_args { uint rows, width, block, groups, side, taps; }; + +// z-lab's dynamic causal conv, per tap t in the block: y = bf16(y + bf16(base_t x[r-t])), y = bf16(y + dyn_t x[r-t]). +[[kernel]] void rc_df_conv(const device bfloat* X [[buffer(0)]], const device bfloat* D [[buffer(1)]], + const device bfloat* base [[buffer(2)]], constant rc_df_conv_args& a [[buffer(3)]], device bfloat* Y [[buffer(4)]], + uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const uint ch = p.x, r = p.y, g = ch / (a.width / a.groups); + // a row's dynamic kernel: [side][tap][group] + const device bfloat* d = D + (size_t)r * 2 * a.taps * a.groups + a.side * a.taps * a.groups; + const device bfloat* bs = base + (size_t)a.side * a.taps * a.width; + float y = 0.0f; + for (uint t = 0; t < a.taps; ++t) { + if (r % a.block < t) break; + const float x = float(X[(size_t)(r - t) * a.width + ch]); + y = float(bfloat(y + float(bfloat(float(bs[(size_t)t * a.width + ch]) * x)))); + y = float(bfloat(fma(float(d[t * a.groups + g]), x, y))); + } + Y[(size_t)r * a.width + ch] = bfloat(y); +} + +struct rc_df_act_args { uint rows, width; }; + +// RicursiveMLP's activation (silu, no clamp) on a stacked gate|up row: bf16(bf16(silu(g)) * u). +[[kernel]] void rc_df_silu(const device bfloat* GU [[buffer(0)]], constant rc_df_act_args& a [[buffer(1)]], + device bfloat* A [[buffer(2)]], uint2 p [[thread_position_in_grid]]) { + if (p.x >= a.width || p.y >= a.rows) return; + const size_t at = (size_t)p.y * 2 * a.width + p.x; + const float g = float(GU[at]); + const float e = precise::exp(-fabs(g)), y = 1.0f / (1.0f + e); + const float s = g < 0.0f ? e * y : y; // e / (1 + e) below 0, which 1 - y would cancel + A[(size_t)p.y * a.width + p.x] = bfloat(float(bfloat(g * s)) * float(GU[at + a.width])); +} + +// The first eight are llama's ll_vec_args, which ll_merge_vec reads; then the block's end, window, ring and floor. +struct rc_df_vec_args { uint rows, pos0, heads, groups, blocks, chunk, first; float scale; uint hi, window, ring, floor; }; + +// A block's attention, a (key head, row, 128-key block) a threadgroup: keys max(p + 1 - window, floor) to hi. +[[kernel]] void rc_df_vec(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], + const device bfloat* V [[buffer(2)]], constant rc_df_vec_args& a [[buffer(3)]], device float* PM [[buffer(4)]], + device float* PL [[buffer(5)]], device float* PO [[buffer(6)]], uint3 tg [[threadgroup_position_in_grid]], + uint g [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const uint kv = tg.x, row = tg.y, z = tg.z; + const uint G = a.heads / a.groups, head = kv * G + g; + const size_t slot = ((size_t)head * a.rows + row) * a.blocks + z; + const uint p = a.pos0 + row; + const uint lo = max(p + 1 > a.window ? p + 1 - a.window : 0, a.floor); + const uint block = a.first + z; + const uint from = max(lo, block * 128), to = min(a.hi, block * 128 + 128); + if (from >= to) { + if (lane == 0) { PM[slot] = -INFINITY; PL[slot] = 0.0f; } + return; + } + const size_t ld = (size_t)a.groups * 128; + const float4 qv = a.scale * float4(*(const device bfloat4*)(Q + ((size_t)row * a.heads + head) * 128 + 4 * lane)); + float4 acc = 0.0f; + float top = -INFINITY, mass = 0.0f; + for (uint i0 = from; i0 < to; i0 += 4) { + float score[4]; + float4 vr[4]; + TF_UNROLL_4 + for (uint u = 0; u < 4; ++u) { + const bool live = i0 + u < to; + const size_t at = (size_t)((live ? i0 + u : from) % a.ring) * ld + kv * 128 + 4 * lane; + vr[u] = float4(*(const device bfloat4*)(V + at)); + const float sc = simd_sum(dot(qv, float4(*(const device bfloat4*)(K + at)))); + score[u] = live ? sc : -INFINITY; + } + const float peak = max(max(top, max(score[0], score[1])), max(score[2], score[3])); + const float rescale = fast::exp(top - peak); + mass *= rescale; + acc *= rescale; + TF_UNROLL_4 + for (uint u = 0; u < 4; ++u) { + const float w = fast::exp(score[u] - peak); + mass += w; + acc += w * vr[u]; + } + top = peak; + } + if (lane == 0) { PM[slot] = top; PL[slot] = mass; } + *(device float4*)(PO + slot * 128 + 4 * lane) = acc; +} + +struct rc_df_topk_args { uint n, stride, chunks, from_ids; }; + +inline bool rc_df_before(float a, uint ia, float b, uint ib) { return a > b || (a == b && ia < ib); } + +// The best 32 of a row's 2048-value chunk (value desc, id asc) by a bitonic sort, out at (r * chunks + c) * 32. +[[kernel]] void rc_df_topk(const device bfloat* L [[buffer(0)]], const device float* VIN [[buffer(1)]], + const device uint* IIN [[buffer(2)]], constant rc_df_topk_args& a [[buffer(3)]], device float* VOUT [[buffer(4)]], + device uint* IOUT [[buffer(5)]], uint2 tg [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + threadgroup float v[2048]; + threadgroup uint id[2048]; + const uint row = tg.y, chunk = tg.x; + for (uint i = t; i < 2048; i += 1024) { + const uint at = chunk * 2048 + i; + if (at < a.n) { + const size_t src = (size_t)row * a.stride + at; + v[i] = a.from_ids ? VIN[src] : float(L[src]); + id[i] = a.from_ids ? IIN[src] : at; + } else { + v[i] = -INFINITY; + id[i] = 0xffffffffu; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint k = 2; k <= 2048; k <<= 1) + for (uint j = k >> 1; j > 0; j >>= 1) { + for (uint i = t; i < 2048; i += 1024) { + const uint l = i ^ j; + if (l > i) { + const bool down = (i & k) == 0; // descending runs where the k-bit is clear + const bool swap = down ? rc_df_before(v[l], id[l], v[i], id[i]) : rc_df_before(v[i], id[i], v[l], id[l]); + if (swap) { + const float tv = v[i]; v[i] = v[l]; v[l] = tv; + const uint ti = id[i]; id[i] = id[l]; id[l] = ti; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (t < 32) { + VOUT[((size_t)row * a.chunks + chunk) * 32 + t] = v[t]; + IOUT[((size_t)row * a.chunks + chunk) * 32 + t] = id[t]; + } +} + +struct rc_df_walk_args { uint slots, rank, top, vocab; }; + +// z-lab's CandidateSelector, greedy: slot e scores c after p as bf16(unary + bf16(sum_r bf16(A[p][r]H[e][r]) B[c][r])). +[[kernel]] void rc_df_walk(const device float* UV [[buffer(0)]], const device uint* UI [[buffer(1)]], + const device bfloat* H [[buffer(2)]], const device bfloat* A [[buffer(3)]], const device bfloat* B [[buffer(4)]], + constant rc_df_walk_args& a [[buffer(5)]], device uint* seq [[buffer(6)]], uint t [[thread_position_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[8][32]; + threadgroup uint prev; + if (t == 0) prev = seq[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = 0; e < a.slots; ++e) { + const float ah = float(bfloat(float(A[(size_t)prev * a.rank + t]) * float(H[(size_t)e * a.rank + t]))); + for (uint c = 0; c < a.top; ++c) { + const uint cand = UI[e * a.top + c]; + const float s = simd_sum(ah * float(B[(size_t)min(cand, a.vocab - 1) * a.rank + t])); + if (lane == 0) part[sg][c] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float best = -INFINITY; + uint bi = 0; + for (uint c = 0; c < a.top; ++c) { + float pair = 0.0f; + for (uint k = 0; k < a.rank / 32; ++k) pair += part[k][c]; + const float s = float(bfloat(UV[e * a.top + c] + float(bfloat(pair)))); + if (UI[e * a.top + c] < a.vocab && s > best) { best = s; bi = c; } + } + prev = UI[e * a.top + bi]; + seq[1 + e] = prev; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index d782e403730..8586e92ddc7 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -277,6 +277,8 @@ pub const ricursive_fp4 = @embedFile("ricursive/fp4.metal"); pub const ricursive_fp4_gemm = gemm_nax ++ @embedFile("ricursive/fp4_gemm.metal"); /// Ripple's prompt attention on the tensor units (llama's kernel over a window, keys in a ring; nax.h inlined at load). pub const ricursive_attention_nax = @embedFile("ricursive/attention_nax.metal"); +/// Ripple's DFlash2 drafter (norms, head prep, K-tap block convolution, block attention, selector) and its taps. +pub const ricursive_dflash2 = @embedFile("ricursive/dflash2.metal"); /// The kernel contract's planted controls: one kernel breaking each gate (zig/tests/contract/). pub const core_contract_controls = @embedFile("core/contract_controls.metal"); diff --git a/zig/src/core/contract/ricursive_records.zig b/zig/src/core/contract/ricursive_records.zig index 6dd4c1e6508..12abf34aece 100644 --- a/zig/src/core/contract/ricursive_records.zig +++ b/zig/src/core/contract/ricursive_records.zig @@ -1,4 +1,4 @@ -//! Ripple-65B's Metal launches (metal_ricursive*.zig): its glue, its prompt attention and the draw it runs. +//! Ripple-65B's Metal launches (metal_ricursive*.zig): its glue, prompt attention, the draw and DFlash2's kernels. const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ .{ .name = "ricursive glue rc_embed", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, @@ -24,4 +24,16 @@ pub const records = [_]M{ .{ .name = "ricursive fp4 gemm rc_fp4_gemm_10", .threads = 256, .tg_memory = 0, .reserved = 256, .offline = false }, .{ .name = "ricursive fp4 gemm rc_fp4_gemm_11", .threads = 256, .tg_memory = 0, .reserved = 256, .offline = false }, .{ .name = "ricursive sample tf_sample_full", .threads = 1024, .tg_memory = 9760, .reserved = 1024, .m1 = 1024, .m2 = 1024 }, + // dflash2.metal: the target's tap and the DFlash2 drafter's kernels + .{ .name = "ricursive dflash2 rc_tap", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_norm", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_norm16", .threads = 256, .tg_memory = 128, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_embed", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_prep", .threads = 32, .tg_memory = 512, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_conv", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_silu", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + // a simdgroup for each of a key head's 10 query heads + .{ .name = "ricursive dflash2 rc_df_vec", .threads = 320, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_topk", .threads = 1024, .tg_memory = 16384, .m1 = 1024, .m2 = 1024 }, + .{ .name = "ricursive dflash2 rc_df_walk", .threads = 256, .tg_memory = 1040, .m1 = 1024, .m2 = 1024 }, }; diff --git a/zig/src/families/ricursive/backend.zig b/zig/src/families/ricursive/backend.zig index e6ab291a347..76eb7243891 100644 --- a/zig/src/families/ricursive/backend.zig +++ b/zig/src/families/ricursive/backend.zig @@ -11,8 +11,11 @@ const row = @import("../step5/backend.zig").row; const gpu_full = lanes.gpu_full; const be = lanes.backend; -/// The longest context a stream may take, the streams at once, and the bytes every stream's caches may hold. -pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64 }; +/// A stream's longest context, the streams at once, the caches' bytes, and a drafter's context bytes a stream. +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64, drafts: bool = false, drafter_bytes: u64 = 0 }; + +/// Window widths the depth rule prices (a pending token and up to 15 drafts). +const max_window = st.window_rows; /// Token slots a stream's handles point at: drawn tokens and host-fed ones (no command in flight reads a fresh one). const ring = 4096; @@ -38,6 +41,9 @@ pub const Metal = struct { landed: u64 = 0, // slots below it are written flights: std.ArrayList(Flight) = .empty, values: []f32, // a logits row as f32, for the host twin of the GPU draw + sink: ?be.FeatureSink = null, // a drafted prompt pass: each chunk's taps to the drafter as it lands + costs: [max_window]lanes.config.Cost = undefined, // window ms by rows, for the depth rule (measure) + timed: usize = 0, pub fn init(gpa: std.mem.Allocator, model: *Model, options: Options) !*Metal { const out = try gpa.create(Metal); @@ -93,11 +99,70 @@ pub const Metal = struct { pub fn facts(self: *const Metal) lanes.Model { // rows are independent in every decode kernel, so any width, alone or beside other streams, gives one-row bits - return .{ .exact_width = st.window_rows, .gpu_tokens = true, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true }; + return .{ .exact_width = st.window_rows, .gpu_tokens = !self.options.drafts, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true, .window_costs = self.costs[0..self.timed] }; + } + + /// A window of each width 1..max_window at position 0 on a throwaway cache, the second of two runs timed. + pub fn measure(self: *Metal) !void { + var cache = try st.Cache.init(self.model.device, &self.model.config, 256); + defer cache.deinit(); + var ids: [max_window]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(1000 + i * 7919 % 50000); + for (1..max_window + 1) |rows| { + var ms: f64 = 0; + for (0..2) |run| { + cache.len = 0; + const t0 = msNow(); + try fwd.run(self.model, &self.scratch, &cache, ids[0..rows], .{ .all = true }); + if (run == 1) ms = msNow() - t0; + } + self.costs[rows - 1] = .{ .width = @intCast(rows), .ms = ms }; + } + self.timed = max_window; + } + + /// A tapped row's bytes: every tap's hidden row, bf16. + fn tapBytes(self: *const Metal) usize { + return @as(usize, self.model.taps) * self.model.config.hidden * 2; + } + + /// The drafter's layers: both scratches keep their rows from now on. + fn prepareFn(ptr: *anyopaque, taps: []const u32) !void { + const self = cast(ptr); + try self.model.setTaps(taps); + if (self.scratch.taps != null) return; + const opts = mtl.ResourceOptions.shared; + const decode = try self.model.device.buffer(st.batch_rows * self.tapBytes(), opts); + errdefer decode.deinit(); + const prompt = try self.model.device.buffer(st.prompt_rows * self.tapBytes(), opts); + self.scratch.taps = decode; + self.prompt.taps = prompt; + if (self.follow) |f| { + f.join(f.ctx, decode); + f.join(f.ctx, prompt); + } + } + + /// Rows [start, start + count) of the stream's latest tapped rows, on the device. + fn featuresFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, start: u64, count: u32) !be.Features { + const self = cast(ptr); + const tp = (try self.cacheOf(stream)).tap; + if (taps.len != self.model.taps or tp.buf == null) return error.UnpreparedRicursiveTaps; + if (count == 0 or start < tp.start or start + count > tp.start + tp.rows) return error.RicursiveTapsNotHeld; + const width = self.tapBytes(); + return .{ .buffer = @intFromPtr(tp.buf.?.id), .offset = tp.off + (start - tp.start) * width, .rows = count, .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }; + } + + fn prefillFeaturesFn(ptr: *anyopaque, stream: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) !void { + const self = cast(ptr); + if (taps.len != self.model.taps) return error.UnpreparedRicursiveTaps; + self.sink = sink; + defer self.sink = null; + return prefillFn(ptr, stream); } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prepare_features = prepareFn, .features = featuresFn, .prefill_features = prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; } fn cast(ptr: *anyopaque) *Metal { @@ -179,13 +244,29 @@ pub const Metal = struct { }; } const s = if (end - at > st.batch_rows) &self.prompt else &self.scratch; - try fwd.run(self.model, s, cache, ids[at..end], .{}); + const taps = if (stream != null) s.taps else null; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = if (taps) |x| .{ .buf = x } else null }); + if (taps) |x| try self.keepTaps(cache, stream.?, x, end - at, base + end == stream.?.prompt().len); cache.len += end - at; at = end; if (stream) |sm| if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len)); } } + /// A drafted prompt chunk's taps: to the drafter as they land, the prompt's last row kept for the first draft. + fn keepTaps(self: *Metal, cache: *st.Cache, stream: *lanes.Stream, x: mtl.Buffer, rows: usize, last: bool) !void { + const width = self.tapBytes(); + if (self.sink) |k| try k.take(k.ptr, stream, .{ .buffer = @intFromPtr(x.id), .rows = @intCast(rows), .row_bytes = @intCast(width), .space = .device, .dtype = .bf16 }, cache.len); + cache.tap = .{ .buf = x, .start = cache.len, .rows = rows }; + if (!last) return; + if (cache.last_tap == null) { + cache.last_tap = try self.model.device.buffer(width, mtl.ResourceOptions.shared); + if (cache.follow) |f| f.join(f.ctx, cache.last_tap.?); + } + @memcpy(cache.last_tap.?.slice(u8, width), x.slice(u8, rows * width)[(rows - 1) * width ..][0..width]); + cache.tap = .{ .buf = cache.last_tap, .start = cache.len + rows - 1, .rows = 1 }; + } + fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void { const self = cast(ptr); try self.drain(); @@ -199,8 +280,8 @@ pub const Metal = struct { m: *Metal, stream: *lanes.Stream, ids: []const u32, - pub fn growth(_: *const @This()) u64 { - return 0; // no drafter: a stream's caches are all it takes + pub fn growth(a: *const @This()) u64 { + return a.m.options.drafter_bytes; // a drafter's context for the stream, beside its caches } pub fn shed(_: *const @This(), _: u64) void {} pub fn restoreBytes(a: *const @This()) u64 { @@ -335,7 +416,15 @@ pub const Metal = struct { @memcpy(ids[total + 1 ..][0..w.tokens.len], w.tokens); total += rows; } - try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true }); + const taps = self.scratch.taps; + try fwd.runShared(self.model, &self.scratch, segments[0..windows.len], ids[0..total], .{ .all = true, .taps = if (taps) |x| .{ .buf = x } else null }); + if (taps) |x| { + var at: usize = 0; + for (segments[0..windows.len]) |seg| { + seg.cache.tap = .{ .buf = x, .off = at * self.tapBytes(), .start = seg.cache.len, .rows = seg.rows }; + at += seg.rows; + } + } const all = self.scratch.logits_all.slice(u16, total * vocab); var base: usize = 0; for (windows, out, segments[0..windows.len]) |w, o, seg| { @@ -428,3 +517,9 @@ fn argmax(l: []const u16) usize { }; return best; } + +fn msNow() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) * 1e3 + @as(f64, @floatFromInt(ts.nsec)) / 1e6; +} diff --git a/zig/src/families/ricursive/contracts.zig b/zig/src/families/ricursive/contracts.zig index 5c4ebe4e27c..e9cf9c7082b 100644 --- a/zig/src/families/ricursive/contracts.zig +++ b/zig/src/families/ricursive/contracts.zig @@ -5,6 +5,7 @@ const ks = @import("kernel_sources"); const cfg = @import("config.zig"); const model = @import("model.zig"); const st = @import("state.zig"); +const df = @import("dflash2.zig"); const frags = @import("../../core/frags.zig"); /// Ripple-65B, the family's one qualified checkpoint. @@ -19,8 +20,15 @@ pub const attention_name = "rc_prompt_attention"; pub const sample_name = "tf_sample_full"; pub const fp4_names = model.fp4_names; pub const fp4_gemm_names = [_][]const u8{ "rc_fp4_gemm_00", "rc_fp4_gemm_01", "rc_fp4_gemm_10", "rc_fp4_gemm_11" }; -/// Every pipeline model.zig builds: glue, llama's row kernels and GEMMs, attention, the draw and the NVFP4 MLP's. -pub const pipelines = glue_names.len + llama_names.len + gemm_names.len + 2 + fp4_names.len + fp4_gemm_names.len; +/// dflash2.metal's pipelines: the target's tap (model.zig's setTaps), then the drafter's (dflash2.zig's). +pub const dflash2_names = blk: { + var out: [df.kernel_names.len + 1][]const u8 = undefined; + out[0] = "rc_tap"; + for (df.kernel_names, 1..) |n, i| out[i] = n; + break :blk out; +}; +/// Every pipeline the family builds: glue, llama's row kernels and GEMMs, attention, the draw, NVFP4's and DFlash2's. +pub const pipelines = glue_names.len + llama_names.len + gemm_names.len + 2 + fp4_names.len + fp4_gemm_names.len + dflash2_names.len; /// The glue's text as model.zig builds it. pub fn glueSource(a: std.mem.Allocator) ![]u8 { @@ -54,6 +62,11 @@ pub fn fp4Library(device: mtl.Device, src: []const u8) !mtl.Library { return mtl.Library.fromSource(device, src, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); } +/// dflash2.metal's library as dflash2.zig and setTaps compile it: MLX's language, precise math functions. +pub fn dflash2Library(device: mtl.Device, src: []const u8) !mtl.Library { + return mtl.Library.fromSource(device, src, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); +} + /// The NVFP4 GEMM's text: nax.h inlined for this GPU (model.zig's build), or as a GPU without tensor units takes it. pub fn fp4GemmSource(device: mtl.Device, a: std.mem.Allocator, units: bool) ![]u8 { if (units) return frags.source(device, a, ks.ricursive_fp4_gemm); @@ -62,7 +75,7 @@ pub fn fp4GemmSource(device: mtl.Device, a: std.mem.Allocator, units: bool) ![]u /// Every pipeline the family runs appears among the registrations' functions. pub fn requireComplete(functions: []const []const u8) !void { - inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names }) |list| for (list) |name| { + inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names, dflash2_names }) |list| for (list) |name| { var seen = false; for (functions) |f| if (std.mem.eql(u8, f, name)) { seen = true; @@ -74,7 +87,7 @@ pub fn requireComplete(functions: []const []const u8) !void { test "ricursive contracts: the roll call wants every pipeline" { var all: [pipelines][]const u8 = undefined; var i: usize = 0; - inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names }) |list| for (list) |name| { + inline for (.{ glue_names, llama_names, gemm_names, [_][]const u8{ attention_name, sample_name }, fp4_names, fp4_gemm_names, dflash2_names }) |list| for (list) |name| { all[i] = name; i += 1; }; diff --git a/zig/src/families/ricursive/dflash2.zig b/zig/src/families/ricursive/dflash2.zig new file mode 100644 index 00000000000..206e4a15544 --- /dev/null +++ b/zig/src/families/ricursive/dflash2.zig @@ -0,0 +1,440 @@ +//! ricursiveAI's DFlash2 drafter for Ripple on Metal (z-lab's DFlash2DraftModel): 16-row blocks over 5 target taps. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const ks = @import("kernel_sources"); +const ck = @import("../../core/checkpoint_metal.zig"); +const shards = @import("../../core/checkpoint.zig"); +const cfg = @import("config.zig"); +const fwd = @import("forward.zig"); +const dc = @import("dflash2_config.zig"); +const Model = @import("model.zig").Model; + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const B = fwd.B; +const b = fwd.b; +const bo = fwd.bo; +const t = fwd.t; +const A = fwd.A; +pub const Config = dc.Config; + +/// Rows a block takes (the trained block). +pub const max_block = 16; +/// Context rows one absorb pass projects at most (a prompt chunk's). +const absorb_rows = 2048; +/// A key block of the draft attention, and the most a row's window spans (the global layer's ring). +const key_block = 128; +const max_key_blocks = dc.global_window / key_block + 2; + +/// One stream's context: each layer's keys and values for the last positions, a ring of Config.ring(layer) slots. +const Lane = struct { + k: [dc.max_layers]mtl.Buffer, + v: [dc.max_layers]mtl.Buffer, + end: u64 = 0, // context rows absorbed: positions [from, end) + from: u64 = 0, // the first position held (a resumed prompt's drafter context starts there) + held: [max_block]u32 = @splat(0), + held_len: u32 = 0, +}; + +/// The drafter's pipelines, in `Kernel` order (the contract's roll call reads them). +pub const kernel_names = [_][:0]const u8{ "rc_df_norm", "rc_df_norm16", "rc_df_embed", "rc_df_prep", "rc_df_conv", "rc_df_silu", "rc_df_vec", "rc_df_topk", "rc_df_walk" }; +const Kernel = enum { norm, norm16, embed, prep, conv, silu, vec, topk, walk }; + +/// The drafter's scratch, fields in init's order. +const fields = [_][]const u8{ "ids", "resid", "x", "xc", "dyn", "qkv", "q", "attn", "y", "yc", "gu", "act", "logits", "pm", "pl", "po", "tv", "ti", "tv2", "ti2", "uv", "ui", "hid", "seq", "fcx", "hctx", "kv" }; + +const NArgs = extern struct { rows: u32, width: u32, eps: f32, add: u32 }; +const PArgs = extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, rope: u32, eps: f32, theta: f32 }; +const VArgs = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, chunk: u32, first: u32, scale: f32, hi: u32, window: u32, ring: u32, floor: u32 }; +const CArgs = extern struct { rows: u32, width: u32, block: u32, groups: u32, side: u32, taps: u32 }; + +pub const Drafter = struct { + gpa: std.mem.Allocator, + target: *Model, + config: Config, + checkpoint: ck.Checkpoint, + w: dc.Weights, + pipes: [kernel_names.len]mtl.Pipeline, + lanes: std.AutoHashMapUnmanaged(*Stream, *Lane) = .empty, + follow: ?mtl.ResidencySet.Follow = null, + step_ms: f64 = 0, + s: [fields.len]mtl.Buffer = undefined, + + /// The drafter's config.json, checked against `target` before any weight is read. + pub fn readConfig(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, target: *const cfg.Config) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(bytes); + return dc.parse(gpa, bytes, target); + } + + pub fn init(gpa: std.mem.Allocator, io: std.Io, target: *Model, dir: []const u8, config: Config) !*Drafter { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const d = try gpa.create(Drafter); + errdefer gpa.destroy(d); + d.* = .{ .gpa = gpa, .target = target, .config = config, .checkpoint = ck.Checkpoint.init(gpa), .w = undefined, .pipes = undefined }; + errdefer d.checkpoint.deinit(); + const files = try shards.shardFiles(gpa, io, dir); + defer shards.freeShardFiles(gpa, files); + for (files) |path| try d.checkpoint.addFile(target.device, path, ""); + d.w = try dc.load(&d.checkpoint, &d.config); + { + const lib = try mtl.Library.fromSource(target.device, ks.ricursive_dflash2, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var made: usize = 0; + errdefer for (d.pipes[0..made]) |p| p.deinit(); + for (kernel_names, 0..) |n, i| { + d.pipes[i] = try mtl.Pipeline.init(target.device, lib, n, false); + made += 1; + } + } + errdefer for (d.pipes) |p| p.deinit(); + const sizes = scratchSizes(&d.config); + var made: usize = 0; + errdefer for (d.s[0..made]) |x| x.deinit(); + for (sizes, 0..) |n, i| { + d.s[i] = try target.device.buffer(n, mtl.ResourceOptions.shared); + made += 1; + } + try d.warm(); + return d; + } + + pub fn deinit(d: *Drafter) void { + d.setResident(null); + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.dropLane(l.*); + d.lanes.deinit(d.gpa); + for (d.s) |x| x.deinit(); + for (d.pipes) |p| p.deinit(); + d.checkpoint.deinit(); + d.gpa.destroy(d); + } + + /// Bytes of the scratch, in `fields` order. + fn scratchSizes(c: *const Config) [fields.len]usize { + const h: usize = c.hidden; + const r: usize = max_block; + const qw: usize = @as(usize, c.heads) * cfg.head_dim; + const kvw: usize = @as(usize, c.kv_heads) * cfg.head_dim; + const vocab: usize = c.vocab; + const chunks: usize = (vocab + 2047) / 2048; + const parts: usize = @as(usize, c.heads) * r * max_key_blocks; + return .{ r * 4, r * h * 4, r * h * 2, r * h * 2, r * c.dyn() * 2, r * (qw + 2 * kvw) * 2, r * qw * 2, r * qw * 2, r * h * 2, r * h * 2, r * 2 * c.ffn * 2, r * c.ffn * 2, r * vocab * 2, parts * 4, parts * 4, parts * cfg.head_dim * 4, r * chunks * 32 * 4, r * chunks * 32 * 4, r * 64 * 4, r * 64 * 4, r * 32 * 4, r * 32 * 4, r * c.rank * 2, 16 * 4, absorb_rows * h * 2, absorb_rows * h * 2, absorb_rows * 2 * kvw * 2 }; + } + + /// Device bytes the drafter holds beside its weights: the scratch. + pub fn fixedBytes(c: *const Config) usize { + var n: usize = 0; + for (scratchSizes(c)) |x| n += x; + return n; + } + + /// Device bytes one stream's context takes. + pub fn laneBytes(c: *const Config) usize { + var n: usize = 0; + for (0..c.layers) |l| n += @as(usize, c.ring(l)) * c.kv_heads * cfg.head_dim * 2 * 2; + return n; + } + + fn buf(d: *const Drafter, comptime f: []const u8) mtl.Buffer { + inline for (fields, 0..) |n, i| if (comptime std.mem.eql(u8, n, f)) return d.s[i]; + @compileError("no drafter buffer " ++ f); + } + + fn pipe(d: *const Drafter, k: Kernel) mtl.Pipeline { + return d.pipes[@backingInt(k)]; + } + + /// The weights' shards and the scratch, for the host's residency set. + pub fn buffers(d: *const Drafter, gpa: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + for (d.checkpoint.shards.items) |sh| try list.append(gpa, sh.buffer); + try list.appendSlice(gpa, &d.s); + } + + pub fn setResident(d: *Drafter, hook: ?mtl.ResidencySet.Follow) void { + if (d.follow) |f| { + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.laneResident(l.*, f, false); + } + d.follow = hook; + if (hook) |f| { + var it = d.lanes.valueIterator(); + while (it.next()) |l| d.laneResident(l.*, f, true); + } + } + + fn laneResident(d: *const Drafter, l: *const Lane, f: mtl.ResidencySet.Follow, on: bool) void { + for (0..d.config.layers) |i| for ([_]mtl.Buffer{ l.k[i], l.v[i] }) |x| if (on) f.join(f.ctx, x) else f.leave(f.ctx, x); + } + + pub fn drafter(d: *Drafter) dr.Drafter { + return .{ .kind = "DFlash2", .ptr = d, .vtable = &.{ .taps = tapsFn, .facts = factsFn, .open = openFn, .absorb = absorbFn, .hold = holdFn, .held = heldFn, .release = releaseFn } }; + } + + fn cast(ptr: *anyopaque) *Drafter { + return @ptrCast(@alignCast(ptr)); + } + + fn tapsFn(ptr: *anyopaque) []const u32 { + return &cast(ptr).config.taps; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + const d = cast(ptr); + return .{ .depth = d.config.block - 1, .step_ms = d.step_ms, .plain_guard = true, .stream_bytes = laneBytes(&d.config) }; + } + + fn newLane(d: *Drafter) !*Lane { + const l = try d.gpa.create(Lane); + errdefer d.gpa.destroy(l); + l.* = .{ .k = undefined, .v = undefined }; + var made: usize = 0; + errdefer for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + }; + for (0..d.config.layers) |i| { + const bytes = @as(usize, d.config.ring(i)) * d.config.kv_heads * cfg.head_dim * 2; + l.k[i] = try d.target.device.buffer(bytes, mtl.ResourceOptions.private); + l.v[i] = d.target.device.buffer(bytes, mtl.ResourceOptions.private) catch |e| { + l.k[i].deinit(); + return e; + }; + made += 1; + } + if (d.follow) |f| d.laneResident(l, f, true); + return l; + } + + fn dropLane(d: *Drafter, l: *Lane) void { + if (d.follow) |f| d.laneResident(l, f, false); + for (0..d.config.layers) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + d.gpa.destroy(l); + } + + fn openFn(ptr: *anyopaque, s: *Stream) anyerror!void { + const d = cast(ptr); + if (d.lanes.contains(s)) return error.DraftStreamOpen; + const l = try d.newLane(); + errdefer d.dropLane(l); + try d.lanes.put(d.gpa, s, l); + } + + fn releaseFn(ptr: *anyopaque, s: *Stream) void { + const d = cast(ptr); + if (d.lanes.fetchRemove(s)) |e| d.dropLane(e.value); + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, out: []const []u32) anyerror!void { + const d = cast(ptr); + for (streams, out) |s, o| { + const l = d.lanes.get(s) orelse return error.DraftStreamUnknown; + if (o.len > l.held_len) return error.DraftHeldFewer; + @memcpy(o, l.held[0..o.len]); + } + } + + fn glue(e: mtl.ComputeEncoder, p: mtl.Pipeline, args: anytype, bufs: []const B, grid: [3]usize, group: [3]usize) void { + e.setPipeline(p); + for (bufs, 0..) |r, slot| if (r.args) e.setValue(args, slot) else e.setBuffer(r.buf, r.off, slot); + e.dispatchGroups(mtl.Size.of(grid[0], grid[1], grid[2]), mtl.Size.of(group[0], group[1], group[2])); + } + + fn threads(e: mtl.ComputeEncoder, p: mtl.Pipeline, args: anytype, bufs: []const B, grid: [3]usize) void { + e.setPipeline(p); + for (bufs, 0..) |r, slot| if (r.args) e.setValue(args, slot) else e.setBuffer(r.buf, r.off, slot); + e.dispatchThreads(mtl.Size.of(grid[0], grid[1], grid[2]), mtl.Size.of(256, 1, 1)); + } + + /// y = x W^T over `rows` rows, `ldy` apart: the target's row kernels to 32 rows, its GEMM past them. + fn project(d: *const Drafter, e: mtl.ComputeEncoder, w: @import("weights.zig").Dense, in: B, out: B, rows: usize, ldy: usize) void { + fwd.denseRows(e, d.target, w, in, out.buf, out.off, rows, ldy); + } + + /// The context rows [p0, p0 + rows) from `src` (taps x hidden bf16 each) into every layer's ring. + fn absorbRows(d: *const Drafter, e: mtl.ComputeEncoder, l: *const Lane, src: B, p0: u64, rows: usize) void { + const c = &d.config; + const kvw: usize = @as(usize, c.kv_heads) * cfg.head_dim; + d.project(e, d.w.fc, src, b(d.buf("fcx")), rows, c.hidden); + glue(e, d.pipe(.norm16), NArgs{ .rows = @intCast(rows), .width = c.hidden, .eps = c.eps, .add = 0 }, &.{ b(d.buf("fcx")), t(d.w.hidden_norm), A, b(d.buf("hctx")) }, .{ rows, 1, 1 }, .{ 256, 1, 1 }); + for (0..c.layers) |i| { + const L = &d.w.layers[i]; + // each layer's k and v of the normed taps, k normed and rotated, into the layer's ring + d.project(e, L.k, b(d.buf("hctx")), b(d.buf("kv")), rows, 2 * kvw); + d.project(e, L.v, b(d.buf("hctx")), bo(d.buf("kv"), kvw * 2), rows, 2 * kvw); + const pa = PArgs{ .rows = @intCast(rows), .heads = 0, .kv_heads = c.kv_heads, .pos0 = @intCast(p0), .stride = @intCast(2 * kvw), .q_off = 0, .k_off = 0, .v_off = @intCast(kvw), .ring = c.ring(i), .rope = @intFromBool(c.rope[i]), .eps = c.eps, .theta = c.theta }; + glue(e, d.pipe(.prep), pa, &.{ b(d.buf("kv")), t(L.q_norm), t(L.k_norm), A, b(d.buf("q")), b(l.k[i]), b(l.v[i]) }, .{ c.kv_heads, rows, 1 }, .{ 32, 1, 1 }); + } + } + + /// Rows [start, start + rows) replace the context from `start`; prompt rows past the longest span are skipped. + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const d = cast(ptr); + const c = &d.config; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + const width: usize = dc.max_taps * @as(usize, c.hidden) * 2; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + const f = it.features; + if (f.space != .device or f.dtype != .bf16 or f.row_bytes != width) return error.DraftFeaturesUnsupported; + if (it.start > l.end or l.end == 0) l.from = it.start; // the rows before it were restored, not absorbed + const src = mtl.Buffer{ .id = @ptrFromInt(f.buffer) }; + const end = it.start + f.rows; + const keep_from = if (it.prompt) @max(it.start, it.stream.prompt_len -| (dc.global_window + c.block)) else it.start; + if (keep_from > it.start) l.from = @max(l.from, keep_from); // a long prompt's oldest rows: never absorbed + var at: u64 = keep_from; + while (at < end) { + const n: usize = @intCast(@min(absorb_rows, end - at)); + d.absorbRows(e, l, bo(src, f.offset + @as(usize, @intCast(at - it.start)) * width), at, n); + at += n; + } + l.end = end; + l.held_len = 0; + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + } + + /// x (n rows, the sublayer's normed input) through `cv`'s prepare: its coefficients into dyn, side 0 into xc. + fn convPrepare(d: *const Drafter, e: mtl.ComputeEncoder, cv: dc.Conv, n: usize) void { + const c = &d.config; + d.project(e, cv.proj, b(d.buf("x")), b(d.buf("dyn")), n, c.dyn()); + d.conv(e, cv, b(d.buf("x")), b(d.buf("xc")), n, 0); + } + + fn conv(d: *const Drafter, e: mtl.ComputeEncoder, cv: dc.Conv, in: B, out: B, n: usize, side: u32) void { + const c = &d.config; + threads(e, d.pipe(.conv), CArgs{ .rows = @intCast(n), .width = c.hidden, .block = c.block, .groups = c.hidden / c.group, .side = side, .taps = c.conv }, &.{ in, b(d.buf("dyn")), t(cv.base), A, out }, .{ c.hidden, n, 1 }); + } + + /// The block [pending, mask x 15] at positions anchor.. through the drafter; seq[1..] its drafts. + fn encodeBlock(d: *const Drafter, e: mtl.ComputeEncoder, l: *const Lane, pending: u32, anchor: u64) void { + const c = &d.config; + const m = d.target; + const n: usize = c.block; + const h: usize = c.hidden; + const qw: usize = @as(usize, c.heads) * cfg.head_dim; + const kvw: usize = @as(usize, c.kv_heads) * cfg.head_dim; + const stride = qw + 2 * kvw; + const ids = d.buf("ids").slice(u32, max_block); + ids[0] = pending; + @memset(ids[1..n], c.mask); + d.buf("seq").slice(u32, 16)[0] = pending; + const E = m.weights.embed; + threads(e, d.pipe(.embed), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = 0, .add = 0 }, &.{ b(d.buf("ids")), bo(E.buf, E.off), A, b(d.buf("resid")) }, .{ h, n, 1 }); + const hi = anchor + n; + for (0..c.layers) |i| { + const L = &d.w.layers[i]; + // input norm (the residual takes the last sublayer's output first, from the second layer on) + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = @intFromBool(i > 0) }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.in_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + d.convPrepare(e, L.attn_conv, n); + d.project(e, L.q, b(d.buf("xc")), b(d.buf("qkv")), n, stride); + d.project(e, L.k, b(d.buf("xc")), bo(d.buf("qkv"), qw * 2), n, stride); + d.project(e, L.v, b(d.buf("xc")), bo(d.buf("qkv"), (qw + kvw) * 2), n, stride); + const pa = PArgs{ .rows = @intCast(n), .heads = c.heads, .kv_heads = c.kv_heads, .pos0 = @intCast(anchor), .stride = @intCast(stride), .q_off = 0, .k_off = @intCast(qw), .v_off = @intCast(qw + kvw), .ring = c.ring(i), .rope = @intFromBool(c.rope[i]), .eps = c.eps, .theta = c.theta }; + glue(e, d.pipe(.prep), pa, &.{ b(d.buf("qkv")), t(L.q_norm), t(L.k_norm), A, b(d.buf("q")), b(l.k[i]), b(l.v[i]) }, .{ c.heads + c.kv_heads, n, 1 }, .{ 32, 1, 1 }); + const span = c.span(i); + const lo = @max((anchor + 1) -| span, l.from); + const first = lo / key_block; + const blocks = (hi - 1) / key_block - first + 1; + const va = VArgs{ .rows = @intCast(n), .pos0 = @intCast(anchor), .heads = c.heads, .groups = c.kv_heads, .blocks = @intCast(blocks), .chunk = key_block, .first = @intCast(first), .scale = 1.0 / @sqrt(@as(f32, cfg.head_dim)), .hi = @intCast(hi), .window = span, .ring = c.ring(i), .floor = @intCast(l.from) }; + glue(e, d.pipe(.vec), va, &.{ b(d.buf("q")), b(l.k[i]), b(l.v[i]), A, b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")) }, .{ c.kv_heads, n, blocks }, .{ 32, c.heads / c.kv_heads, 1 }); + glue(e, m.ll(.merge_vec), va, &.{ b(d.buf("pm")), b(d.buf("pl")), b(d.buf("po")), A, b(d.buf("attn")) }, .{ c.heads, n, 1 }, .{ 1024, 1, 1 }); + d.project(e, L.o, b(d.buf("attn")), b(d.buf("y")), n, h); + // the attention conv's finish (side 1, its prepare's coefficients), then the post-attention norm + d.conv(e, L.attn_conv, b(d.buf("y")), b(d.buf("yc")), n, 1); + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(L.post_norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + d.convPrepare(e, L.mlp_conv, n); + d.project(e, L.gate, b(d.buf("xc")), b(d.buf("gu")), n, 2 * c.ffn); + d.project(e, L.up, b(d.buf("xc")), bo(d.buf("gu"), @as(usize, c.ffn) * 2), n, 2 * c.ffn); + threads(e, d.pipe(.silu), extern struct { rows: u32, width: u32 }{ .rows = @intCast(n), .width = c.ffn }, &.{ b(d.buf("gu")), A, b(d.buf("act")) }, .{ c.ffn, n, 1 }); + d.project(e, L.down, b(d.buf("act")), b(d.buf("y")), n, h); + d.conv(e, L.mlp_conv, b(d.buf("y")), b(d.buf("yc")), n, 1); + } + glue(e, d.pipe(.norm), NArgs{ .rows = @intCast(n), .width = c.hidden, .eps = c.eps, .add = 1 }, &.{ b(d.buf("resid")), b(d.buf("yc")), t(d.w.norm), A, b(d.buf("x")) }, .{ n, 1, 1 }, .{ 256, 1, 1 }); + // rows 1-15: the target's head, each row's top 32 (three passes of 2048), the selector's projection and path + const slots = n - 1; + const xr = bo(d.buf("x"), h * 2); + d.project(e, m.weights.head, xr, b(d.buf("logits")), slots, c.vocab); + d.project(e, d.w.hproj, xr, b(d.buf("hid")), slots, c.rank); + const chunks: u32 = (c.vocab + 2047) / 2048; + const TArgs = extern struct { n: u32, stride: u32, chunks: u32, from_ids: u32 }; + glue(e, d.pipe(.topk), TArgs{ .n = c.vocab, .stride = c.vocab, .chunks = chunks, .from_ids = 0 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv")), b(d.buf("ti")) }, .{ chunks, slots, 1 }, .{ 1024, 1, 1 }); + const second: u32 = (chunks * 32 + 2047) / 2048; + glue(e, d.pipe(.topk), TArgs{ .n = chunks * 32, .stride = chunks * 32, .chunks = second, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv")), b(d.buf("ti")), A, b(d.buf("tv2")), b(d.buf("ti2")) }, .{ second, slots, 1 }, .{ 1024, 1, 1 }); + glue(e, d.pipe(.topk), TArgs{ .n = second * 32, .stride = second * 32, .chunks = 1, .from_ids = 1 }, &.{ b(d.buf("logits")), b(d.buf("tv2")), b(d.buf("ti2")), A, b(d.buf("uv")), b(d.buf("ui")) }, .{ 1, slots, 1 }, .{ 1024, 1, 1 }); + const WArgs = extern struct { slots: u32, rank: u32, top: u32, vocab: u32 }; + glue(e, d.pipe(.walk), WArgs{ .slots = @intCast(slots), .rank = c.rank, .top = c.top, .vocab = c.vocab }, &.{ b(d.buf("uv")), b(d.buf("ui")), b(d.buf("hid")), t(d.w.pred), t(d.w.succ), A, b(d.buf("seq")) }, .{ 1, 1, 1 }, .{ c.rank, 1, 1 }); + } + + /// Each stream's `depth` drafts after `pending` at `position`: a whole block each (its rows see each other). + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const d = cast(ptr); + const c = &d.config; + for (items) |it| { + const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; + const anchor = it.position - 1; + if (l.end != anchor) return error.DraftContextGap; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeBlock(e, l, it.pending, anchor); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + const seq = d.buf("seq").slice(u32, 16); + for (seq[1..][0..it.depth], l.held[0..it.depth]) |x, *y| { + if (x >= c.vocab) return error.DraftNonfinite; + y.* = x; + } + l.held_len = it.depth; + } + } + + /// The pipelines' first launch, then a block timed (the depth rule prices a draft at a block's time over its rows). + fn warm(d: *Drafter) !void { + const l = try d.newLane(); + defer d.dropLane(l); + var ms: f64 = 0; + for (0..3) |run| { + const t0 = msNow(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.encodeBlock(e, l, 2, 0); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| return failed(msg); + if (run == 2) ms = msNow() - t0; + } + d.step_ms = ms / @as(f64, @floatFromInt(d.config.block - 1)); + } + + fn failed(msg: [*:0]const u8) anyerror { + std.log.err("ricursive DFlash2 drafter: command buffer failed: {s}", .{msg}); + return error.GpuFailed; + } +}; + +fn msNow() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) * 1e3 + @as(f64, @floatFromInt(ts.nsec)) / 1e6; +} diff --git a/zig/src/families/ricursive/dflash2_config.zig b/zig/src/families/ricursive/dflash2_config.zig new file mode 100644 index 00000000000..5d6b263dbce --- /dev/null +++ b/zig/src/families/ricursive/dflash2_config.zig @@ -0,0 +1,255 @@ +//! ricursiveAI's DFlash2 drafter for Ripple (Ripple-65B-Preview-DFlash2): its config and bf16 weights as published. +const std = @import("std"); +const ck = @import("../../core/checkpoint_metal.zig"); +const wts = @import("weights.zig"); +const cfg = @import("config.zig"); + +/// The release's 16,384-token draft window: the global layer's training rows (`inference/server/README.md`). +pub const global_window = 16384; +/// Streams a drafted server serves at most: each stream drafts in its own pass, so more tie plain, then trail it. +pub const max_streams = 2; + +/// Streams a drafted server opens: a named --parallel up to `max_streams`, else `max_streams`; null refuses more. +pub fn streams(lanes: u32, named: bool) ?u32 { + if (!named) return max_streams; + return if (lanes > max_streams) null else @max(lanes, 1); +} +/// Layers, tapped target layers and convolution taps this drafter has (the release's). +pub const max_layers = 5; +pub const max_taps = 5; + +pub const Config = struct { + layers: u32, + heads: u32, + kv_heads: u32, + hidden: u32, + ffn: u32, + vocab: u32, + window: u32, // the sliding layers' window + block: u32, + mask: u32, + rank: u32, + top: u32, + group: u32, + conv: u32, // the block convolution's taps + taps: [max_taps]u32, + global: [max_layers]bool = @splat(false), // full attention over the draft window + rope: [max_layers]bool = @splat(true), // false on the NoPE layer + theta: f32, + eps: f32, + + /// Keys a layer sees before a row: the sliding window, or the draft window on the global layer. + pub fn span(c: *const Config, l: usize) u32 { + return if (c.global[l]) global_window else c.window; + } + + /// A layer's ring of keys: its span and a block past it, whole 128-key blocks. + pub fn ring(c: *const Config, l: usize) u32 { + return std.mem.alignForward(u32, c.span(l) + c.block, 128); + } + + /// The coefficients a row's kernel projection writes: [side][tap][group]. + pub fn dyn(c: *const Config) u32 { + return 2 * c.conv * (c.hidden / c.group); + } +}; + +pub const Error = error{ NotRippleDFlash2, UnqualifiedRippleDFlash2 } || std.mem.Allocator.Error; + +/// The drafter's config.json; `target` its Ripple: the published drafter's geometry exactly, or a refusal. +pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, target: *const cfg.Config) Error!Config { + var doc = std.json.parseFromSlice(std.json.Value, gpa, bytes, .{}) catch return error.NotRippleDFlash2; + defer doc.deinit(); + if (doc.value != .object) return error.NotRippleDFlash2; + const o = doc.value.object; + const arch = o.get("architectures") orelse return error.NotRippleDFlash2; + if (arch != .array or arch.array.items.len != 1 or arch.array.items[0] != .string or !std.mem.eql(u8, arch.array.items[0].string, "DFlash2DraftModel")) return error.NotRippleDFlash2; + const d = o.get("dflash_config") orelse return error.NotRippleDFlash2; + if (d != .object) return error.NotRippleDFlash2; + const dc = d.object; + var c: Config = .{ + .layers = try int(o, "num_hidden_layers"), + .heads = try int(o, "num_attention_heads"), + .kv_heads = try int(o, "num_key_value_heads"), + .hidden = try int(o, "hidden_size"), + .ffn = try int(o, "intermediate_size"), + .vocab = try int(o, "vocab_size"), + .window = try int(o, "sliding_window"), + .block = try int(dc, "block_size"), + .mask = try int(dc, "mask_token_id"), + .rank = try int(dc, "selector_rank"), + .top = try int(dc, "selector_top_k"), + .group = try int(dc, "conv_group_size"), + .conv = try int(dc, "conv_kernel_size"), + .taps = undefined, + .theta = try float(o, "rope_theta"), + .eps = try float(o, "rms_norm_eps"), + }; + const taps = dc.get("target_layer_ids") orelse return error.NotRippleDFlash2; + if (taps != .array or taps.array.items.len != max_taps) return error.UnqualifiedRippleDFlash2; + for (taps.array.items, &c.taps) |x, *y| { + if (x != .integer or x.integer < 0 or x.integer >= target.layers) return error.UnqualifiedRippleDFlash2; + y.* = @intCast(x.integer); + } + if (c.layers != max_layers) return error.UnqualifiedRippleDFlash2; + const types = o.get("layer_types") orelse return error.NotRippleDFlash2; + if (types != .array or types.array.items.len != c.layers) return error.UnqualifiedRippleDFlash2; + for (types.array.items, 0..) |x, i| { + if (x != .string) return error.UnqualifiedRippleDFlash2; + if (std.mem.eql(u8, x.string, "full_attention")) c.global[i] = true else if (!std.mem.eql(u8, x.string, "sliding_attention")) return error.UnqualifiedRippleDFlash2; + } + // the NoPE layer: `no_rope_layers` in the drafter's config.json + if (o.get("no_rope_layers")) |nr| { + if (nr != .array) return error.UnqualifiedRippleDFlash2; + for (nr.array.items) |x| { + if (x != .integer or x.integer < 0 or x.integer >= c.layers) return error.UnqualifiedRippleDFlash2; + c.rope[@intCast(x.integer)] = false; + } + } + if (!(try qualified(o, &c, target))) return error.UnqualifiedRippleDFlash2; + return c; +} + +/// The published drafter's shape beside this target, the one the kernels and the release's server were checked at. +fn qualified(o: std.json.ObjectMap, c: *const Config, target: *const cfg.Config) Error!bool { + if ((try int(o, "head_dim")) != cfg.head_dim) return false; + if (o.get("attention_bias")) |b| if (b != .bool or b.bool) return false; + if (o.get("ffn_clamp_threshold")) |x| if (x != .null) return false; // the MLP runs unclamped + const expected = [_]bool{ false, false, false, false, true }; + const roped = [_]bool{ true, true, true, true, false }; + return c.hidden == target.hidden and c.vocab == target.vocab and c.mask < c.vocab and c.heads == 80 and + c.kv_heads == 8 and c.ffn == 40960 and c.window == 4096 and c.block == 16 and c.rank == 256 and c.top == 32 and + c.group == 16 and c.conv == 4 and c.hidden % c.group == 0 and c.theta == 10000 and + std.mem.eql(bool, &c.global, &expected) and std.mem.eql(bool, &c.rope, &roped); +} + +fn int(o: std.json.ObjectMap, k: []const u8) Error!u32 { + const v = o.get(k) orelse return error.NotRippleDFlash2; + if (v != .integer or v.integer <= 0 or v.integer > std.math.maxInt(u32)) return error.NotRippleDFlash2; + return @intCast(v.integer); +} + +fn float(o: std.json.ObjectMap, k: []const u8) Error!f32 { + const v = o.get(k) orelse return error.NotRippleDFlash2; + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| @floatCast(f), + else => error.NotRippleDFlash2, + }; +} + +pub const Conv = struct { base: wts.Tensor, proj: wts.Dense }; +pub const Layer = struct { + in_norm: wts.Tensor, + post_norm: wts.Tensor, + q_norm: wts.Tensor, + k_norm: wts.Tensor, + q: wts.Dense, + k: wts.Dense, + v: wts.Dense, + o: wts.Dense, + gate: wts.Dense, + up: wts.Dense, + down: wts.Dense, + attn_conv: Conv, + mlp_conv: Conv, +}; + +pub const Weights = struct { + fc: wts.Dense, // the taps' concatenation into the hidden width + hidden_norm: wts.Tensor, + norm: wts.Tensor, + hproj: wts.Dense, // the selector's hidden projection + pred: wts.Tensor, + succ: wts.Tensor, + layers: [max_layers]Layer, +}; + +/// Every tensor the release stores, each at its exact shape in bf16. +pub fn load(c: *const ck.Checkpoint, f: *const Config) !Weights { + const h: usize = f.hidden; + const kvw: usize = @as(usize, f.kv_heads) * cfg.head_dim; + const qw: usize = @as(usize, f.heads) * cfg.head_dim; + var w: Weights = .{ + .fc = try wts.dense(c, "", "fc.weight", h, h * max_taps), + .hidden_norm = try wts.get(c, "", "hidden_norm.weight", &.{h}), + .norm = try wts.get(c, "", "norm.weight", &.{h}), + .hproj = try wts.dense(c, "", "candidate_selector.hidden_projection.weight", f.rank, h), + .pred = try wts.get(c, "", "candidate_selector.predecessor_codebook", &.{ f.vocab, f.rank }), + .succ = try wts.get(c, "", "candidate_selector.successor_codebook", &.{ f.vocab, f.rank }), + .layers = undefined, + }; + for (&w.layers, 0..) |*l, i| { + var nb: [32]u8 = undefined; + const p = try std.fmt.bufPrint(&nb, "layers.{d}.", .{i}); + l.* = .{ + .in_norm = try wts.get(c, p, "input_layernorm.weight", &.{h}), + .post_norm = try wts.get(c, p, "post_attention_layernorm.weight", &.{h}), + .q_norm = try wts.get(c, p, "self_attn.q_norm.weight", &.{cfg.head_dim}), + .k_norm = try wts.get(c, p, "self_attn.k_norm.weight", &.{cfg.head_dim}), + .q = try wts.dense(c, p, "self_attn.q_proj.weight", qw, h), + .k = try wts.dense(c, p, "self_attn.k_proj.weight", kvw, h), + .v = try wts.dense(c, p, "self_attn.v_proj.weight", kvw, h), + .o = try wts.dense(c, p, "self_attn.o_proj.weight", h, qw), + .gate = try wts.dense(c, p, "mlp.gate_proj.weight", f.ffn, h), + .up = try wts.dense(c, p, "mlp.up_proj.weight", f.ffn, h), + .down = try wts.dense(c, p, "mlp.down_proj.weight", h, f.ffn), + .attn_conv = .{ .base = try wts.get(c, p, "attention_conv.base_kernel", &.{ 2, f.conv, h }), .proj = try wts.dense(c, p, "attention_conv.kernel_projection.weight", f.dyn(), h) }, + .mlp_conv = .{ .base = try wts.get(c, p, "mlp_conv.base_kernel", &.{ 2, f.conv, h }), .proj = try wts.dense(c, p, "mlp_conv.kernel_projection.weight", f.dyn(), h) }, + }; + } + return w; +} + +test "ricursive dflash2: the published drafter's config is qualified beside Ripple, another refused" { + const a = std.testing.allocator; + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + const bytes = @embedFile("fixtures/dflash2_config.json"); + const c = try parse(a, bytes, &target); + try std.testing.expectEqualSlices(u32, &.{ 1, 20, 39, 58, 77 }, &c.taps); + try std.testing.expectEqual(@as(u32, 4224), c.ring(0)); + try std.testing.expectEqual(@as(u32, 16512), c.ring(4)); + try std.testing.expectEqual(@as(u32, 2560), c.dyn()); + try std.testing.expect(!c.rope[4] and c.rope[3] and c.global[4] and !c.global[0]); + const other = try std.mem.replaceOwned(u8, a, bytes, "\"block_size\": 16", "\"block_size\": 8"); + defer a.free(other); + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, other, &target)); + const clamped = try std.mem.replaceOwned(u8, a, bytes, "\"no_rope_layers\"", "\"ffn_clamp_threshold\": 20, \"no_rope_layers\""); + defer a.free(clamped); + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, clamped, &target)); + const not = try std.mem.replaceOwned(u8, a, bytes, "DFlash2DraftModel", "Qwen3ForCausalLM"); + defer a.free(not); + try std.testing.expectError(error.NotRippleDFlash2, parse(a, not, &target)); +} + +test "ricursive dflash2: a drafter beside another target, past its layers or with its layers moved is refused" { + const a = std.testing.allocator; + const target = try cfg.parse(a, @embedFile("fixtures/config.json")); + const bytes = @embedFile("fixtures/dflash2_config.json"); + var wider = target; + wider.hidden = 6144; + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, bytes, &wider)); + var other_vocab = target; + other_vocab.vocab = 131072; + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, bytes, &other_vocab)); + const cases = [_][2][]const u8{ + .{ " 77\n ]", " 80\n ]" }, // a tap at the target's layer count + .{ "\"no_rope_layers\": [\n 4\n ]", "\"no_rope_layers\": [\n 3\n ]" }, // the NoPE layer moved + .{ "\"sliding_attention\",\n \"full_attention\"", "\"full_attention\",\n \"sliding_attention\"" }, // the global layer moved + }; + for (cases) |c| { + const changed = try std.mem.replaceOwned(u8, a, bytes, c[0], c[1]); + defer a.free(changed); + try std.testing.expect(!std.mem.eql(u8, changed, bytes)); + try std.testing.expectError(error.UnqualifiedRippleDFlash2, parse(a, changed, &target)); + } +} + +test "ricursive dflash2: two streams when --parallel is not named, a named count past two refused" { + try std.testing.expectEqual(@as(?u32, max_streams), streams(8, false)); + try std.testing.expectEqual(@as(?u32, max_streams), streams(1, false)); + try std.testing.expectEqual(@as(?u32, 1), streams(1, true)); + try std.testing.expectEqual(@as(?u32, 2), streams(2, true)); + try std.testing.expectEqual(@as(?u32, null), streams(3, true)); + try std.testing.expectEqual(@as(?u32, null), streams(8, true)); +} diff --git a/zig/src/families/ricursive/fixtures/dflash2_config.json b/zig/src/families/ricursive/fixtures/dflash2_config.json new file mode 100644 index 00000000000..f712f33ad91 --- /dev/null +++ b/zig/src/families/ricursive/fixtures/dflash2_config.json @@ -0,0 +1,65 @@ +{ + "architectures": [ + "DFlash2DraftModel" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bos_token_id": 100257, + "dflash_config": { + "block_size": 16, + "conv_group_size": 16, + "conv_kernel_size": 4, + "mask_token_id": 100278, + "selector_rank": 256, + "selector_top_k": 32, + "target_layer_ids": [ + 1, + 20, + 39, + 58, + 77 + ] + }, + "draft_vocab_size": 100352, + "dtype": "bfloat16", + "eos_token_id": [ + 100265, + 100257 + ], + "head_dim": 128, + "hidden_act": "silu", + "hidden_size": 5120, + "initializer_range": 0.02, + "intermediate_size": 40960, + "is_causal": false, + "layer_types": [ + "sliding_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "full_attention" + ], + "max_position_embeddings": 131072, + "max_window_layers": 5, + "model_type": "qwen3", + "no_rope_layers": [ + 4 + ], + "num_attention_heads": 80, + "num_hidden_layers": 5, + "num_key_value_heads": 8, + "num_target_layers": 80, + "pad_token_id": 100277, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "rope_theta": 10000.0, + "rope_type": "default" + }, + "rope_theta": 10000.0, + "sliding_window": 4096, + "tie_word_embeddings": false, + "transformers_version": "5.12.1", + "use_cache": true, + "use_sliding_window": true, + "vocab_size": 100352 +} diff --git a/zig/src/families/ricursive/forward.zig b/zig/src/families/ricursive/forward.zig index dc77e1370af..c3c8fedaa6f 100644 --- a/zig/src/families/ricursive/forward.zig +++ b/zig/src/families/ricursive/forward.zig @@ -23,16 +23,16 @@ const VArgs = extern struct { rows: u32, pos: u32, heads: u32, groups: u32, bloc const every_key = std.math.maxInt(i32); pub const B = struct { buf: mtl.Buffer = undefined, off: usize = 0, args: bool = false }; -fn b(buf: mtl.Buffer) B { +pub fn b(buf: mtl.Buffer) B { return .{ .buf = buf }; } -fn bo(buf: mtl.Buffer, off: usize) B { +pub fn bo(buf: mtl.Buffer, off: usize) B { return .{ .buf = buf, .off = off }; } -fn t(x: wts.Tensor) B { +pub fn t(x: wts.Tensor) B { return .{ .buf = x.buffer, .off = x.offset }; } -const A = B{ .args = true }; +pub const A = B{ .args = true }; const Enc = struct { e: mtl.ComputeEncoder, @@ -49,31 +49,8 @@ const Enc = struct { if (groups) x.e.dispatchGroups(g3, t3) else x.e.dispatchThreads(g3, t3); } - /// y [rows, d.n] (rows `ldy` apart, at byte `out_off`) = x W^T: the GEMM a prompt chunk, the row kernels a window. fn dense(x: Enc, d: wts.Dense, in: B, out: mtl.Buffer, out_off: usize, n_rows: usize, ldy: usize) void { - const e = x.e; - if (n_rows <= st.batch_rows) { - // the variant holding the rows in registers: 1, 2, 4, 8, 16 or 32 - const v: @import("model.zig").Llama = if (n_rows <= 1) .matvec_1 else if (n_rows <= 2) .matvec_2 else if (n_rows <= 4) .matvec_4 else if (n_rows <= 8) .matvec_8 else if (n_rows <= 16) .matvec_16 else .matvec_32; - e.setPipeline(x.m.ll(v)); - e.setBuffer(in.buf, in.off, 0); - e.setBuffer(d.buf, d.off, 1); - e.setValue(MArgs{ .rows = @intCast(n_rows), .n = @intCast(d.n), .k = @intCast(d.k), .ldy = @intCast(ldy) }, 2); - e.setBuffer(out, out_off, 3); - e.dispatchGroups(mtl.Size.of((d.n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); - return; - } - const tn = (d.n + 127) / 128; - const tm = (n_rows + 63) / 64; - e.setPipeline(x.m.gemm[@intFromBool(n_rows % 64 == 0)][@intFromBool(d.n % 128 == 0)]); - e.setBuffer(in.buf, in.off, 0); - e.setBuffer(d.buf, d.off, 1); - var p: [16]i32 = @splat(0); - const vals = [_]usize{ n_rows, d.n, d.k, d.k, d.k, ldy, tn, tm, 2, d.k / 256, 0, 0, 0, 0, 0 }; - for (vals, 0..) |v, i| p[i] = @intCast(v); - e.setBytes(std.mem.asBytes(&p), 2); - e.setBuffer(out, out_off, 3); - e.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); + denseRows(x.e, x.m, d, in, out, out_off, n_rows, ldy); } /// An MLP projection: bf16, or NVFP4 rows; a prompt chunk dequantizes exactly, then the GEMM applies the global. @@ -127,8 +104,34 @@ const Enc = struct { } }; -/// All rows' logits or the last's; ids on the GPU; the last row drawn on the GPU; committed unwaited into `flight`. -pub const Out = struct { all: bool = false, timing: ?*Timing = null, ids: ?B = null, draw: ?Draw = null, flight: ?*mtl.CommandBuffer = null }; +/// y [rows, d.n] (rows `ldy` apart, at byte `out_off`) = x W^T: the GEMM past 32 rows, the row kernels to 32. +pub fn denseRows(e: mtl.ComputeEncoder, m: *const Model, d: wts.Dense, in: B, out: mtl.Buffer, out_off: usize, n_rows: usize, ldy: usize) void { + if (n_rows <= st.batch_rows) { + // the variant holding the rows in registers: 1, 2, 4, 8, 16 or 32 + const v: @import("model.zig").Llama = if (n_rows <= 1) .matvec_1 else if (n_rows <= 2) .matvec_2 else if (n_rows <= 4) .matvec_4 else if (n_rows <= 8) .matvec_8 else if (n_rows <= 16) .matvec_16 else .matvec_32; + e.setPipeline(m.ll(v)); + e.setBuffer(in.buf, in.off, 0); + e.setBuffer(d.buf, d.off, 1); + e.setValue(MArgs{ .rows = @intCast(n_rows), .n = @intCast(d.n), .k = @intCast(d.k), .ldy = @intCast(ldy) }, 2); + e.setBuffer(out, out_off, 3); + e.dispatchGroups(mtl.Size.of((d.n + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + return; + } + const tn = (d.n + 127) / 128; + const tm = (n_rows + 63) / 64; + e.setPipeline(m.gemm[@intFromBool(n_rows % 64 == 0)][@intFromBool(d.n % 128 == 0)]); + e.setBuffer(in.buf, in.off, 0); + e.setBuffer(d.buf, d.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ n_rows, d.n, d.k, d.k, d.k, ldy, tn, tm, 2, d.k / 256, 0, 0, 0, 0, 0 }; + for (vals, 0..) |v, i| p[i] = @intCast(v); + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(out, out_off, 3); + e.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, 2), mtl.Size.of(32, 4, 2)); +} + +/// All rows' logits or the last's, ids or draws on the GPU, committed into `flight`; `taps`: a drafter's features. +pub const Out = struct { all: bool = false, timing: ?*Timing = null, ids: ?B = null, draw: ?Draw = null, flight: ?*mtl.CommandBuffer = null, taps: ?B = null }; /// A GPU draw of the last row's logits: argmax, or the keyed sampler at `position` (lanes' gpu_rule and gpu_full). pub const Draw = struct { @@ -174,7 +177,14 @@ pub fn runShared(m: *const Model, s: *st.Scratch, segments: []const Segment, ids const ea = Args{ .rows = @intCast(n), .width = @intCast(h), .scale = c.embed_scale }; x.glue(m.pipe(.embed), ea, &.{ out.ids orelse b(s.ids), bo(W.embed.buf, W.embed.off), A, b(s.resid), b(s.v0) }, .{ h, n, 1 }, .{ 256, 1, 1 }, false); x.addNorm(n, null, W.layers[0].input_norm, W.layers[0].attn.blend); - for (W.layers, 0..) |l, i| try layer(x, segments, l, i, n, if (i + 1 < W.layers.len) W.layers[i + 1] else null); + for (W.layers, 0..) |l, i| { + try layer(x, segments, l, i, n, if (i + 1 < W.layers.len) W.layers[i + 1] else null); + // a tapped layer's residual before the final norm: z-lab's `hidden_states[layer + 1]` (extract_context_feature) + if (out.taps) |tb| if (m.tap_at[i] >= 0) { + const ta = [4]u32{ @intCast(n), @intCast(h), m.taps, @intCast(m.tap_at[i]) }; + x.glue(m.tap.?, ta, &.{ b(s.resid), A, tb }, .{ h, n, 1 }, .{ 256, 1, 1 }, false); + }; + } if (out.all) { x.dense(W.head, b(s.x), s.logits_all, 0, n, c.vocab); } else { diff --git a/zig/src/families/ricursive/model.zig b/zig/src/families/ricursive/model.zig index 4109af6e93a..a28fe2e542d 100644 --- a/zig/src/families/ricursive/model.zig +++ b/zig/src/families/ricursive/model.zig @@ -37,6 +37,10 @@ pub const Model = struct { fp4: ?Fp4 = null, /// RoPE's inverse frequencies: fp32 [head_dim / 2]. inv: mtl.Buffer, + /// A drafter's taps: each layer's place in its features (-1 untapped), their count, and the copy (dflash2.metal). + tap_at: [cfg.max_layers]i8 = @splat(-1), + taps: u32 = 0, + tap: ?mtl.Pipeline = null, pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { const pool = mtl.objc.Pool.push(); @@ -44,6 +48,9 @@ pub const Model = struct { const m = try gpa.create(Model); errdefer gpa.destroy(m); m.gpa = gpa; + m.tap_at = @splat(-1); + m.taps = 0; + m.tap = null; m.config = try cfg.Config.read(gpa, io, dir); m.device = try mtl.Device.init(); errdefer m.device.deinit(); @@ -107,7 +114,25 @@ pub const Model = struct { return m.llama[@backingInt(g)]; } + /// The drafter's layers, in the order its features concatenate them; the copy compiled once. + pub fn setTaps(m: *Model, layers: []const u32) !void { + if (layers.len == 0 or layers.len > 16) return error.UnsupportedRicursiveTaps; + var at: [cfg.max_layers]i8 = @splat(-1); + for (layers, 0..) |l, i| { + if (l >= m.config.layers or at[l] >= 0) return error.UnsupportedRicursiveTaps; + at[l] = @intCast(i); + } + if (m.tap == null) { + const lib = try mtl.Library.fromSource(m.device, ks.ricursive_dflash2, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + m.tap = try mtl.Pipeline.init(m.device, lib, "rc_tap", false); + } + m.tap_at = at; + m.taps = @intCast(layers.len); + } + pub fn deinit(m: *Model) void { + if (m.tap) |p| p.deinit(); m.inv.deinit(); if (m.fp4) |*f| f.deinit(); for (m.gemm) |row| for (row) |p| p.deinit(); diff --git a/zig/src/families/ricursive/ricursive.zig b/zig/src/families/ricursive/ricursive.zig index 2f00b7e37a6..a4076afc702 100644 --- a/zig/src/families/ricursive/ricursive.zig +++ b/zig/src/families/ricursive/ricursive.zig @@ -8,6 +8,8 @@ pub const backend = @import("backend.zig"); pub const budget = @import("budget.zig"); pub const snapshot = @import("snapshot.zig"); pub const contracts = @import("contracts.zig"); +pub const dflash2 = @import("dflash2.zig"); +pub const dflash2_config = @import("dflash2_config.zig"); test { _ = config; @@ -16,4 +18,5 @@ test { _ = budget; _ = snapshot; _ = contracts; + _ = dflash2_config; } diff --git a/zig/src/families/ricursive/state.zig b/zig/src/families/ricursive/state.zig index 736dbc93c30..a480e6c93f5 100644 --- a/zig/src/families/ricursive/state.zig +++ b/zig/src/families/ricursive/state.zig @@ -58,6 +58,9 @@ pub const Cache = struct { capacity: usize, len: usize = 0, follow: ?mtl.ResidencySet.Follow = null, + /// The latest tapped rows a drafter may absorb: positions [start, start + rows), in a scratch's or last_tap. + tap: Tap = .{}, + last_tap: ?mtl.Buffer = null, // the prompt's last row's taps, kept for the first draft pub fn setResident(self: *Cache, hook: ?mtl.ResidencySet.Follow) void { if (self.follow) |f| mtl.resident.fields.apply(self, f, false); @@ -91,9 +94,12 @@ pub const Cache = struct { self.setResident(null); self.kv.deinit(); self.logits.deinit(); + if (self.last_tap) |x| x.deinit(); } }; +pub const Tap = struct { buf: ?mtl.Buffer = null, off: usize = 0, start: usize = 0, rows: usize = 0 }; + pub const fields = [_][]const u8{ "ids", "resid", "v0", "x", "vx", "q", "g", "qn", "att", "y", "gu", "act", "logits_all", "pm", "pl", "po", "wq" }; /// Bytes of each Scratch buffer for `rows` rows at once, in `fields` order. @@ -137,6 +143,7 @@ pub const Scratch = struct { pl: mtl.Buffer, po: mtl.Buffer, wq: mtl.Buffer, // a prompt chunk's NVFP4 projection as bf16 (its global left to the GEMM) + taps: ?mtl.Buffer = null, // with a drafter: every row's tapped residuals (bf16 [rows, taps, hidden]) rows: usize, /// Buffers for `rows` rows at once (batch_rows for decode, prompt_rows for prompt chunks). @@ -150,11 +157,13 @@ pub const Scratch = struct { made += 1; } s.rows = rows; + s.taps = null; return s; } pub fn deinit(s: *Scratch) void { inline for (fields) |f| @field(s, f).deinit(); + if (s.taps) |x| x.deinit(); } }; diff --git a/zig/src/families/ricursive/weights.zig b/zig/src/families/ricursive/weights.zig index 636acf6f3ba..2603195ffee 100644 --- a/zig/src/families/ricursive/weights.zig +++ b/zig/src/families/ricursive/weights.zig @@ -59,7 +59,7 @@ fn require(t: Tensor, dtype: @TypeOf(t.dtype), dims: []const usize) error{Unexpe } /// The bf16 tensor `prefix ++ suffix` of exactly `dims`. -fn get(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, dims: []const usize) !Tensor { +pub fn get(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, dims: []const usize) !Tensor { return getAs(c, prefix, suffix, .bf16, dims); } @@ -89,7 +89,7 @@ fn proj(c: *const ck.Checkpoint, f: *const cfg.Config, prefix: []const u8, compt } /// The release's bf16 [n, k] matrix in place: k whole 256s for the GEMM's steps, 8-byte aligned for the row kernel. -fn dense(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, n: usize, k: usize) !Dense { +pub fn dense(c: *const ck.Checkpoint, prefix: []const u8, suffix: []const u8, n: usize, k: usize) !Dense { const w = try get(c, prefix, suffix, &.{ n, k }); if (k % 256 != 0 or w.offset % 8 != 0) { std.log.err("ricursive: {s}{s} at byte {d}: the row kernels need 8-byte rows of whole 256s", .{ prefix, suffix, w.offset }); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index c5e81f395fc..7ebb3010bb1 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -295,7 +295,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; if (@import("qwen27_mtp.zig").refusal(o.mtp_drafts, o.mtp_confidence, o.drafter != null, std.mem.eql(u8, t, "qwen3_5") and dense)) |why| return why; - if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark) and Llama (a smaller Llama on the same tokenizer)"; + if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop") and !std.mem.eql(u8, t, "ricursive")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark), Llama (a smaller Llama on the same tokenizer) and Ripple (its DFlash2 drafter)"; const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; diff --git a/zig/src/native/ricursive.zig b/zig/src/native/ricursive.zig index 4b95b112a7a..082c2c242bd 100644 --- a/zig/src/native/ricursive.zig +++ b/zig/src/native/ricursive.zig @@ -12,6 +12,8 @@ const Host = struct { io: std.Io, model: *fr.Model, metal: *fr.backend.Metal, + draft: ?*fr.dflash2.Drafter = null, // --drafter: the publisher's DFlash2 drafter, reading the target's taps + wrap: ?lanes.drafted.Drafted = null, warm: mtl.keepalive.Target = undefined, // the residency set's, or the bare queue's, for the lane host's idle ticker resident: ?Resident = null, // weights and scratch kept wired between requests, when they fit the 70% limit config: lanes.Config, @@ -28,6 +30,8 @@ const Host = struct { h.core.deinit(); h.config.deinit(h.gpa); drop(h); + if (h.wrap) |*w| w.deinit(); + if (h.draft) |d| d.deinit(); h.metal.deinit(); h.model.deinit(); h.gpa.destroy(h); @@ -35,6 +39,11 @@ const Host = struct { }; pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const drafted = o.drafts and o.drafter != null; + const lanes_n: u32 = if (drafted) fr.dflash2_config.streams(o.lanes, o.lanes_fixed) orelse { + problem.* = try std.fmt.allocPrint(a, "--drafter with --parallel {d}: Ripple's DFlash2 drafter is served with up to {d} streams; each stream drafts in its own pass, so past that it ties plain decode on most replies and then falls behind it; lower --parallel, or serve without --drafter", .{ o.lanes, fr.dflash2_config.max_streams }); + return null; + } else o.lanes; const pool = mtl.objc.Pool.push(); defer pool.pop(); const model = fr.Model.load(gpa, io, o.dir) catch |err| { @@ -47,16 +56,24 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope return null; }; errdefer model.deinit(); + const draft = try loadDrafter(a, gpa, io, o, model, problem) orelse if (drafted) { + model.deinit(); + return null; + } else null; + errdefer if (draft) |d| d.deinit(); var ram: u64 = 0; var len: usize = @sizeOf(u64); if (std.c.sysctlbyname("hw.memsize", &ram, &len, null, 0) != 0) ram = 0; // the decode window's and the prompt chunk's buffers - const scratch: u64 = fr.state.scratchBytes(&model.config, fr.state.batch_rows) + fr.state.scratchBytes(&model.config, fr.state.prompt_rows); + var scratch: u64 = fr.state.scratchBytes(&model.config, fr.state.batch_rows) + fr.state.scratchBytes(&model.config, fr.state.prompt_rows); + // a drafter's weights and scratch, and the target's tapped rows for it + if (draft) |d| scratch += d.checkpoint.residentBytes() + fr.dflash2.Drafter.fixedBytes(&d.config) + (fr.state.batch_rows + fr.state.prompt_rows) * fr.dflash2_config.max_taps * model.config.hidden * 2; const budget = try fr.budget.caches(ram, model.device.maxWorkingSet(), null, model.checkpoint.residentBytes() + scratch); const most: usize = @min(model.config.context, fr.state.max_capacity); const fits = fr.budget.longest(&model.config, budget, most); if (o.context) |asked| if (asked > fr.config.max_context) { problem.* = try std.fmt.allocPrint(a, "--context {d}: the native Ripple engine is checked to {d} tokens; longer contexts are refused until a run at that length qualifies them", .{ asked, fr.config.max_context }); + if (draft) |d| d.deinit(); model.deinit(); return null; }; @@ -66,26 +83,37 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope try std.fmt.allocPrint(a, "--context {d}: this Mac's Ripple caches fit {d} tokens beside the weights under its load limit (75% of RAM)", .{ asked, fits }) else try a.dupe(u8, "this Mac's load limit (75% of RAM) leaves no room for a Ripple stream's caches beside the weights"); + if (draft) |d| d.deinit(); model.deinit(); // after the message, so a failed allocation leaves the model to the errdefer return null; } std.log.info("ricursive: {d:.1} GiB for caches, context up to {d} tokens ({d:.2} GiB a full stream)", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window, @as(f64, @floatFromInt(fr.state.cacheBytes(&model.config, @intCast(window + 1)))) / (1 << 30) }); - const streams: u32 = @max(o.lanes, 1); + const streams: u32 = @max(lanes_n, 1); const h = try gpa.create(Host); errdefer gpa.destroy(h); h.gpa = gpa; h.io = io; h.model = model; h.resident = null; - h.metal = try fr.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = streams, .budget = budget }); + h.draft = null; + h.wrap = null; + const lane_bytes: u64 = if (draft) |d| fr.dflash2.Drafter.laneBytes(&d.config) else 0; + h.metal = try fr.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = streams, .budget = budget, .drafts = draft != null, .drafter_bytes = lane_bytes }); errdefer h.metal.deinit(); try h.metal.warm(); - h.config = try lanes.Config.init(gpa, h.metal.facts(), fr.state.window_rows, fr.state.window_rows - 1); + if (draft) |d| { + try h.metal.measure(); // the depth rule prices drafts against the window forward's cost by rows + h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter()); + h.draft = d; + } + errdefer if (h.wrap) |*w| w.deinit(); + const facts = if (h.wrap) |*w| w.facts(h.metal.facts()) else h.metal.facts(); + h.config = try lanes.Config.init(gpa, facts, fr.state.window_rows, fr.state.window_rows - 1); errdefer h.config.deinit(gpa); h.clock = .{ .io = io }; - h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock()); + h.core = lanes.Engine.init(gpa, &h.config, if (h.wrap) |*w| w.backend() else h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = fr.state.prompt_rows, .structures = true, .logprobs = true }); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = lanes_n, .context_window = @intCast(window), .prefill_step = fr.state.prompt_rows, .draft_sources = .{ .drafter = if (draft != null) .{ .kind = "DFlash2 drafter", .name = o.drafter_name orelse o.drafter.? } else null }, .structures = true, .logprobs = true }); h.host.info_.reasoning_optional = true; // Ripple writes `` itself when it thinks, and answers bare otherwise h.host.info_.thinking_budget = false; // its think markers are spelled, not one token each: no close can be forced h.cache = null; @@ -116,12 +144,17 @@ fn hold(h: *Host) !void { try list.append(h.gpa, m.inv); try mtl.resident.fields.append(h.gpa, &list, &h.metal.scratch); try mtl.resident.fields.append(h.gpa, &list, &h.metal.prompt); + if (h.draft) |d| try d.buffers(h.gpa, &list); h.resident = try Resident.hold(h.gpa, h.io, m.device, m.queue, list.items, "ricursive"); - if (h.resident) |*r| h.metal.setResident(r.follow()); + if (h.resident) |*r| { + h.metal.setResident(r.follow()); + if (h.draft) |d| d.setResident(r.follow()); + } h.warm = if (h.resident) |*r| r.target() else .{ .queue = m.queue }; } fn drop(h: *Host) void { + if (h.draft) |d| d.setResident(null); h.metal.setResident(null); if (h.resident) |*r| r.deinit(); h.resident = null; @@ -141,3 +174,23 @@ fn fitCache(ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const }; _ = store.giveBack(restoring, prompt, Left{ .s = store }); } + +/// --drafter's DFlash2 drafter for this target, loaded and warmed; null with `problem` set when it is refused. +fn loadDrafter(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, model: *fr.Model, problem: *[]const u8) !?*fr.dflash2.Drafter { + if (!o.drafts) return null; + const dir = o.drafter orelse return null; + const c = fr.dflash2.Drafter.readConfig(gpa, io, dir, &model.config) catch |err| { + problem.* = switch (err) { + error.NotRippleDFlash2 => try std.fmt.allocPrint(a, "--drafter: {s} is not a DFlash2 drafter (DFlash2DraftModel); Ripple takes ricursiveAI/Ripple-65B-Preview-DFlash2", .{dir}), + error.UnqualifiedRippleDFlash2 => try std.fmt.allocPrint(a, "--drafter: {s} is not the drafter checked against this Ripple (ricursiveAI/Ripple-65B-Preview-DFlash2's geometry and taps)", .{dir}), + else => try std.fmt.allocPrint(a, "--drafter: {s}'s config.json cannot be read ({s})", .{ dir, @errorName(err) }), + }; + return null; + }; + const d = fr.dflash2.Drafter.init(gpa, io, model, dir, c) catch |err| { + problem.* = try std.fmt.allocPrint(a, "--drafter: the DFlash2 drafter in {s} cannot load ({s}); it is served bf16, as published", .{ dir, @errorName(err) }); + return null; + }; + std.log.info("ricursive drafter: {s}: DFlash2, {d} layers, bf16, {d:.2} GiB of weights, {d}-row blocks over layers {any}", .{ dir, c.layers, @as(f64, @floatFromInt(d.checkpoint.residentBytes())) / (1 << 30), c.block, c.taps }); + return d; +} diff --git a/zig/tests/contract/metal_ricursive_all.zig b/zig/tests/contract/metal_ricursive_all.zig index 41c47bbde3f..8f8b96758f9 100644 --- a/zig/tests/contract/metal_ricursive_all.zig +++ b/zig/tests/contract/metal_ricursive_all.zig @@ -1,4 +1,4 @@ -//! Ripple's registrations as one set: its kernels (NVFP4 too) and controls, llama's, the draw; and the roll call. +//! Ripple's registrations as one set: its kernels (NVFP4, DFlash2 too) and controls, llama's, the draw; the roll call. const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); @@ -10,6 +10,7 @@ const sample = @import("metal_ricursive_sample.zig"); const fp4 = @import("metal_ricursive_fp4.zig"); const fp4_gemm = @import("metal_ricursive_fp4_gemm.zig"); const controls = @import("metal_ricursive_controls.zig"); +const dflash2 = @import("metal_ricursive_dflash2.zig"); const llama = @import("metal_llama.zig"); const dense = @import("metal_llama_dense.zig"); const llama_attention = @import("metal_llama_attention.zig"); @@ -18,9 +19,10 @@ const g = contract.gates; const family = rc.family; const R = rc.R; -/// The label Ripple's registrations of llama's pipelines carry, and those at o_proj's reduction. +/// The label Ripple's registrations of llama's pipelines carry, those at o_proj's reduction, and its DFlash2 drafter's. const label = "ricursive llama"; const o_label = label ++ " o"; +const draft_label = label ++ " dflash2"; const matvec_rows = [_]u32{ 1, 2, 4, 8, 16, 32 }; fn wanted(only: ?[]const u8, name: []const u8) bool { @@ -56,6 +58,21 @@ fn oGemmShapes(am: bool, an: bool) [2]c.Shape { const merge_shapes = [_]c.Shape{ .{ .rows = 16, .n = R.heads, .k = 544 }, .{ .rows = 16, .n = R.heads, .k = 9 } }; const argmax_shapes = [_]c.Shape{.{ .rows = 1, .n = 1, .k = R.vocab }}; +/// The drafter's one new reduction, fc's 25,600 (an absorb to 32 rows); its o_proj's 10,240 is the target's. +fn draftMatvecShapes(per: u32) [2]c.Shape { + const k = R.hidden * dflash2.D.taps; + return .{ .{ .rows = per, .n = 1024, .k = k }, .{ .rows = per, .n = R.hidden, .k = k } }; +} + +/// fc's GEMM over a 2,048-row absorb (its 64-row tiles repeat) and a ragged one; its 5,120 outputs are whole tiles. +fn draftGemmShapes(am: bool) [2]c.Shape { + const k = R.hidden * dflash2.D.taps; + return if (am) .{ .{ .rows = 64, .n = 1024, .k = k }, .{ .rows = 128, .n = 1024, .k = k } } else .{ .{ .rows = 33, .n = 1024, .k = k }, .{ .rows = 100, .n = 1024, .k = k } }; +} + +/// The drafter's merge over a sliding layer's most blocks (34) and the global layer's (130). +const draft_merge_shapes = [_]c.Shape{ .{ .rows = 16, .n = R.heads, .k = 34 }, .{ .rows = 16, .n = R.heads, .k = 130 } }; + /// The probes made for a run, freed together. pub const Set = struct { point: std.ArrayList(*rc.Pointwise) = .empty, @@ -71,9 +88,12 @@ pub const Set = struct { fp4_matvec: std.ArrayList(*fp4.Matvec) = .empty, fp4_dequant: std.ArrayList(*fp4.Dequant) = .empty, fp4_gemm: std.ArrayList(*fp4_gemm.Gemm) = .empty, + dflash2: dflash2.Suite = .{}, pub fn deinit(s: *Set, a: std.mem.Allocator) void { + s.dflash2.deinit(a); inline for (@typeInfo(Set).@"struct".field_names) |f| { + if (comptime std.mem.eql(u8, f, "dflash2")) continue; const list = &@field(s, f); for (list.items) |p| { p.deinit(); @@ -166,6 +186,8 @@ pub const Set = struct { if (wanted(only, sample.spec().name)) try keep(a, &s.sample, try sample.Sample.init(a, device, queue), kernels); try s.collectFp4(a, device, queue, tensor, kernels, only, &functions); try s.collectO(a, device, queue, tensor, kernels, only); + try s.collectDraft(a, device, queue, tensor, kernels, only); + try s.dflash2.collect(.{ .a = a, .device = device, .queue = queue, .kernels = kernels, .only = only }, &functions); try family.requireComplete(functions.items); try s.plant(a, device, queue, tensor, kernels, only); } @@ -213,10 +235,44 @@ pub const Set = struct { } } + /// llama's pipelines at the shapes only the DFlash2 drafter runs them at (already on the roll call above). + fn collectDraft(s: *Set, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, tensor: bool, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + var buf: [64]u8 = undefined; + for (matvec_rows, family.llama_names[0..matvec_rows.len]) |per, fun| { + if (!wanted(only, try std.fmt.bufPrint(&buf, "{s} {s}", .{ draft_label, fun }))) continue; + var m = try dense.Matvec.init(a, device, queue, per, .none); + m.retarget(draft_label, draftMatvecShapes(per)) catch |err| { + m.deinit(); + return err; + }; + try keep(a, &s.matvec, m, kernels); + } + // fc's 5,120 outputs are whole 128-column tiles: only the forms with `an` run + for ([_]bool{ false, true }) |am| { + if (!tensor or !wanted(only, try std.fmt.bufPrint(&buf, "{s} ll_gemm_{d}1", .{ draft_label, @intFromBool(am) }))) continue; + var m = try dense.Gemm.init(a, device, queue, am, true, .none); + m.retarget(draft_label, draftGemmShapes(am)) catch |err| { + m.deinit(); + return err; + }; + try keep(a, &s.gemm, m, kernels); + } + if (wanted(only, draft_label ++ " ll_merge_vec")) { + var m = try llama_attention.MergeVec.init(a, device, queue, .none); + m.name = draft_label ++ " ll_merge_vec"; + m.served = &draft_merge_shapes; + try keep(a, &s.merge, m, kernels); + } + } + /// Each control: its kernel built with one planted fault, registered beside the kernels. fn plant(s: *Set, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, tensor: bool, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { for (std.enums.values(controls.Mutation)) |m| { if (m == .none or !wanted(only, m.name())) continue; + if (m.dflash2()) { + try s.dflash2.plant(.{ .a = a, .device = device, .queue = queue, .kernels = kernels, .only = only }, m); + continue; + } switch (m) { .embed_own_row => try keep(a, &s.point, try rc.Pointwise.init(a, device, queue, .embed, m), kernels), .gate_early_round => try keep(a, &s.point, try rc.Pointwise.init(a, device, queue, .gate, m), kernels), @@ -234,14 +290,15 @@ pub const Set = struct { .fp4_gemm_no_global => if (tensor) { try keep(a, &s.fp4_gemm, try fp4_gemm.Gemm.init(a, device, queue, false, false, m), kernels); }, - .none => unreachable, + .none, .df_tap_next_slot, .df_norm_half_mean, .df_norm16_no_weight, .df_embed_own_row, .df_prep_ropes_nope, .df_conv_three_taps, .df_silu_no_negative, .df_vec_no_floor, .df_topk_ascending, .df_walk_from_pending => unreachable, } } } }; -/// Gate 5's texts for `ricursive ` launches: the glue, the draw, or the attention (nax.h inlined; fragments pre-M5). +/// Gate 5's texts for `ricursive ` launches: the glue, DFlash2's, the draw, or the attention (nax.h inlined pre-M5). pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !struct { here: []const u8, pre_m5: []const u8 } { + if (std.mem.startsWith(u8, name, "ricursive dflash2 ")) return .{ .here = sources.ricursive_dflash2, .pre_m5 = sources.ricursive_dflash2 }; if (std.mem.indexOf(u8, name, " attention ") != null) { const head = try family.attentionHeader(a); const body = try std.mem.replaceOwned(u8, a, sources.ricursive_attention_nax, "#include \"../nax.h\"", sources.nax); diff --git a/zig/tests/contract/metal_ricursive_controls.zig b/zig/tests/contract/metal_ricursive_controls.zig index 5061837c076..074b80a3621 100644 --- a/zig/tests/contract/metal_ricursive_controls.zig +++ b/zig/tests/contract/metal_ricursive_controls.zig @@ -3,6 +3,7 @@ const std = @import("std"); const mtl = @import("metal"); const contract = @import("contract"); const tf = @import("tensorfold"); +const ks = @import("kernel_sources"); const family = tf.ricursive.contracts; pub const Mutation = enum { @@ -22,6 +23,21 @@ pub const Mutation = enum { fp4_global_late, fp4_dequant_unscaled, fp4_gemm_no_global, + df_tap_next_slot, + df_norm_half_mean, + df_norm16_no_weight, + df_embed_own_row, + df_prep_ropes_nope, + df_conv_three_taps, + df_silu_no_negative, + df_vec_no_floor, + df_topk_ascending, + df_walk_from_pending, + + /// A control of the DFlash2 drafter's kernels (dflash2.metal), planted by metal_ricursive_dflash2.zig. + pub fn dflash2(m: Mutation) bool { + return @backingInt(m) >= @backingInt(Mutation.df_tap_next_slot); + } pub fn name(m: Mutation) []const u8 { return switch (m) { @@ -41,6 +57,16 @@ pub const Mutation = enum { .fp4_global_late => "control: metal ricursive fp4 matvec, the global applied after the sum rounds to bf16", .fp4_dequant_unscaled => "control: metal ricursive fp4 dequant, a block's values left without its scale", .fp4_gemm_no_global => "control: metal ricursive fp4 gemm, the sums never take the global", + .df_tap_next_slot => "control: metal ricursive dflash2 tap, the residual lands in the next tap's slot", + .df_norm_half_mean => "control: metal ricursive dflash2 norm, the mean of squares is halved", + .df_norm16_no_weight => "control: metal ricursive dflash2 norm16, the weight is never applied", + .df_embed_own_row => "control: metal ricursive dflash2 embed, row r reads table row r, not row ids[r]", + .df_prep_ropes_nope => "control: metal ricursive dflash2 prep, the NoPE layer's q and k are rotated too", + .df_conv_three_taps => "control: metal ricursive dflash2 conv, the fourth tap is dropped", + .df_silu_no_negative => "control: metal ricursive dflash2 silu, a negative gate takes its magnitude's sigmoid", + .df_vec_no_floor => "control: metal ricursive dflash2 vec, each row also sees the keys below the floor", + .df_topk_ascending => "control: metal ricursive dflash2 topk, the sort runs ascending", + .df_walk_from_pending => "control: metal ricursive dflash2 walk, every slot scores after the pending token", }; } @@ -69,6 +95,16 @@ pub const Mutation = enum { .fp4_global_late => .{ .from = "bfloat(sum * a.global)", .to = "bfloat(float(bfloat(sum)) * a.global)" }, .fp4_dequant_unscaled => .{ .from = "D[at * 4 + c] = bfloat4(w[c]);", .to = "D[at * 4 + c] = bfloat4(w[c] / rc_e4m3(S[at]));" }, .fp4_gemm_no_global => .{ .from = "acc[i][j] *= global;", .to = "acc[i][j] *= 1.0f;" }, + .df_tap_next_slot => .{ .from = "F[((size_t)p.y * a.taps + a.at) * a.width + p.x]", .to = "F[((size_t)p.y * a.taps + a.at + 1) * a.width + p.x]" }, + .df_norm_half_mean => .{ .from = "precise::rsqrt(total / float(width) + eps)", .to = "precise::rsqrt(total / float(2 * width) + eps)" }, + .df_norm16_no_weight => .{ .from = "bfloat(float(w[i]) * float(bfloat(float(x[i]) * inv)))", .to = "bfloat(float(bfloat(float(x[i]) * inv)))" }, + .df_embed_own_row => .{ .from = "float(E[(size_t)ids[p.y] * a.width + p.x])", .to = "float(E[(size_t)p.y * a.width + p.x])" }, + .df_prep_ropes_nope => .{ .from = "if (a.rope == 0) {", .to = "if (false) {" }, + .df_conv_three_taps => .{ .from = "for (uint t = 0; t < a.taps; ++t) {", .to = "for (uint t = 0; t + 1 < a.taps; ++t) {" }, + .df_silu_no_negative => .{ .from = "const float s = g < 0.0f ? e * y : y;", .to = "const float s = y;" }, + .df_vec_no_floor => .{ .from = "max(p + 1 > a.window ? p + 1 - a.window : 0, a.floor)", .to = "p + 1 > a.window ? p + 1 - a.window : 0" }, + .df_topk_ascending => .{ .from = "const bool down = (i & k) == 0;", .to = "const bool down = (i & k) != 0;" }, + .df_walk_from_pending => .{ .from = "prev = UI[e * a.top + bi];\n seq[1 + e] = prev;", .to = "seq[1 + e] = UI[e * a.top + bi];" }, }; } }; @@ -91,6 +127,13 @@ pub fn glueLibrary(device: mtl.Device, a: std.mem.Allocator, m: Mutation) !mtl.L return mtl.Library.fromSource(device, src, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); } +/// dflash2.metal as dflash2.zig and model.zig's setTaps compile it, with the control's edit. +pub fn dflash2Library(device: mtl.Device, a: std.mem.Allocator, m: Mutation) !mtl.Library { + const src = try apply(a, ks.ricursive_dflash2, m); + defer a.free(src); + return family.dflash2Library(device, src); +} + /// A spec's name and control for a probe built with `m`. pub fn mark(k: contract.gates.Kernel, m: Mutation) contract.gates.Kernel { var out = k; diff --git a/zig/tests/contract/metal_ricursive_dflash2.zig b/zig/tests/contract/metal_ricursive_dflash2.zig new file mode 100644 index 00000000000..0f53f9eb91b --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2.zig @@ -0,0 +1,534 @@ +//! Ripple's DFlash2 drafter kernels (dflash2.metal) under the contract: norms, embed and taps here, the rest in _*.zig. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const attn = @import("metal_ricursive_dflash2_attn.zig"); +const act = @import("metal_ricursive_dflash2_act.zig"); +const pick = @import("metal_ricursive_dflash2_pick.zig"); + +const c = contract.spec; +const g = contract.gates; +const family = tf.ricursive.contracts; +const dc = tf.ricursive.dflash2_config; +pub const Mutation = controls.Mutation; + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +/// A value as fp32 then bf16 rounds it (to nearest even, twice). +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +/// A value as fp32 rounds it. +pub fn f32r(v: f64) f64 { + return @as(f32, @floatCast(v)); +} + +/// A value's spread through fp32 steps and bf16 rounding points. +pub const Range = struct { + lo: f64, + hi: f64, + pub fn point(v: f64) Range { + return .{ .lo = v, .hi = v }; + } + /// Each end moved by `ulps` fp32 roundings of its own size. + pub fn fp32(a: Range, ulps: f64) Range { + const u = ulps * c.unit(.f32); + return .{ .lo = a.lo - u * @abs(a.lo) - 0x1p-149, .hi = a.hi + u * @abs(a.hi) + 0x1p-149 }; + } + pub fn bf16(a: Range) Range { + return .{ .lo = bf(a.lo), .hi = bf(a.hi) }; + } + pub fn add(a: Range, b: Range) Range { + return .{ .lo = a.lo + b.lo, .hi = a.hi + b.hi }; + } + pub fn neg(a: Range) Range { + return .{ .lo = -a.hi, .hi = -a.lo }; + } + pub fn mul(a: Range, b: Range) Range { + const p = [4]f64{ a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi }; + return .{ .lo = @min(@min(p[0], p[1]), @min(p[2], p[3])), .hi = @max(@max(p[0], p[1]), @max(p[2], p[3])) }; + } +}; + +/// The allowance a range gives about `want`: the farther end. +pub fn spread(want: f64, r: Range) f64 { + return @max(@abs(want - r.lo), @abs(r.hi - want)); +} + +pub const nan = std.math.nan(f32); +pub const inf = std.math.inf(f32); + +/// Random bf16 bits in [lo, hi). +pub fn fillBf(rng: std.Random, out: []u16, lo: f32, hi: f32) void { + for (out) |*v| v.* = c.toBf16(lo + rng.float(f32) * (hi - lo)); +} + +pub const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +/// The published drafter's geometry beside Ripple-65B (dflash2_config.zig's qualified check). +pub const D = struct { + pub const hidden: u32 = @intCast(family.ripple.hidden); + pub const vocab: u32 = @intCast(family.ripple.vocab); + pub const heads: u32 = 80; + pub const kv: u32 = 8; + pub const ffn: u32 = 40960; + pub const window: u32 = 4096; + pub const global: u32 = dc.global_window; + pub const block: u32 = 16; + pub const rank: u32 = 256; + pub const top: u32 = 32; + pub const group: u32 = 16; + pub const conv: u32 = 4; + pub const taps: u32 = dc.max_taps; + pub const theta: f32 = 10000; + pub const eps: f32 = 1e-6; + /// The longest context the engine serves (ricursive's --context cap): positions stay below it. + pub const context: u32 = 262144; + + /// A layer's ring: its span and a block past it, whole 128-key blocks (Config.ring). + pub fn ring(span: u32) u32 { + return std.mem.alignForward(u32, span + block, 128); + } +}; + +/// dflash2.metal's pipeline `name`, built with the control's edit. +pub fn pipeline(device: mtl.Device, a: std.mem.Allocator, name: [:0]const u8, m: Mutation) !mtl.Pipeline { + const lib = try controls.dflash2Library(device, a, m); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, name, false); +} + +/// What a probe's registration needs: the run's allocator, GPU, the kernel list and the --only filter. +pub const Ctx = struct { a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8 }; + +/// The drafter's probes, freed together. +pub const Suite = struct { + owned: std.ArrayList(Owned) = .empty, + + const Owned = struct { ctx: *anyopaque, free: *const fn (*anyopaque, std.mem.Allocator) void }; + + /// T's probe for `v` built with `m`, kept and registered when its name holds `only`. + pub fn add(s: *Suite, x: Ctx, comptime T: type, v: T.Variant, m: Mutation) !void { + const name = if (m == .none) T.spec(v).name else m.name(); + if (x.only) |o| if (std.mem.indexOf(u8, name, o) == null) return; + const t = try x.a.create(T); + t.* = T.init(x.a, x.device, x.queue, v, m) catch |err| { + x.a.destroy(t); + return err; + }; + const free = struct { + fn f(p: *anyopaque, a: std.mem.Allocator) void { + const y: *T = @ptrCast(@alignCast(p)); + y.deinit(); + a.destroy(y); + } + }.f; + s.owned.append(x.a, .{ .ctx = t, .free = free }) catch |err| { + free(t, x.a); + return err; + }; + try x.kernels.append(x.a, t.kernel()); + } + + /// Every kernel's registrations; dflash2.metal's pipelines go on the roll call. + pub fn collect(s: *Suite, x: Ctx, functions: *std.ArrayList([]const u8)) !void { + for (family.dflash2_names) |n| try functions.append(x.a, n); + try s.add(x, Tap, .tap, .none); + for (std.enums.values(Norm.Variant)) |v| try s.add(x, Norm, v, .none); + try s.add(x, Embed, .embed, .none); + try attn.collect(s, x); + try act.collect(s, x); + try pick.collect(s, x); + } + + /// One control: its kernel built with the planted fault, at the variant the fault shows in. + pub fn plant(s: *Suite, x: Ctx, m: Mutation) !void { + switch (m) { + .df_tap_next_slot => try s.add(x, Tap, .tap, m), + .df_norm_half_mean => try s.add(x, Norm, .norm_add, m), + .df_norm16_no_weight => try s.add(x, Norm, .norm16, m), + .df_embed_own_row => try s.add(x, Embed, .embed, m), + .df_prep_ropes_nope => try s.add(x, attn.Prep, .global_block, m), + .df_conv_three_taps => try s.add(x, act.Conv, .side1, m), + .df_silu_no_negative => try s.add(x, act.Silu, .silu, m), + .df_vec_no_floor => try s.add(x, attn.Vec, .floor, m), + .df_topk_ascending => try s.add(x, pick.TopK, .logits, m), + .df_walk_from_pending => try s.add(x, pick.Walk, .walk, m), + else => return error.NotADflash2Control, + } + } + + pub fn deinit(s: *Suite, a: std.mem.Allocator) void { + for (s.owned.items) |o| o.free(o.ctx, a); + s.owned.deinit(a); + } +}; + +// --- rc_df_norm, rc_df_norm16: the release's RMSNorm of fp32 rows (bf16(R + X) first) or bf16 rows, 256 threads --- + +/// Each thread's fma chain over width / 256 inputs, a 5-level simd_sum, then the 8 simdgroups' parts in turn. +fn normDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 5 + 8; +} + +/// Gate 4's norm rows: integers in [-32, 32], so fp32 sums of squares are exact in any order. +fn stressRows(rng: std.Random, x: []f32) void { + for (x) |*v| v.* = @as(f32, @floatFromInt(rng.uintLessThan(u32, 65))) - 32; +} + +pub const Norm = struct { + /// The block's norms of the fp32 residual (layer 0's input, then each after bf16(R + X)); the context's bf16 rows. + pub const Variant = enum { norm, norm_add, norm16 }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + /// The rows as the norm reads them (after the add), the fp32 residual before it, X and w as bf16. + x: []f32 = &.{}, + r0: []f32 = &.{}, + xb: []u16 = &.{}, + w: []u16 = &.{}, + res: rig_.Ref = undefined, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn spec(v: Variant) c.Spec { + // the draft block's 16 rows; fc's rows of a context absorb (2,048), and a few + const block: []const c.Shape = &.{.{ .rows = D.block, .n = 1, .k = D.hidden }}; + const context: []const c.Shape = &.{ .{ .rows = 2048, .n = 1, .k = D.hidden }, .{ .rows = 7, .n = 1, .k = D.hidden } }; + return .{ + .name = switch (v) { + .norm => "ricursive dflash2 rc_df_norm fp32 rows", + .norm_add => "ricursive dflash2 rc_df_norm bf16(R + X) rows", + .norm16 => "ricursive dflash2 rc_df_norm16", + }, + .accum = .f32, + .depth = normDepth, + // the mean's division, + eps, precise rsqrt (2), x * inv, then w's product + .ops = 6, + // bf16(x * inv) before w's product + .mids = 1, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{}, .{ .size = 256, .step = 1, .min = 1 } }, + .served = if (v == .norm16) context else block, // n unused + .sums = .{ .bf16 = 0, .why = norm_why }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Norm { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, a, if (v == .norm16) "rc_df_norm16" else "rc_df_norm", m), .v = v, .m = m }; + } + pub fn deinit(t: *Norm) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Norm) void { + inline for (.{ "x", "r0", "xb", "w" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Norm) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Norm); + + fn fp32Rows(t: *const Norm) bool { + return t.v != .norm16; + } + + pub fn prepare(t: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + const n = shape.rows * shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(f32, n); + t.r0 = try t.a.alloc(f32, n); + t.xb = try t.a.alloc(u16, n); + t.w = try t.a.alloc(u16, shape.k); + fillBf(rng, t.w, -0.5, 0.5); + for (t.r0) |*v| v.* = (rng.float(f32) * 2 - 1) * (if (rng.uintLessThan(u32, 64) == 7) @as(f32, 20) else 1); + fillBf(rng, t.xb, -2, 2); + if (fill == .stress) { + stressRows(rng, t.r0); + for (t.xb, t.r0) |*b, r| b.* = if (t.v == .norm_add) 0 else c.toBf16(r); + } + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, shape.k / 3 }, .{ 1, shape.k / 2 }, .{ 2, shape.k - 1 }, .{ 3, 0 }, .{ 3, shape.k - 1 } }; + const put = [_]f32{ nan, inf, -inf, inf, -inf }; + for (at, put) |p, v| if (p[0] < shape.rows) { + const i = p[0] * shape.k + p[1]; + if (t.v == .norm) t.r0[i] = v else t.xb[i] = c.toBf16(v); + }; + } + for (t.x, t.r0, t.xb) |*x, r, b| x.* = switch (t.v) { + .norm16 => c.fromBf16(b), + .norm => r, + .norm_add => @floatCast(bf(@as(f32, r + c.fromBf16(b)))), + }; + if (t.fp32Rows()) t.res = try t.rig.scratch(n * 4); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.xb)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.out = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Norm) !void { + const n = t.shape.rows * t.shape.k; + if (t.fp32Rows()) @memcpy(t.rig.bytes(t.res, n * 4), std.mem.sliceAsBytes(t.r0)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + const args = extern struct { rows: u32, width: u32, eps: f32, add: u32 }{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.k), .eps = D.eps, .add = @intFromBool(t.v == .norm_add) }; + if (t.fp32Rows()) { + p.e.setBuffer(t.res.buf, t.res.off, 0); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 1); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 2); + p.e.setValue(args, 3); + p.e.setBuffer(t.out.buf, t.out.off, 4); + } else { + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setValue(args, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + } + p.e.dispatchGroups(mtl.Size.of(t.shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + if (!t.fp32Rows()) return; + // R as the run left it: the rows the norm read, bit for bit (a NaN as a NaN) + const got = std.mem.bytesAsSlice(f32, t.rig.bytes(t.res, n * 4)); + for (got, t.x) |gv, want| if (!(@as(u32, @bitCast(gv)) == @as(u32, @bitCast(want)) or (std.math.isNan(gv) and std.math.isNan(want)))) return error.ResidualRowsDiffer; + } + + pub fn count(t: *Norm) usize { + return t.shape.rows * t.shape.k; + } + + const Sim = struct { c.Accum, g.Order }; + + fn inv(t: *const Norm, row: usize, acc: ?Sim) !f64 { + const k = t.shape.k; + const sq = try t.a.alloc(f64, k); + defer t.a.free(sq); + for (sq, t.x[row * k ..][0..k]) |*s, x| s.* = @as(f64, x) * x; + var ss: f64 = 0; + for (sq) |s| ss += s; + if (acc) |o| ss = contract.rows.sumIn(o[0], o[1], sq); + return 1 / @sqrt(ss / @as(f64, @floatFromInt(k)) + @as(f64, D.eps)); + } + + fn outputs(t: *Norm, out: []f64, mag: ?[]f64, acc: ?Sim) !void { + const k = t.shape.k; + for (0..t.shape.rows) |r| { + const s = try t.inv(r, acc); + for (0..k) |i| { + const w: f64 = c.fromBf16(t.w[i]); + const y = w * (@as(f64, t.x[r * k + i]) * s); + out[r * k + i] = y; + if (mag) |m| m[r * k + i] = if (std.math.isFinite(y)) @abs(y) / 2 else 0; // y ~ ss^-1/2 + } + } + } + + pub fn reference(t: *Norm, want: []f64, mag: []f64) !void { + try t.outputs(want, mag, null); + } + pub fn simulate(t: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(out, null, .{ acc, order }); + } +}; + +// --- rc_df_embed: the block's ids through the target's table into the fp32 residual, unscaled -------------------- + +pub const Embed = struct { + pub const Variant = enum { embed }; + /// Table rows the probe holds: ids only index it. + const table = 64; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + e: []u16 = &.{}, + ids: []u32 = &.{}, + ins: [2]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: the block's positions; n: the hidden width (k unused). + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_df_embed", + .accum = .none, + .depth = noSums, + .out = .f32, + .tiles = .{ .{}, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{.{ .rows = D.block, .n = D.hidden, .k = 1 }}, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Embed { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, a, "rc_df_embed", m), .m = m }; + } + pub fn deinit(t: *Embed) void { + t.a.free(t.e); + t.a.free(t.ids); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Embed) g.Kernel { + return controls.mark(.{ .spec = spec(.embed), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Embed); + + pub fn prepare(t: *Embed, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > table or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.e); + t.a.free(t.ids); + t.e = &.{}; + t.ids = &.{}; + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.e = try t.a.alloc(u16, table * shape.n); + fillBf(rng, t.e, -2, 2); + t.ids = try t.a.alloc(u32, shape.rows); + // no row reads its own table row + for (t.ids, 0..) |*id, i| id.* = @intCast((i * 5 + 3) % table); + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, r| { + if (r < shape.rows) t.e[t.ids[r] * shape.n + (r * 7) % shape.n] = c.toBf16(v); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.ids)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.e)); + t.out = try t.rig.output(t.count() * 4); + return true; + } + + pub fn run(t: *Embed) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.ins[0].buf, t.ins[0].off, 0); + p.e.setBuffer(t.ins[1].buf, t.ins[1].off, 1); + p.e.setValue(extern struct { rows: u32, width: u32, eps: f32, add: u32 }{ .rows = @intCast(t.shape.rows), .width = @intCast(t.shape.n), .eps = 0, .add = 0 }, 2); + p.e.setBuffer(t.out.buf, t.out.off, 3); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Embed) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *Embed, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + w.* = c.fromBf16(t.e[t.ids[i / n] * n + i % n]); + m.* = 0; + } + } +}; + +// --- rc_tap: the target's residual after a tapped layer, as bf16, into its slot among the taps ------------------- + +pub const Tap = struct { + pub const Variant = enum { tap }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + r: []u16 = &.{}, + old: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: positions; n: the hidden width; k: the taps; the other taps' slots stay put. + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_tap", + .accum = .none, + .depth = noSums, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + // a decode window's rows and a prompt chunk's + .served = &.{ .{ .rows = D.block, .n = D.hidden, .k = D.taps }, .{ .rows = 2048, .n = D.hidden, .k = D.taps } }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Tap { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try pipeline(device, a, "rc_tap", m), .m = m }; + } + pub fn deinit(t: *Tap) void { + t.a.free(t.r); + t.a.free(t.old); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Tap) g.Kernel { + return controls.mark(.{ .spec = spec(.tap), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Tap); + + /// The tap written: the next to last, so a slot past it is still inside the features. + fn tap(t: *const Tap) usize { + return t.shape.k - 2; + } + + pub fn prepare(t: *Tap, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k < 2) return false; + t.rig.reset(); + t.a.free(t.r); + t.a.free(t.old); + t.r = &.{}; + t.old = &.{}; + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.r = try t.a.alloc(u16, shape.rows * shape.n); + fillBf(rng, t.r, -64, 64); + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, i| { + t.r[(i * 7) % t.r.len] = c.toBf16(v); + }; + t.old = try t.a.alloc(u16, t.count()); + fillBf(rng, t.old, -1, 1); + t.in = try t.rig.input(std.mem.sliceAsBytes(t.r)); + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Tap) !void { + @memcpy(t.rig.bytes(t.out, t.count() * 2), std.mem.sliceAsBytes(t.old)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setValue([4]u32{ @intCast(t.shape.rows), @intCast(t.shape.n), @intCast(t.shape.k), @intCast(t.tap()) }, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Tap) usize { + return t.shape.rows * t.shape.k * t.shape.n; + } + + pub fn reference(t: *Tap, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + const r = i / (t.shape.k * n); + const slot = i / n % t.shape.k; + w.* = c.fromBf16(if (slot == t.tap()) t.r[r * n + i % n] else t.old[i]); + m.* = 0; + } + } +}; diff --git a/zig/tests/contract/metal_ricursive_dflash2_act.zig b/zig/tests/contract/metal_ricursive_dflash2_act.zig new file mode 100644 index 00000000000..a9967961e31 --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2_act.zig @@ -0,0 +1,230 @@ +//! The drafter's activation (rc_df_silu) and grouped four-tap block convolution (rc_df_conv) under the contract. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const d = @import("metal_ricursive_dflash2.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = d.D; +const Mutation = d.Mutation; +const bf = d.bf; +const fillBf = d.fillBf; +const nan = d.nan; +const inf = d.inf; + +pub fn collect(s: *d.Suite, x: d.Ctx) !void { + try s.add(x, Silu, .silu, .none); + for (std.enums.values(Conv.Variant)) |v| try s.add(x, Conv, v, .none); +} + +// --- rc_df_silu: the release's SiLU of the gate times up, at its bf16 points --------------------------------------- + +pub const Silu = struct { + pub const Variant = enum { silu }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + gu: []u16 = &.{}, + in: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: positions; n: the ffn width (k unused). + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_df_silu", + .accum = .none, + .depth = d.noSums, + // precise exp (2 ulps), the add, the division, the sigmoid's own e * y (1), g * s, then * up + .ops = 6, + .mids = 1, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{ .size = 256, .step = 1, .min = 1 }, .{} }, + .served = &.{.{ .rows = D.block, .n = D.ffn, .k = 1 }}, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Silu { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_silu", m), .m = m }; + } + pub fn deinit(t: *Silu) void { + t.a.free(t.gu); + t.rig.deinit(); + t.pipe.deinit(); + } + pub fn kernel(t: *Silu) g.Kernel { + return controls.mark(.{ .spec = spec(.silu), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Silu); + + pub fn prepare(t: *Silu, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.gu); + t.gu = &.{}; + t.shape = shape; + const n = shape.n; + t.gu = try t.a.alloc(u16, shape.rows * 2 * n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + // gates past +-20 reach silu's flat ends; ups both signs + for (0..shape.rows) |r| { + fillBf(rng, t.gu[r * 2 * n ..][0..n], -24, 24); + fillBf(rng, t.gu[r * 2 * n + n ..][0..n], -4, 4); + } + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf, nan, inf, -inf }, 0..) |v, i| { + const r = i % shape.rows; + t.gu[r * 2 * n + (if (i < 3) 0 else n) + (i * 7) % n] = c.toBf16(v); + }; + t.in = try t.rig.input(std.mem.sliceAsBytes(t.gu)); + t.out = try t.rig.output(shape.rows * n * 2); + return true; + } + + pub fn run(t: *Silu) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + p.e.setBuffer(t.in.buf, t.in.off, 0); + p.e.setValue([2]u32{ @intCast(t.shape.rows), @intCast(t.shape.n) }, 1); + p.e.setBuffer(t.out.buf, t.out.off, 2); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Silu) usize { + return t.shape.rows * t.shape.n; + } + + pub fn reference(t: *Silu, want: []f64, mag: []f64) !void { + const n = t.shape.n; + for (want, mag, 0..) |*w, *m, i| { + const r = i / n; + const gate: f64 = c.fromBf16(t.gu[r * 2 * n + i % n]); + w.* = gate / (1 + @exp(-gate)) * c.fromBf16(t.gu[r * 2 * n + n + i % n]); + m.* = 0; + } + } +}; + +// --- rc_df_conv: the grouped four-tap block convolution, exact at its bf16 points ----------------------------------- + +pub const Conv = struct { + /// Side 0 (the sublayer input's prepare) and side 1 (its output), each with its own taps of base and the deltas. + pub const Variant = enum { side0, side1 }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + d: []u16 = &.{}, + base: []u16 = &.{}, + ins: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + + /// Rows: block positions; n: the hidden width (groups of 16 channels); k: the taps. + pub fn spec(v: Variant) c.Spec { + return .{ + .name = if (v == .side0) "ricursive dflash2 rc_df_conv side 0" else "ricursive dflash2 rc_df_conv side 1", + .accum = .none, + .depth = d.noSums, + .out = .bf16, + .tiles = .{ .{ .size = D.block, .step = 1, .min = 1 }, .{ .size = 256, .step = D.group, .min = D.group }, .{} }, + .served = &.{.{ .rows = D.block, .n = D.hidden, .k = D.conv }}, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Conv { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_conv", m), .v = v, .m = m }; + } + pub fn deinit(t: *Conv) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Conv) void { + inline for (.{ "x", "d", "base" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Conv) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Conv); + + fn groups(t: *const Conv) usize { + return t.shape.n / D.group; + } + fn side(t: *const Conv) usize { + return @backingInt(t.v); + } + /// Row r's coefficient delta for (side, tap, group): dyn's [side][tap][group] layout. + fn delta(t: *const Conv, r: usize, s: usize, tap: usize, gi: usize) f64 { + const k = t.shape.k; + return c.fromBf16(t.d[((r * 2 + s) * k + tap) * t.groups() + gi]); + } + + pub fn prepare(t: *Conv, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % D.group != 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, shape.rows * shape.n); + t.d = try t.a.alloc(u16, shape.rows * 2 * shape.k * t.groups()); + t.base = try t.a.alloc(u16, 2 * shape.k * shape.n); + fillBf(rng, t.x, -4, 4); + fillBf(rng, t.d, -0.5, 0.5); + fillBf(rng, t.base, -1.5, 1.5); + if (fill == .nonfinite) for ([_]f32{ nan, inf, -inf }, 0..) |v, i| { + t.x[(1 + i) * shape.n + 5 * i] = c.toBf16(v); + t.d[((i * 2 + t.side()) * shape.k) * t.groups() % t.d.len] = c.toBf16(v); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.d)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.base)); + t.out = try t.rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(t: *Conv) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue([6]u32{ @intCast(t.shape.rows), @intCast(t.shape.n), D.block, @intCast(t.groups()), @intCast(t.side()), @intCast(t.shape.k) }, 3); + p.e.setBuffer(t.out.buf, t.out.off, 4); + p.e.dispatchThreads(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(256, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Conv) usize { + return t.shape.rows * t.shape.n; + } + + /// z-lab's order per tap inside the block: y = bf16(y + bf16(base x[r - t])), then y = bf16(y + delta x[r - t]). + pub fn reference(t: *Conv, want: []f64, mag: []f64) !void { + const n = t.shape.n; + const s = t.side(); + for (want, mag, 0..) |*w, *m, i| { + const r = i / n; + const ch = i % n; + const gi = ch / D.group; + var y: f64 = 0; + for (0..t.shape.k) |tap| { + if (r % D.block < tap) break; + const x: f64 = c.fromBf16(t.x[i - tap * n]); + y = bf(y + bf(@as(f64, c.fromBf16(t.base[(s * t.shape.k + tap) * n + ch])) * x)); + y = bf(y + t.delta(r, s, tap, gi) * x); + } + w.* = y; + m.* = 0; + } + } +}; diff --git a/zig/tests/contract/metal_ricursive_dflash2_attn.zig b/zig/tests/contract/metal_ricursive_dflash2_attn.zig new file mode 100644 index 00000000000..86f24670bbf --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2_attn.zig @@ -0,0 +1,539 @@ +//! The drafter's attention under the contract: rc_df_prep (head norms, rotary or NoPE, the ring) and rc_df_vec. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const d = @import("metal_ricursive_dflash2.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = d.D; +const Range = d.Range; +const Mutation = d.Mutation; +const bf = d.bf; +const f32r = d.f32r; +const u = c.unit(.f32); +const Sim = struct { c.Accum, g.Order }; + +pub fn collect(s: *d.Suite, x: d.Ctx) !void { + for (std.enums.values(Prep.Variant)) |v| try s.add(x, Prep, v, .none); + for (std.enums.values(Vec.Variant)) |v| try s.add(x, Vec, v, .none); +} + +/// cos over [lo, hi] (sin as cos(x - pi/2)): the ends' values, or +-1 where an extremum falls inside. +fn cosRange(lo: f64, hi: f64) Range { + if (hi - lo >= 2 * std.math.pi) return .{ .lo = -1, .hi = 1 }; + var r = Range{ .lo = @min(@cos(lo), @cos(hi)), .hi = @max(@cos(lo), @cos(hi)) }; + var k = @ceil(lo / std.math.pi); + while (k * std.math.pi <= hi) : (k += 1) { + if (@mod(k, 2) == 0) r.hi = 1 else r.lo = -1; + } + return r; +} + +/// The last position before the served context's end at 3 keys before a wrap of `ring`. +fn farPos(ring: u32) u32 { + return D.context / ring * ring - 3; +} + +// --- rc_df_prep: q and k heads normed and rotated (or not, on the NoPE layer), k and v into the ring ------------- + +pub const Prep = struct { + /// A block on a sliding layer near the ring's wrap or past 261k positions, on the global NoPE layer; and absorbs. + pub const Variant = enum { sliding_block, sliding_far, global_block, sliding_context, global_context }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + x: []u16 = &.{}, + qw: []u16 = &.{}, + kw: []u16 = &.{}, + old: []u16 = &.{}, + ins: [3]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + + fn context(v: Variant) bool { + return v == .sliding_context or v == .global_context; + } + fn global(t: *const Prep) bool { + return t.v == .global_block or t.v == .global_context; + } + fn ring(t: *const Prep) u32 { + return D.ring(if (t.global()) D.global else D.window); + } + fn heads(t: *const Prep) u32 { + return if (context(t.v)) 0 else D.heads; + } + + /// Rows: positions; n: the heads launched (q then kv); k: the head dim. + pub fn spec(v: Variant) c.Spec { + return .{ + .name = switch (v) { + .sliding_block => "ricursive dflash2 rc_df_prep sliding block", + .sliding_far => "ricursive dflash2 rc_df_prep sliding block past 261k", + .global_block => "ricursive dflash2 rc_df_prep NoPE block", + .sliding_context => "ricursive dflash2 rc_df_prep sliding context", + .global_context => "ricursive dflash2 rc_df_prep NoPE context", + }, + .accum = .f32, + .depth = prepDepth, + .out = .bf16, + .tiles = .{ .{ .size = 1 }, .{}, .{} }, + .served = if (context(v)) &.{ .{ .rows = 2048, .n = D.kv, .k = 128 }, .{ .rows = 5, .n = D.kv, .k = 128 } } else &.{ .{ .rows = D.block, .n = D.heads + D.kv, .k = 128 }, .{ .rows = 1, .n = D.heads + D.kv, .k = 128 } }, + .sums = .{ .bf16 = 0, .why = d.norm_why }, + }; + } + /// Each lane's 4 fmas, then a 5-level simd_sum. + fn prepDepth(_: c.Shape) usize { + return 9; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Prep { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_prep", m), .v = v, .m = m }; + } + pub fn deinit(t: *Prep) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Prep) void { + inline for (.{ "x", "qw", "kw", "old" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Prep) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Prep); + + fn pos0(t: *const Prep) u32 { + if (t.fill == .stress) return 0; // gate 4 at positions 0-3: the rotation's own spread stays far under a sum's + return if (t.v == .sliding_far) farPos(t.ring()) else t.ring() - 3; + } + fn rope(t: *const Prep) bool { + return !t.global(); + } + /// X's row as dflash2.zig lays it: a block's q, k and v heads; a context's k and v projections. + fn layout(t: *const Prep) struct { stride: usize, q: usize, k: usize, v: usize } { + const kvw: usize = D.kv * 128; + const qw: usize = t.heads() * 128; + return if (t.heads() == 0) .{ .stride = 2 * kvw, .q = 0, .k = 0, .v = kvw } else .{ .stride = qw + 2 * kvw, .q = 0, .k = qw, .v = qw + kvw }; + } + fn sizes(t: *const Prep) [3]usize { + const ringed: usize = @as(usize, t.ring()) * D.kv * 128; + return .{ @max(1, t.shape.rows * t.heads() * 128), ringed, ringed }; + } + + pub fn prepare(t: *Prep, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n != t.heads() + D.kv or shape.k != 128) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const l = t.layout(); + t.x = try t.a.alloc(u16, shape.rows * l.stride); + d.fillBf(rng, t.x, -3, 3); + if (fill == .stress) for (t.x) |*v| { + v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 65))) - 32); + }; + if (fill == .nonfinite) for ([_]f32{ d.nan, d.inf, -d.inf, d.inf }, 0..) |v, i| { + // a q head (or a context's k head) a value each, then a k head's + const r = i % shape.rows; + const at = if (i < 2) l.q + (if (t.heads() == 0) l.k else 0) + 5 + 31 * i else l.k + 128 + 7 * i; + t.x[r * l.stride + at] = c.toBf16(v); + }; + t.qw = try t.a.alloc(u16, 128); + t.kw = try t.a.alloc(u16, 128); + d.fillBf(rng, t.qw, -0.5, 0.5); + d.fillBf(rng, t.kw, -0.5, 0.5); + const sz = t.sizes(); + t.old = try t.a.alloc(u16, sz[0] + sz[1] + sz[2]); + d.fillBf(rng, t.old, -1, 1); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.qw)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.kw)); + for (&t.outs, sz) |*o, n| o.* = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Prep) !void { + const sz = t.sizes(); + var at: usize = 0; + for (t.outs, sz) |o, n| { + @memcpy(t.rig.bytes(o, n * 2), std.mem.sliceAsBytes(t.old[at..][0..n])); + at += n; + } + const l = t.layout(); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + const Args = extern struct { rows: u32, heads: u32, kv_heads: u32, pos0: u32, stride: u32, q_off: u32, k_off: u32, v_off: u32, ring: u32, rope: u32, eps: f32, theta: f32 }; + p.e.setValue(Args{ .rows = @intCast(t.shape.rows), .heads = t.heads(), .kv_heads = D.kv, .pos0 = t.pos0(), .stride = @intCast(l.stride), .q_off = @intCast(l.q), .k_off = @intCast(l.k), .v_off = @intCast(l.v), .ring = t.ring(), .rope = @intFromBool(t.rope()), .eps = D.eps, .theta = D.theta }, 3); + for (t.outs, 4..) |o, i| p.e.setBuffer(o.buf, o.off, i); + p.e.dispatchGroups(mtl.Size.of(t.shape.n, t.shape.rows, 1), mtl.Size.of(32, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Prep) usize { + const sz = t.sizes(); + return sz[0] + sz[1] + sz[2]; + } + + /// Where head (row, unit)'s outputs land: its q row, or its ring slot's k (v beside it, in the third buffer). + fn dest(t: *const Prep, row: usize, unit: usize) usize { + const sz = t.sizes(); + const h = t.heads(); + if (unit < h) return (row * h + unit) * 128; + const slot = (t.pos0() + row) % t.ring(); + return sz[0] + (slot * D.kv + unit - h) * 128; + } + + /// One head's 128 outputs: float64 at the kernel's rounding points (fp32's angle), and the range fp32 allows. + fn head(t: *const Prep, row: usize, unit: usize, sim: ?Sim, want: *[128]f64, low: *[128]f64, high: *[128]f64) void { + const l = t.layout(); + const is_q = unit < t.heads(); + const src = t.x[row * l.stride + (if (is_q) l.q + unit * 128 else l.k + (unit - t.heads()) * 128) ..][0..128]; + const w = if (is_q) t.qw else t.kw; + var sq: [128]f64 = undefined; + var ss: f64 = 0; + for (&sq, src) |*s, b| { + s.* = @as(f64, c.fromBf16(b)) * c.fromBf16(b); + ss += s.*; + } + if (sim) |o| ss = contract.rows.sumIn(o[0], o[1], &sq); + const inv = 1 / @sqrt(ss / 128 + @as(f64, D.eps)); + // the sum's chain (none for gate 4's exact sums), + eps and precise rsqrt's 2 ulps, halved through ss^-1/2 + const e_inv = (if (t.fill == .stress or sim != null) 0 else c.gamma(9, u)) / 2 + 3 * u; + var nrm: [128]f64 = undefined; + var nr: [128]Range = undefined; + for (src, w, 0..) |b, wb, j| { + const v: f64 = c.fromBf16(b); + const wv: f64 = c.fromBf16(wb); + nrm[j] = bf(wv * bf(v * inv)); + nr[j] = Range.point(v * inv).fp32(e_inv / u + 1).bf16().mul(Range.point(wv)).bf16(); + } + if (!t.rope()) { + want.* = nrm; + for (nr, low, high) |r, *lo, *hi| { + lo.* = r.lo; + hi.* = r.hi; + } + return; + } + const p: u32 = t.pos0() + @as(u32, @intCast(row)); + for (0..128) |j| { + const i = j % 64; + const e = f32r(@as(f64, @floatFromInt(2 * i)) / 128); + const freq = std.math.pow(f64, D.theta, e); + const angle = f32r(@as(f64, @floatFromInt(p)) * f32r(1 / f32r(freq))); + // precise pow (16 ulps), the reciprocal (2.5), the product (1); then precise cos and sin (4 ulps of 1) + const exact = @as(f64, @floatFromInt(p)) / freq; + const da = exact * 19.5 * u + 0x1p-149; + const cr = cosRange(exact - da, exact + da); + const sr = cosRange(exact - da - std.math.pi / 2.0, exact + da - std.math.pi / 2.0); + const cs = (Range{ .lo = cr.lo - 0x1p-22, .hi = cr.hi + 0x1p-22 }).bf16(); + const sn = (Range{ .lo = sr.lo - 0x1p-22, .hi = sr.hi + 0x1p-22 }).bf16(); + const rot = if (j < 64) -nrm[j + 64] else nrm[j - 64]; + const rr = if (j < 64) nr[j + 64].neg() else nr[j - 64]; + want[j] = bf(bf(nrm[j] * bf(@cos(angle))) + bf(rot * bf(@sin(angle)))); + const y = nr[j].mul(cs).bf16().add(rr.mul(sn).bf16()).fp32(1).bf16(); + low[j] = y.lo; + high[j] = y.hi; + } + } + + fn all(t: *Prep, want: []f64, low: ?[]f64, high: ?[]f64, sim: ?Sim) void { + const sz = t.sizes(); + for (want, t.old) |*w, o| w.* = c.fromBf16(o); + if (low) |lo| @memcpy(lo, want); + if (high) |hi| @memcpy(hi, want); + const l = t.layout(); + for (0..t.shape.rows) |row| for (0..t.shape.n) |unit| { + var hw: [128]f64 = undefined; + var hl: [128]f64 = undefined; + var hh: [128]f64 = undefined; + t.head(row, unit, sim, &hw, &hl, &hh); + const at = t.dest(row, unit); + @memcpy(want[at..][0..128], &hw); + if (low) |lo| @memcpy(lo[at..][0..128], &hl); + if (high) |hi| @memcpy(hi[at..][0..128], &hh); + if (unit < t.heads()) continue; + const vs = t.x[row * l.stride + l.v + (unit - t.heads()) * 128 ..][0..128]; + for (want[at + sz[1] ..][0..128], vs, 0..) |*w, b, j| { + w.* = c.fromBf16(b); + if (low) |lo| lo[at + sz[1] + j] = w.*; + if (high) |hi| hi[at + sz[1] + j] = w.*; + } + }; + } + + pub fn reference(t: *Prep, want: []f64, mag: []f64) !void { + t.all(want, null, null, null); + @memset(mag, 0); + } + pub fn intervals(t: *Prep, low: []f64, high: []f64) !void { + const want = try t.a.alloc(f64, t.count()); + defer t.a.free(want); + t.all(want, low, high, null); + } + pub fn bounds(t: *Prep, want: []const f64, _: []const f64, allow: []f64) !void { + const buf = try t.a.alloc(f64, 2 * t.count()); + defer t.a.free(buf); + try t.intervals(buf[0..t.count()], buf[t.count()..]); + for (allow, want, buf[0..t.count()], buf[t.count()..]) |*l, w, lo, hi| l.* = if (std.math.isFinite(w)) d.spread(w, .{ .lo = lo, .hi = hi }) else 0; + } + pub fn simulate(t: *Prep, acc: c.Accum, order: g.Order, out: []f64) !void { + t.all(out, null, null, .{ acc, order }); + } +}; + +// --- rc_df_vec: a block's attention partials over 128-key blocks of a layer's ring -------------------------------- + +pub const Vec = struct { + /// A sliding layer, the global layer, and the global layer over a resumed prompt's context (keys from a floor). + pub const Variant = enum { sliding, global, floor }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + q: []u16 = &.{}, + k: []u16 = &.{}, + val: []u16 = &.{}, + old: []f32 = &.{}, + ins: [3]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + + fn ring(t: *const Vec) u32 { + return D.ring(if (t.v == .sliding) D.window else D.global); + } + + /// Rows: the block's positions; n: q heads; k: the window (the layer's, and a short one with partial blocks). + pub fn spec(v: Variant) c.Spec { + return .{ + .name = switch (v) { + .sliding => "ricursive dflash2 rc_df_vec sliding layer", + .global => "ricursive dflash2 rc_df_vec global layer", + .floor => "ricursive dflash2 rc_df_vec global layer above a floor", + }, + .accum = .f32, + .depth = vecDepth, + .out = .f32, + .nan = .{ .stated = "a NaN score is skipped by the running max (Metal's max, as fmax) and makes the block's mass and output NaN" }, + .tiles = .{ .{ .size = 1 }, .{}, .{} }, + .served = switch (v) { + .sliding => &.{ .{ .rows = D.block, .n = D.heads, .k = D.window }, .{ .rows = D.block, .n = D.heads, .k = 300 } }, + .global, .floor => &.{ .{ .rows = D.block, .n = D.heads, .k = D.global }, .{ .rows = D.block, .n = D.heads, .k = 1300 } }, + }, + .sums = .{ .f16 = 100, .bf16 = 100 }, + }; + } + /// A score's: q's scale, a lane's 4-term dot, a 5-level simd_sum. + fn vecDepth(_: c.Shape) usize { + return 10; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !Vec { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_vec", m), .v = v, .m = m }; + } + pub fn deinit(t: *Vec) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Vec) void { + inline for (.{ "q", "k", "val", "old" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Vec) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Vec); + + const Plan = struct { anchor: u32, hi: u32, floor: u32, first: u32, blocks: u32 }; + /// The anchor near the context's end, row 0's window from 3 keys before a block's end, the floor 1,000 keys in. + fn plan(t: *const Vec) Plan { + const w: u32 = @intCast(t.shape.k); + const lo0 = (farPos(t.ring()) + 3 - w) / 128 * 128 + 125; + const anchor = lo0 + w - 1; + const hi = anchor + @as(u32, @intCast(t.shape.rows)); + const floor: u32 = if (t.v == .floor) lo0 + 1000 else 0; + const lo = @max(lo0, floor); + return .{ .anchor = anchor, .hi = hi, .floor = floor, .first = lo / 128, .blocks = (hi - 1) / 128 - lo / 128 + 1 }; + } + fn slots(t: *const Vec) usize { + return t.shape.n * t.shape.rows * t.plan().blocks; + } + fn scale(t: *const Vec) f32 { + return if (t.fill == .stress) 1 else 1.0 / @sqrt(128.0); + } + + pub fn prepare(t: *Vec, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > D.block or shape.n != D.heads or shape.k > t.ring() - D.block) return false; + if (t.v == .floor and shape.k <= 1000) return false; // the floor lies inside row 0's window + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const kvn: usize = @as(usize, t.ring()) * D.kv * 128; + t.q = try t.a.alloc(u16, shape.rows * D.heads * 128); + t.k = try t.a.alloc(u16, kvn); + t.val = try t.a.alloc(u16, kvn); + d.fillBf(rng, t.q, -3, 3); + d.fillBf(rng, t.k, -3, 3); + d.fillBf(rng, t.val, -2, 2); + if (fill == .stress) { + // big products, mirrored halves (k negated, a few nudged): partials near 2^20, scores in the hundreds + for (0..t.q.len / 128) |h| for (0..64) |j| { + const qv: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + t.q[h * 128 + j] = c.toBf16(qv); + t.q[h * 128 + 64 + j] = c.toBf16(qv); + }; + for (0..kvn / 128) |h| for (0..64) |j| { + const kv: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + const nudge: f32 = if (j < 2) @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 3))) - 1) else 0; + t.k[h * 128 + j] = c.toBf16(kv); + t.k[h * 128 + 64 + j] = c.toBf16(-kv + nudge); + }; + for (t.val) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 9))) - 4); + } + if (fill == .nonfinite) { + const p = t.plan(); + const r: usize = t.ring(); + // a key's NaN component, +inf in a query, -inf in a value (keys of the last block, kv head 0) + t.k[((p.hi - 2) % r) * D.kv * 128 + 3] = c.toBf16(d.nan); + t.q[(1 * D.heads + 5) * 128 + 9] = c.toBf16(d.inf); + t.val[((p.hi - 1) % r) * D.kv * 128 + 2] = c.toBf16(-d.inf); + } + t.old = try t.a.alloc(f32, t.slots() * 128); + for (t.old) |*o| o.* = rng.float(f32); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.k)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.val)); + t.outs[0] = try t.rig.output(t.slots() * 4); + t.outs[1] = try t.rig.output(t.slots() * 4); + t.outs[2] = try t.rig.output(t.slots() * 128 * 4); + return true; + } + + pub fn run(t: *Vec) !void { + @memcpy(t.rig.bytes(t.outs[2], t.slots() * 128 * 4), std.mem.sliceAsBytes(t.old)); + const p = t.plan(); + const e = t.rig.begin(); + e.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| e.e.setBuffer(r.buf, r.off, i); + const Args = extern struct { rows: u32, pos0: u32, heads: u32, groups: u32, blocks: u32, chunk: u32, first: u32, scale: f32, hi: u32, window: u32, ring: u32, floor: u32 }; + e.e.setValue(Args{ .rows = @intCast(t.shape.rows), .pos0 = p.anchor, .heads = D.heads, .groups = D.kv, .blocks = p.blocks, .chunk = 128, .first = p.first, .scale = t.scale(), .hi = p.hi, .window = @intCast(t.shape.k), .ring = t.ring(), .floor = p.floor }, 3); + for (t.outs, 4..) |o, i| e.e.setBuffer(o.buf, o.off, i); + e.e.dispatchGroups(mtl.Size.of(D.kv, t.shape.rows, p.blocks), mtl.Size.of(32, D.heads / D.kv, 1)); + try t.rig.finish(e); + } + + pub fn count(t: *Vec) usize { + return t.slots() * 130; + } + + const Out = struct { want: []f64, allow: ?[]f64 = null, sim: ?Sim = null }; + + /// Every slot's (m, l, o) in float64 (fmax's NaN rule), and its allowance: spread, fast exp, the sums' chains. + fn outputs(t: *Vec, o: Out) !void { + const p = t.plan(); + const n = t.slots(); + const r: usize = t.ring(); + const G = D.heads / D.kv; + const sc: f64 = t.scale(); + for (o.want[2 * n ..], t.old) |*w, v| w.* = v; + if (o.allow) |al| @memset(al, 0); + var s: [128]f64 = undefined; + var e: [128]f64 = undefined; + var terms: [128]f64 = undefined; + for (0..D.heads) |h| for (0..t.shape.rows) |row| for (0..p.blocks) |z| { + const slot = (h * t.shape.rows + row) * p.blocks + z; + const pos = p.anchor + row; + const lo = @max(if (pos + 1 > t.shape.k) pos + 1 - t.shape.k else 0, p.floor); + const blk = p.first + z; + const from = @max(lo, blk * 128); + const to = @min(p.hi, blk * 128 + 128); + if (from >= to) { + o.want[slot] = -std.math.inf(f64); + o.want[n + slot] = 0; + continue; + } + const kv = h / G; + const keys = to - from; + var m: f64 = -std.math.inf(f64); + var least: f64 = std.math.inf(f64); + var big_e: f64 = 0; + for (0..keys) |i| { + const at = ((from + i) % r) * D.kv * 128 + kv * 128; + var abs: f64 = 0; + var sum: f64 = 0; + for (0..128) |j| { + terms[j] = sc * c.fromBf16(t.q[(row * D.heads + h) * 128 + j]) * c.fromBf16(t.k[at + j]); + sum += terms[j]; + abs += @abs(terms[j]); + } + s[i] = if (o.sim) |q| contract.rows.sumIn(q[0], q[1], &terms) else sum; + e[i] = if (t.fill == .stress) 0 else c.gamma(10, u) * abs; + big_e = @max(big_e, e[i]); + if (!std.math.isNan(s[i])) { + m = @max(m, s[i]); + least = @min(least, s[i]); + } + } + var l: f64 = 0; + var wabs: [128]f64 = @splat(0); + var po: [128]f64 = @splat(0); + var vmax: [128]f64 = @splat(0); + for (0..keys) |i| { + const w = @exp(s[i] - m); + l += w; + const at = ((from + i) % r) * D.kv * 128 + kv * 128; + for (&po, &wabs, 0..) |*y, *wa, j| { + const vv: f64 = c.fromBf16(t.val[at + j]); + y.* += w * vv; + wa.* += w * @abs(vv); + vmax[j] = @max(vmax[j], @abs(vv)); + } + } + o.want[slot] = m; + o.want[n + slot] = l; + for (po, 0..) |y, j| o.want[2 * n + slot * 128 + j] = y; + const al = o.allow orelse continue; + const steps: f64 = @floatFromInt((keys + 3) / 4); + const range = if (std.math.isFinite(m - least)) m - least else 0; + const rel = (@exp(2 * big_e) - 1) + (3 + 4 * range + 5 * steps) * u + c.gamma(@as(f64, @floatFromInt(keys)) + steps, u); + // Metal flushes subnormals: a weight or product under 2^-126 may be 0 + const flush = @as(f64, @floatFromInt(keys)) * 0x1p-126; + al[slot] = big_e + 0x1p-149; + al[n + slot] = rel * l + flush; + for (wabs, vmax, 0..) |wa, vm, j| al[2 * n + slot * 128 + j] = rel * wa + flush * (1 + vm); + }; + } + + pub fn reference(t: *Vec, want: []f64, mag: []f64) !void { + try t.outputs(.{ .want = want }); + @memset(mag, 0); + } + pub fn bounds(t: *Vec, _: []const f64, _: []const f64, allow: []f64) !void { + const want = try t.a.alloc(f64, t.count()); + defer t.a.free(want); + try t.outputs(.{ .want = want, .allow = allow }); + } + pub fn simulate(t: *Vec, acc: c.Accum, order: g.Order, out: []f64) !void { + try t.outputs(.{ .want = out, .sim = .{ acc, order } }); + } +}; diff --git a/zig/tests/contract/metal_ricursive_dflash2_pick.zig b/zig/tests/contract/metal_ricursive_dflash2_pick.zig new file mode 100644 index 00000000000..1aa9604d017 --- /dev/null +++ b/zig/tests/contract/metal_ricursive_dflash2_pick.zig @@ -0,0 +1,385 @@ +//! The drafter's picks under the contract: the chunked top-k (rc_df_topk) and the greedy walk (rc_df_walk), by rule. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const controls = @import("metal_ricursive_controls.zig"); +const d = @import("metal_ricursive_dflash2.zig"); + +const c = contract.spec; +const g = contract.gates; +const D = d.D; +const Mutation = d.Mutation; +const bf = d.bf; +const u = c.unit(.f32); +const Sim = struct { c.Accum, g.Order }; + +pub fn collect(s: *d.Suite, x: d.Ctx) !void { + for (std.enums.values(TopK.Variant)) |v| try s.add(x, TopK, v, .none); + try s.add(x, Walk, .walk, .none); +} + +/// The block's draft slots: rows 1-15 go through the head, the top-k and the walk. +const slots = D.block - 1; +/// dflash2.zig's passes: each 2,048-value chunk's best 32, then the chunks' bests twice more. +const chunks1 = (D.vocab + 2047) / 2048; +const chunks2 = (chunks1 * 32 + 2047) / 2048; + +// --- rc_df_topk: each 2,048-value chunk's best 32 (value desc, id asc) by a bitonic sort -------------------------- + +pub const TopK = struct { + /// The first pass over a row's logits, then the two passes over the chunks' bests (ids carried). + pub const Variant = enum { logits, bests, last }; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + v: Variant, + m: Mutation, + shape: c.Shape = undefined, + l: []u16 = &.{}, + vin: []f32 = &.{}, + iin: []u32 = &.{}, + ins: [3]rig_.Ref = undefined, + outs: [2]rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: the draft slots; n: the values a row (k unused). + pub fn spec(v: Variant) c.Spec { + return .{ + .name = switch (v) { + .logits => "ricursive dflash2 rc_df_topk logits", + .bests => std.fmt.comptimePrint("ricursive dflash2 rc_df_topk {d} chunks' bests", .{chunks1}), + .last => std.fmt.comptimePrint("ricursive dflash2 rc_df_topk {d} chunk's bests", .{chunks2}), + }, + .accum = .none, + .depth = d.noSums, + .out = .raw, + .nan = .{ .stated = "finite rows: each chunk's 32 largest (value desc, id asc) as a host sort gives them; with NaN or infinities: the sorting network as Metal compares (NaN compares false), replayed bit for bit" }, + .tiles = .{ .{}, .{ .size = 2048, .step = 1, .min = 1 }, .{} }, + .served = switch (v) { + .logits => &.{.{ .rows = slots, .n = D.vocab, .k = 1 }}, + .bests => &.{.{ .rows = slots, .n = chunks1 * 32, .k = 1 }}, + .last => &.{.{ .rows = slots, .n = chunks2 * 32, .k = 1 }}, + }, + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, m: Mutation) !TopK { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_topk", m), .v = v, .m = m }; + } + pub fn deinit(t: *TopK) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *TopK) void { + inline for (.{ "l", "vin", "iin" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *TopK) g.Kernel { + return controls.mark(.{ .spec = spec(t.v), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(TopK); + + fn chunks(t: *const TopK) usize { + return (t.shape.n + 2047) / 2048; + } + fn fromIds(t: *const TopK) bool { + return t.v != .logits; + } + + pub fn prepare(t: *TopK, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = shape.rows * shape.n; + t.l = try t.a.alloc(u16, if (t.fromIds()) 1 else n); + t.vin = try t.a.alloc(f32, if (t.fromIds()) n else 1); + t.iin = try t.a.alloc(u32, if (t.fromIds()) n else 1); + // coarse logits, so equal values occur and ids must break the ties + for (t.l) |*x| x.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 512))) / 16 - 16); + for (t.vin) |*x| x.* = @as(f32, @floatFromInt(rng.uintLessThan(u32, 512))) / 16 - 16; + for (t.iin, 0..) |*x, i| x.* = @intCast((i % shape.n) * 61 % D.vocab); + if (fill == .nonfinite) for ([_]f32{ d.nan, d.inf, -d.inf, d.nan }, 0..) |x, k| { + const i = (k % shape.rows) * shape.n + (k * 37) % shape.n; + if (t.fromIds()) t.vin[i] = x else t.l[i] = c.toBf16(x); + }; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.l)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.vin)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.iin)); + t.outs[0] = try t.rig.output(shape.rows * t.chunks() * 32 * 4); + t.outs[1] = try t.rig.output(shape.rows * t.chunks() * 32 * 4); + return true; + } + + pub fn run(t: *TopK) !void { + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue([4]u32{ @intCast(t.shape.n), @intCast(t.shape.n), @intCast(t.chunks()), @intFromBool(t.fromIds()) }, 3); + p.e.setBuffer(t.outs[0].buf, t.outs[0].off, 4); + p.e.setBuffer(t.outs[1].buf, t.outs[1].off, 5); + p.e.dispatchGroups(mtl.Size.of(t.chunks(), t.shape.rows, 1), mtl.Size.of(1024, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *TopK) usize { + return 2 * t.shape.rows * t.chunks() * 32 * 4; + } + pub fn reference(_: *TopK, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + const P = struct { v: f32, id: u32 }; + fn first(_: void, a: P, b: P) bool { + return a.v > b.v or (a.v == b.v and a.id < b.id); + } + + pub fn check(t: *TopK, _: g.Gate) !?[]const u8 { + const vals = std.mem.bytesAsSlice(f32, t.rig.bytes(t.outs[0], t.count() / 2)); + const ids = std.mem.bytesAsSlice(u32, t.rig.bytes(t.outs[1], t.count() / 2)); + const buf = try t.a.alloc(P, 2048); + defer t.a.free(buf); + for (0..t.shape.rows) |r| for (0..t.chunks()) |ch| { + var finite = true; + for (buf, 0..) |*x, i| { + const at = ch * 2048 + i; + x.* = if (at < t.shape.n) .{ .v = if (t.fromIds()) t.vin[r * t.shape.n + at] else c.fromBf16(t.l[r * t.shape.n + at]), .id = if (t.fromIds()) t.iin[r * t.shape.n + at] else @intCast(at) } else .{ .v = -std.math.inf(f32), .id = 0xffffffff }; + if (at < t.shape.n and !std.math.isFinite(x.v)) finite = false; + } + if (finite) std.sort.pdq(P, buf, {}, first) else { + var k: usize = 2; + while (k <= 2048) : (k <<= 1) { + var j = k >> 1; + while (j > 0) : (j >>= 1) for (0..2048) |i| { + const l = i ^ j; + if (l <= i) continue; + const swap = if (i & k == 0) first({}, buf[l], buf[i]) else first({}, buf[i], buf[l]); + if (swap) std.mem.swap(P, &buf[i], &buf[l]); + }; + } + } + const o = (r * t.chunks() + ch) * 32; + for (buf[0..32], vals[o..][0..32], ids[o..][0..32], 0..) |want, gv, gi, i| { + if ((@as(u32, @bitCast(want.v)) != @as(u32, @bitCast(gv)) and !(std.math.isNan(want.v) and std.math.isNan(gv))) or want.id != gi) + return try std.fmt.bufPrint(&t.msg, "row {d} chunk {d} place {d}: ({d}, {d}) where the host has ({d}, {d})", .{ r, ch, i, gv, gi, want.v, want.id }); + } + }; + return null; + } +}; + +// --- rc_df_walk: the selector's greedy path through each slot's top candidates ---------------------------------- + +pub const Walk = struct { + pub const Variant = enum { walk }; + /// The vocabulary only bounds ids (and clamps B's row); 8,192 rows keep A and B small. + const vocab = 8192; + const top = D.top; + /// seq: the pending token, a slot's draft each, and a tail the kernel must leave alone. + const seq_len = 20; + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + m: Mutation, + shape: c.Shape = undefined, + fill: g.Fill = .random, + uv: []f32 = &.{}, + ui: []u32 = &.{}, + h: []u16 = &.{}, + pa: []u16 = &.{}, + pb: []u16 = &.{}, + seq: [seq_len]u32 = undefined, + ins: [5]rig_.Ref = undefined, + out: rig_.Ref = undefined, + msg: [200]u8 = undefined, + + /// Rows: the draft slots; n: candidates a slot; k: the selector's rank. + pub fn spec(_: Variant) c.Spec { + return .{ + .name = "ricursive dflash2 rc_df_walk", + .accum = .f32, + .depth = walkDepth, + .out = .raw, + .nan = .{ .stated = "each slot takes the first candidate with the largest score (a NaN never wins; ids past the vocabulary are skipped), within near ties of float64, and walks on from the id it took" }, + .tiles = .{ .{}, .{}, .{} }, + .served = &.{ .{ .rows = slots, .n = top, .k = D.rank }, .{ .rows = 1, .n = top, .k = D.rank } }, + }; + } + /// A product, a 5-level simd_sum, the 8 simdgroups' parts in turn after the unary score. + fn walkDepth(_: c.Shape) usize { + return 15; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, _: Variant, m: Mutation) !Walk { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = try d.pipeline(device, a, "rc_df_walk", m), .m = m }; + } + pub fn deinit(t: *Walk) void { + t.free(); + t.rig.deinit(); + t.pipe.deinit(); + } + fn free(t: *Walk) void { + inline for (.{ "uv", "ui", "h", "pa", "pb" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + pub fn kernel(t: *Walk) g.Kernel { + return controls.mark(.{ .spec = spec(.walk), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Walk); + + pub fn prepare(t: *Walk, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.rows > slots or shape.n != top or shape.k != D.rank) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const k = shape.k; + const s = shape.rows; + t.uv = try t.a.alloc(f32, s * top); + t.ui = try t.a.alloc(u32, s * top); + t.h = try t.a.alloc(u16, s * k); + t.pa = try t.a.alloc(u16, vocab * k); + t.pb = try t.a.alloc(u16, vocab * k); + for (t.uv) |*x| x.* = rng.float(f32) * 4 - 2; + for (0..s) |e| { + // distinct candidates, the last two past the vocabulary (the top-k's padding and the vocabulary's end) + for (t.ui[e * top ..][0..top], 0..) |*x, cnd| x.* = @intCast((e * 977 + cnd * 251) % vocab); + t.ui[e * top + top - 1] = 0xffffffff; + t.ui[e * top + top - 2] = vocab; + } + d.fillBf(rng, t.h, -1, 1); + d.fillBf(rng, t.pa, -1, 1); + d.fillBf(rng, t.pb, -1, 1); + if (fill == .stress) { + // A integers times H = 1 (exact bf16 products), B's halves mirrored: partials near 2^21, small scores + @memset(t.h, c.toBf16(1)); + for (0..vocab) |r| for (0..k / 2) |j| { + t.pa[r * k + j] = c.toBf16(@floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 256))) - 128)); + t.pa[r * k + k / 2 + j] = t.pa[r * k + j]; + const b: f32 = @floatFromInt(64 + rng.uintLessThan(u32, 64)); + t.pb[r * k + j] = c.toBf16(b); + t.pb[r * k + k / 2 + j] = c.toBf16(-b + (if (j < 4) @as(f32, @floatFromInt(rng.uintLessThan(u32, 3))) - 1 else 0)); + }; + for (t.uv) |*x| x.* = @floatFromInt(rng.uintLessThan(u32, 8)); + } + if (fill == .nonfinite) { + t.uv[0 * top + 3] = d.nan; + if (s > 1) t.uv[1 * top + 5] = d.inf; + if (s > 2) t.uv[2 * top + 7] = -d.inf; + } + @memset(&t.seq, 0); + t.seq[0] = 1234; + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.uv)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.ui)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.h)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.pa)); + t.ins[4] = try t.rig.input(std.mem.sliceAsBytes(t.pb)); + t.out = try t.rig.output(t.seq.len * 4); + return true; + } + + pub fn run(t: *Walk) !void { + @memcpy(t.rig.bytes(t.out, t.seq.len * 4), std.mem.sliceAsBytes(&t.seq)); + const p = t.rig.begin(); + p.e.setPipeline(t.pipe); + for (t.ins, 0..) |r, i| p.e.setBuffer(r.buf, r.off, i); + p.e.setValue([4]u32{ @intCast(t.shape.rows), @intCast(t.shape.k), top, vocab }, 5); + p.e.setBuffer(t.out.buf, t.out.off, 6); + p.e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(t.shape.k, 1, 1)); + try t.rig.finish(p); + } + + pub fn count(t: *Walk) usize { + return t.seq.len * 4; + } + + /// Slot e's bf16(unary + bf16(pair)) after `prev` (pair in float64 or simulated); bounds add two bf16 roundings. + fn scores(t: *const Walk, e: usize, prev: u32, sim: ?Sim, out: *[top]f64, bnd: *[top]f64) void { + const k = t.shape.k; + var terms: [D.rank]f64 = undefined; + for (0..top) |cnd| { + const id = t.ui[e * top + cnd]; + const row = @min(id, vocab - 1); + var abs: f64 = 0; + var sum: f64 = 0; + for (0..k) |r| { + const ah = bf(@as(f64, c.fromBf16(t.pa[@as(usize, prev) * k + r])) * c.fromBf16(t.h[e * k + r])); + terms[r] = ah * c.fromBf16(t.pb[@as(usize, row) * k + r]); + sum += terms[r]; + abs += @abs(terms[r]); + } + const pair = if (sim) |o| contract.rows.sumIn(o[0], o[1], terms[0..k]) else sum; + const unary = t.uv[e * top + cnd]; + out[cnd] = bf(unary + bf(pair)); + const err = c.gamma(15, u) * abs; + bnd[cnd] = if (t.fill == .stress or sim != null) 0 else err + 0x1p-7 * (@abs(unary) + 2 * (abs + err)); + } + } + + /// The kernel's choice on float64 scores: the first candidate strictly above all before it, valid ids only. + fn choose(t: *const Walk, e: usize, s: *const [top]f64) usize { + var best = -std.math.inf(f64); + var bi: usize = 0; + for (0..top) |cnd| if (t.ui[e * top + cnd] < vocab and s[cnd] > best) { + best = s[cnd]; + bi = cnd; + }; + return bi; + } + + fn walk(t: *Walk, sim: ?Sim) [seq_len]u32 { + var seq = t.seq; + var s: [top]f64 = undefined; + var b: [top]f64 = undefined; + for (0..t.shape.rows) |e| { + t.scores(e, seq[e], sim, &s, &b); + seq[1 + e] = t.ui[e * top + t.choose(e, &s)]; + } + return seq; + } + + /// Raw outputs: the seq buffer's bytes as the replay leaves them (gate 4's stress has no near ties). + pub fn reference(t: *Walk, want: []f64, mag: []f64) !void { + const seq = t.walk(null); + for (want, std.mem.sliceAsBytes(&seq)) |*w, byte| w.* = @floatFromInt(byte); + @memset(mag, 0); + } + pub fn simulate(t: *Walk, acc: c.Accum, order: g.Order, out: []f64) !void { + const seq = t.walk(.{ acc, order }); + for (out, std.mem.sliceAsBytes(&seq)) |*w, byte| w.* = @floatFromInt(byte); + } + pub fn bounds(_: *Walk, _: []const f64, _: []const f64, allow: []f64) !void { + @memset(allow, 0); + } + + /// Each slot's id: a candidate tied near float64's choice (it, off finite scores), the walk going on from it. + pub fn check(t: *Walk, _: g.Gate) !?[]const u8 { + const got = std.mem.bytesAsSlice(u32, t.rig.bytes(t.out, t.count())); + if (got[0] != t.seq[0]) return try std.fmt.bufPrint(&t.msg, "seq[0] changed", .{}); + for (t.seq[t.shape.rows + 1 ..], got[t.shape.rows + 1 ..]) |w, x| if (w != x) return try std.fmt.bufPrint(&t.msg, "it wrote past its slots", .{}); + var s: [top]f64 = undefined; + var b: [top]f64 = undefined; + for (0..t.shape.rows) |e| { + t.scores(e, got[e], null, &s, &b); + const w = t.choose(e, &s); + const id = got[1 + e]; + const cand = for (0..top) |cnd| { + if (t.ui[e * top + cnd] == id) break cnd; + } else return try std.fmt.bufPrint(&t.msg, "slot {d} took {d}, not one of its candidates", .{ e, id }); + if (cand == w) continue; + if (!std.math.isFinite(s[w]) or !std.math.isFinite(s[cand]) or id >= vocab or !(s[cand] >= s[w] - b[cand] - b[w])) + return try std.fmt.bufPrint(&t.msg, "slot {d} took candidate {d} ({d}) where float64 takes {d} ({d})", .{ e, cand, s[cand], w, s[w] }); + } + return null; + } +}; From e98eec8c8c63998e02cbcb194dec487c4eb4dc51 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:00:53 -0600 Subject: [PATCH 159/361] ricursive: a --drafter server answers logprobs, drafting on or off The drafted wrapper offers the target's first-token row only when asked, and the host left it off while advertising logprobs, so a logprobs request on a --drafter server failed at its first token even with drafting off. The host now builds the wrapper through dflash2_config.wrap, which asks for it, as the Flint host does. A host test runs a logprobs stream through that wrapper with drafting on and off, greedy and sampled, against the plain target, row for row (lanes exports its drafted fixture for it). --- zig/src/core/lanes/lanes.zig | 1 + zig/src/families/ricursive/dflash2_config.zig | 8 +++ .../families/ricursive/dflash2_rows_test.zig | 52 +++++++++++++++++++ zig/src/families/ricursive/ricursive.zig | 1 + zig/src/native/ricursive.zig | 2 +- 5 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 zig/src/families/ricursive/dflash2_rows_test.zig diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index e32b7299864..2bed7691557 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -50,6 +50,7 @@ pub const logprob = @import("logprob.zig"); pub const grammar = @import("grammar.zig"); pub const grammar_time = @import("grammar_time.zig"); pub const grammar_fake = @import("grammar_fake.zig"); // a stand-in libtfgrammar for tests +pub const drafted_fixture = @import("drafted_test.zig"); // its fake drafter and prompts, for a family's wrapper tests pub const Engine = engine.Engine; pub const Config = config.Config; diff --git a/zig/src/families/ricursive/dflash2_config.zig b/zig/src/families/ricursive/dflash2_config.zig index 5d6b263dbce..57513bb0048 100644 --- a/zig/src/families/ricursive/dflash2_config.zig +++ b/zig/src/families/ricursive/dflash2_config.zig @@ -1,5 +1,6 @@ //! ricursiveAI's DFlash2 drafter for Ripple (Ripple-65B-Preview-DFlash2): its config and bf16 weights as published. const std = @import("std"); +const lane = @import("lanes"); const ck = @import("../../core/checkpoint_metal.zig"); const wts = @import("weights.zig"); const cfg = @import("config.zig"); @@ -9,6 +10,13 @@ pub const global_window = 16384; /// Streams a drafted server serves at most: each stream drafts in its own pass, so more tie plain, then trail it. pub const max_streams = 2; +/// The --drafter server's backend: it advertises logprobs, so the wrapper must offer Ripple's first-token row. +pub fn wrap(gpa: std.mem.Allocator, target: lane.backend.Backend, drafter: lane.drafter.Drafter) !lane.drafted.Drafted { + var w = try lane.drafted.Drafted.init(gpa, target, drafter); + w.first_rows = true; + return w; +} + /// Streams a drafted server opens: a named --parallel up to `max_streams`, else `max_streams`; null refuses more. pub fn streams(lanes: u32, named: bool) ?u32 { if (!named) return max_streams; diff --git a/zig/src/families/ricursive/dflash2_rows_test.zig b/zig/src/families/ricursive/dflash2_rows_test.zig new file mode 100644 index 00000000000..bcde55bc167 --- /dev/null +++ b/zig/src/families/ricursive/dflash2_rows_test.zig @@ -0,0 +1,52 @@ +//! A --drafter server's logprobs: each token's row, drafting on or off, is the one the plain target gives. +const std = @import("std"); +const lanes = @import("lanes"); +const dc = @import("dflash2_config.zig"); +const fixture = lanes.drafted_fixture; +const Row = lanes.LogprobRow; + +const gpa = std.testing.allocator; + +const Run = struct { tokens: []u32, rows: []Row, drafted: u64 }; + +/// A stream asking for 3 logprobs a token: through the host's wrapper with drafting `drafts`, or on the bare target. +fn run(wrapped: bool, drafts: bool, sampling: ?lanes.sampling.Sampling) !Run { + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var head: fixture.FakeDrafter = .{}; + defer head.deinit(); + var w = try dc.wrap(gpa, target.backend(), head.drafter()); + defer w.deinit(); + var cfg = try lanes.Config.init(gpa, if (wrapped) w.facts(fixture.base()) else fixture.base(), 16, 15); + defer cfg.deinit(gpa); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, if (wrapped) w.backend() else target.backend(), clock.clock()); + defer engine.deinit(); + var s = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &fixture.p1, .max_new = 40, .eos = &.{96}, .sampling = sampling, .drafts = drafts, .logprobs = 3 }); + defer s.deinit(gpa); + try engine.addStream(&s); + while (engine.activeCount() > 0) try engine.step(); + try std.testing.expectEqual(s.emitted().len, s.rows.items.len); + return .{ .tokens = try gpa.dupe(u32, s.emitted()), .rows = try gpa.dupe(Row, s.rows.items), .drafted = s.drafted }; +} + +test "a drafter server answers logprobs with drafting on and off, row for row the plain target's" { + for ([_]?lanes.sampling.Sampling{ null, fixture.sampled }) |sampling| { + const plain = try run(false, false, sampling); + defer gpa.free(plain.tokens); + defer gpa.free(plain.rows); + for ([_]bool{ true, false }) |drafts| { + const got = try run(true, drafts, sampling); + defer gpa.free(got.tokens); + defer gpa.free(got.rows); + try std.testing.expectEqual(drafts, got.drafted > 0); + try std.testing.expectEqualSlices(u32, plain.tokens, got.tokens); + for (plain.rows, got.rows) |p, d| { + try std.testing.expectEqual(p.token, d.token); + try std.testing.expectEqual(p.logprob, d.logprob); + try std.testing.expectEqualSlices(u32, p.ids[0..p.count], d.ids[0..d.count]); + try std.testing.expectEqualSlices(f32, p.logprobs[0..p.count], d.logprobs[0..d.count]); + } + } + } +} diff --git a/zig/src/families/ricursive/ricursive.zig b/zig/src/families/ricursive/ricursive.zig index a4076afc702..243a3eee912 100644 --- a/zig/src/families/ricursive/ricursive.zig +++ b/zig/src/families/ricursive/ricursive.zig @@ -19,4 +19,5 @@ test { _ = snapshot; _ = contracts; _ = dflash2_config; + _ = @import("dflash2_rows_test.zig"); } diff --git a/zig/src/native/ricursive.zig b/zig/src/native/ricursive.zig index 082c2c242bd..2d0af98248b 100644 --- a/zig/src/native/ricursive.zig +++ b/zig/src/native/ricursive.zig @@ -103,7 +103,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope try h.metal.warm(); if (draft) |d| { try h.metal.measure(); // the depth rule prices drafts against the window forward's cost by rows - h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter()); + h.wrap = try fr.dflash2_config.wrap(gpa, h.metal.backend(), d.drafter()); h.draft = d; } errdefer if (h.wrap) |*w| w.deinit(); From 7620d573fde8707eb0e78db87377b79a469ba7e8 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:00:53 -0600 Subject: [PATCH 160/361] docs: Ripple's recipe quotes the 75-kernel contract run and the drafter's logprobs check --- docs/recipes/ripple-65b-metal.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/recipes/ripple-65b-metal.md b/docs/recipes/ripple-65b-metal.md index fc21a3e533e..559694a0b54 100644 --- a/docs/recipes/ripple-65b-metal.md +++ b/docs/recipes/ripple-65b-metal.md @@ -86,11 +86,14 @@ publisher's W4A4 kernels. Every kernel is registered with the kernel contract (`zig/tests/contract/metal_ricursive*.zig`, the roll call in `contracts.zig`): the glue, decode and prompt attention for both layer kinds, the NVFP4 row kernels, dequantization and GEMM, and llama's row projections, merge, argmax and GEMM again at Ripple's shapes (every reduction it runs: k 5,120, -10,240 for the attention output and 40,960). Fifteen planted controls each edit one kernel's source, and each must turn -its gate red. `tf-kernel-contract --only ricursive` on the M5 Ultra: +10,240 for the attention output and 40,960). The DFlash2 drafter adds its own kernels (the target's tap, the +drafter's embedding, norms, conv, rotation, attention, SiLU, top-k and walk), llama's row projections and GEMM at the +drafter's shapes, and the full-vocabulary sampler. Twenty-five planted controls (ten of them in the drafter's kernels) +each edit one kernel's source, and each must turn its gate red. `tf-kernel-contract --only ricursive` on the M5 Ultra +(23 Nov 2026): ``` -SUMMARY 46 kernels: 46 pass gates 1-4, 0 fail, 0 known findings; 15 controls: 15 red as planted, 0 missed; 0 limit problems; gates 645430 ms, limits 140 ms +SUMMARY 75 kernels: 75 pass gates 1-4, 0 fail, 0 known findings; 25 controls: 25 red as planted, 0 missed; 0 limit problems; gates 874094 ms, limits 505 ms ``` ## Correctness (M5 Ultra, 4 Nov 2026) @@ -227,8 +230,9 @@ with first tokens of 3.24 to 7.98 s; they are left out of the table. Plain, two No quality suite was run. Contexts past 258,039 tokens were not run, so `--context` stops at 262,144 and refuses the card's 1M by name. Ripple's think markers are spelled from several tokens, not one each, so a thinking budget -(which forces a close) and logprobs (which cut the reply at its close token) are refused by name, and a reply's -`reasoning_tokens` reads 0. No images: +(which forces a close) is refused by name, and a reply's `reasoning_tokens` reads 0. Logprobs are served, with +`--drafter` too: on the NVFP4 release with the drafter (23 Nov 2026), a greedy and a seeded sampled request with +`top_logprobs: 3` gave the same tokens and rows with drafting on (3.58 and 3.56 tokens a round) and off. No images: Ripple has no vision tower. Only the M5's tensor units were checked; M1 to M4 Macs are refused at load, and smaller RAM is untested. Beside the bf16 release the drafter was checked for drafted == plain and one stream's speed only (two drafted streams run one at a time there, see above); its structured output, seeded sampling, soak and resumed turns were From 3e51d24f8e988530be83c55685daa902c5c9d1a8 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:28:23 -0600 Subject: [PATCH 161/361] ricursive: a drafting stream's ring stays in the ledger from admission to release, and the context fits the first ring --- zig/src/families/ricursive/backend.zig | 20 +- zig/src/families/ricursive/budget.zig | 28 ++ zig/src/families/ricursive/dflash2.zig | 24 +- .../ricursive/dflash2_charge_test.zig | 242 ++++++++++++++++++ zig/src/families/ricursive/ricursive.zig | 1 + zig/src/families/ricursive/state.zig | 1 + zig/src/native/ricursive.zig | 10 +- 7 files changed, 310 insertions(+), 16 deletions(-) create mode 100644 zig/src/families/ricursive/dflash2_charge_test.zig diff --git a/zig/src/families/ricursive/backend.zig b/zig/src/families/ricursive/backend.zig index 76eb7243891..4a8f940eb9c 100644 --- a/zig/src/families/ricursive/backend.zig +++ b/zig/src/families/ricursive/backend.zig @@ -97,6 +97,11 @@ pub const Metal = struct { return cache; } + /// The ledger's bytes for a stream of `capacity` (budget.charge), held from admission to release. + pub fn charge(self: *const Metal, stream: *const lanes.Stream, capacity: usize) u64 { + return budget.charge(&self.model.config, capacity, stream.drafts, self.options.drafter_bytes); + } + pub fn facts(self: *const Metal) lanes.Model { // rows are independent in every decode kernel, so any width, alone or beside other streams, gives one-row bits return .{ .exact_width = st.window_rows, .gpu_tokens = !self.options.drafts, .hidden_rows = true, .batch_rows = st.batch_rows, .mtp = false, .speculate = false, .speculate_early = false, .drafts = 1, .max_streams = self.options.streams, .streams_exact = true, .window_costs = self.costs[0..self.timed] }; @@ -274,14 +279,14 @@ pub const Metal = struct { if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidRicursivePrompt; if (stream.images.len > 0) return error.RicursiveHasNoImageTower; const capacity = ids.len + stream.max_new + 1; - const need = st.cacheBytes(&self.model.config, capacity); - // the stream's caches fit before anything is made; kept states trim first + const need = self.charge(stream, capacity); + // the stream's caches (and its drafter ring) fit before anything is made; kept states trim first const Admit = struct { m: *Metal, stream: *lanes.Stream, ids: []const u32, - pub fn growth(a: *const @This()) u64 { - return a.m.options.drafter_bytes; // a drafter's context for the stream, beside its caches + pub fn growth(_: *const @This()) u64 { + return 0; // the drafter ring is in the stream's charge, held until release } pub fn shed(_: *const @This(), _: u64) void {} pub fn restoreBytes(a: *const @This()) u64 { @@ -301,7 +306,7 @@ pub const Metal = struct { }; const admit: Admit = .{ .m = self, .stream = stream, .ids = ids }; budget.admitStream(&self.ledger, need, &admit) catch |err| { - if (err == error.LaneMemory) std.log.warn("ricursive: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need + admit.growth()), gib(self.ledger.held), gib(self.ledger.limit) }); + if (err == error.LaneMemory) std.log.warn("ricursive: a {d}-token stream needs {d:.1} GiB of caches; {d:.1} of {d:.1} GiB are held", .{ capacity, gib(need), gib(self.ledger.held), gib(self.ledger.limit) }); return err; // LaneMemory: the lane host queues the stream until another finishes, or fails it alone }; errdefer { // as releaseFn: the bytes back and the prompt cache's room fitted to them (admission trimmed it) @@ -311,9 +316,10 @@ pub const Metal = struct { const cache = try self.createCache(capacity); errdefer self.gpa.destroy(cache); errdefer cache.deinit(); + cache.charge = need; try self.caches.put(self.gpa, stream, cache); // a mark's save finds it there errdefer _ = self.caches.remove(stream); - // the kept states may use what the stream's growth copy and the slot's old cache gave back + // the kept states fitted to what the stream's charge (its caches and any drafter ring) leaves if (self.room) |r| r.fit(r.ctx, self.ledger.left(), stream.reuse.saved, ids); stream.cached = 0; if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there @@ -468,7 +474,7 @@ pub const Metal = struct { const self = cast(ptr); self.drain() catch |err| std.log.err("ricursive: a step in flight failed at release: {s}", .{@errorName(err)}); if (self.caches.fetchRemove(stream)) |entry| { - self.ledger.give(st.cacheBytes(&self.model.config, entry.value.capacity)); + self.ledger.give(entry.value.charge); entry.value.deinit(); self.gpa.destroy(entry.value); if (self.room) |r| r.fit(r.ctx, self.ledger.left(), null, &.{}); diff --git a/zig/src/families/ricursive/budget.zig b/zig/src/families/ricursive/budget.zig index a7b51364c7b..768ca181468 100644 --- a/zig/src/families/ricursive/budget.zig +++ b/zig/src/families/ricursive/budget.zig @@ -8,6 +8,11 @@ pub const Ledger = llama.Ledger; pub const caches = llama.caches; pub const admitStream = llama.admitStream; +/// A stream's ledger bytes from admission to release: its caches, and its drafter ring if it drafts. +pub fn charge(c: *const cfg.Config, capacity: usize, drafts: bool, ring: u64) u64 { + return st.cacheBytes(c, capacity) + (if (drafts) ring else 0); +} + /// The longest context whose stream (its caches and logits row) fits in `bytes`, at most `most`. pub fn longest(c: *const cfg.Config, bytes: u64, most: usize) usize { if (st.cacheBytes(c, 2) > bytes) return 0; @@ -20,6 +25,29 @@ pub fn longest(c: *const cfg.Config, bytes: u64, most: usize) usize { return lo; } +/// The longest context whose first stream fits in `bytes` with its drafter ring (`ring`; 0 without a drafter). +pub fn longestDrafted(c: *const cfg.Config, bytes: u64, ring: u64, most: usize) usize { + return if (ring > bytes) 0 else longest(c, bytes - ring, most); +} + +test "ricursive budget: a drafter's first ring bounds the context, C + D fits the window and C + D - 1 does not" { + const gpa = std.testing.allocator; + const c = try cfg.parse(gpa, @embedFile("fixtures/config.json")); + const dflash2 = @import("dflash2.zig"); + const dcfg = try @import("dflash2_config.zig").parse(gpa, @embedFile("fixtures/dflash2_config.json"), &c); + const ring: u64 = dflash2.Drafter.laneBytes(&dcfg); + const n: usize = 262144; + const caches_n = st.cacheBytes(&c, n + 1); // a stream of the whole window: its caches and its logits row + // automatic sizing takes the longest that fits; --context n is refused past it: both read this bound + try std.testing.expectEqual(n, longestDrafted(&c, caches_n + ring, ring, n)); + try std.testing.expect(longestDrafted(&c, caches_n + ring - 1, ring, n) < n); + // without a drafter the bound is the caches' alone, as before + try std.testing.expectEqual(n, longestDrafted(&c, caches_n, 0, n)); + try std.testing.expect(longestDrafted(&c, caches_n - 1, 0, n) < n); + try std.testing.expectEqual(longest(&c, caches_n + ring - 1, n), longestDrafted(&c, caches_n + ring - 1, 0, n)); + try std.testing.expectEqual(@as(usize, 0), longestDrafted(&c, ring - 1, ring, n)); +} + test "ricursive budget: a 262,144-token stream's caches fit 17 GiB, not 16" { const c = try cfg.parse(std.testing.allocator, @embedFile("fixtures/config.json")); const gib: u64 = 1 << 30; diff --git a/zig/src/families/ricursive/dflash2.zig b/zig/src/families/ricursive/dflash2.zig index 206e4a15544..93a7cdeee93 100644 --- a/zig/src/families/ricursive/dflash2.zig +++ b/zig/src/families/ricursive/dflash2.zig @@ -31,6 +31,7 @@ const max_key_blocks = dc.global_window / key_block + 2; const Lane = struct { k: [dc.max_layers]mtl.Buffer, v: [dc.max_layers]mtl.Buffer, + made: bool = false, // the ring is made at the stream's first absorb or hold, after the target admitted its charge end: u64 = 0, // context rows absorbed: positions [from, end) from: u64 = 0, // the first position held (a resumed prompt's drafter context starts there) held: [max_block]u32 = @splat(0), @@ -168,6 +169,7 @@ pub const Drafter = struct { } fn laneResident(d: *const Drafter, l: *const Lane, f: mtl.ResidencySet.Follow, on: bool) void { + if (!l.made) return; for (0..d.config.layers) |i| for ([_]mtl.Buffer{ l.k[i], l.v[i] }) |x| if (on) f.join(f.ctx, x) else f.leave(f.ctx, x); } @@ -188,10 +190,18 @@ pub const Drafter = struct { return .{ .depth = d.config.block - 1, .step_ms = d.step_ms, .plain_guard = true, .stream_bytes = laneBytes(&d.config) }; } + /// A lane with its ring made (warm's). fn newLane(d: *Drafter) !*Lane { const l = try d.gpa.create(Lane); errdefer d.gpa.destroy(l); l.* = .{ .k = undefined, .v = undefined }; + try d.makeRing(l); + return l; + } + + /// The lane's ring buffers, once; a failure leaves none made. + fn makeRing(d: *Drafter, l: *Lane) !void { + if (l.made) return; var made: usize = 0; errdefer for (0..made) |i| { l.k[i].deinit(); @@ -206,24 +216,26 @@ pub const Drafter = struct { }; made += 1; } + l.made = true; if (d.follow) |f| d.laneResident(l, f, true); - return l; } fn dropLane(d: *Drafter, l: *Lane) void { if (d.follow) |f| d.laneResident(l, f, false); - for (0..d.config.layers) |i| { + if (l.made) for (0..d.config.layers) |i| { l.k[i].deinit(); l.v[i].deinit(); - } + }; d.gpa.destroy(l); } fn openFn(ptr: *anyopaque, s: *Stream) anyerror!void { const d = cast(ptr); if (d.lanes.contains(s)) return error.DraftStreamOpen; - const l = try d.newLane(); - errdefer d.dropLane(l); + // no ring yet: on the streamed prompt pass this runs before the target admits the stream's charge + const l = try d.gpa.create(Lane); + errdefer d.gpa.destroy(l); + l.* = .{ .k = undefined, .v = undefined }; try d.lanes.put(d.gpa, s, l); } @@ -285,6 +297,7 @@ pub const Drafter = struct { const width: usize = dc.max_taps * @as(usize, c.hidden) * 2; for (items) |it| { const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + try d.makeRing(l); const f = it.features; if (f.space != .device or f.dtype != .bf16 or f.row_bytes != width) return error.DraftFeaturesUnsupported; if (it.start > l.end or l.end == 0) l.from = it.start; // the rows before it were restored, not absorbed @@ -385,6 +398,7 @@ pub const Drafter = struct { const c = &d.config; for (items) |it| { const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown; + try d.makeRing(l); if (it.depth == 0 or it.depth > c.block - 1 or it.position == 0) return error.DraftDepth; const anchor = it.position - 1; if (l.end != anchor) return error.DraftContextGap; diff --git a/zig/src/families/ricursive/dflash2_charge_test.zig b/zig/src/families/ricursive/dflash2_charge_test.zig new file mode 100644 index 00000000000..b7442749a77 --- /dev/null +++ b/zig/src/families/ricursive/dflash2_charge_test.zig @@ -0,0 +1,242 @@ +//! A --drafter server's memory plan: one charge a stream from admission to release, its drafter ring made after it. +const std = @import("std"); +const lanes = @import("lanes"); +const cfg = @import("config.zig"); +const st = @import("state.zig"); +const budget = @import("budget.zig"); +const dc = @import("dflash2_config.zig"); +const fixture = lanes.drafted_fixture; +const be = lanes.backend; +const dr = lanes.drafter; +const Stream = lanes.Stream; + +const gpa = std.testing.allocator; + +/// The lanes fake as Ripple's target: each prompt pass admits the stream's charge as backend.prefillFn does. +const Target = struct { + fake: lanes.fake.Fake, + c: *const cfg.Config, + ring: u64, + ledger: budget.Ledger, + charges: std.AutoHashMapUnmanaged(*Stream, u64) = .empty, + live: u64 = 0, // bytes made: caches at admission, rings when the drafter makes them + peak: u64 = 0, + vt: be.Backend.VTable = undefined, + + fn deinit(t: *Target) void { + t.charges.deinit(gpa); + t.fake.deinit(); + } + + fn backend(t: *Target) be.Backend { + var b = t.fake.backend(); + t.vt = b.vtable.*; + t.vt.prefill = prefill; + t.vt.prefill_features = prefillFeatures; + t.vt.release = release; + b.vtable = &t.vt; + return b; + } + + fn of(ptr: *anyopaque) *Target { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return @fieldParentPtr("fake", f); + } + + fn made(t: *Target, bytes: u64) !void { + t.live += bytes; + t.peak = @max(t.peak, t.live); + try std.testing.expect(t.live <= t.ledger.held and t.ledger.held <= t.ledger.limit); + } + + /// The whole prompt pass (a stream drafting off): its charge admitted, then the fake's pass. + fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { + try of(ptr).admitted(s); + try of(ptr).fake.backend().vtable.prefill(ptr, s); + } + + /// The streamed pass (a stream drafting on): its charge admitted, the fake's pass, then its rows to the drafter. + fn prefillFeatures(ptr: *anyopaque, s: *Stream, taps: []const u32, sink: be.FeatureSink) anyerror!void { + const t = of(ptr); + try t.admitted(s); + try t.fake.backend().vtable.prefill(ptr, s); + const n: u32 = @intCast(s.prompt().len); + try sink.take(sink.ptr, s, try t.fake.backend().vtable.features.?(ptr, s, taps, 0, n), 0); + } + + /// The stream's charge taken as backend.prefillFn takes it, and its caches made. + fn admitted(t: *Target, s: *Stream) !void { + const capacity = s.prompt().len + s.max_new + 1; + const need = budget.charge(t.c, capacity, s.drafts, t.ring); + const Admit = struct { + pub fn growth(_: *const @This()) u64 { + return 0; + } + pub fn shed(_: *const @This(), _: u64) void {} + pub fn restoreBytes(_: *const @This()) u64 { + return 0; + } + pub fn dropRestore(_: *const @This()) void {} + pub fn trim(_: *const @This(), _: u64) void {} + pub fn prepare(_: *const @This()) !void {} + }; + try budget.admitStream(&t.ledger, need, &Admit{}); + try t.charges.put(gpa, s, need); + try t.made(st.cacheBytes(t.c, capacity)); + } + + fn release(ptr: *anyopaque, s: *Stream) void { + const t = of(ptr); + if (t.charges.fetchRemove(s)) |kv| { + t.ledger.give(kv.value); // the same bytes admission took + t.live -= kv.value - (if (s.drafts) t.ring else 0); + } + t.fake.backend().vtable.release(ptr, s); + } +}; + +/// The fake drafter with Ripple's ring rule: none at open, made at the stream's first absorb or hold. +const Rings = struct { + inner: fixture.FakeDrafter = .{}, + t: *Target, + rings: std.AutoHashMapUnmanaged(*Stream, void) = .empty, + vt: dr.Drafter.VTable = undefined, + + fn deinit(r: *Rings) void { + r.rings.deinit(gpa); + r.inner.deinit(); + } + + fn drafter(r: *Rings) dr.Drafter { + var d = r.inner.drafter(); + r.vt = d.vtable.*; + r.vt.absorb = absorb; + r.vt.hold = hold; + r.vt.release = release; + d.vtable = &r.vt; + return d; + } + + fn of(ptr: *anyopaque) *Rings { + const f: *fixture.FakeDrafter = @ptrCast(@alignCast(ptr)); + return @fieldParentPtr("inner", f); + } + + fn make(r: *Rings, s: *Stream) !void { + if (r.rings.contains(s)) return; + try std.testing.expect(r.t.charges.contains(s)); // the target admitted the stream's charge first + try r.rings.put(gpa, s, {}); + try r.t.made(r.t.ring); + } + + fn absorb(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const r = of(ptr); + for (items) |it| try r.make(it.stream); + return r.inner.drafter().vtable.absorb(ptr, items); + } + + fn hold(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const r = of(ptr); + for (items) |it| try r.make(it.stream); + return r.inner.drafter().vtable.hold(ptr, items); + } + + fn release(ptr: *anyopaque, s: *Stream) void { + const r = of(ptr); + if (r.rings.remove(s)) r.t.live -= r.t.ring; + r.inner.drafter().vtable.release(ptr, s); + } +}; + +/// A Ripple config and its drafter's ring, and a stream's caches at the fixture prompt's capacity. +const Plan = struct { c: cfg.Config, ring: u64, caches: u64 }; + +const max_new = 40; + +fn plan() !Plan { + const c = try cfg.parse(gpa, @embedFile("fixtures/config.json")); + const d = try dc.parse(gpa, @embedFile("fixtures/dflash2_config.json"), &c); + const ring: u64 = @import("dflash2.zig").Drafter.laneBytes(&d); + return .{ .c = c, .ring = ring, .caches = st.cacheBytes(&c, fixture.p1.len + max_new + 1) }; +} + +/// The wrapper's prompt pass for `streams` under `limit`: each one's outcome, in order, none released between them. +fn admit(p: *const Plan, limit: u64, drafts: []const bool, out: []anyerror!void) !struct { held: u64, peak: u64, rings: usize } { + var t: Target = .{ .fake = .{ .gpa = gpa }, .c = &p.c, .ring = p.ring, .ledger = .{ .limit = limit } }; + defer t.deinit(); + var r: Rings = .{ .t = &t }; + defer r.deinit(); + var w = try dc.wrap(gpa, t.backend(), r.drafter()); + defer w.deinit(); + const b = w.backend(); + var ss: [2]Stream = undefined; + for (drafts, 0..) |on, i| ss[i] = try Stream.init(gpa, .{ .id = "s", .prompt = &fixture.p1, .max_new = max_new, .eos = &.{96}, .drafts = on }); + defer for (ss[0..drafts.len]) |*s| s.deinit(gpa); + for (ss[0..drafts.len], out) |*s, *o| o.* = b.vtable.prefill(b.ptr, s); + const held = t.ledger.held; + const peak = t.peak; + const rings = r.rings.count(); + for (ss[0..drafts.len]) |*s| b.vtable.release(b.ptr, s); + try std.testing.expectEqual(@as(u64, 0), t.ledger.held); // every charge given back as taken + try std.testing.expectEqual(@as(u64, 0), t.live); + return .{ .held = held, .peak = peak, .rings = rings }; +} + +test "two drafting streams are charged their rings too: the second waits when both do not fit" { + const p = try plan(); + const one = p.caches + p.ring; + var out: [2]anyerror!void = undefined; + // room for one drafting stream and a second's caches, not its ring: the second is refused, not admitted short + const got = try admit(&p, 2 * one - 1, &.{ true, true }, &out); + try out[0]; + try std.testing.expectError(error.LaneMemory, out[1]); + try std.testing.expectEqual(one, got.held); // the first stream's ring stays in the ledger after its admission + try std.testing.expectEqual(@as(usize, 1), got.rings); + try std.testing.expect(got.peak <= 2 * one - 1); + // with room for both, both hold their caches and rings + const both = try admit(&p, 2 * one, &.{ true, true }, &out); + try out[0]; + try out[1]; + try std.testing.expectEqual(2 * one, both.held); + try std.testing.expectEqual(@as(usize, 2), both.rings); +} + +test "a stream with drafting off is charged its caches only: it fits exactly where a drafting one does not" { + const p = try plan(); + var out: [1]anyerror!void = undefined; + const off = try admit(&p, p.caches, &.{false}, &out); + try out[0]; + try std.testing.expectEqual(p.caches, off.held); + try std.testing.expectEqual(@as(usize, 0), off.rings); + _ = try admit(&p, p.caches + p.ring - 1, &.{true}, &out); + try std.testing.expectError(error.LaneMemory, out[0]); + const on = try admit(&p, p.caches + p.ring, &.{true}, &out); + try out[0]; + try std.testing.expectEqual(p.caches + p.ring, on.held); +} + +test "the streamed prompt pass makes a drafter ring only after the target admitted the stream's charge" { + const p = try plan(); + var out: [2]anyerror!void = undefined; + // Rings.make checks the charge is held before a ring is made, and Target.made that nothing made passes the ledger + const got = try admit(&p, 2 * (p.caches + p.ring), &.{ true, false }, &out); + try out[0]; + try out[1]; + try std.testing.expectEqual(@as(usize, 1), got.rings); + try std.testing.expectEqual(2 * p.caches + p.ring, got.peak); +} + +test "Ripple's drafter opens a stream with no ring: its buffers wait for the first absorb or hold" { + var d: @import("dflash2.zig").Drafter = undefined; + d.gpa = gpa; + d.lanes = .empty; + d.follow = null; + defer d.lanes.deinit(gpa); + var s = try Stream.init(gpa, .{ .id = "s", .prompt = &fixture.p1, .max_new = max_new, .eos = &.{96} }); + defer s.deinit(gpa); + const x = d.drafter(); + try x.vtable.open(x.ptr, &s); + try std.testing.expect(!d.lanes.get(&s).?.made); + x.vtable.release(x.ptr, &s); + try std.testing.expectEqual(@as(usize, 0), d.lanes.count()); +} diff --git a/zig/src/families/ricursive/ricursive.zig b/zig/src/families/ricursive/ricursive.zig index 243a3eee912..e1de5b3cffd 100644 --- a/zig/src/families/ricursive/ricursive.zig +++ b/zig/src/families/ricursive/ricursive.zig @@ -20,4 +20,5 @@ test { _ = contracts; _ = dflash2_config; _ = @import("dflash2_rows_test.zig"); + _ = @import("dflash2_charge_test.zig"); } diff --git a/zig/src/families/ricursive/state.zig b/zig/src/families/ricursive/state.zig index a480e6c93f5..6657d0a0955 100644 --- a/zig/src/families/ricursive/state.zig +++ b/zig/src/families/ricursive/state.zig @@ -61,6 +61,7 @@ pub const Cache = struct { /// The latest tapped rows a drafter may absorb: positions [start, start + rows), in a scratch's or last_tap. tap: Tap = .{}, last_tap: ?mtl.Buffer = null, // the prompt's last row's taps, kept for the first draft + charge: u64 = 0, // the ledger's bytes for the stream (Metal.charge), given back as taken pub fn setResident(self: *Cache, hook: ?mtl.ResidencySet.Follow) void { if (self.follow) |f| mtl.resident.fields.apply(self, f, false); diff --git a/zig/src/native/ricursive.zig b/zig/src/native/ricursive.zig index 2d0af98248b..07c5a326f9c 100644 --- a/zig/src/native/ricursive.zig +++ b/zig/src/native/ricursive.zig @@ -70,7 +70,9 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope if (draft) |d| scratch += d.checkpoint.residentBytes() + fr.dflash2.Drafter.fixedBytes(&d.config) + (fr.state.batch_rows + fr.state.prompt_rows) * fr.dflash2_config.max_taps * model.config.hidden * 2; const budget = try fr.budget.caches(ram, model.device.maxWorkingSet(), null, model.checkpoint.residentBytes() + scratch); const most: usize = @min(model.config.context, fr.state.max_capacity); - const fits = fr.budget.longest(&model.config, budget, most); + // with a drafter, the first stream's ring is held beside its caches: the window fits both + const lane_bytes: u64 = if (draft) |d| fr.dflash2.Drafter.laneBytes(&d.config) else 0; + const fits = fr.budget.longestDrafted(&model.config, budget, lane_bytes, most); if (o.context) |asked| if (asked > fr.config.max_context) { problem.* = try std.fmt.allocPrint(a, "--context {d}: the native Ripple engine is checked to {d} tokens; longer contexts are refused until a run at that length qualifies them", .{ asked, fr.config.max_context }); if (draft) |d| d.deinit(); @@ -79,10 +81,11 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope }; const window: i64 = o.context orelse @intCast(@min(fits, fr.config.max_context)); if (window < 1 or window > fits) { + const beside: []const u8 = if (draft != null) " and a stream's drafter ring" else ""; problem.* = if (o.context) |asked| - try std.fmt.allocPrint(a, "--context {d}: this Mac's Ripple caches fit {d} tokens beside the weights under its load limit (75% of RAM)", .{ asked, fits }) + try std.fmt.allocPrint(a, "--context {d}: this Mac's Ripple caches fit {d} tokens beside the weights{s} under its load limit (75% of RAM)", .{ asked, fits, beside }) else - try a.dupe(u8, "this Mac's load limit (75% of RAM) leaves no room for a Ripple stream's caches beside the weights"); + try std.fmt.allocPrint(a, "this Mac's load limit (75% of RAM) leaves no room for a Ripple stream's caches beside the weights{s}", .{beside}); if (draft) |d| d.deinit(); model.deinit(); // after the message, so a failed allocation leaves the model to the errdefer return null; @@ -97,7 +100,6 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.resident = null; h.draft = null; h.wrap = null; - const lane_bytes: u64 = if (draft) |d| fr.dflash2.Drafter.laneBytes(&d.config) else 0; h.metal = try fr.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = streams, .budget = budget, .drafts = draft != null, .drafter_bytes = lane_bytes }); errdefer h.metal.deinit(); try h.metal.warm(); From ef6bf1bea8e50ee992e809236a4d105081581a6e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:37:52 +0000 Subject: [PATCH 162/361] changelog: #2260 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e4ae3e8913..1c88adeca12 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 +- Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. + - Inkling 2 Mini: `enable_thinking: false` and `reasoning_effort: "none"` now reach the chat template as thinking effort 0 instead of the default 0.9; thinking-on replies are unchanged (#4876). - Inkling 2 Mini on CUDA: the loop gate runs as a down half and an up half, so one-stream decode is about 28% faster on GB10 with identical tokens (#4697). Thanks @jschmied. From dcdb52889b33c451cf55be975dd9aa694b5ced9c Mon Sep 17 00:00:00 2001 From: BadAd84 Date: Fri, 20 Nov 2026 23:38:27 +0000 Subject: [PATCH 163/361] flashnext cuda: the fused BF16 read-out is on by default Unset or blank now takes the three-launch read-out on a CUDA prompt pass of 768 rows or more with BF16 read-out weights; TF_FLASHNEXT_READOUT_FUSED=0 restores the five launches. The setting keeps exactly 0 and 1, and a malformed value is still refused by name. Metal, HIP and a CUDA checkpoint whose read-out is MLX affine keep their own read-out when the setting is unset; an explicit 1 is still refused there by name. That keeps every default path that has no fused tiles as it was. The kept-state key still carries the resolved form in bit 1 of the hc_fuse slot, so the default resolves to that bit and setting 0 restores the key main writes today. Tests: the environment table pins the new default and the accepted-forms text that names it; the reader's test drives unset, empty, whitespace-only, 0, 1 and a malformed value, and checks the three refusal call sites; the Forms test asserts unset is on and 0 is off; the disk identity test asserts unset and 0 differ; the dispatcher test asserts 0 keeps the five launches and the fused form starts at 768 rows on prompt passes only. (cherry picked from commit a4b97900ffbfa498ecaea5c862ae159c09608262) --- docs/environment.md | 2 +- .../flashnext-readout-fused/README.md | 3 ++ docs/recipes/flash-next-cuda.md | 7 +-- zig/src/families/flashnext/cuda_batch_hc.zig | 24 ++++++++++ .../families/flashnext/cuda_batch_kernels.zig | 2 +- zig/src/families/flashnext/cuda_disk.zig | 2 +- zig/src/families/flashnext/cuda_prompt_wt.zig | 2 +- zig/src/families/flashnext/engine_load.zig | 2 +- zig/src/families/flashnext/hip/load.zig | 2 +- zig/src/families/flashnext/readout_fused.zig | 46 ++++++++++++++----- zig/src/native/cuda_disk_policy_test.zig | 23 ++++++++-- zig/src/platform/environment.zig | 2 +- .../platform/environment_flashnext_test.zig | 4 +- zig/tests/fixtures/gradient-serving.tsv | 2 +- 14 files changed, 97 insertions(+), 26 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 7c21e763c9b..3ecd467dbf6 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -201,7 +201,7 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_SHARED_DRAFTS` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_SHARED_SIDE` | Exactly `0` or `1`; default on | | `TF_FLASHNEXT_HC_FUSE` | Exactly `0` or `1`; default on | -| `TF_FLASHNEXT_READOUT_FUSED` | Exactly `0` or `1`; default off | +| `TF_FLASHNEXT_READOUT_FUSED` | Exactly `0` or `1`; default on. `0` restores the five-launch read-out; Metal, HIP and an MLX affine read-out refuse an explicit `1` | | `TF_FLASHNEXT_KEEP_LATE` | Exactly `0` or `1`; unset or blank leaves the choice to the loader | | `TF_FLASHNEXT_DECODE_GRAPH` | Exactly `0` or `1`; default off | | `TF_FLASHNEXT_SPLIT_DENSE` | Exactly `0` or `1`; default on: two ranks split the BF16 dense projections | diff --git a/docs/receipts/flashnext-readout-fused/README.md b/docs/receipts/flashnext-readout-fused/README.md index be01941a27a..e95d74d65d8 100644 --- a/docs/receipts/flashnext-readout-fused/README.md +++ b/docs/receipts/flashnext-readout-fused/README.md @@ -5,6 +5,9 @@ rows, in three launches instead of five: the down projection forms the normed ro forms them again in its epilogue and mixes the four streams there, and the writeback before it skips its normalize. Unset or blank is main's chain. +This receipt was recorded while the setting was off by default. The default is now on; the unset and blank arms below are +the chain only at the commits they name, and their measured numbers are kept as recorded. + ## Source and environment - Main: `41a72fd2578dfbdd73b25663da78d5fc0047bd95`. Branch: this pull request at diff --git a/docs/recipes/flash-next-cuda.md b/docs/recipes/flash-next-cuda.md index b0ee2602f2a..f3d857b2201 100644 --- a/docs/recipes/flash-next-cuda.md +++ b/docs/recipes/flash-next-cuda.md @@ -97,9 +97,10 @@ its path. - `--no-drafts` serves without the MTP head; `"draft": false` on a request does the same for that request. - `TF_FLASHNEXT_READOUT_ROWS` (default 64, `0` never) is the rows from which the hyper-connection read-out takes the prompt tiles. Same bits either way; `128` keeps 16-stream decode rounds on the row kernels, up to 7% quicker on a GB10. -- `TF_FLASHNEXT_READOUT_FUSED=1` (default off) runs a prompt pass's BF16 hyper-connection read-out, from 768 rows, on - two fused tiles that form the normed rows on chip. Same bits; cold prompts of 8k to 64k tokens 2.8% to 3.5% quicker - on a GB10 with the NVFP4 checkpoint. Metal, HIP and an MLX affine read-out refuse it by name. +- `TF_FLASHNEXT_READOUT_FUSED` (default on, `0` restores the five launches) runs a prompt pass's BF16 + hyper-connection read-out, from 768 rows, on two fused tiles that form the normed rows on chip. Same bits; cold + prompts of 8k to 64k tokens 2.8% to 3.5% quicker on a GB10 with the NVFP4 checkpoint. Metal, HIP and an MLX affine + read-out refuse an explicit `1` and keep their own read-out when it is unset. - `TF_FLASHNEXT_CHUNK` (1 to 16,384, default 3,072) caps the rows of one prompt pass. Every pass reads the weights of every expert its rows route to, so fewer, larger passes cost less a token; but a pass runs to its end, so a stream decoding during a pass waits up to the whole pass for its next token. See diff --git a/zig/src/families/flashnext/cuda_batch_hc.zig b/zig/src/families/flashnext/cuda_batch_hc.zig index 312f9898cc6..667ed910feb 100644 --- a/zig/src/families/flashnext/cuda_batch_hc.zig +++ b/zig/src/families/flashnext/cuda_batch_hc.zig @@ -66,3 +66,27 @@ pub fn readoutNative(pass: anytype, hc_w: wt.HcW, r0: usize, n: usize) !void { try pass.k.nativeMatmul(pass.stream, act, low, n, up, s.hc_up, s.native_part, .bf16); try pass.tri.hcDenseMix(s.hc_up, norm, s.mixed + r0 * dims * 2, s.xsm + r0 * (dims / 32) * 4, n, dims, streams); } + +test "fused read-out: on takes the tiles from 768 rows and 0 keeps the five launches" { + const cuda = @import("cuda"); + const zero: cuda.DeviceBuffer = .{ .d = undefined, .ptr = 0, .len = 0 }; + const hc_w: wt.HcW = .{ + .scale = zero, + .down = .{ .w = zero, .s = zero, .b = zero, .n = low, .k = wide, .native = cuda.modelopt.bf16Weight(0, low, wide) }, + .up = .{ .w = zero, .s = zero, .b = zero, .n = wide, .k = low, .native = cuda.modelopt.bf16Weight(0, wide, low) }, + .n_down = low, + .has_inj = 0, + }; + const Pass = struct { + k: struct { forms: struct { readout_fused: bool } }, + hooks: struct { prompt: bool }, + }; + const enabled = Pass{ .k = .{ .forms = .{ .readout_fused = true } }, .hooks = .{ .prompt = true } }; + const disabled = Pass{ .k = .{ .forms = .{ .readout_fused = false } }, .hooks = .{ .prompt = true } }; + const decode = Pass{ .k = .{ .forms = .{ .readout_fused = true } }, .hooks = .{ .prompt = false } }; + try std.testing.expect(promptFused(enabled, hc_w, tiles.fused_rows)); + try std.testing.expect(promptFused(enabled, hc_w, 3072)); + try std.testing.expect(!promptFused(disabled, hc_w, 3072)); + try std.testing.expect(!promptFused(enabled, hc_w, tiles.fused_rows - 1)); + try std.testing.expect(!promptFused(decode, hc_w, 3072)); +} diff --git a/zig/src/families/flashnext/cuda_batch_kernels.zig b/zig/src/families/flashnext/cuda_batch_kernels.zig index 26f34d3d8ea..2d8ff01d617 100644 --- a/zig/src/families/flashnext/cuda_batch_kernels.zig +++ b/zig/src/families/flashnext/cuda_batch_kernels.zig @@ -42,7 +42,7 @@ pub const Forms = struct { in_pass: bool = true, // TF_FLASHNEXT_KEEP_INPASS readout_rows: usize = 64, // TF_FLASHNEXT_READOUT_ROWS (maxInt: never) fact_rows: usize = 64, // TF_FLASHNEXT_FACT_ROWS (maxInt: never) - readout_fused: bool = false, // TF_FLASHNEXT_READOUT_FUSED + readout_fused: bool = true, // TF_FLASHNEXT_READOUT_FUSED pub fn resolve() Forms { return .{ diff --git a/zig/src/families/flashnext/cuda_disk.zig b/zig/src/families/flashnext/cuda_disk.zig index 3ba452793da..89982c58841 100644 --- a/zig/src/families/flashnext/cuda_disk.zig +++ b/zig/src/families/flashnext/cuda_disk.zig @@ -122,7 +122,7 @@ pub fn policyOf(c: anytype) [13]u64 { e.busy_chunk, // TF_FLASHNEXT_GDN_FUSED, and TF_FLASHNEXT_GDN_CHAIN_TPR in bit 1 (unset leaves the key as it was) @intFromBool(f.gdn_fused) | @as(u64, @intFromBool(f.gdn_chain_tpr)) << 1, - // TF_FLASHNEXT_HC_FUSE, and TF_FLASHNEXT_READOUT_FUSED in bit 1 (unset leaves the key as it was) + // TF_FLASHNEXT_HC_FUSE, and TF_FLASHNEXT_READOUT_FUSED in bit 1 @intFromBool(f.hc_fuse) | @as(u64, @intFromBool(f.readout_fused)) << 1, @intFromBool(f.in_pass), f.readout_rows, diff --git a/zig/src/families/flashnext/cuda_prompt_wt.zig b/zig/src/families/flashnext/cuda_prompt_wt.zig index d94dec71780..4c38a240b6d 100644 --- a/zig/src/families/flashnext/cuda_prompt_wt.zig +++ b/zig/src/families/flashnext/cuda_prompt_wt.zig @@ -524,7 +524,7 @@ pub fn loadHc(gpa: std.mem.Allocator, driver: *cuda.Driver, store: *Store, prefi defer if (inject) gpa.free(inj_w); defer if (inject) gpa.free(inj_s); defer if (inject) gpa.free(inj_b); - try @import("readout_fused.zig").refuse("CUDA with an MLX affine read-out", @import("readout_fused.zig").on()); + try @import("readout_fused.zig").refuse("CUDA with an MLX affine read-out", @import("readout_fused.zig").requested()); const k8 = wide / 8; if (words.len != n * k8 * 4) return error.UnexpectedTensor; var down_q = try uploadTiled(gpa, driver, words, scales, biases, n, k8); diff --git a/zig/src/families/flashnext/engine_load.zig b/zig/src/families/flashnext/engine_load.zig index 739b305db47..d0f7f3d5e5a 100644 --- a/zig/src/families/flashnext/engine_load.zig +++ b/zig/src/families/flashnext/engine_load.zig @@ -48,7 +48,7 @@ pub fn loadConfigured(gpa: Allocator, io: std.Io, model_dir: []const u8, dump_di try window.validate(speed_up != null or platform.c.getenv("TF_FLASHNEXT_TP") != null); try load_admission.check(gpa, io, model_dir); var selected = window; - try @import("readout_fused.zig").refuse("Metal", @import("readout_fused.zig").on()); + try @import("readout_fused.zig").refuse("Metal", @import("readout_fused.zig").requested()); try @import("fused_split.zig").refuse("Metal", try @import("fused_split.zig").on()); const memory = @import("flashnext_memory"); const weights = try memory.weightBytes(@import("core").checkpoint_host, gpa, io, model_dir); diff --git a/zig/src/families/flashnext/hip/load.zig b/zig/src/families/flashnext/hip/load.zig index 016b0cac3ca..c25d3bf4547 100644 --- a/zig/src/families/flashnext/hip/load.zig +++ b/zig/src/families/flashnext/hip/load.zig @@ -393,7 +393,7 @@ test "the MTP head's HIP names follow the index's root, so oMLX's top-level mtp. /// One rank's weights (`rank` null: the whole model) from `ck`; rank 0 also holds the MTP head under `mtp_root`. pub fn load(gpa: Allocator, d: *const hip.Runtime, ck: *core.checkpoint.Checkpoint, c: *const config.Config, rank: ?Rank, act: model.Kind, mtp_root: []const u8) !Weights { - try @import("../readout_fused.zig").refuse("HIP", @import("../readout_fused.zig").on()); + try @import("../readout_fused.zig").refuse("HIP", @import("../readout_fused.zig").requested()); try @import("../fused_split.zig").refuse("HIP", try @import("../fused_split.zig").on()); var w: Weights = .{ .gpa = gpa }; errdefer w.deinit(); diff --git a/zig/src/families/flashnext/readout_fused.zig b/zig/src/families/flashnext/readout_fused.zig index 718b30eed96..61ee83af82a 100644 --- a/zig/src/families/flashnext/readout_fused.zig +++ b/zig/src/families/flashnext/readout_fused.zig @@ -3,25 +3,49 @@ const std = @import("std"); const name = "TF_FLASHNEXT_READOUT_FUSED"; -/// The setting as the startup check accepted it: unset, blank or 0 is off. +/// The setting as the startup check accepted it: unset or blank is on, 0 off. pub fn on() bool { // the startup check refused every malformed value already, so a plain default stands here - return @import("sys").environment.read(bool, name, false) catch false; + return @import("sys").environment.read(bool, name, true) catch true; } -/// A backend or read-out without the fused tiles stops the start with the setting on rather than taking the chain. -pub fn refuse(what: []const u8, fused: bool) !void { - if (!fused) return; +/// Whether the setting's text asks for the fused tiles: an explicit 1, never unset, blank or 0. +pub fn requested() bool { + const raw = @import("sys").environment.rawText(name) orelse return false; + return std.mem.trim(u8, raw, " \t\r\n").len != 0 and on(); +} + +/// A backend or read-out without the fused tiles stops the start when the setting asks for them. +pub fn refuse(what: []const u8, asked: bool) !void { + if (!asked) return; if (!@import("builtin").is_test) std.log.err("{s}=1: Flash Next on {s} has no fused read-out tiles; unset it or set 0", .{ name, what }); return error.InvalidEnvironment; } -test "fused read-out: on stops Metal, HIP and an affine CUDA read-out, and off starts them" { - try std.testing.expectError(error.InvalidEnvironment, refuse("Metal", true)); - try refuse("HIP", false); - const metal = "try @import(\"readout_fused.zig\").refuse(\"Metal\", @import(\"readout_fused.zig\").on());"; - const hip = "try @import(\"../readout_fused.zig\").refuse(\"HIP\", @import(\"../readout_fused.zig\").on());"; - const affine = "try @import(\"readout_fused.zig\").refuse(\"CUDA with an MLX affine read-out\", @import(\"readout_fused.zig\").on());"; +test "fused read-out: an explicit 1 stops Metal, HIP and an affine CUDA read-out, and unset or 0 starts them" { + const env = @import("sys").env; + _ = env.unsetenv(name); + defer _ = env.unsetenv(name); + try std.testing.expect(on()); + try std.testing.expect(!requested()); + try refuse("Metal", requested()); + _ = env.setenv(name, "", 1); + try std.testing.expect(!requested()); + try refuse("HIP", requested()); + _ = env.setenv(name, " \t\r\n", 1); + try std.testing.expect(!requested()); + _ = env.setenv(name, "0", 1); + try std.testing.expect(!on()); + try refuse("Metal", requested()); + _ = env.setenv(name, "1", 1); + try std.testing.expect(on()); + try std.testing.expect(requested()); + try std.testing.expectError(error.InvalidEnvironment, refuse("CUDA with an MLX affine read-out", requested())); + _ = env.setenv(name, "2", 1); + try std.testing.expect(on()); + const metal = "try @import(\"readout_fused.zig\").refuse(\"Metal\", @import(\"readout_fused.zig\").requested());"; + const hip = "try @import(\"../readout_fused.zig\").refuse(\"HIP\", @import(\"../readout_fused.zig\").requested());"; + const affine = "try @import(\"readout_fused.zig\").refuse(\"CUDA with an MLX affine read-out\", @import(\"readout_fused.zig\").requested());"; try std.testing.expect(std.mem.indexOf(u8, @embedFile("engine_load.zig"), metal) != null); try std.testing.expect(std.mem.indexOf(u8, @embedFile("hip/load.zig"), hip) != null); try std.testing.expect(std.mem.indexOf(u8, @embedFile("cuda_prompt_wt.zig"), affine) != null); diff --git a/zig/src/native/cuda_disk_policy_test.zig b/zig/src/native/cuda_disk_policy_test.zig index d490a1a676a..d259aa7d141 100644 --- a/zig/src/native/cuda_disk_policy_test.zig +++ b/zig/src/native/cuda_disk_policy_test.zig @@ -179,9 +179,9 @@ test "disk identity: Flash Next CUDA resolved prompt rows, kernel forms and expe try changed.append(t.allocator, try flashKey(&x, &c)); @field(k.forms, field) = 64; } - k.forms.readout_fused = true; // TF_FLASHNEXT_READOUT_FUSED=1: a prompt pass's BF16 read-out on the fused tiles + k.forms.readout_fused = false; // TF_FLASHNEXT_READOUT_FUSED=0: the five launches, as main ran them try changed.append(t.allocator, try flashKey(&x, &c)); - k.forms.readout_fused = false; + k.forms.readout_fused = true; k.expert_tile = .{ .mod = undefined, .fns = undefined, .resident = .{ 64, 64 }, .selection = .up }; const up = try flashKey(&x, &c); k.expert_tile.?.selection = .both; // the same grids: the selection alone moves the key @@ -228,9 +228,10 @@ test "disk identity: Flash Next CUDA prompt forms take each setting's value at l _ = env.unsetenv(n); }; try t.expectEqualDeep(Forms{}, Forms.resolve()); + try t.expect(Forms.resolve().readout_fused); // TF_FLASHNEXT_READOUT_FUSED is on unless set to 0 for (names) |n| _ = env.setenv(n, "0", 1); const never = std.math.maxInt(usize); - try t.expectEqualDeep(Forms{ .gdn_fused = false, .hc_fuse = false, .in_pass = false, .readout_rows = never, .fact_rows = never }, Forms.resolve()); + try t.expectEqualDeep(Forms{ .gdn_fused = false, .hc_fuse = false, .in_pass = false, .readout_rows = never, .fact_rows = never, .readout_fused = false }, Forms.resolve()); _ = env.setenv("TF_FLASHNEXT_READOUT_ROWS", "128", 1); _ = env.setenv("TF_FLASHNEXT_FACT_ROWS", "32", 1); try t.expectEqual(@as(usize, 128), Forms.resolve().readout_rows); @@ -241,6 +242,22 @@ test "disk identity: Flash Next CUDA prompt forms take each setting's value at l try t.expect(Forms.resolve().gdn_chain_tpr); } +test "disk identity: the fused read-out is on unless TF_FLASHNEXT_READOUT_FUSED is 0" { + const env = @import("sys").env; + const Engine = @typeInfo(@FieldType(flash.Cuda, "engine")).pointer.child; + const Forms = @FieldType(@FieldType(Engine, "batch_k"), "forms"); + _ = env.unsetenv("TF_FLASHNEXT_READOUT_FUSED"); + defer _ = env.unsetenv("TF_FLASHNEXT_READOUT_FUSED"); + const unset = Forms.resolve().readout_fused; + _ = env.setenv("TF_FLASHNEXT_READOUT_FUSED", "0", 1); + const zero = Forms.resolve().readout_fused; + _ = env.setenv("TF_FLASHNEXT_READOUT_FUSED", "1", 1); + try t.expect(unset); + try t.expect(!zero); + try t.expect(unset != zero); + try t.expect(Forms.resolve().readout_fused); +} + const nemotron = @import("nemotron"); fn nemotronKey(x: *Fixture, e: anytype) !u64 { diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 66963f8826f..711af5d540f 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -290,7 +290,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_SHARED_DRAFTS", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_SHARED_SIDE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_HC_FUSE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, - .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, .{ .name = "TF_FLASHNEXT_KEEP_LATE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (unset or blank leaves it unset)" }, .{ .name = "TF_FLASHNEXT_DECODE_GRAPH", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_FLASHNEXT_SPLIT_DENSE", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (default 1)" }, diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index 8f0e235a87f..ae9a214ac3d 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -62,11 +62,12 @@ test "Flash Next strict env: every switch keeps exactly 0 and 1 and refuses the }; } -test "Flash Next strict env: the dense split and head shard switches keep their own defaults, blank as unset" { +test "Flash Next strict env: the dense split, head shard and fused read-out switches keep their own defaults, blank as unset" { const Switch = struct { name: [:0]const u8, default: bool }; for ([_]Switch{ .{ .name = "TF_FLASHNEXT_SPLIT_DENSE", .default = true }, .{ .name = "TF_FLASHNEXT_SHARD_HEAD", .default = false }, + .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .default = true }, }) |s| { // unset, empty and whitespace-only all read as unset, so each keeps the default its reader passes for ([_]?[]const u8{ null, "", " ", "\t", " \t\r\n" }) |raw| { @@ -77,6 +78,7 @@ test "Flash Next strict env: the dense split and head shard switches keep their try t.expect(try e.value(bool, s.name, "1", false)); for ([_][]const u8{ "2", "00", "1 ", "-1", "1.0", "yes", "on", "true", "x" }) |raw| try check(s.name, raw, false); } + try t.expectEqualStrings("0 or 1 (default 1)", e.rule("TF_FLASHNEXT_READOUT_FUSED").forms); } test "Flash Next strict env: every count keeps its whole numbers and refuses junk, negatives, overflow" { diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index cc29d84eeb5..8a9ade3392a 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -157,7 +157,7 @@ zig/src/families/flashnext/cuda_prompt.zig 829c7614d2a8aa4858da5e5d44be67528cc6f zig/src/families/flashnext/cuda_prompt_load.zig 334d68cfca85c15c9d986d0c6b4f8f2a38569309b21bdac6d365935d73c115cd raw zig/src/families/flashnext/cuda_prompt_main.zig 2543cd166dc80cd97b1ca1ce930a6150f9d36b52ee231744606f83bf54f0669d raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) zig/src/families/flashnext/cuda_prompt_step.zig e04030fb4a4fdb8780704a1bc0b5ba4b786159ab08a927fe32a636a893129d0c raw -zig/src/families/flashnext/cuda_prompt_wt.zig 712eecd6796349dbd0cb0aa1c17465082a27c383c7b849410b252fd74907f709 raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged#3413 (an MLX affine read-out refuses TF_FLASHNEXT_READOUT_FUSED=1 by name; unchanged when unset) +zig/src/families/flashnext/cuda_prompt_wt.zig 74269b31058861405a72e56a1c7a9eff58d2bd9567b7554262a059a6c4068214 raw #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged#3413 (an MLX affine read-out refuses TF_FLASHNEXT_READOUT_FUSED=1 by name; unchanged when unset); the fused read-out is on by default, and only an explicit 1 is refused zig/src/families/flashnext/cuda_qmm.zig 6d035feb053691cc9750a369c86a5463d41ed942764ad85b861bb628c106dccf raw zig/src/families/flashnext/cuda_rank_engine.zig 575ebbf4656d8a064a9e1945527a3a12a54a2879f56d2dbfe0f2e51d3014d102 raw zig/src/families/flashnext/cuda_rank_media.zig e5c268c8cf257934bb49fe401ba6213ea8b108258bbfd4d06edb990d568c3c2b raw From 9edf2f89d45b3620c9b65195e802530250a6f09e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:58:32 +0000 Subject: [PATCH 164/361] changelog: #4799 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c88adeca12..59f2d737f0b 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 +- Flash Next on CUDA: the fused read-out is now the default, making prompt processing about 3-5% faster on GB10 with identical tokens; `TF_FLASHNEXT_READOUT_FUSED=0` keeps the old path (#4799). Thanks @BadAd84. + - Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. - Inkling 2 Mini: `enable_thinking: false` and `reasoning_effort: "none"` now reach the chat template as thinking effort 0 instead of the default 0.9; thinking-on replies are unchanged (#4876). From 0495b3460d4466a5bd65eb0c9e646a86a6ab63df Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:40:55 +0800 Subject: [PATCH 165/361] h3: MiniMax-H3-Image's prompt path and image decoder on CUDA, with their selftests and timings The net change of #3733 at 5855d56a34 over its merge base 6d0a128b0c, as one commit: the branch's merge commits hold changes of their own. --- build.zig | 7 + .../h3-image-cuda-gb10-0bfee52e/README.md | 38 ++ .../decoder-selftest.txt | 45 ++ .../prompt-selftest.txt | 16 + docs/recipes/minimax-h3-cuda.md | 43 ++ zig/build/cuda.zig | 7 +- zig/build/dsv41_cuda.zig | 1 + zig/build/h3_host.zig | 14 +- zig/build/h3_image_decoder.zig | 22 + zig/build/h3_image_decoder_cuda.zig | 18 + zig/build/h3_image_encoder.zig | 5 +- zig/build/h3_image_metal.zig | 28 + zig/build/h3_image_prompt_cuda.zig | 46 ++ zig/build/h3_image_prompt_host.zig | 66 +++ zig/build/kernel_contract.zig | 5 +- zig/build/qwen_contract.zig | 5 +- zig/kernels/cuda/h3_image_decoder.cu | 299 ++++++++++ zig/kernels/cuda/h3_image_prompt.cu | 180 ++++++ zig/src/core/checkpoint_fixture.zig | 13 + .../core/contract/h3_image_cuda_records.zig | 40 ++ zig/src/core/contract/registry_joins.zig | 2 + zig/src/core/h3_core.zig | 4 + zig/src/families/h3/checkpoint.zig | 288 ++++++++- zig/src/families/h3/clock.zig | 7 + zig/src/families/h3/image_decoder.zig | 53 ++ zig/src/families/h3/image_decoder_cuda.zig | 353 +++++++++++ .../h3/image_decoder_cuda_selftest.zig | 284 +++++++++ zig/src/families/h3/image_decoder_host.zig | 167 ++++++ .../families/h3/image_decoder_host_test.zig | 85 +++ zig/src/families/h3/image_decoder_metal.zig | 38 +- .../families/h3/image_decoder_reference.zig | 40 +- zig/src/families/h3/prompt.zig | 1 + zig/src/families/h3/prompt_case.zig | 41 ++ zig/src/families/h3/prompt_case_test.zig | 68 +++ zig/src/families/h3/prompt_cuda.zig | 548 ++++++++++++++++++ .../families/h3/prompt_cuda_products_test.zig | 261 +++++++++ zig/src/families/h3/prompt_reference.zig | 81 ++- zig/src/families/h3/qwen_copy.zig | 48 ++ zig/src/families/h3/read_ahead.zig | 54 +- zig/src/families/h3/tensors.zig | 13 +- zig/tests/cuda/contract_h3_image_decoder.zig | 415 +++++++++++++ zig/tests/cuda/contract_h3_image_prompt.zig | 470 +++++++++++++++ zig/tests/cuda/contract_h3_image_ref.zig | 366 ++++++++++++ zig/tests/cuda/contract_h3_register.zig | 66 +++ zig/tests/cuda/contract_limits.zig | 10 + zig/tests/cuda/contract_tests.zig | 22 +- zig/tests/h3_image_decoder_cuda.zig | 155 +++++ zig/tests/h3_image_decoder_host.zig | 54 ++ zig/tests/h3_image_encoder.zig | 2 +- zig/tests/h3_image_files.zig | 71 +++ zig/tests/h3_image_match.zig | 48 ++ zig/tests/h3_image_prompt_cuda.zig | 532 +++++++++++++++++ zig/tests/h3_image_prompt_host.zig | 207 +++++++ 53 files changed, 5603 insertions(+), 149 deletions(-) create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/README.md create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/prompt-selftest.txt create mode 100644 zig/build/h3_image_decoder_cuda.zig create mode 100644 zig/build/h3_image_metal.zig create mode 100644 zig/build/h3_image_prompt_cuda.zig create mode 100644 zig/build/h3_image_prompt_host.zig create mode 100644 zig/kernels/cuda/h3_image_decoder.cu create mode 100644 zig/kernels/cuda/h3_image_prompt.cu create mode 100644 zig/src/core/contract/h3_image_cuda_records.zig create mode 100644 zig/src/core/h3_core.zig create mode 100644 zig/src/families/h3/clock.zig create mode 100644 zig/src/families/h3/image_decoder_cuda.zig create mode 100644 zig/src/families/h3/image_decoder_cuda_selftest.zig create mode 100644 zig/src/families/h3/image_decoder_host.zig create mode 100644 zig/src/families/h3/image_decoder_host_test.zig create mode 100644 zig/src/families/h3/prompt_case.zig create mode 100644 zig/src/families/h3/prompt_case_test.zig create mode 100644 zig/src/families/h3/prompt_cuda.zig create mode 100644 zig/src/families/h3/prompt_cuda_products_test.zig create mode 100644 zig/src/families/h3/qwen_copy.zig create mode 100644 zig/tests/cuda/contract_h3_image_decoder.zig create mode 100644 zig/tests/cuda/contract_h3_image_prompt.zig create mode 100644 zig/tests/cuda/contract_h3_image_ref.zig create mode 100644 zig/tests/cuda/contract_h3_register.zig create mode 100644 zig/tests/h3_image_decoder_cuda.zig create mode 100644 zig/tests/h3_image_decoder_host.zig create mode 100644 zig/tests/h3_image_files.zig create mode 100644 zig/tests/h3_image_match.zig create mode 100644 zig/tests/h3_image_prompt_cuda.zig create mode 100644 zig/tests/h3_image_prompt_host.zig diff --git a/build.zig b/build.zig index 841e2c3fc54..4d111ca78f7 100644 --- a/build.zig +++ b/build.zig @@ -123,6 +123,8 @@ pub fn build(b: *std.Build) void { @import("zig/build/h3_image_prompt.zig").tests(b, target, test_step); @import("zig/build/h3_image_decoder.zig").compileHost(b, target); @import("zig/build/h3_image_contract.zig").steps(b, target, optimize); + @import("zig/build/h3_image_decoder.zig").hostSteps(b, target, optimize, test_step); + @import("zig/build/h3_image_prompt_host.zig").steps(b, target, optimize, test_step); @import("zig/build/ling_host.zig").tests(b, target, test_step); @import("zig/build/inkling2_host.zig").tests(b, target, test_step); @import("zig/build/gpt_oss_host.zig").tests(b, test_step); @@ -186,6 +188,11 @@ pub fn build(b: *std.Build) void { test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = dashboard })).step); // the backend options are declared for every target, so one build script may pass the same flags on every OS const cuda_options = @import("zig/build/options.zig").cuda(b); + // their selftests read checkpoints through mmap, which Windows lacks + if (target.result.os.tag != .windows) { + @import("zig/build/h3_image_decoder_cuda.zig").steps(b, target, optimize, cuda_options, test_step); + @import("zig/build/h3_image_prompt_cuda.zig").steps(b, target, optimize, cuda_options, test_step); + } const tp_options = @import("zig/build/options.zig").tp(b); switch (target.result.os.tag) { .macos => metalTargets(b, target, optimize, draft_ids, build_options, test_step), diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/README.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/README.md new file mode 100644 index 00000000000..a2de1d611fa --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/README.md @@ -0,0 +1,38 @@ +# MiniMax-H3-Image's CUDA selftests on a GB10 + +`tf-h3-image-decoder-cuda selftest` and `tf-h3-image-prompt-cuda selftest`, built at `0bfee52e` with +`-Dsm=121 -Doptimize=ReleaseFast`, on an NVIDIA GB10 (sm_121, driver 580.173.02). The run's checkout was +`0b573dd2` (that commit plus the job script), so the tool code is the same. + +- `decoder-selftest.txt`: every check passes. Every block of the 24 is gated at 90% identical to the float64 + reference on the GPU's own input; the lowest is block 9 at 92.037%, worst 2.00 ULP, relative 8.87e-4. + The pictures pass the Metal decoder's bytes bound (80% identical, at most 2 apart): 88.889% and + 92.164% identical, at most 1 apart. 25 tiles of 16 x 16 take 43.6 ms a tile. +- `prompt-selftest.txt`: every gate passes; the worst row is 4.66e-2 of its row's RMS on + `condition_proj`, the refiner and the final norm. + +Both tools build synthetic models and compare against the host's float64 reference; no weights are read. + +The same run's kernel contract passes gates 1 to 4 but exits nonzero on its limits: + +```text +SUMMARY 685 kernels: 685 pass gates 1-4, 0 fail, 8 known findings; 422 controls: 422 red as planted, 0 missed; 188 limit problems; gates 3449547 ms, limits 765095 ms +FAIL kernel-contract: 0 gate failures, 0 controls missed, 188 limit problems +FAIL kernel-contract: TestFailed +``` + +Of the 188, 183 are `main` kernels with no compiled usage recorded (`qwen4_*`, `qwen35*`, `nvfp4_experts_tile`, +`exl3_experts`, `flashnext_mtp`) and 3 are live launches of `main` kernels recorded as 0 (`fn_row_topk`, +`tf_exl3_prompt_gu`, `tf_exl3_prompt_down`). The other 2 are `h3p_norm` and `h3p_heads` on sm_121, measured +at 27 and 40 registers against stale records of 25 and 38. `kernel-contract-limits` exits 1 with 28 stale +records, 10 of them these two kernels'. This branch sets both records to that run's `RECORD` lines. A limits-only run +at `5ef2a963` (that commit plus the job script) checks both current on all five SMs — `h3p_norm` at 31, 35, 35, 27 and +27 registers, `h3p_heads` at 32, 36, 36, 40 and 40 — and exits 1 only on the 18 stale records inherited from `main` +(`fn_row_topk`, `tf_exl3_prompt_gu`, `tf_exl3_prompt_down`, and `tf_q35_gdn_slots_1`, `_2` and `_4` on sm_80), with no +`h3p_*` or `h3d_*` entry: + +```text +INFO limits fatbins: images built by nvcc 13.0, checked against nvcc 13.0's records +FAIL kernel-contract-limits: 18 problems +FAIL kernel-contract-limits: TestFailed +``` diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt new file mode 100644 index 00000000000..fd51a2f9104 --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt @@ -0,0 +1,45 @@ +CUDA decoder: 24 synthetic blocks made in 1.7 s +6 x 10 cells: 1 tiles of 6 x 10 cells, 65 tokens each + embedding: 66560 values, 99.997% identical, worst 1.00 ULP, relative 1.91e-5 (pass) + block 0: 66560 values, 96.946% identical, worst 2.00 ULP, relative 5.73e-4 (pass) + block 1: 66560 values, 98.063% identical, worst 2.00 ULP, relative 4.47e-4 (pass) + norm_out and proj_out: 46080 values, 99.987% identical, worst 1.00 ULP, relative 8.06e-5 (pass) + output after 2 blocks: 46080 values, 47.750% identical, worst 3.00 ULP, relative 3.28e-3 (pass) + decode in passes of 1: bit-identical to the staged tiles assembled + picture bytes: 88.889% identical, at most 1 apart (pass) + output after 24 blocks: 46080 values, 11.966% identical, worst 16.00 ULP, relative 1.48e-2 (pass) + block 0: 66560 values, 96.946% identical, worst 2.00 ULP, relative 5.73e-4 (pass) + block 1: 66560 values, 98.063% identical, worst 2.00 ULP, relative 4.47e-4 (pass) + block 2: 66560 values, 94.363% identical, worst 2.00 ULP, relative 7.42e-4 (pass) + block 3: 66560 values, 96.121% identical, worst 3.00 ULP, relative 6.09e-4 (pass) + block 4: 66560 values, 98.442% identical, worst 1.00 ULP, relative 4.14e-4 (pass) + block 5: 66560 values, 95.891% identical, worst 2.00 ULP, relative 6.35e-4 (pass) + block 6: 66560 values, 98.505% identical, worst 1.00 ULP, relative 3.83e-4 (pass) + block 7: 66560 values, 95.907% identical, worst 2.00 ULP, relative 6.38e-4 (pass) + block 8: 66560 values, 93.726% identical, worst 2.00 ULP, relative 8.24e-4 (pass) + block 9: 66560 values, 92.037% identical, worst 2.00 ULP, relative 8.87e-4 (pass) + block 10: 66560 values, 94.423% identical, worst 2.00 ULP, relative 7.63e-4 (pass) + block 11: 66560 values, 96.878% identical, worst 2.00 ULP, relative 5.55e-4 (pass) + block 12: 66560 values, 96.525% identical, worst 2.00 ULP, relative 5.70e-4 (pass) + block 13: 66560 values, 94.471% identical, worst 2.00 ULP, relative 7.52e-4 (pass) + block 14: 66560 values, 97.876% identical, worst 2.00 ULP, relative 4.55e-4 (pass) + block 15: 66560 values, 97.973% identical, worst 1.00 ULP, relative 4.36e-4 (pass) + block 16: 66560 values, 96.242% identical, worst 1.00 ULP, relative 5.99e-4 (pass) + block 17: 66560 values, 97.491% identical, worst 2.00 ULP, relative 5.01e-4 (pass) + block 18: 66560 values, 97.686% identical, worst 2.00 ULP, relative 5.06e-4 (pass) + block 19: 66560 values, 96.774% identical, worst 1.00 ULP, relative 5.20e-4 (pass) + block 20: 66560 values, 95.536% identical, worst 2.00 ULP, relative 6.17e-4 (pass) + block 21: 66560 values, 97.975% identical, worst 2.00 ULP, relative 4.22e-4 (pass) + block 22: 66560 values, 96.083% identical, worst 1.00 ULP, relative 6.09e-4 (pass) + block 23: 66560 values, 97.218% identical, worst 1.00 ULP, relative 5.02e-4 (pass) +20 x 28 cells: 4 tiles of 16 x 16 cells, 261 tokens each + embedding: 1069056 values, 99.999% identical, worst 0.00 ULP, relative 4.04e-8 (pass) + block 0: 1069056 values, 96.012% identical, worst 2.50 ULP, relative 6.22e-4 (pass) + block 1: 1069056 values, 95.394% identical, worst 2.00 ULP, relative 6.76e-4 (pass) + norm_out and proj_out: 786432 values, 99.865% identical, worst 1.00 ULP, relative 9.49e-5 (pass) + output after 2 blocks: 786432 values, 54.937% identical, worst 3.00 ULP, relative 2.77e-3 (pass) + decode in passes of 3: bit-identical to the staged tiles assembled + decode in passes of 4: bit-identical to the staged tiles assembled + picture bytes: 92.164% identical, at most 1 apart (pass) +timing: 25 tiles of 16 x 16, 24 blocks: 1.09 s in passes, 1.09 s on the GPU, 43.6 ms a tile +selftest: pass diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/prompt-selftest.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/prompt-selftest.txt new file mode 100644 index 00000000000..67ea0e64dcc --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/prompt-selftest.txt @@ -0,0 +1,16 @@ +synthetic text model 256 wide (2 layers run of 3), refiner 384 wide, 70 rows +text encoder rows, a text prompt: cosine 0.9999962, relative error 2.76e-3, 0.6706 bit-equal, worst value 1.94e-2 of its row's RMS (pass) + the float32-sum host run: cosine 0.9999962, relative error 2.76e-3, 0.6722 bit-equal +condition_proj, refiner and final norm on the GPU's encoder rows: cosine 0.9999892, relative error 4.64e-3, 0.4663 bit-equal, worst value 4.66e-2 of its row's RMS (pass) + the float32-sum host run: cosine 0.9999934, relative error 3.63e-3, 0.5841 bit-equal +encoded in 0.007 s; again, byte for byte the same: true +a no-op vision (embedding rows spliced back, DeepStack zero) byte for byte the text-only run: true +text encoder rows, a reference's vision and DeepStack rows at equal-axis positions: cosine 0.9999980, relative error 2.02e-3, 0.7948 bit-equal, worst value 1.52e-2 of its row's RMS (pass) + the float32-sum host run: cosine 0.9999980, relative error 2.02e-3, 0.7948 bit-equal +text encoder rows after layer 0 only, vision and DeepStack: cosine 1.0000000, relative error 0.00e0, 1.0000 bit-equal, worst value 0.00e0 of its row's RMS (pass) + the float32-sum host run: cosine 1.0000000, relative error 0.00e0, 1.0000 bit-equal +text encoder rows, vision spliced and DeepStack zero: cosine 0.9999980, relative error 1.99e-3, 0.7944 bit-equal, worst value 1.52e-2 of its row's RMS (pass) + the float32-sum host run: cosine 0.9999980, relative error 1.99e-3, 0.7944 bit-equal +text encoder rows, DeepStack on embedding-row pads: cosine 0.9999979, relative error 2.05e-3, 0.7948 bit-equal, worst value 2.30e-2 of its row's RMS (pass) + the float32-sum host run: cosine 0.9999979, relative error 2.05e-3, 0.7948 bit-equal +PASS every gate diff --git a/docs/recipes/minimax-h3-cuda.md b/docs/recipes/minimax-h3-cuda.md index ecb812ac327..0996d5dc765 100644 --- a/docs/recipes/minimax-h3-cuda.md +++ b/docs/recipes/minimax-h3-cuda.md @@ -43,3 +43,46 @@ zig build compile-cuda-tests -Dtarget=x86_64-linux-gnu ``` This step has no NVCC or Metal compiler dependency and does not execute the resulting binary. + +## MiniMax-H3-Image's prompt path and image decoder on these blocks + +The image pipeline's two CPU-bound stages run on the same CUDA blocks as the clip transformer, each writing the +file its Metal sibling writes, so a stage swaps on a Spark with no Metal and no PyTorch: + +```sh +zig build tf-h3-image-prompt-cuda tf-h3-image-decoder-cuda -Dnvcc=/usr/local/cuda/bin/nvcc -Dsm=121 -Doptimize=ReleaseFast +zig-out/bin/tf-h3-image-prompt-cuda TEXT_ENCODER_DIR MODEL_DIR prompt.txt out/case.safetensors 2048x2048 42 +zig-out/bin/tf-h3-image-decoder-cuda MODEL_DIR out/case.latent.f32 128 128 out/case.png 2048x2048 +zig-out/bin/tf-h3-image-decoder-cuda reference MODEL_DIR out/case.latent.f32 128 128 out/case-gpu.png out/case-host.png 2048x2048 +``` + +`tf-h3-image-prompt-cuda` runs Qwen3-VL to layer 50 and the token refiner with one layer's weights uploaded at a +time. `tf-h3-image-decoder-cuda` runs the VAE in bf16 over batched tiles. The CPU tools +(`tf-h3-image-prompt-host`, `tf-h3-image-decoder-host`) are independent reference implementations of the same case +writer and decoder chain. Both GPU tools have a synthetic selftest against the host's float64 reference: `selftest` +on the prompt tool, the default run on the decoder tool. `reference` decodes one latent on the GPU and on the host +reference decoder and fails past the 3e-2 full-chain relative bound. + +The decoder's selftest gates each of the 24 blocks, on the GPU's own input, at 90% of values identical to the float64 +reference (worst 8 ULPs, relative 2e-3), and the picture after two blocks at 80% of bytes identical and at most 2 +apart, the Metal decoder's bounds (its recipe reports the measured at most 1 apart, not its bound). Its RMS norm sums +the row's squares in f64, so the norm's mean rounds as the reference's does, at no measurable cost (43.4 ms a tile +against 43.2 ms). The prompt's norm and head kernels sum their squares in f64 too, so their inverse roots are the host +reference's bits, and the head kernel rounds each normed value before the turn, as the host does. The prompt's selftest +gates its text, refiner and vision rows against the same float32-noise bounds. +On the GB10 both pass every check: the decoder's 37 checks pass and its lowest block (9) reads 92.037% identical. +[The run's lines](../receipts/h3-image-cuda-gb10-0bfee52e/README.md) are each block's. Other served SMs compile but +were not run. + +Same prompt, seed 42, six distilled steps, BF16 throughout, one GB10: + +| Stage | CPU reference | CUDA | Gate | +|---|---:|---:|---| +| Prompt, 2048² | 88 s | 18.0 s cold, 20.1 s warm mean | selftest passes | +| Prompt, 4096² | 98 s | 18.3 s cold, 18.5 s warm mean | selftest passes | +| Decoder, 2048² | 218 s | 5.6 s (5.25 s on the GPU) | selftest passes | +| Decoder, 4096² | 771 s | 20.4 s (20.3 s warm mean) | selftest passes | + +The 2048² latent decoded on both paths is 56.65 dB PSNR from the host reference (86.180% of bytes identical, 99.923% +within 1, at most 5 apart, relative error 3.15e-3 against the 3e-2 bound). CPU times are the host reference tools on +the same case; the GPU times are warm means over three repeats after one cold run. diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 9956b346939..844e11d6f37 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -88,6 +88,11 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu break :blk run.captureStdOut(.{}); }, .{ .name = "h3", .flags = &.{"-O3"} }, sms) else null; @import("h3_host.zig").library(b, target, optimize, h3_image); + // MiniMax-H3-Image's decoder and prompt kernel images, built to the served flags, for the contract + const h3_image_fatbins: [2]?std.Build.LazyPath = if (nvcc) |tool| .{ + fatbin(b, tool, version.?, .{ .name = "h3_image_decoder", .flags = &.{ "-O3", "--fmad=false" }, .min_sm = 80 }, sms), + fatbin(b, tool, version.?, .{ .name = "h3_image_prompt", .flags = &.{"-O3"}, .min_sm = 80 }, sms), + } else .{ null, null }; const cuda = @import("cuda_runtime.zig").runtimeWithTargets(b, target, optimize, if (nvcc != null or prebuilt != null) &images else &.{}, null, if (nvcc != null and prebuilt == null) sms else ""); const mods = family(b, target, optimize, cuda, draft_ids); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip }); @@ -148,7 +153,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu b.step("compile-modelopt-startup", "Compile actual native startup with test-only absent GPU images").dependOn(&startup.step); const controls_file = opts.contract_controls; const controls = if (controls_file) |file| b.graph.cwdRelativePath(file) else if (nvcc) |tool| fatbin(b, tool, version.?, .{ .name = "contract_controls", .src = "contract_controls_set", .flags = &.{"-O3"} }, sms) else null; - const contract_images = @import("qwen_contract.zig").images(b, runner_exe, controls, h3_image, kernels, &images); + const contract_images = @import("qwen_contract.zig").images(b, runner_exe, controls, h3_image, h3_image_fatbins, kernels, &images); contract_images.dependOn(fatbin_step); @import("cuda_contract_deepseek.zig").images(b, runner_exe, contract_images, kernels, &images, prebuilt, nvcc, version, sms, opts.cuobjdump); @import("dsv41_serve.zig").install(b, target, optimize, cuda, nvcc != null or prebuilt != null); diff --git a/zig/build/dsv41_cuda.zig b/zig/build/dsv41_cuda.zig index b3e19f0cc64..3c40736e9d3 100644 --- a/zig/build/dsv41_cuda.zig +++ b/zig/build/dsv41_cuda.zig @@ -84,6 +84,7 @@ pub fn steps(b: *std.Build) void { controls.addOption(bool, "controls", true); consumers.addOptions("contract_options", controls); consumers.addAnonymousImport("fatbin_h3", .{ .root_source_file = b.addWriteFiles().add("compile-h3", "SYNTHETIC-COMPILE-ONLY") }); + for ([_][]const u8{ "h3_image_decoder", "h3_image_prompt" }) |n| consumers.addAnonymousImport(b.fmt("fatbin_{s}", .{n}), .{ .root_source_file = b.addWriteFiles().add(b.fmt("compile-{s}", .{n}), "SYNTHETIC-COMPILE-ONLY") }); consumers.addAnonymousImport("fatbin_contract_controls", .{ .root_source_file = b.addWriteFiles().add("compile-controls", "SYNTHETIC-COMPILE-ONLY") }); @import("cuda_contract_deepseek.zig").inert(b, consumers); const consumer_object = b.addObject(.{ .name = "contract-consumers", .root_module = consumers }); diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index 532f422a9ea..385fef383ce 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -2,7 +2,7 @@ const std = @import("std"); pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { - const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .Debug, .link_libc = true }); + const core = coreModule(b, target); const root = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/geometry_test.zig"), .target = target, .imports = &.{.{ .name = "core", .module = core }} }); const filter = b.option([]const u8, "h3-filter", "Run one H3 host regression"); const cases = b.addTest(.{ .root_module = root, .filters = if (filter) |f| &.{f} else &.{} }); @@ -21,7 +21,7 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = .Debug }) } }; const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports }); const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) }); - const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core } } }) }); + const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "checkpoint_fixture", .module = fixture(b, core) } } }) }); const compile = b.step("compile-h3-host", "Compile the actual H3 tools (tf-h3-dit, tf-h3-image) without compiling or executing shaders"); compile.dependOn(&tool.step); compile.dependOn(&picture_tool.step); @@ -95,9 +95,15 @@ pub fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu step.dependOn(&b.addInstallArtifact(lib, .{}).step); } -/// The core module for the CUDA side's checkpoint (h3/checkpoint.zig). +/// The core files H3 reads, for every H3 module (core/h3_core.zig). pub fn coreModule(b: *std.Build, target: std.Build.ResolvedTarget) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .link_libc = true }); + return b.createModule(.{ .root_source_file = b.path("zig/src/core/h3_core.zig"), .target = target, .link_libc = true }); +} + +/// `checkpoint_fixture` for a tool that also holds `core`, which owns the fixture's file. +pub fn fixture(b: *std.Build, core: *std.Build.Module) *std.Build.Module { + const file = b.addWriteFiles().add("h3_fixture_alias.zig", "pub const Entry = f.Entry;\npub const image = f.image;\npub const aligned = f.aligned;\npub const write = f.write;\nconst f = @import(\"core\").checkpoint_fixture;\n"); + return b.createModule(.{ .root_source_file = file, .imports = &.{.{ .name = "core", .module = core }} }); } /// H3's clip and picture tools share the maintained Metal family and core checkpoint reader. diff --git a/zig/build/h3_image_decoder.zig b/zig/build/h3_image_decoder.zig index 78ddf5094c8..a7fbee3e820 100644 --- a/zig/build/h3_image_decoder.zig +++ b/zig/build/h3_image_decoder.zig @@ -27,3 +27,25 @@ pub fn compileHost(b: *std.Build, target: std.Build.ResolvedTarget) void { const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-host-compile", .root_module = module(b, target, .Debug, metal) }); b.step("compile-h3-image-decoder-host", "Compile tf-h3-image-decoder without compiling or executing shaders").dependOn(&exe.step); } + +/// `zig build tf-h3-image-decoder-host` (any OS, no GPU) and `test-h3-image-decoder-host`. +pub fn hostSteps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, test_step: *std.Build.Step) void { + const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-host", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder_host.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "h3_image_decoder_host", .module = host(b, target, optimize) }} }) }); + b.step("tf-h3-image-decoder-host", "MiniMax-H3-Image's image decoder on the CPU: a latent to a PNG, no GPU").dependOn(&b.addInstallArtifact(exe, .{}).step); + const native = b.graph.host; + const cases = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_host_test.zig"), .target = native, .optimize = .ReleaseFast, .imports = hostImports(b, native, .ReleaseFast) }) }); + const run = b.addRunArtifact(cases); + b.step("test-h3-image-decoder-host", "The CPU image decoder: tiles across cores equal the serial reference chain").dependOn(&run.step); + test_step.dependOn(&run.step); +} + +fn host(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_host.zig"), .target = target, .optimize = optimize, .imports = hostImports(b, target, optimize) }); +} + +/// `core` and the picture writer on it, for the decoder's CPU and CUDA paths. +pub fn hostImports(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) []const std.Build.Module.Import { + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "core", .module = core }} }); + return b.allocator.dupe(std.Build.Module.Import, &.{ .{ .name = "core", .module = core }, .{ .name = "picture_writer", .module = writer } }) catch @panic("OOM"); +} diff --git a/zig/build/h3_image_decoder_cuda.zig b/zig/build/h3_image_decoder_cuda.zig new file mode 100644 index 00000000000..884e83f5d30 --- /dev/null +++ b/zig/build/h3_image_decoder_cuda.zig @@ -0,0 +1,18 @@ +//! MiniMax-H3-Image's image decoder on CUDA: the fatbin via `-Dnvcc` (compile-only without it) and the CLI. +const std = @import("std"); + +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, opts: @import("options.zig").Cuda, test_step: *std.Build.Step) void { + // no FMA contraction: the norms', attention's and SwiGLU's fp32 multiply-adds round as the host reference's do + const image = if (opts.nvcc) |nvcc| @import("cuda_fatbin.zig").fatbin(b, nvcc, b.addSystemCommand(&.{ nvcc, "--version" }).captureStdOut(.{}), .{ .name = "h3_image_decoder", .flags = &.{ "-O3", "--fmad=false" }, .min_sm = 80 }, opts.sms) else b.addWriteFiles().add("h3-image-decoder-compile-only.fatbin", ""); + const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); + const core = @import("h3_host.zig").coreModule(b, target); + const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize }); + const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "picture_writer", .module = writer } } }); + decoder.addAnonymousImport("fatbin_h3_image_decoder", .{ .root_source_file = image }); + const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-cuda", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ + .{ .name = "h3_image_decoder_cuda", .module = decoder }, + } }) }); + b.step("tf-h3-image-decoder-cuda", "MiniMax-H3-Image's image decoder on CUDA: a latent to a PNG, or its self-test").dependOn(&b.addInstallArtifact(exe, .{}).step); + // a build compiles the Zig side only; nvcc and a CUDA device are needed for the fatbin and the run. + test_step.dependOn(&exe.step); +} diff --git a/zig/build/h3_image_encoder.zig b/zig/build/h3_image_encoder.zig index a280f2b9a59..e55dfbd6dbc 100644 --- a/zig/build/h3_image_encoder.zig +++ b/zig/build/h3_image_encoder.zig @@ -2,11 +2,12 @@ const std = @import("std"); fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { - const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const core = @import("h3_host.zig").coreModule(b, target); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_encoder.zig") }); const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); + const codec = b.createModule(.{ .root_source_file = b.path("zig/src/core/picture/picture.zig"), .target = target, .optimize = optimize, .link_libc = true }); const noise = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); - return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "core", .module = core }, .{ .name = "torch_noise", .module = noise } } }); + return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "picture_codec", .module = codec }, .{ .name = "torch_noise", .module = noise } } }); } /// `zig build tf-h3-image-encoder`: a reference picture to its clean rows, or `selftest`; needs no Metal compiler. diff --git a/zig/build/h3_image_metal.zig b/zig/build/h3_image_metal.zig new file mode 100644 index 00000000000..9361607853a --- /dev/null +++ b/zig/build/h3_image_metal.zig @@ -0,0 +1,28 @@ +//! MiniMax-H3-Image's Metal tools: the transformer on a case file, a picture case, the edit encoder, the prompt tool +const std = @import("std"); + +/// The picture tools on `metal`; `sources` is the Metal kernels' source module. +pub fn tools(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, sources: *std.Build.Module) void { + const h3_kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); + const h3_core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const h3_mod = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = h3_core }, .{ .name = "h3_kernels", .module = h3_kernels }, .{ .name = "kernel_sources", .module = sources } } }); + const h3_dit = b.addExecutable(.{ .name = "tf-h3-dit", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/h3_dit.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod } }, + }) }); + b.step("tf-h3-dit", "FastH3's Metal transformer against a case file: velocities, every step, timings").dependOn(&b.addInstallArtifact(h3_dit, .{}).step); + const h3_image = b.addExecutable(.{ .name = "tf-h3-image", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/h3_image.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod }, .{ .name = "core", .module = h3_core } }, + }) }); + b.step("tf-h3-image", "MiniMax-H3-Image's Metal transformer on a picture case: six distilled steps, teacher-forced and gated").dependOn(&b.addInstallArtifact(h3_image, .{}).step); + @import("h3_image_encoder.zig").tool(b, target, optimize, metal); + @import("h3_image_prompt.zig").install(b, target, optimize, metal); + @import("h3_image_decoder.zig").tool(b, target, optimize, metal); +} diff --git a/zig/build/h3_image_prompt_cuda.zig b/zig/build/h3_image_prompt_cuda.zig new file mode 100644 index 00000000000..a469a46b696 --- /dev/null +++ b/zig/build/h3_image_prompt_cuda.zig @@ -0,0 +1,46 @@ +//! MiniMax-H3-Image's prompt path on CUDA: tf-h3-image-prompt-cuda, its kernel image built by `-Dnvcc` or compile-only +const std = @import("std"); + +/// `zig build tf-h3-image-prompt-cuda`: a prompt to the refiner's text rows on CUDA, and its synthetic selftest +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, opts: @import("options.zig").Cuda, test_step: *std.Build.Step) void { + const image = if (opts.nvcc) |nvcc| + @import("cuda_fatbin.zig").fatbin(b, nvcc, b.addSystemCommand(&.{ nvcc, "--version" }).captureStdOut(.{}), .{ .name = "h3_image_prompt", .flags = &.{"-O3"}, .min_sm = 80 }, opts.sms) + else + b.addWriteFiles().add("h3-image-prompt-compile-only.fatbin", ""); + const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); + const core = @import("h3_host.zig").coreModule(b, target); + const fixture = @import("h3_host.zig").fixture(b, core); + const rope = @import("h3_image_prompt.zig").rope(b, target); + const prompt = b.createModule(.{ + .root_source_file = b.path("zig/src/families/h3/prompt_cuda.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "cuda", .module = cuda }, + .{ .name = "core", .module = core }, + .{ .name = "qwen_vl_rope", .module = rope }, + .{ .name = "checkpoint_fixture", .module = fixture }, + }, + }); + prompt.addAnonymousImport("fatbin_h3_image_prompt", .{ .root_source_file = image }); + const tool = b.createModule(.{ + .root_source_file = b.path("zig/tests/h3_image_prompt_cuda.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "h3_prompt_cuda", .module = prompt }, + .{ .name = "tokenizer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }) }, + .{ .name = "checkpoint_fixture", .module = fixture }, + .{ .name = "moss_noise", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }) }, + }, + }); + const exe = b.addExecutable(.{ .name = "tf-h3-image-prompt-cuda", .root_module = tool }); + b.step("tf-h3-image-prompt-cuda", "MiniMax-H3-Image's prompt to its text rows on CUDA: Qwen3-VL to layer 50, the token refiner").dependOn(&b.addInstallArtifact(exe, .{}).step); + test_step.dependOn(&exe.step); + const tests = b.addTest(.{ .root_module = prompt }); + test_step.dependOn(&b.addRunArtifact(tests).step); + const tool_tests = b.addTest(.{ .root_module = tool }); + test_step.dependOn(&b.addRunArtifact(tool_tests).step); +} diff --git a/zig/build/h3_image_prompt_host.zig b/zig/build/h3_image_prompt_host.zig new file mode 100644 index 00000000000..200322ce509 --- /dev/null +++ b/zig/build/h3_image_prompt_host.zig @@ -0,0 +1,66 @@ +//! tf-h3-image-prompt-host: the prompt stage on the CPU, Mac or the Spark alike — no Metal. +const std = @import("std"); +const prompt = @import("h3_image_prompt.zig"); + +/// `zig build tf-h3-image-prompt-host` (any -Dtarget, among them aarch64-linux-gnu for the Spark) and +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, test_step: *std.Build.Step) void { + const tool_step = b.step("tf-h3-image-prompt-host", "MiniMax-H3-Image's prompt stage on the CPU: Qwen3-VL to layer 50, the token refiner, the picture case"); + const exe = b.addExecutable(.{ .name = "tf-h3-image-prompt-host", .root_module = tool(b, target, optimize) }); + tool_step.dependOn(&b.addInstallArtifact(exe, .{}).step); + + const run = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/families/h3/prompt_case_test.zig"), + .target = target, + .link_libc = true, + .imports = &.{ + .{ .name = "checkpoint_fixture", .module = fixture(b, target, optimize) }, + .{ .name = "moss_noise", .module = noise(b, target, optimize) }, + .{ .name = "qwen_vl_rope", .module = prompt.rope(b, target) }, + }, + }) })); + const tests = b.step("test-h3-image-prompt-host", "The prompt stage's case writer: byte for byte the Metal tool's layout, and torch's CPU randn"); + tests.dependOn(&run.step); + test_step.dependOn(&run.step); +} + +/// The tool's module: the prompt path's host pieces (its Metal-only parts stay unanalyzed), the host checkpoint +fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + const core = @import("h3_host.zig").coreModule(b, target); + const host_prompt = b.createModule(.{ + .root_source_file = b.path("zig/src/families/h3/prompt.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "qwen_vl_rope", .module = prompt.rope(b, target) }, + .{ .name = "checkpoint_fixture", .module = @import("h3_host.zig").fixture(b, core) }, + }, + }); + const checkpoint = b.createModule(.{ + .root_source_file = b.path("zig/src/families/h3/checkpoint.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{.{ .name = "core", .module = core }}, + }); + return b.createModule(.{ + .root_source_file = b.path("zig/tests/h3_image_prompt_host.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "h3_prompt", .module = host_prompt }, + .{ .name = "h3_checkpoint", .module = checkpoint }, + .{ .name = "tokenizer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }) }, + .{ .name = "moss_noise", .module = noise(b, target, optimize) }, + }, + }); +} + +fn fixture(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target, .optimize = optimize }); +} + +fn noise(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); +} diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index f763661d93d..411220d791d 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -226,7 +226,7 @@ pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil } /// Linux: `kernel-contract` runs tf-cuda-test's kernel-contract command (kernels from -Dnvcc or -Dfatbins). -pub fn cuda(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build.LazyPath, h3: ?std.Build.LazyPath) *std.Build.Step { +pub fn cuda(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build.LazyPath, h3: ?std.Build.LazyPath, h3_image: [2]?std.Build.LazyPath) *std.Build.Step { const opts = b.addOptions(); opts.addOption(bool, "controls", controls != null); runner.root_module.addOptions("contract_options", opts); @@ -234,9 +234,12 @@ pub fn cuda(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build runner.root_module.addAnonymousImport("fatbin_contract_controls", .{ .root_source_file = controls orelse empty }); // MiniMax H3's image (the tf-h3 library's) for its kernels' registrations runner.root_module.addAnonymousImport("fatbin_h3", .{ .root_source_file = h3 orelse b.addWriteFiles().add("h3.fatbin", "") }); + const names = [2][]const u8{ "h3_image_decoder", "h3_image_prompt" }; + for (names, h3_image) |n, file| runner.root_module.addAnonymousImport(b.fmt("fatbin_{s}", .{n}), .{ .root_source_file = file orelse b.addWriteFiles().add(b.fmt("{s}.fatbin", .{n}), "") }); const install = b.step("kernel-contract-fatbins", "Install all CUDA contract images (fatbin/)"); if (controls) |file| install.dependOn(&b.addInstallFile(file, "fatbin/contract_controls.fatbin").step); if (h3) |file| install.dependOn(&b.addInstallFile(file, "fatbin/h3.fatbin").step); + for (names, h3_image) |n, file| if (file) |f| install.dependOn(&b.addInstallFile(f, b.fmt("fatbin/{s}.fatbin", .{n})).step); const run = b.addRunArtifact(runner); run.addArg("kernel-contract"); b.step("kernel-contract", "Every registered CUDA kernel through the contract's gates on this GPU, each control red").dependOn(&run.step); diff --git a/zig/build/qwen_contract.zig b/zig/build/qwen_contract.zig index f9cc88a68f2..488bad997d6 100644 --- a/zig/build/qwen_contract.zig +++ b/zig/build/qwen_contract.zig @@ -32,8 +32,8 @@ pub fn host(b: *std.Build, core: *std.Build.Module, all: *std.Build.Step) void { imageTests(b, core, all); } -pub fn images(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build.LazyPath, h3: ?std.Build.LazyPath, kernels: anytype, files: []const ?std.Build.LazyPath) *std.Build.Step { - const install = @import("kernel_contract.zig").cuda(b, runner, controls, h3); +pub fn images(b: *std.Build, runner: *std.Build.Step.Compile, controls: ?std.Build.LazyPath, h3: ?std.Build.LazyPath, h3_image: [2]?std.Build.LazyPath, kernels: anytype, files: []const ?std.Build.LazyPath) *std.Build.Step { + const install = @import("kernel_contract.zig").cuda(b, runner, controls, h3, h3_image); for (kernels, files) |k, file| { if (std.mem.eql(u8, k.name, "moe") or std.mem.eql(u8, k.name, "experts") or std.mem.eql(u8, k.name, "qwen36_mtp") or std.mem.eql(u8, k.name, "sample") or std.mem.eql(u8, k.name, "glm_glue")) { if (file) |image| install.dependOn(&b.addInstallFile(image, b.fmt("fatbin/{s}.fatbin", .{k.name})).step); @@ -62,6 +62,7 @@ fn imageTests(b: *std.Build, core: *std.Build.Module, all: *std.Build.Step) void tests.addOptions("contract_options", opts); tests.addAnonymousImport("fatbin_contract_controls", .{ .root_source_file = files.add("contract_controls.fatbin", "contract_controls") }); tests.addAnonymousImport("fatbin_h3", .{ .root_source_file = files.add("h3.fatbin", "h3") }); + for ([_][]const u8{ "h3_image_decoder", "h3_image_prompt" }) |n| tests.addAnonymousImport(b.fmt("fatbin_{s}", .{n}), .{ .root_source_file = files.add(b.fmt("{s}.fatbin", .{n}), n) }); const run = b.addRunArtifact(b.addTest(.{ .root_module = tests, .filters = &.{"contract image:"} })); b.step("test-contract-images-host", "Live contract image routing and unknown-name refusal with inert bytes").dependOn(&run.step); all.dependOn(&run.step); diff --git a/zig/kernels/cuda/h3_image_decoder.cu b/zig/kernels/cuda/h3_image_decoder.cu new file mode 100644 index 00000000000..1e42a44ce05 --- /dev/null +++ b/zig/kernels/cuda/h3_image_decoder.cu @@ -0,0 +1,299 @@ +// MiniMax-H3-Image's VAE image decoder on CUDA: bf16 tensors, fp32 sums, the RMS norm's f64 sum. +#include +#include +#include +#include +#include "common/reduce.cuh" + +typedef __nv_bfloat16 bf16; + +static __device__ __forceinline__ float f(bf16 x) { return __bfloat162float(x); } +static __device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16(x)); } + +// Correctly rounded reciprocal square root, as the host's float64 1/sqrt rounded to f32. +static __device__ __forceinline__ float inv_sqrt(float x) { return __frsqrt_rn(x); } + +// One parameter block for every kernel: the pass's tiles and their geometry, a product's size, the norms' epsilon. +struct H3dShape { + unsigned tiles; + unsigned h; + unsigned w; + unsigned tokens; + unsigned rows; + unsigned cols; + unsigned m; + unsigned n; + unsigned k; + unsigned mode; + float eps; + float scale; +}; + +// Keys a lane holds in the attention: 9 a lane, 288 a warp, past a 16 x 16 tile's 261 tokens. +#define H3D_SLOTS 9 + +extern "C" { + +// Each tile's cells rounded to bf16, then post_quant_conv (24 to 24 with bias) to bf16: tok [tiles * h * w, 24]. +__global__ void __launch_bounds__(256) h3d_post_quant( + const float* lat, const uint2* org, const bf16* pw, const bf16* pb, + bf16* tok, H3dShape p) { + const unsigned x = blockIdx.x * blockDim.x + threadIdx.x; + const unsigned y = blockIdx.y * blockDim.y + threadIdx.y; + const unsigned cells = p.h * p.w; + if (x >= 24 || y >= p.tiles * cells) return; + const unsigned tile = y / cells; + const unsigned i = y % cells; + const size_t r = org[tile].x + i / p.w; + const size_t c = org[tile].y + i % p.w; + const size_t plane = (size_t)p.rows * p.cols; + float acc = 0.0f; + for (unsigned k = 0; k < 24; ++k) acc += f(pw[x * 24 + k]) * f(__float2bfloat16(lat[k * plane + r * p.cols + c])); + tok[(size_t)y * 24 + x] = __float2bfloat16(acc + f(pb[x])); +} + +// A tile's sequence: x_embedder (24 to 1,024 with bias) on its cells to bf16, then the 4 registers and a zero token. +__global__ void __launch_bounds__(256) h3d_embed( + const bf16* tok, const bf16* ew, const bf16* eb, const bf16* reg, + bf16* x, H3dShape p) { + const unsigned j = blockIdx.x * blockDim.x + threadIdx.x; + const unsigned y = blockIdx.y; + if (j >= 1024 || y >= p.tiles * p.tokens) return; + const unsigned cells = p.h * p.w; + const unsigned tile = y / p.tokens; + const unsigned t = y % p.tokens; + bf16 v = __float2bfloat16(0.0f); + if (t < cells) { + const bf16* in = tok + ((size_t)tile * cells + t) * 24; + float acc = 0.0f; + for (unsigned k = 0; k < 24; ++k) acc += f(ew[j * 24 + k]) * f(in[k]); + v = __float2bfloat16(acc + f(eb[j])); + } else if (t < cells + 4) { + v = reg[(t - cells) * 1024 + j]; + } + x[(size_t)y * 1024 + j] = v; +} + +// The row's 1,024 squares in f64, so the mean rounds as the host reference's f64 sum does. +static __device__ __forceinline__ double h3d_sum_sq(double v, double* part) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = v; + __syncthreads(); + double total = 0.0; + for (int w = 0; w < 8; ++w) total += part[w]; + __syncthreads(); + return total; +} + +// RMSNorm, one row of 1,024 a block of 256: y = bf16((x * rsqrt(mean(x^2) + eps)) * g), the products in fp32. +__global__ void __launch_bounds__(256) h3d_rms_norm( + const bf16* x, const bf16* g, bf16* y, H3dShape p) { + __shared__ double part[8]; + const unsigned row = blockIdx.x; + const unsigned t = threadIdx.x; + const bf16* xr = x + (size_t)row * 1024; + float v[4]; + double sq = 0.0; +#pragma unroll + for (unsigned i = 0; i < 4; ++i) { + v[i] = f(xr[t + 256 * i]); + sq += (double)v[i] * (double)v[i]; + } + const float inv = inv_sqrt((float)(h3d_sum_sq(sq, part) / 1024.0) + p.eps); +#pragma unroll + for (unsigned i = 0; i < 4; ++i) y[(size_t)row * 1024 + t + 256 * i] = __float2bfloat16(v[i] * inv * f(g[t + 256 * i])); +} + +// norm_out: LayerNorm in fp32 (weight and bias), then bf16 as proj_out's input. One row a block of 256. +__global__ void __launch_bounds__(256) h3d_layer_norm( + const bf16* x, const bf16* g, const bf16* b, bf16* y, H3dShape p) { + __shared__ float sums[8]; + __shared__ float squares[8]; + const unsigned row = blockIdx.x; + const unsigned t = threadIdx.x; + const bf16* xr = x + (size_t)row * 1024; + float v[4]; + float s = 0.0f; +#pragma unroll + for (unsigned i = 0; i < 4; ++i) { + v[i] = f(xr[t + 256 * i]); + s += v[i]; + } + const float mean = tf_common::block_sum_serial(s, sums) / 1024.0f; + float sq = 0.0f; +#pragma unroll + for (unsigned i = 0; i < 4; ++i) sq += (v[i] - mean) * (v[i] - mean); + const float rstd = inv_sqrt(tf_common::block_sum_serial(sq, squares) / 1024.0f + p.eps); +#pragma unroll + for (unsigned i = 0; i < 4; ++i) { + const unsigned c = t + 256 * i; + y[(size_t)row * 1024 + c] = __float2bfloat16((v[i] - mean) * rstd * f(g[c]) + f(b[c])); + } +} + +#define H3D_TILE 128 +#define H3D_STEP 16 + +// y [m, n] = x [m, k] . w [n, k]^T fp32: each output summed in increasing K by unfused, individually rounded fp32 ops. +__global__ void __launch_bounds__(256) h3d_linear( + const bf16* x, const bf16* w, float* y, H3dShape p) { + // One float of padding a row spreads the K-major stores across banks. + __shared__ float xs[H3D_STEP][H3D_TILE + 1]; + __shared__ float ws[H3D_STEP][H3D_TILE + 1]; + const unsigned tx = threadIdx.x % 16; + const unsigned ty = threadIdx.x / 16; + const unsigned row0 = blockIdx.y * H3D_TILE; + const unsigned col0 = blockIdx.x * H3D_TILE; + float acc[8][8] = {}; + for (unsigned k0 = 0; k0 < p.k; k0 += H3D_STEP) { +#pragma unroll + for (unsigned j = 0; j < 8; ++j) { + const unsigned e = threadIdx.x + 256 * j; + const unsigned r = e / H3D_STEP; + const unsigned kk = e % H3D_STEP; + const bool in_k = k0 + kk < p.k; + xs[kk][r] = in_k && row0 + r < p.m ? f(x[(size_t)(row0 + r) * p.k + k0 + kk]) : 0.0f; + ws[kk][r] = in_k && col0 + r < p.n ? f(w[(size_t)(col0 + r) * p.k + k0 + kk]) : 0.0f; + } + __syncthreads(); +#pragma unroll + for (unsigned kk = 0; kk < H3D_STEP; ++kk) { + float a[8], b[8]; +#pragma unroll + for (unsigned i = 0; i < 8; ++i) a[i] = xs[kk][ty + 16 * i]; +#pragma unroll + for (unsigned j = 0; j < 8; ++j) b[j] = ws[kk][tx + 16 * j]; +#pragma unroll + for (unsigned i = 0; i < 8; ++i) +#pragma unroll + for (unsigned j = 0; j < 8; ++j) acc[i][j] = __fadd_rn(acc[i][j], __fmul_rn(a[i], b[j])); + } + __syncthreads(); + } +#pragma unroll + for (unsigned i = 0; i < 8; ++i) { + const unsigned row = row0 + ty + 16 * i; + if (row >= p.m) continue; +#pragma unroll + for (unsigned j = 0; j < 8; ++j) { + const unsigned col = col0 + tx + 16 * j; + if (col < p.n) y[(size_t)row * p.n + col] = acc[i][j]; + } + } +} + +// y = bf16(acc + b); mode 1 LayerScale y = bf16(y + bf16(bf16(acc + b) * s)) at the Metal epilogue's rounding. +__global__ void __launch_bounds__(256) h3d_finish( + const float* acc, const bf16* b, const bf16* s, bf16* y, H3dShape p) { + const unsigned x = blockIdx.x * blockDim.x + threadIdx.x; + const unsigned row = blockIdx.y * blockDim.y + threadIdx.y; + if (x >= p.n || row >= p.m) return; + const size_t at = (size_t)row * p.n + x; + const float out = bf(acc[at] + f(b[x])); + if (p.mode == 0) { + y[at] = __float2bfloat16(out); + } else { + y[at] = __float2bfloat16(f(y[at]) + bf(out * f(s[x]))); + } +} + +// Per row and head: q and k RMS-normed (no weight) to bf16, their first 32 dims turned half-style in bf16; v copied. +__global__ void __launch_bounds__(32) h3d_heads( + const bf16* qkv, const bf16* cs, const bf16* sn, + bf16* q, bf16* k, bf16* v, H3dShape p) { + const unsigned row = blockIdx.x; + const unsigned head = blockIdx.y; + const unsigned lane = threadIdx.x; + const unsigned tile = row / p.tokens; + const unsigned t = row % p.tokens; + const bf16* src = qkv + (size_t)row * 3072 + head * 192; + const size_t to = (((size_t)tile * 16 + head) * p.tokens + t) * 64; + const float c = f(cs[t * 32 + lane]); + const float s = f(sn[t * 32 + lane]); +#pragma unroll + for (unsigned part = 0; part < 2; ++part) { + const float a = f(src[part * 64 + lane]); + const float z = f(src[part * 64 + 32 + lane]); + const float inv = inv_sqrt(tf_common::warp_sum(a * a + z * z) / 64.0f + p.eps); + const float na = bf(a * inv); + const float other = __shfl_xor_sync(0xffffffffu, na, 16); + const float turned = lane < 16 ? -other : other; + bf16* out = (part == 0 ? q : k) + to; + out[lane] = __float2bfloat16(bf(na * c) + bf(turned * s)); + out[32 + lane] = __float2bfloat16(z * inv); + } + v[to + lane] = src[128 + lane]; + v[to + 32 + lane] = src[160 + lane]; +} + +// softmax(q k^T / 8) v, a warp a query over its tile's keys; fp32 scores, softmax and sums. Grid [T / 8, 16, tiles]. +__global__ void __launch_bounds__(256) h3d_attention( + const bf16* q, const bf16* k, const bf16* v, bf16* o, H3dShape p) { + __shared__ float qs[8 * 64]; + __shared__ float ps[8 * 32 * H3D_SLOTS]; + const unsigned lane = threadIdx.x & 31; + const unsigned sg = threadIdx.x >> 5; + const unsigned T = p.tokens; + const unsigned query = blockIdx.x * 8 + sg; + if (query >= T) return; + const unsigned head = blockIdx.y; + const unsigned tile = blockIdx.z; + const size_t base = ((size_t)tile * 16 + head) * T * 64; + float* qr = qs + sg * 64; + float* pr = ps + sg * 32 * H3D_SLOTS; + qr[lane] = f(q[base + (size_t)query * 64 + lane]); + qr[lane + 32] = f(q[base + (size_t)query * 64 + 32 + lane]); + __syncwarp(); + float sc[H3D_SLOTS]; + float top = -INFINITY; +#pragma unroll + for (unsigned i = 0; i < H3D_SLOTS; ++i) { + const unsigned key = lane + 32 * i; + sc[i] = -INFINITY; + if (key < T) { + const bf16* kr = k + base + (size_t)key * 64; + float dot = 0.0f; + for (unsigned d = 0; d < 64; ++d) dot += qr[d] * f(kr[d]); + sc[i] = dot * p.scale; + top = fmaxf(top, sc[i]); + } + } + top = tf_common::warp_max(top); + float total = 0.0f; +#pragma unroll + for (unsigned i = 0; i < H3D_SLOTS; ++i) { + const unsigned key = lane + 32 * i; + if (key < T) { + const float e = expf(sc[i] - top); + pr[key] = e; + total += e; + } + } + total = tf_common::warp_sum(total); + __syncwarp(); + float a0 = 0.0f; + float a1 = 0.0f; + for (unsigned key = 0; key < T; ++key) { + const float pk = pr[key]; + const bf16* vr = v + base + (size_t)key * 64 + 2 * lane; + a0 += pk * f(vr[0]); + a1 += pk * f(vr[1]); + } + const size_t at = ((size_t)tile * T + query) * 1024 + head * 64 + 2 * lane; + o[at] = __float2bfloat16(a0 / total); + o[at + 1] = __float2bfloat16(a1 / total); +} + +// act = bf16(bf16(SiLU(gate)) * value), w1's rows read as [gate 4,096 | value 4,096]. Threads [4,096, m]. +__global__ void __launch_bounds__(256) h3d_swiglu(const bf16* wide, bf16* act, H3dShape p) { + const unsigned x = blockIdx.x * blockDim.x + threadIdx.x; + const unsigned y = blockIdx.y * blockDim.y + threadIdx.y; + if (x >= 4096 || y >= p.m) return; + const bf16* r = wide + (size_t)y * 8192; + const float g = f(r[x]); + const float silu = bf(g / (1.0f + expf(-g))); + act[(size_t)y * 4096 + x] = __float2bfloat16(silu * f(r[4096 + x])); +} + +} // extern "C" diff --git a/zig/kernels/cuda/h3_image_prompt.cu b/zig/kernels/cuda/h3_image_prompt.cu new file mode 100644 index 00000000000..413194a8f95 --- /dev/null +++ b/zig/kernels/cuda/h3_image_prompt.cu @@ -0,0 +1,180 @@ +// MiniMax-H3-Image's prompt stage on CUDA: bf16 in, fp32 products, the norms' squares in f64, bf16 out. +#include +#include +#include + +typedef __nv_bfloat16 bf16; + +static __device__ float f(bf16 v) { return __bfloat162float(v); } +static __device__ bf16 h(float v) { return __float2bfloat16_rn(v); } + +// exp(x) one rounding from exact as the reference computes it: expf is up to 2 ULPs off. +static __device__ float exact_exp(float x) { return (float)exp((double)x); } + +// One RMSNorm value: mode 0 bf16(w * bf16(x * r)) as Qwen's text, mode 1 bf16(x * r * w) as H3; r f64, the weight fp32. +static __device__ float h3p_normed(float x, double r, float w, int mode) { + const float p = (float)((double)x * r); + return mode == 0 ? __fmul_rn(w, f(h(p))) : __fmul_rn(p, w); +} + +// y = RMSNorm(x) by w: squares summed in f64 in the host's order, so the inverse root is the reference's bits. +extern "C" __global__ void __launch_bounds__(256) h3p_norm( + const bf16* x, const float* w, bf16* y, int width, int mode, float eps) { + __shared__ double r; + const int row = blockIdx.x; + const bf16* xr = x + (size_t)row * width; + bf16* yr = y + (size_t)row * width; + if (threadIdx.x == 0) { + double s = 0.0; + for (int i = 0; i < width; ++i) { + const double v = f(xr[i]); + s += v * v; + } + r = 1.0 / sqrt(s / (double)width + (double)eps); + } + __syncthreads(); + for (int i = threadIdx.x; i < width; i += 256) yr[i] = h(h3p_normed(f(xr[i]), r, w[i], mode)); +} + +// q then k heads of 128 normed in place (mode as h3p_norm) and turned by cos, sin [rows, 64]; a warp a head, in order. +extern "C" __global__ void __launch_bounds__(256) h3p_heads( + bf16* q, bf16* k, const float* wq, const float* wk, const float* cs, const float* sn, + int heads, int kv_heads, int q_row, int k_row, int head, int mode, int rotary, float eps) { + const int row = blockIdx.x; + const int hh = blockIdx.y * 8 + (threadIdx.x >> 5); + if (hh >= heads + kv_heads) return; + const int lane = threadIdx.x & 31; + const bool is_q = hh < heads; + bf16* x = is_q ? q + (size_t)row * q_row + (size_t)hh * head + : k + (size_t)row * k_row + (size_t)(hh - heads) * head; + const float* w = is_q ? wq : wk; + double ss = 0.0; + for (int i = 0; i < 128; ++i) { + const double v = f(x[i]); + ss += v * v; + } + float v[4]; + for (int i = 0; i < 4; ++i) v[i] = f(x[lane * 4 + i]); + __syncwarp(); + const double r = 1.0 / sqrt(ss / 128.0 + (double)eps); + for (int i = 0; i < 4; ++i) v[i] = h3p_normed(v[i], r, w[lane * 4 + i], mode); + if (rotary) { + // round as the host stores the norm; channel c pairs with c +- 64 (16 lanes away); products round first. + for (int i = 0; i < 4; ++i) v[i] = f(h(v[i])); + const float sign = lane < 16 ? -1.0f : 1.0f; + for (int i = 0; i < 4; ++i) { + const float o = __shfl_xor_sync(0xffffffffu, v[i], 16); + const size_t at = (size_t)row * 64 + (lane & 15) * 4 + i; + v[i] = __fadd_rn(f(h(__fmul_rn(v[i], cs[at]))), f(h(__fmul_rn(sign * o, sn[at])))); + } + } + for (int i = 0; i < 4; ++i) x[lane * 4 + i] = h(v[i]); +} + +// One key's score: q . k over 128 in order, times scale, as the host reference's. +static __device__ float h3p_score(const bf16* q, const bf16* k, float scale) { + float s = 0.0f; + for (int i = 0; i < 128; ++i) s = __fadd_rn(s, __fmul_rn(f(q[i]), f(k[i]))); + return __fmul_rn(s, scale); +} + +// o = softmax(q k^T / sqrt(128)) v in bf16, a warp a row's head: the top score, then the host's in-order sums. +extern "C" __global__ void __launch_bounds__(256) h3p_attention( + const bf16* q, const bf16* k, const bf16* v, bf16* o, + int rows, int heads, int kv_heads, int q_row, int k_row, int v_row, int head, + int causal, float scale) { + const int row = blockIdx.x; + const int hh = blockIdx.y * 8 + (threadIdx.x >> 5); + if (hh >= heads) return; + const int lane = threadIdx.x & 31; + const int kv = hh / (heads / kv_heads); + const bf16* qp = q + (size_t)row * q_row + (size_t)hh * head; + const bf16* kp = k + (size_t)kv * head; + const bf16* vp = v + (size_t)kv * head + lane * 4; + const int end = causal ? row + 1 : rows; + float top = -INFINITY; + for (int j = lane; j < end; j += 32) top = fmaxf(top, h3p_score(qp, kp + (size_t)j * k_row, scale)); + for (int k_ = 16; k_; k_ >>= 1) top = fmaxf(top, __shfl_xor_sync(0xffffffffu, top, k_)); + float l = 0.0f; + float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + for (int j0 = 0; j0 < end; j0 += 32) { + // the warp's next 32 keys' weights, one a lane, then read back in key order + const int j = j0 + lane; + const float mine = j < end ? exact_exp(__fadd_rn(h3p_score(qp, kp + (size_t)j * k_row, scale), -top)) : 0.0f; + for (int u = 0; u < 32 && j0 + u < end; ++u) { + const float e = __shfl_sync(0xffffffffu, mine, u); + l = __fadd_rn(l, e); + const bf16* vr = vp + (size_t)(j0 + u) * v_row; + for (int i = 0; i < 4; ++i) acc[i] = __fadd_rn(acc[i], __fmul_rn(e, f(vr[i]))); + } + } + bf16* out = o + (size_t)row * heads * 128 + (size_t)hh * 128 + lane * 4; + for (int i = 0; i < 4; ++i) out[i] = h(__fdiv_rn(acc[i], l)); +} + +// o = silu(g) * v bf16: mode 0 bf16(bf16(g / e) v), mode 1 bf16(bf16(g * bf16(1 / e)) v) as H3; strides may differ. +extern "C" __global__ void __launch_bounds__(256) h3p_glu( + const bf16* g, const bf16* v, bf16* o, int width, int g_row, int v_row, int mode) { + const int c = blockIdx.x * 256 + threadIdx.x; + const int row = blockIdx.y; + if (c >= width) return; + const float x = f(g[(size_t)row * g_row + c]); + const float e = 1.0f + exact_exp(-x); + const float s = mode == 0 ? f(h(__fdiv_rn(x, e))) : f(h(__fmul_rn(x, f(h(__fdiv_rn(1.0f, e)))))); + o[(size_t)row * width + c] = h(__fmul_rn(s, f(v[(size_t)row * v_row + c]))); +} + + +// x = bf16(x + bf16(y)): round the fp32 product before the residual add. +extern "C" __global__ void __launch_bounds__(256) h3p_add(bf16* x, const float* y, int n) { + const int i = blockIdx.x * 256 + threadIdx.x; + if (i < n) x[i] = h(__fadd_rn(f(x[i]), f(h(y[i])))); +} + +// x rows idx[i] = bf16(x + y[i]): DeepStack's features added at the image pads, y bf16. +extern "C" __global__ void __launch_bounds__(256) h3p_scatter_add( + bf16* x, const bf16* y, const unsigned* idx, int width) { + const int c = blockIdx.x * 256 + threadIdx.x; + const int i = blockIdx.y; + if (c >= width) return; + const size_t to = (size_t)idx[i] * width + c; + x[to] = h(__fadd_rn(f(x[to]), f(y[(size_t)i * width + c]))); +} + +// The embedding gather: x rows = table's rows `ids`, bf16 copied as stored. +extern "C" __global__ void __launch_bounds__(256) h3p_embed( + const bf16* table, const unsigned* ids, bf16* x, int width) { + const int c = blockIdx.x * 256 + threadIdx.x; + const int row = blockIdx.y; + if (c >= width) return; + x[(size_t)row * width + c] = table[(size_t)ids[row] * width + c]; +} + +// Vision rows spliced into the stream: x rows pads[i] = rows[i], whole bf16 rows. +extern "C" __global__ void __launch_bounds__(256) h3p_splice( + bf16* x, const bf16* rows_, const unsigned* pads, int width) { + const int c = blockIdx.x * 256 + threadIdx.x; + const int i = blockIdx.y; + if (c >= width) return; + x[(size_t)pads[i] * width + c] = rows_[(size_t)i * width + c]; +} + +// y [rows, n] fp32 = x [rows, k] . w [n, k]^T bf16: K summed sequentially, its bf16 rounding the reference's own. +extern "C" __global__ void __launch_bounds__(256) h3p_linear( + const bf16* x, const bf16* w, float* y, int rows, int n, int k) { + const int at = blockIdx.x * 256 + threadIdx.x; + if (at >= rows * n) return; + const int row = at / n; + const int col = at % n; + const bf16* xr = x + (size_t)row * k; + const bf16* wr = w + (size_t)col * k; + float sum = 0.0f; + for (int i = 0; i < k; ++i) sum = __fadd_rn(sum, __fmul_rn(f(xr[i]), f(wr[i]))); + y[at] = sum; +} + +// y [n] = bf16(x [n]): a product's fp32 rows at their one rounding to bf16, the reference's every output. +extern "C" __global__ void __launch_bounds__(256) h3p_round(const float* x, bf16* y, int n) { + const int i = blockIdx.x * 256 + threadIdx.x; + if (i < n) y[i] = h(x[i]); +} diff --git a/zig/src/core/checkpoint_fixture.zig b/zig/src/core/checkpoint_fixture.zig index de3c51d2a56..52aff8356e8 100644 --- a/zig/src/core/checkpoint_fixture.zig +++ b/zig/src/core/checkpoint_fixture.zig @@ -33,6 +33,19 @@ pub fn image(a: std.mem.Allocator, entries: []const Entry) ![]u8 { return out; } +/// A safetensors image whose data starts on 16 bytes: the header padded with spaces, every tensor aligned. +pub fn aligned(a: std.mem.Allocator, entries: []const Entry) ![]u8 { + const plain = try image(a, entries); + const header: usize = @intCast(std.mem.readInt(u64, plain[0..8], .little)); + const pad = (16 - (8 + header) % 16) % 16; + const out = try a.alloc(u8, plain.len + pad); + std.mem.writeInt(u64, out[0..8], header + pad, .little); + @memcpy(out[8..][0..header], plain[8..][0..header]); + @memset(out[8 + header ..][0..pad], ' '); + @memcpy(out[8 + header + pad ..], plain[8 + header ..]); + return out; +} + pub fn write(a: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, name: []const u8, entries: []const Entry) !void { const bytes = try image(a, entries); defer a.free(bytes); diff --git a/zig/src/core/contract/h3_image_cuda_records.zig b/zig/src/core/contract/h3_image_cuda_records.zig new file mode 100644 index 00000000000..8ed635bdd85 --- /dev/null +++ b/zig/src/core/contract/h3_image_cuda_records.zig @@ -0,0 +1,40 @@ +//! MiniMax-H3-Image's CUDA launches. +const std = @import("std"); +const limits = @import("limits.zig"); +const registry = @import("registry.zig"); + +fn record(comptime symbol: []const u8, comptime image: []const u8, threads: u32, min_sm: u32, usage: [limits.sms.len]limits.Usage) registry.CudaRecord { + return .{ .launch = .{ .name = "h3_image " ++ symbol, .symbol = symbol, .image = image, .threads = threads, .min_sm = min_sm }, .usage = usage }; +} + +/// nvcc 13.0's usage, the compiler of the release fatbins (kernel-contract-limits, 16 Nov 2026). +pub const records = [_]registry.CudaRecord{ + record("h3d_post_quant", "h3_image_decoder", 256, 80, .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } }), + record("h3d_embed", "h3_image_decoder", 256, 80, .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } }), + record("h3d_rms_norm", "h3_image_decoder", 256, 80, .{ .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 32, .static = 64, .bound = 256 } }), + record("h3d_layer_norm", "h3_image_decoder", 256, 80, .{ .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 32, .static = 64, .bound = 256 }, .{ .regs = 26, .static = 64, .bound = 256 }, .{ .regs = 26, .static = 64, .bound = 256 } }), + record("h3d_linear", "h3_image_decoder", 256, 80, .{ .{ .regs = 98, .static = 16512, .bound = 256 }, .{ .regs = 98, .static = 16512, .bound = 256 }, .{ .regs = 98, .static = 16512, .bound = 256 }, .{ .regs = 127, .static = 16512, .bound = 256 }, .{ .regs = 127, .static = 16512, .bound = 256 } }), + record("h3d_finish", "h3_image_decoder", 256, 80, .{ .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }), + record("h3d_heads", "h3_image_decoder", 32, 80, .{ .{ .regs = 23, .static = 0, .bound = 32 }, .{ .regs = 24, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 }, .{ .regs = 21, .static = 0, .bound = 32 }, .{ .regs = 21, .static = 0, .bound = 32 } }), + record("h3d_attention", "h3_image_decoder", 256, 80, .{ .{ .regs = 37, .static = 11264, .bound = 256 }, .{ .regs = 48, .static = 11264, .bound = 256 }, .{ .regs = 48, .static = 11264, .bound = 256 }, .{ .regs = 48, .static = 11264, .bound = 256 }, .{ .regs = 48, .static = 11264, .bound = 256 } }), + record("h3d_swiglu", "h3_image_decoder", 256, 80, .{ .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 } }), + record("h3p_norm", "h3_image_prompt", 256, 80, .{ .{ .regs = 31, .static = 8, .bound = 256 }, .{ .regs = 35, .static = 8, .bound = 256 }, .{ .regs = 35, .static = 8, .bound = 256 }, .{ .regs = 27, .static = 8, .bound = 256 }, .{ .regs = 27, .static = 8, .bound = 256 } }), + record("h3p_heads", "h3_image_prompt", 256, 80, .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } }), + record("h3p_attention", "h3_image_prompt", 256, 80, .{ .{ .regs = 31, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 } }), + record("h3p_glu", "h3_image_prompt", 256, 80, .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 17, .static = 0, .bound = 256 } }), + record("h3p_add", "h3_image_prompt", 256, 80, .{ .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }), + record("h3p_scatter_add", "h3_image_prompt", 256, 80, .{ .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }), + record("h3p_embed", "h3_image_prompt", 256, 80, .{ .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }), + record("h3p_splice", "h3_image_prompt", 256, 80, .{ .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }), + record("h3p_linear", "h3_image_prompt", 256, 80, .{ .{ .regs = 29, .static = 0, .bound = 256 }, .{ .regs = 37, .static = 0, .bound = 256 }, .{ .regs = 37, .static = 0, .bound = 256 }, .{ .regs = 29, .static = 0, .bound = 256 }, .{ .regs = 29, .static = 0, .bound = 256 } }), + record("h3p_round", "h3_image_prompt", 256, 80, .{ .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 8, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }), +}; + +test "MiniMax-H3-Image CUDA: every launch is in the live registry and fits every SM" { + for (records) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(std.mem.eql(u8, active.launch.name, r.launch.name)); + try std.testing.expectEqual(@as(usize, 1), found); + try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true)); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 7cd96798c8e..c23eccd9b53 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -63,6 +63,7 @@ pub const cuda_pending = @import("qwen_whole_records.zig").records ++ @import("ricursive_prep_records.zig").cuda ++ @import("ricursive_attn_records.zig").cuda ++ @import("registry_media.zig").cuda_pending; + @import("h3_image_cuda_records.zig").records; pub const metal_before = @import("fsr_records.zig").metal ++ @import("scale_index_records.zig").metal ++ @import("lfm3_records.zig").metal; @@ -161,4 +162,5 @@ test { _ = @import("inkling2_loop_metal_records.zig"); _ = @import("inkling2_runtime_metal_records.zig"); _ = @import("inkling2_dspark_metal_records.zig"); + _ = @import("h3_image_cuda_records.zig"); } diff --git a/zig/src/core/h3_core.zig b/zig/src/core/h3_core.zig new file mode 100644 index 00000000000..bac9f71a465 --- /dev/null +++ b/zig/src/core/h3_core.zig @@ -0,0 +1,4 @@ +//! The core files H3 reads (safetensors, checked read-ahead, its fixture); image tools' pictures are their own module. +pub const safetensors = @import("safetensors.zig"); +pub const checkpoint_read_ahead = @import("checkpoint_read_ahead.zig"); +pub const checkpoint_fixture = @import("checkpoint_fixture.zig"); diff --git a/zig/src/families/h3/checkpoint.zig b/zig/src/families/h3/checkpoint.zig index 81751a6221c..ebbf3f1164d 100644 --- a/zig/src/families/h3/checkpoint.zig +++ b/zig/src/families/h3/checkpoint.zig @@ -9,6 +9,8 @@ const c = struct { extern "c" fn lseek(fd: c_int, offset: i64, whence: c_int) i64; extern "c" fn mmap(addr: ?*anyopaque, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: i64) ?*anyopaque; extern "c" fn munmap(addr: ?*anyopaque, len: usize) c_int; + extern "c" fn madvise(addr: ?*anyopaque, len: usize, advice: c_int) c_int; + extern "c" fn posix_fadvise(fd: c_int, offset: i64, len: i64, advice: c_int) c_int; }; /// Where a tensor sits in the data that follows the header. @@ -27,6 +29,8 @@ pub fn locate(names: st.Header, name: []const u8) !Span { pub const Checkpoint = struct { bytes: []const u8, + /// Open until `deinit`, so `evict` can drop the file's pages from the page cache. + fd: c_int, header: []const u8, data: usize, names: st.Header, @@ -41,24 +45,73 @@ pub const Checkpoint = struct { fn openWith(path: [*:0]const u8, comptime Ops: type) !Checkpoint { const fd = Ops.open(path, 0); if (fd < 0) return error.CannotOpen; - defer _ = Ops.close(fd); + errdefer _ = Ops.close(fd); const size = Ops.lseek(fd, 0, 2); if (size < 16) return error.CannotOpen; const len = std.math.cast(usize, size) orelse return error.CheckpointTooLarge; - const at = Ops.mmap(null, len, 1, 2, fd, 0) orelse return error.CannotMap; - if (@intFromPtr(at) == std.math.maxInt(usize)) return error.CannotMap; - errdefer _ = Ops.munmap(at, len); - const bytes = @as([*]const u8, @ptrCast(at))[0..len]; + const mapped = Ops.mmap(null, len, 1, 2, fd, 0) orelse return error.CannotMap; + if (@intFromPtr(mapped) == std.math.maxInt(usize)) return error.CannotMap; + errdefer _ = Ops.munmap(mapped, len); + const bytes = @as([*]const u8, @ptrCast(mapped))[0..len]; const n = st.headerSize(std.mem.readInt(u64, bytes[0..8], .little), len) catch return error.BadHeader; var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); errdefer arena.deinit(); const names = st.parseHeader(arena.allocator(), bytes[8..][0..n], len - 8 - n) catch return error.BadHeader; - return .{ .bytes = bytes, .header = bytes[8 .. 8 + n], .data = 8 + n, .names = names, .arena = arena }; + return .{ .bytes = bytes, .fd = fd, .header = bytes[8 .. 8 + n], .data = 8 + n, .names = names, .arena = arena }; } pub fn deinit(self: *Checkpoint) void { + self.deinitWith(c); + } + + fn deinitWith(self: *Checkpoint, comptime Ops: type) void { self.arena.deinit(); - _ = c.munmap(@ptrCast(@constCast(self.bytes.ptr)), self.bytes.len); + _ = Ops.munmap(@ptrCast(@constCast(self.bytes.ptr)), self.bytes.len); + _ = Ops.close(self.fd); + } + + /// Discards the pages from the mapping and page cache; faulted back from disk on a later read. Linux only. + pub fn evict(self: *const Checkpoint) void { + if (@import("builtin").os.tag != .linux) return; + _ = c.madvise(@ptrCast(@constCast(self.bytes.ptr)), self.bytes.len, 4); // MADV_DONTNEED + _ = c.posix_fadvise(self.fd, 0, 0, 4); // POSIX_FADV_DONTNEED: a cached copy would crowd out the prompt's + } + + /// The tensor `name` of `dtype` and `count` values: its bytes as stored. + pub fn at(self: *const Checkpoint, name: []const u8, dtype: st.DType, count: usize) ![]const u8 { + const e = self.names.get(name) orelse { + report.say("no tensor {s}", .{name}); + return error.MissingTensor; + }; + const size = std.math.mul(usize, count, dtype.size()) catch return error.BadTensor; + if (e.dtype != dtype or e.end - e.begin != size) { + report.say("tensor {s}: unexpected type or size", .{name}); + return error.BadTensor; + } + if (self.data > self.bytes.len or e.end > self.bytes.len - self.data) return error.BadHeader; + return self.bytes[self.data + e.begin ..][0 .. e.end - e.begin]; + } + + /// The tensor `name` (float32 or bf16) as float32 values on the host. + pub fn floats(self: *const Checkpoint, a: std.mem.Allocator, name: []const u8) ![]f32 { + const e = self.names.get(name) orelse { + report.say("no tensor {s}", .{name}); + return error.MissingTensor; + }; + if (self.data > self.bytes.len or e.end > self.bytes.len - self.data) return error.BadHeader; + const from = self.bytes[self.data + e.begin ..]; + const out = try a.alloc(f32, (e.end - e.begin) / e.dtype.size()); + for (out, 0..) |*o, i| o.* = switch (e.dtype) { + .f32 => @bitCast(std.mem.readInt(u32, from[4 * i ..][0..4], .little)), + .bf16 => @bitCast(@as(u32, std.mem.readInt(u16, from[2 * i ..][0..2], .little)) << 16), + else => return error.BadTensor, + }; + return out; + } + + /// A one-file view through the sharded interface; closed by this checkpoint's `deinit`. + pub fn shards(self: *Checkpoint) Shards { + return .{ .files = self[0..1], .owned = false }; } pub fn bf16(self: *const Checkpoint, name: []const u8) !Entry { @@ -71,6 +124,136 @@ pub const Checkpoint = struct { } }; +/// The block count advertised in one header: null when it names no block, an error when it names them badly. +pub fn blockCount(a: std.mem.Allocator, header: []const u8) !?usize { + const parsed = try std.json.parseFromSlice(std.json.Value, a, header, .{}); + defer parsed.deinit(); + if (parsed.value != .object) return error.BadBlocks; + const obj = parsed.value.object; + var count: ?usize = null; + for (obj.keys()) |key| { + if (!std.mem.startsWith(u8, key, "blocks.")) continue; + const rest = key[7..]; + const dot = std.mem.indexOfScalar(u8, rest, '.') orelse return error.BadBlocks; + const id = std.fmt.parseInt(usize, rest[0..dot], 10) catch return error.BadBlocks; + if (dot == 0 or (dot > 1 and rest[0] == '0')) return error.BadBlocks; + count = @max(count orelse 0, std.math.add(usize, id, 1) catch return error.BadBlocks); + } + return count; +} + +/// `fmt` of `args` as a C path in `buf`, its terminator inside the buffer. +fn cPath(buf: *[1024]u8, comptime fmt: []const u8, args: anytype) ![*:0]const u8 { + const text = std.fmt.bufPrint(buf[0 .. buf.len - 1], fmt, args) catch return error.NameTooLong; + buf[text.len] = 0; + return @ptrCast(text.ptr); +} + +/// A checkpoint in shards, each mapped once; a tensor is found in whichever holds it. +pub const Shards = struct { + files: []Checkpoint, + /// `open` allocated the list; a single file's `shards()` view borrows it. + owned: bool = true, + + /// `dir`'s `count` shards named `{stem}-{i:05}-of-{count:05}.safetensors`, both released and diffusers stems. + pub fn open(gpa: std.mem.Allocator, dir: []const u8, count: usize) !Shards { + if (count == 0 or dir.len == 0) return error.BadShardIndex; + const files = try gpa.alloc(Checkpoint, count); + var made: usize = 0; + errdefer { + for (files[0..made]) |*file| file.deinit(); + gpa.free(files); + } + const shard = "{s}/{s}-{d:0>5}-of-{d:0>5}.safetensors"; + var path: [1024]u8 = undefined; + var stem: []const u8 = "model"; + for (files, 1..) |*file, i| { + file.* = Checkpoint.open(try cPath(&path, shard, .{ dir, stem, i, count })) catch |err| first: { + if (i > 1 or std.mem.eql(u8, stem, "diffusion_pytorch_model")) return err; + stem = "diffusion_pytorch_model"; + break :first try Checkpoint.open(try cPath(&path, shard, .{ dir, stem, i, count })); + }; + made += 1; + } + return .{ .files = files }; + } + + /// Unmaps every shard and frees the list when `open` allocated it. + pub fn deinit(self: *Shards, gpa: std.mem.Allocator) void { + for (self.files) |*file| file.deinit(); + if (self.owned) gpa.free(self.files); + self.files = &.{}; + } + + /// Every shard's `evict`: once the weights sit on the device, a resident process pins no host copy of them. + pub fn evict(self: *const Shards) void { + for (self.files) |*file| file.evict(); + } + + pub fn entry(self: *const Shards, name: []const u8) ?st.Entry { + for (self.files) |*file| if (file.names.get(name)) |e| return e; + return null; + } + + /// The bf16 tensor `name` in whichever shard holds it. + pub fn bf16(self: *const Shards, name: []const u8) !Checkpoint.Entry { + for (self.files) |*file| if (file.names.get(name) != null) return file.bf16(name); + report.say("tensor {s}: {t}", .{ name, error.MissingTensor }); + return error.MissingTensor; + } + + /// The tensor `name` of `dtype` and `count` values: its bytes as stored, in whichever shard holds it. + pub fn at(self: *const Shards, name: []const u8, dtype: st.DType, count: usize) ![]const u8 { + for (self.files) |*file| if (file.names.get(name) != null) return file.at(name, dtype, count); + report.say("no tensor {s}", .{name}); + return error.MissingTensor; + } + + /// The tensor `name` (float32 or bf16) as float32 values, in whichever shard holds it. + pub fn floats(self: *const Shards, a: std.mem.Allocator, name: []const u8) ![]f32 { + for (self.files) |*file| if (file.names.get(name) != null) return file.floats(a, name); + report.say("no tensor {s}", .{name}); + return error.MissingTensor; + } + + /// The deepest block index across every shard's header; a shard may hold no block tensors. + pub fn layers(self: *const Shards, a: std.mem.Allocator) !usize { + var last: ?usize = null; + for (self.files) |*file| { + if (try blockCount(a, file.header)) |n| last = @max(last orelse 0, n); + } + return last orelse error.BadBlocks; + } +}; + +/// A checkpoint folder whose shards are mapped on first use, each once, until `deinit`. +pub const Folder = FolderWith(c); + +fn FolderWith(comptime Ops: type) type { + return struct { + const Self = @This(); + + dir: []const u8, + /// Shard file name to its mapping; the names outlive the folder. + files: std.StringArrayHashMapUnmanaged(Checkpoint) = .empty, + + /// The shard `file`, mapped on its first call; a failed open leaves nothing behind. + pub fn shard(self: *Self, gpa: std.mem.Allocator, file: []const u8) !*Checkpoint { + const gop = try self.files.getOrPut(gpa, file); + if (gop.found_existing) return gop.value_ptr; + errdefer self.files.swapRemoveAt(gop.index); + var path: [1024]u8 = undefined; + gop.value_ptr.* = try Checkpoint.openWith(try cPath(&path, "{s}/{s}", .{ self.dir, file }), Ops); + return gop.value_ptr; + } + + pub fn deinit(self: *Self, gpa: std.mem.Allocator) void { + for (self.files.values()) |*file| file.deinitWith(Ops); + self.files.deinit(gpa); + } + }; +} + /// core's index of `header`, for the tests. fn indexOf(a: std.mem.Allocator, header: []const u8, data_len: usize) !st.Header { return st.parseHeader(a, header, data_len); @@ -129,7 +312,7 @@ test "h3 arithmetic: tensor sizes and offsets reject overflow" { try std.testing.expectError(error.BadSafetensors, indexOf(arena.allocator(), "{\"a\":{\"dtype\":\"BF16\",\"shape\":[18446744073709551615,2],\"data_offsets\":[0,0]}}", 0)); var bytes: [16]u8 = @splat(0); const header = "{\"a\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}"; - const ck: Checkpoint = .{ .bytes = &bytes, .data = std.math.maxInt(usize), .header = header, .names = try indexOf(arena.allocator(), header, 2), .arena = .init(std.testing.allocator) }; + const ck: Checkpoint = .{ .bytes = &bytes, .fd = -1, .data = std.math.maxInt(usize), .header = header, .names = try indexOf(arena.allocator(), header, 2), .arena = .init(std.testing.allocator) }; try std.testing.expectError(error.BadHeader, ck.bf16("a")); } @@ -159,3 +342,92 @@ test "a tensor is found by core's index: not a dtype in another field, not a loo for ([_][]const u8{ "{\"w\":{\"dtype\":\"BF16\",", "{\"w\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}x", "{\"w\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]},\"w\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}" }) |bad| if (indexOf(a, bad, 2)) |_| return error.TestUnexpectedResult else |_| {}; } +fn safetensors(a: std.mem.Allocator, header: []const u8, data: []const u8) ![]u8 { + const out = try a.alloc(u8, 8 + header.len + data.len); + std.mem.writeInt(u64, out[0..8], header.len, .little); + @memcpy(out[8..][0..header.len], header); + @memcpy(out[8 + header.len ..], data); + return out; +} + +test "a sharded checkpoint finds a tensor in whichever shard holds it and counts blocks across the headers" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(std.testing.io, ".", a); + // shard 1: norm1 only; shard 2: a bf16 matrix and an f32 vector + const one = try safetensors(a, "{\"blocks.0.norm1.weight\":{\"dtype\":\"BF16\",\"shape\":[4],\"data_offsets\":[0,8]}}", &.{ 0, 60, 0, 62, 0, 64, 0, 66 }); + const two = try safetensors(a, "{\"blocks.2.norm1.weight\":{\"dtype\":\"BF16\",\"shape\":[2],\"data_offsets\":[0,4]},\"w\":{\"dtype\":\"F32\",\"shape\":[2],\"data_offsets\":[4,12]}}", &.{ 0, 66, 0, 68, 0, 0, 128, 63, 0, 0, 0, 64 }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model-00001-of-00002.safetensors", .data = one }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model-00002-of-00002.safetensors", .data = two }); + var shards = try Shards.open(a, dir, 2); + defer shards.deinit(a); + try std.testing.expectEqual(@as(usize, 3), try shards.layers(a)); + const e = try shards.bf16("blocks.2.norm1.weight"); + try std.testing.expectEqual(@as(usize, 1), e.rows); + try std.testing.expectEqualSlices(u8, &.{ 0, 66, 0, 68 }, e.bytes); + try std.testing.expectError(error.MissingTensor, shards.bf16("none")); + const f = try shards.floats(a, "w"); + try std.testing.expectEqualSlices(f32, &.{ 1.0, 2.0 }, f); + const g = try shards.at("blocks.0.norm1.weight", .bf16, 4); + try std.testing.expectEqualSlices(u8, &.{ 0, 60, 0, 62, 0, 64, 0, 66 }, g); +} + +test "shard headers with no blocks, a gapped id and a bad id" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expectEqual(@as(?usize, null), try blockCount(a, "{\"time_embedder.proj_in.weight\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}")); + try std.testing.expectEqual(@as(?usize, 2), try blockCount(a, "{\"blocks.0.a\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]},\"blocks.1.b\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}")); + try std.testing.expectEqual(@as(?usize, 10), try blockCount(a, "{\"blocks.9.a\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}")); + try std.testing.expectError(error.BadBlocks, blockCount(a, "{\"blocks.01.a\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]},\"blocks.1.a\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}")); + try std.testing.expectError(error.BadShardIndex, Shards.open(a, "x", 0)); +} + +test "a count-checked fetch refuses a tensor shorter than asked, another dtype and a size that overflows" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var bytes: [8]u8 = @splat(0); + const header = "{\"w\":{\"dtype\":\"F32\",\"shape\":[2],\"data_offsets\":[0,8]}}"; + const ck: Checkpoint = .{ .bytes = &bytes, .fd = -1, .data = 0, .header = header, .names = try indexOf(arena.allocator(), header, 8), .arena = .init(std.testing.allocator) }; + try std.testing.expectEqual(@as(usize, 8), (try ck.at("w", .f32, 2)).len); + try std.testing.expectError(error.BadTensor, ck.at("w", .f32, 3)); + try std.testing.expectError(error.BadTensor, ck.at("w", .bf16, 4)); + try std.testing.expectError(error.BadTensor, ck.at("w", .f32, std.math.maxInt(usize) / 2 + 3)); + try std.testing.expectError(error.BadBlocks, blockCount(arena.allocator(), "{\"blocks.18446744073709551615.a\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}")); +} + +test "h3 ownership: a folder maps a shard once, retries a failed open and unmaps what it mapped" { + const Count = struct { + var maps: usize = 0; + var unmaps: usize = 0; + const open = c.open; + const close = c.close; + const lseek = c.lseek; + fn mmap(addr: ?*anyopaque, len: usize, prot: c_int, flags: c_int, fd: c_int, offset: i64) ?*anyopaque { + maps += 1; + return c.mmap(addr, len, prot, flags, fd, offset); + } + fn munmap(addr: ?*anyopaque, len: usize) c_int { + unmaps += 1; + return c.munmap(addr, len); + } + }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try tmp.dir.realPathFileAlloc(std.testing.io, ".", std.testing.allocator); + defer std.testing.allocator.free(dir); + var folder: FolderWith(Count) = .{ .dir = dir }; + try std.testing.expectError(error.CannotOpen, folder.shard(std.testing.allocator, "a.safetensors")); + try std.testing.expectEqual(@as(usize, 0), folder.files.count()); + const file = try safetensors(std.testing.allocator, "{\"w\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}", &.{ 0, 63 }); + defer std.testing.allocator.free(file); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.safetensors", .data = file }); + const first = try folder.shard(std.testing.allocator, "a.safetensors"); + try std.testing.expectEqual(first, try folder.shard(std.testing.allocator, "a.safetensors")); + try std.testing.expectEqual(@as(usize, 1), Count.maps); + folder.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(usize, 1), Count.unmaps); +} diff --git a/zig/src/families/h3/clock.zig b/zig/src/families/h3/clock.zig new file mode 100644 index 00000000000..427ac1005b6 --- /dev/null +++ b/zig/src/families/h3/clock.zig @@ -0,0 +1,7 @@ +const std = @import("std"); + +pub fn seconds() f64 { + var ts: std.c.timespec = undefined; + if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(f64, @floatFromInt(ts.sec)) + @as(f64, @floatFromInt(ts.nsec)) * 1e-9; +} diff --git a/zig/src/families/h3/image_decoder.zig b/zig/src/families/h3/image_decoder.zig index 7b5c9c1cc6a..c3bc38b1ebc 100644 --- a/zig/src/families/h3/image_decoder.zig +++ b/zig/src/families/h3/image_decoder.zig @@ -153,6 +153,59 @@ pub fn check(a: std.mem.Allocator, header: *const st.Header, items: []const Item culprit.* = ""; } +/// The decoder side of one safetensors file: its parsed header, the plan's items, the tensor bytes. +pub const Weights = struct { + header: st.Header, + items: []Item, + /// Where tensor bytes start in the file; the header's data offsets are relative to it. + start: usize, + bytes: []const u8, +}; + +/// The decoder's tensors of the safetensors file `file`, checked against `plan`. +pub fn weights(a: std.mem.Allocator, file: []const u8, plan: Plan) !Weights { + if (file.len < 8) return error.H3BadVaeTensor; + const len = try st.headerSize(std.mem.readInt(u64, file[0..8], .little), file.len); + const header = try st.parseHeader(a, file[8..][0..len], file.len - 8 - len); + const items = try plan.items(a); + var culprit: []const u8 = ""; + check(a, &header, items, &culprit) catch |err| { + std.log.err("h3 image decoder: {s}: {s} (the decoder reads F32 tensors at the released shapes)", .{ culprit, @errorName(err) }); + return err; + }; + return .{ .header = header, .items = items, .start = 8 + len, .bytes = file[8 + len ..] }; +} + +/// The checked tensors of `w`, each F32 value rounded to bf16 in `out`, `plan.total()` values. +pub fn read(w: Weights, out: []u16) void { + for (w.items) |it| { + const e = w.header.get(it.name).?; + const src = w.bytes[e.begin..e.end]; + for (out[it.offset..][0..count(it.part)], 0..) |*o, i| { + o.* = rounding.bits(@bitCast(std.mem.readInt(u32, src[4 * i ..][0..4], .little))); + } + } +} + +/// Synthetic weights from `seed` for the self-tests: matrices by their fan-in, gains near 1, small biases. +pub fn synthetic(a: std.mem.Allocator, plan: Plan, seed: u64, out: []u16) !void { + for (try plan.items(a), 0..) |it, i| { + var prng = std.Random.DefaultPrng.init(seed +% i *% 0x9e3779b97f4a7c15); + const r = prng.random(); + const fan: f32 = @floatFromInt(if (it.part.shape.len > 1) it.part.shape[1] else 1); + for (out[it.offset..][0..count(it.part)]) |*o| { + const u = r.float(f32) * 2 - 1; + o.* = rounding.bits(switch (it.part.fill) { + .matrix => u * @sqrt(3.0 / fan), + .bias => u * 0.1, + .gain => 1 + u * 0.25, + .layer_scale => 0.3 + u * 0.2, + .tokens => u * 1.5, + }); + } + } +} + /// A tile of h x w cells: both sides from 1 to 16 cells; returns its token count, h * w + the suffix. pub fn tokens(h: usize, w: usize) !usize { if (h == 0 or w == 0 or h > most_cells or w > most_cells) return error.H3UnsupportedVae; diff --git a/zig/src/families/h3/image_decoder_cuda.zig b/zig/src/families/h3/image_decoder_cuda.zig new file mode 100644 index 00000000000..6d6e2852629 --- /dev/null +++ b/zig/src/families/h3/image_decoder_cuda.zig @@ -0,0 +1,353 @@ +//! MiniMax-H3-Image's image decoder on CUDA, bf16 tiles in batches: K sequential fp32, h3d_finish at Metal's points. +const std = @import("std"); +const report = @import("report.zig"); +const cuda = @import("cuda"); +pub const host = @import("image_decoder.zig"); +pub const vae = @import("picture_vae.zig"); +pub const reference = @import("image_decoder_reference.zig"); +pub const host_decoder = @import("image_decoder_host.zig"); + +const W = host.width; +const F = host.ffn; + +const image align(16) = @embedFile("fatbin_h3_image_decoder").*; +const kernel_names = [_][:0]const u8{ "h3d_post_quant", "h3d_embed", "h3d_rms_norm", "h3d_layer_norm", "h3d_linear", "h3d_finish", "h3d_heads", "h3d_attention", "h3d_swiglu" }; + +/// h3_image_decoder.cu's H3dShape. +const Shape = extern struct { + tiles: u32 = 0, + h: u32 = 0, + w: u32 = 0, + tokens: u32 = 0, + rows: u32 = 0, + cols: u32 = 0, + m: u32 = 0, + n: u32 = 0, + k: u32 = 0, + mode: u32 = 0, + eps: f32 = vae.eps, + scale: f32 = host.scale, +}; + +pub const selftest = @import("image_decoder_cuda_selftest.zig"); + +pub const Timing = struct { wall: f64 = 0, gpu: f64 = 0 }; + +/// What one pass runs: the embedding, blocks [from, to), then norm_out and proj_out. +pub const Stages = struct { embed: bool = true, from: usize = 0, to: usize, final: bool = true }; + +/// Tiles a pass holds at most; `scratch` is sized at `prepare`. +pub const most_batch = 64; + +pub const seconds = @import("clock.zig").seconds; + +pub const Decoder = struct { + gpa: std.mem.Allocator, + driver: cuda.Driver, + ctx: cuda.Context, + module: cuda.Module, + functions: [kernel_names.len]cuda.Function, + queue: cuda.Stream, + plan: host.Plan, + theta: f32, + /// Every parameter in bf16 on the device, laid out as `plan` says. + weights: cuda.DeviceBuffer, + /// The raw latent [24, rows, cols] in fp32 that passes read their tiles from. + latent: ?cuda.DeviceBuffer = null, + rows: usize = 0, + cols: usize = 0, + /// One device buffer of scratch for `batch` tiles of h x w cells, `tokens` each. + scratch: ?cuda.DeviceBuffer = null, + /// The tiles the last pass held (what `stream` and `projected` read back). + passed: usize = 0, + batch: usize = 0, + h: usize = 0, + w: usize = 0, + tokens: usize = 0, + view: View = .{}, + /// A download's staging: `stream` or `projected` bytes, reused between reads. + staged: std.ArrayListUnmanaged(u8) = .empty, + + /// A scratch view's byte offset inside `scratch`. + const View = struct { + x: usize = 0, + xn: usize = 0, + wide: usize = 0, + q: usize = 0, + k: usize = 0, + v: usize = 0, + o: usize = 0, + act: usize = 0, + out: usize = 0, + tok: usize = 0, + cos: usize = 0, + sin: usize = 0, + origins: usize = 0, + acc: usize = 0, + }; + + /// `layers` blocks and `theta`, weights unfilled; heap-made so `DeviceBuffer.d` and driver pointers stay stable. + pub fn init(gpa: std.mem.Allocator, layers: usize, theta: f32) !*Decoder { + const plan = try host.Plan.init(layers); + const d = try gpa.create(Decoder); + errdefer gpa.destroy(d); + d.* = .{ .gpa = gpa, .driver = undefined, .ctx = undefined, .module = undefined, .functions = undefined, .queue = undefined, .plan = plan, .theta = theta, .weights = undefined }; + d.driver = try cuda.Driver.open(); + errdefer d.driver.close(); + d.ctx = try cuda.Context.shared(&d.driver); + errdefer d.ctx.deinit(); + d.module = try cuda.Module.load(&d.driver, &image); + errdefer d.module.unload(); + inline for (kernel_names, 0..) |name, i| d.functions[i] = try d.module.function(name); + // the legacy default stream: copies on it stay ordered with this decoder's own launches + d.queue = .{ .d = &d.driver, .handle = null }; + d.weights = try cuda.DeviceBuffer.alloc(&d.driver, plan.total() * 2); + errdefer d.weights.free(); + return d; + } + + pub fn drain(d: *Decoder) !void { + try d.ctx.makeCurrent(); + try d.driver.synchronize(); + } + + /// A failed drain keeps the decoder live for a retry rather than freeing under pending work. + pub fn deinit(d: *Decoder) void { + d.tryDeinit() catch |e| { + report.say("H3 image decoder retained at close: {t}", .{e}); + }; + } + + fn tryDeinit(d: *Decoder) !void { + try d.drain(); + d.staged.deinit(d.gpa); + if (d.scratch) |*s| s.free(); + if (d.latent) |*l| l.free(); + d.weights.free(); + d.module.unload(); + d.ctx.deinit(); + d.driver.close(); + d.gpa.destroy(d); + } + + fn function(d: *const Decoder, comptime name: []const u8) cuda.Function { + inline for (kernel_names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return d.functions[i]; + @compileError("no kernel " ++ name); + } + + fn launch(d: *const Decoder, comptime name: []const u8, grid: cuda.Dim3, block: cuda.Dim3, shared: u32, call: *cuda.Args) !void { + try cuda.launch.launch(d.function(name), .{ .grid = grid, .block = block, .shared = shared }, d.queue, call); + } + + /// The decoder's tensors of `path` (the VAE's safetensors), checked, each F32 rounded to bf16 in `plan`'s layout. + pub fn load(d: *Decoder, io: std.Io, a: std.mem.Allocator, path: []const u8) !void { + const bytes = try host_decoder.read(io, a, path, 8 << 30); + const w = try host.weights(a, bytes, d.plan); + const bits = try a.alloc(u16, d.plan.total()); + host.read(w, bits); + try d.weights.upload(0, std.mem.sliceAsBytes(bits)); + } + + /// Synthetic weights from `seed` for the self-test: matrices by their fan-in, gains near 1, small biases. + pub fn synthetic(d: *Decoder, a: std.mem.Allocator, seed: u64) !void { + const bits = try a.alloc(u16, d.plan.total()); + try host.synthetic(a, d.plan, seed, bits); + try d.weights.upload(0, std.mem.sliceAsBytes(bits)); + } + + /// The raw latent [24, rows, cols] in, and scratch for passes of up to `batch` tiles of h x w cells. + pub fn prepare(d: *Decoder, raw: []const f32, rows: usize, cols: usize, h: usize, w: usize, batch: usize) !void { + if (raw.len != try host.latentLength(rows, cols)) return error.H3BadLatentLength; + if (h > rows or w > cols) return error.H3BadTiles; + const n = try host.tokens(h, w); + if (batch == 0 or batch > most_batch) return error.H3BadTiles; + try d.ctx.makeCurrent(); + try d.drain(); + if (d.latent) |*l| l.free(); + d.latent = null; + const lat = try cuda.DeviceBuffer.fromHost(&d.driver, std.mem.sliceAsBytes(raw)); + d.latent = lat; + errdefer { + if (d.latent) |*l| l.free(); + d.latent = null; + } + if (d.scratch) |*s| s.free(); + d.scratch = null; + const m = batch * n; + // x, xn, wide, q, k, v, o, act, out (bf16 rows); tok's cells; the rotary tables; origins; acc fp32 + const sizes = [_]usize{ m * W * 2, m * W * 2, m * 2 * F * 2, m * W * 2, m * W * 2, m * W * 2, m * W * 2, m * F * 2, m * host.patch * 2, batch * h * w * host.channels * 2, n * vae.rotated * 2, n * vae.rotated * 2, batch * 8, m * 2 * F * 4 }; + var total: usize = 0; + for (sizes) |s| total += std.mem.alignForward(usize, s, 256); + const buf = try cuda.DeviceBuffer.alloc(&d.driver, total); + d.scratch = buf; + errdefer { + if (d.scratch) |*s| s.free(); + d.scratch = null; + } + var at: usize = 0; + var offs: [sizes.len]usize = undefined; + for (&offs, sizes) |*o, s| { + o.* = at; + at += std.mem.alignForward(usize, s, 256); + } + d.view = .{ .x = offs[0], .xn = offs[1], .wide = offs[2], .q = offs[3], .k = offs[4], .v = offs[5], .o = offs[6], .act = offs[7], .out = offs[8], .tok = offs[9], .cos = offs[10], .sin = offs[11], .origins = offs[12], .acc = offs[13] }; + const cs = try d.gpa.alloc(u16, n * vae.rotated); + defer d.gpa.free(cs); + const sn = try d.gpa.alloc(u16, cs.len); + defer d.gpa.free(sn); + try host.rotary(h, w, d.theta, cs, sn); + try buf.upload(d.view.cos, std.mem.sliceAsBytes(cs)); + try buf.upload(d.view.sin, std.mem.sliceAsBytes(sn)); + d.rows = rows; + d.cols = cols; + d.h = h; + d.w = w; + d.tokens = n; + d.batch = batch; + d.passed = 0; + } + + /// `which` bytes of the scratch buffer to the host, reused staging; the caller copies before the next call. + fn read(d: *Decoder, off: usize, len: usize) ![]u8 { + if (d.staged.items.len < len) try d.staged.resize(d.gpa, len); + try d.scratch.?.download(off, d.staged.items[0..len]); + return d.staged.items[0..len]; + } + + /// The stream [tiles * tokens, 1,024] (bf16 bits) after the last pass, which the next pass reads. + pub fn stream(d: *Decoder) ![]u16 { + const bytes = try d.read(d.view.x, d.passed * d.tokens * W * 2); + return @as([*]u16, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / 2]; + } + + /// proj_out's rows [tiles * tokens, 768] (bf16 bits) after the last pass that ran the final stage. + pub fn projected(d: *Decoder) ![]const u16 { + const bytes = try d.read(d.view.out, d.passed * d.tokens * host.patch * 2); + return @as([*]const u16, @ptrCast(@alignCast(bytes.ptr)))[0 .. bytes.len / 2]; + } + + fn dev(d: *const Decoder, off: usize) u64 { + return d.scratch.?.ptr + off; + } + + fn param(d: *const Decoder, offset: usize) u64 { + return d.weights.ptr + offset * 2; + } + + fn args(d: *const Decoder, ptrs: []const u64) cuda.Args { + _ = d; + var a: cuda.Args = .{}; + for (ptrs) |p| a.add(p); + return a; + } + + /// One pass: `stages` on the tiles whose first cells (row, column) are `origins`. + pub fn pass(d: *Decoder, origins: []const [2]u32, stages: Stages) !Timing { + if (d.scratch == null or origins.len == 0 or origins.len > d.batch) return error.H3BadTiles; + if (stages.from > stages.to or stages.to > d.plan.layers) return error.H3BadTiles; + for (origins) |o| { + if (o[0] + d.h > d.rows or o[1] + d.w > d.cols) return error.H3BadTiles; + } + try d.ctx.makeCurrent(); + // Drain queued work before destroying events on error. + var begin = try cuda.Event.init(&d.driver, true); + defer begin.deinit(); + var end = try cuda.Event.init(&d.driver, true); + defer end.deinit(); + errdefer cuda.completion.drain(&d.driver, d.queue, "H3 image decoder pass did not drain"); + try d.scratch.?.upload(d.view.origins, std.mem.sliceAsBytes(origins)); + const started = seconds(); + try begin.record(d.queue); + const s: Shape = .{ .tiles = @intCast(origins.len), .h = @intCast(d.h), .w = @intCast(d.w), .tokens = @intCast(d.tokens), .rows = @intCast(d.rows), .cols = @intCast(d.cols), .m = @intCast(origins.len * d.tokens) }; + if (stages.embed) { + var a = d.args(&.{ d.latent.?.ptr, d.dev(d.view.origins), d.param(d.plan.head(.post_w)), d.param(d.plan.head(.post_b)), d.dev(d.view.tok) }); + a.add(s); + try d.launch("h3d_post_quant", .{ .x = 1, .y = @intCast((origins.len * d.h * d.w + 7) / 8), .z = 1 }, .{ .x = 32, .y = 8 }, 0, &a); + var b = d.args(&.{ d.dev(d.view.tok), d.param(d.plan.head(.embed_w)), d.param(d.plan.head(.embed_b)), d.param(d.plan.head(.registers)), d.dev(d.view.x) }); + b.add(s); + try d.launch("h3d_embed", .{ .x = 4, .y = s.m, .z = 1 }, .{ .x = 256, .y = 1 }, 0, &b); + } + for (stages.from..stages.to) |i| try d.layer(s, i); + if (stages.final) { + var a = d.args(&.{ d.dev(d.view.x), d.param(d.plan.tail(.norm_w)), d.param(d.plan.tail(.norm_b)), d.dev(d.view.xn) }); + a.add(s); + try d.launch("h3d_layer_norm", .{ .x = s.m, .y = 1, .z = 1 }, .{ .x = 256 }, 0, &a); + try d.gemm(s, d.view.xn, d.plan.tail(.proj_w), d.plan.tail(.proj_b), null, d.view.out, host.patch, W); + } + try end.record(d.queue); + try end.synchronize(); + d.passed = origins.len; + return .{ .wall = seconds() - started, .gpu = @as(f64, try cuda.Event.elapsedMs(begin, end)) / 1e3 }; + } + + /// y = bf16(x w^T + b) via an ordered fp32 sum, or with `scale` the LayerScale residual. + fn gemm(d: *Decoder, s: Shape, x: usize, w: usize, b: usize, scale: ?usize, y: usize, n: usize, k: usize) !void { + var p = s; + p.n = @intCast(n); + p.k = @intCast(k); + p.mode = @intFromBool(scale != null); + var product = d.args(&.{ d.dev(x), d.param(w), d.dev(d.view.acc) }); + product.add(p); + try d.launch("h3d_linear", .{ .x = @intCast((n + 127) / 128), .y = @intCast((s.m + 127) / 128), .z = 1 }, .{ .x = 256 }, 0, &product); + const grid: cuda.Dim3 = .{ .x = @intCast((n + 31) / 32), .y = @intCast((s.m + 7) / 8), .z = 1 }; + const block: cuda.Dim3 = .{ .x = 32, .y = 8 }; + var a = d.args(&.{ d.dev(d.view.acc), d.param(b), d.param(scale orelse b), d.dev(y) }); + a.add(p); + try d.launch("h3d_finish", grid, block, 0, &a); + } + + /// Block `i` on the pass's stream in place. + fn layer(d: *Decoder, s: Shape, i: usize) !void { + const p = d.plan; + var a = d.args(&.{ d.dev(d.view.x), d.param(p.block(i, .norm1)), d.dev(d.view.xn) }); + a.add(s); + try d.launch("h3d_rms_norm", .{ .x = s.m, .y = 1, .z = 1 }, .{ .x = 256 }, 0, &a); + try d.gemm(s, d.view.xn, p.block(i, .qkv_w), p.block(i, .qkv_b), null, d.view.wide, 3 * W, W); + var h = d.args(&.{ d.dev(d.view.wide), d.dev(d.view.cos), d.dev(d.view.sin), d.dev(d.view.q), d.dev(d.view.k), d.dev(d.view.v) }); + h.add(s); + try d.launch("h3d_heads", .{ .x = s.m, .y = host.heads, .z = 1 }, .{ .x = 32 }, 0, &h); + var t = d.args(&.{ d.dev(d.view.q), d.dev(d.view.k), d.dev(d.view.v), d.dev(d.view.o) }); + t.add(s); + try d.launch("h3d_attention", .{ .x = @intCast((s.tokens + 7) / 8), .y = host.heads, .z = s.tiles }, .{ .x = 256 }, 0, &t); + try d.gemm(s, d.view.o, p.block(i, .out_w), p.block(i, .out_b), p.block(i, .scale1), d.view.x, W, W); + var r = d.args(&.{ d.dev(d.view.x), d.param(p.block(i, .norm2)), d.dev(d.view.xn) }); + r.add(s); + try d.launch("h3d_rms_norm", .{ .x = s.m, .y = 1, .z = 1 }, .{ .x = 256 }, 0, &r); + try d.gemm(s, d.view.xn, p.block(i, .w1_w), p.block(i, .w1_b), null, d.view.wide, 2 * F, W); + var u = d.args(&.{ d.dev(d.view.wide), d.dev(d.view.act) }); + u.add(s); + try d.launch("h3d_swiglu", .{ .x = @intCast(F / 32), .y = @intCast((s.m + 7) / 8), .z = 1 }, .{ .x = 32, .y = 8 }, 0, &u); + try d.gemm(s, d.view.act, p.block(i, .w2_w), p.block(i, .w2_b), p.block(i, .scale2), d.view.x, W, F); + } + + /// The decoded picture [3, 16 rows, 16 cols] (normalised) of a raw latent: tiles in batches, blended in fp32. + pub fn decode(d: *Decoder, a: std.mem.Allocator, c: *const vae.Config, raw: []const f32, rows: usize, cols: usize, layers: usize, batch: usize, out: []f32) !Timing { + const t = try host.tiles(a, c, rows, cols); + if (layers > d.plan.layers) return error.H3BadTiles; + const per = @min(batch, @min(most_batch, t.total())); + try d.prepare(raw, rows, cols, t.h, t.w, per); + var assembly = try vae.Assembler.init(a, t.rows, t.cols, 3, out); + const tile = try a.alloc(f32, 3 * t.h * t.w * vae.cell_pixels * vae.cell_pixels); + const origins = try a.alloc([2]u32, per); + var took: Timing = .{}; + var k: usize = 0; + while (k < t.total()) { + const n = @min(per, t.total() - k); + for (origins[0..n], 0..) |*o, i| { + const at = t.at(k + i); + o.* = .{ @intCast(at.row), @intCast(at.col) }; + } + const one = try d.pass(origins[0..n], .{ .to = layers }); + took.wall += one.wall; + took.gpu += one.gpu; + const projected_rows = try d.projected(); + for (0..n) |i| { + try host.unpatchify(projected_rows[i * d.tokens * host.patch ..][0 .. t.h * t.w * host.patch], t.h, t.w, tile); + const at = t.at(k + i); + try assembly.place(at.r, at.c, tile); + } + k += n; + } + return took; + } +}; diff --git a/zig/src/families/h3/image_decoder_cuda_selftest.zig b/zig/src/families/h3/image_decoder_cuda_selftest.zig new file mode 100644 index 00000000000..154d855d079 --- /dev/null +++ b/zig/src/families/h3/image_decoder_cuda_selftest.zig @@ -0,0 +1,284 @@ +//! The CUDA image decoder's selftest: synthetic weights vs the float64 reference; needs a CUDA device and the fatbin. +const std = @import("std"); +const dec = @import("image_decoder_cuda.zig"); +const host = @import("image_decoder.zig"); + +const ref = dec.reference; +const rounding = @import("bf16_round"); +const vae = dec.vae; +const W = host.width; +const side = vae.cell_pixels; + +/// Blocks chained into the picture's check; one tile also runs all 24 chained, and gates each on the GPU's own input. +const checked = 2; + +/// Errors count bf16 ULPs of max(|reference|, its row's RMS); the host's fp32 sums spread as far from its float64 ones. +pub const bounds = struct { + /// fp32 sums against float64 move a bf16 output only where they straddle a rounding point: at most 1 ULP. + pub const product_ulps: f64 = 1; + pub const product_same: f64 = 0.99; + /// One block on the GPU's own input (host fp32 sums: 95% identical, worst 4 ULPs, 7e-4); the RMS sum in f64. + pub const block_ulps: f64 = 8; + pub const block_same: f64 = 0.9; + pub const block_relative: f64 = 2e-3; + /// The output after two blocks chained (host fp32 sums: relative 2.9e-3, worst 3 ULPs) and after 24 (1.5e-2). + pub const chain_ulps: f64 = 8; + pub const chain_relative: f64 = 6e-3; + pub const deep_relative: f64 = 3e-2; + /// The assembled picture's bytes after two blocks: a value a ULP or two apart truncates at most two steps apart. + pub const bytes_same: f64 = 0.8; + pub const bytes_most: u8 = 2; +}; + +/// The picture's gate: the Metal decoder's bytes bound, 80% identical and at most 2 apart. +fn picturePass(fraction: f64, most: u8) bool { + return fraction >= bounds.bytes_same and most <= bounds.bytes_most; +} + +test "picture gate: the Metal decoder's bytes bound at its edges" { + try std.testing.expect(picturePass(bounds.bytes_same, bounds.bytes_most)); + try std.testing.expect(!picturePass(bounds.bytes_same - 0.001, 0)); + try std.testing.expect(!picturePass(1.0, bounds.bytes_most + 1)); +} + +/// bf16's ULP at magnitude v: 2^(e - 8) for v in [2^(e - 1), 2^e). +fn ulp(v: f64) f64 { + if (v == 0) return 0x1p-133; + return std.math.ldexp(@as(f64, 1), std.math.frexp(v).exponent - 8); +} + +const Stat = struct { + count: usize = 0, + same: usize = 0, + worst: f64 = 0, + diff: f64 = 0, + norm: f64 = 0, + + /// GPU bf16 bits against bf16-exact reference values, in rows of `width`. + fn add(s: *Stat, gpu: []const u16, want: []const f32, width: usize) void { + var row: usize = 0; + while (row < want.len) : (row += width) { + const wr = want[row..][0..width]; + var ms: f64 = 0; + for (wr) |v| ms += @as(f64, v) * v; + const rms = @sqrt(ms / @as(f64, @floatFromInt(width))); + for (gpu[row..][0..width], wr) |g, v| { + const x = rounding.value(g); + const d = @abs(@as(f64, x) - v); + s.count += 1; + s.same += @intFromBool(x == v); + s.diff += d * d; + s.norm += @as(f64, v) * v; + s.worst = @max(s.worst, d / ulp(@max(@abs(v), rms))); + } + } + } + + fn sameFraction(s: Stat) f64 { + return @as(f64, @floatFromInt(s.same)) / @as(f64, @floatFromInt(@max(s.count, 1))); + } + + fn relative(s: Stat) f64 { + return @sqrt(s.diff / @max(s.norm, 1e-300)); + } + + fn report(s: Stat, name: []const u8, most_ulps: f64, least_same: f64, most_relative: f64) bool { + const ok = s.worst <= most_ulps and s.sameFraction() >= least_same and s.relative() <= most_relative; + std.debug.print(" {s}: {d} values, {d:.3}% identical, worst {d:.2} ULP, relative {e:.2} ({s})\n", .{ name, s.count, 100 * s.sameFraction(), s.worst, s.relative(), if (ok) "pass" else "FAIL" }); + return ok; + } +}; + +/// A latent of rows x cols cells: its tiles in one pass for the stage checks, then decoded in passes of `batch`. +const Case = struct { rows: usize, cols: usize, batch: usize, deep: bool }; + +pub fn run(gpa: std.mem.Allocator, a: std.mem.Allocator) !bool { + const started = dec.seconds(); + const d = try dec.Decoder.init(gpa, vae.layers, 100); + defer d.deinit(); + try d.synthetic(a, 0x5eed); + std.debug.print("CUDA decoder: {d} synthetic blocks made in {d:.1} s\n", .{ vae.layers, dec.seconds() - started }); + const weights = try a.alloc(u16, d.plan.total()); + try host.synthetic(a, d.plan, 0x5eed, weights); + const model: ref.Model = .{ .w = weights, .plan = d.plan }; + const config: vae.Config = .{ .mean = @splat(0), .std = @splat(1), .tile = 256, .overlap = 64, .rope_theta = 100 }; + var ok = true; + // one 6 x 10 tile (ids on axes of 6 and 10 cells), then 2 x 2 tiles of 16 x 16 decoded in passes of 3 and 1 + for ([_]Case{ .{ .rows = 6, .cols = 10, .batch = 1, .deep = true }, .{ .rows = 20, .cols = 28, .batch = 3, .deep = false } }) |c| { + ok = try case(a, d, model, &config, c) and ok; + } + try timing(a, d, &config); + std.debug.print("selftest: {s}\n", .{if (ok) "pass" else "FAIL"}); + return ok; +} + +fn synthetic(a: std.mem.Allocator, rows: usize, cols: usize) ![]f32 { + const latent = try a.alloc(f32, try host.latentLength(rows, cols)); + var prng = std.Random.DefaultPrng.init(rows * 1000 + cols); + for (latent) |*v| v.* = (prng.random().float(f32) * 2 - 1) * 2; + return latent; +} + +/// The reference's sequences of every tile of `t`, from the latent through the embedding. +fn embedAll(a: std.mem.Allocator, model: ref.Model, latent: []const f32, c: Case, t: host.Tiles, out: []f32) !void { + const cells = t.h * t.w; + const per = out.len / t.total(); + const tile_latent = try a.alloc(f32, host.channels * cells); + for (0..t.total()) |k| { + const at = t.at(k); + ref.crop(latent, c.rows, c.cols, at.row, at.col, t.h, t.w, tile_latent); + try ref.embed(model, tile_latent, t.h, t.w, out[k * per ..][0..per]); + } +} + +fn case(a: std.mem.Allocator, d: *dec.Decoder, model: ref.Model, config: *const vae.Config, c: Case) !bool { + const latent = try synthetic(a, c.rows, c.cols); + const t = try host.tiles(a, config, c.rows, c.cols); + const tiles = t.total(); + const cells = t.h * t.w; + std.debug.print("{d} x {d} cells: {d} tiles of {d} x {d} cells, {d} tokens each\n", .{ c.rows, c.cols, tiles, t.h, t.w, cells + host.suffix }); + try d.prepare(latent, c.rows, c.cols, t.h, t.w, tiles); + const n = d.tokens; + const per = n * W; + const pixels = 3 * cells * side * side; + const origins = try a.alloc([2]u32, tiles); + for (origins, 0..) |*o, k| { + const at = t.at(k); + o.* = .{ @intCast(at.row), @intCast(at.col) }; + } + const cos = try a.alloc(u16, n * vae.rotated); + const sin = try a.alloc(u16, n * vae.rotated); + try host.rotary(t.h, t.w, config.rope_theta, cos, sin); + const scratch = try ref.Scratch.init(a, n); + var ok = true; + + // the embedding: post_quant_conv, x_embedder, the registers and the zero token + _ = try d.pass(origins, .{ .to = 0, .final = false }); + const chained = try a.alloc(f32, tiles * per); + try embedAll(a, model, latent, c, t, chained); + const embedded = try a.alloc(u16, tiles * per); + @memcpy(embedded, try d.stream()); + var embedding: Stat = .{}; + embedding.add(embedded, chained, W); + ok = embedding.report("embedding", bounds.product_ulps, bounds.product_same, 1) and ok; + + // each checked block on the GPU's own input, and the reference's chain beside it + const input = try a.alloc(f32, tiles * per); + for (0..checked) |i| { + ok = try block(d, model, scratch, origins, i, embedded, input, cos, sin) and ok; + for (0..tiles) |k| try ref.layer(model, scratch, i, chained[k * per ..][0..per], n, cos, sin); + } + + // norm_out and proj_out on the GPU's stream, then the reference's chain against the GPU's + for (input, embedded) |*o, b| o.* = rounding.value(b); + _ = try d.pass(origins, .{ .embed = false, .from = checked, .to = checked }); + const gpu_rows = try a.alloc(u16, tiles * n * host.patch); + @memcpy(gpu_rows, try d.projected()); + const want = try a.alloc(f32, cells * host.patch); + const want_bits = try a.alloc(u16, want.len); + const ref_tiles = try a.alloc(f32, tiles * pixels); + const gpu_tiles = try a.alloc(f32, tiles * pixels); + var final: Stat = .{}; + var chain: Stat = .{}; + for (0..tiles) |k| { + const gpu = gpu_rows[k * n * host.patch ..][0 .. cells * host.patch]; + try host.unpatchify(gpu, t.h, t.w, gpu_tiles[k * pixels ..][0..pixels]); + try ref.final(model, scratch, input[k * per ..][0..per], cells, want); + final.add(gpu, want, host.patch); + try ref.final(model, scratch, chained[k * per ..][0..per], cells, want); + chain.add(gpu, want, host.patch); + for (want_bits, want) |*o, v| o.* = rounding.bits(v); + try host.unpatchify(want_bits, t.h, t.w, ref_tiles[k * pixels ..][0..pixels]); + } + ok = final.report("norm_out and proj_out", bounds.product_ulps, bounds.product_same, 1) and ok; + ok = chain.report("output after 2 blocks", bounds.chain_ulps, 0, bounds.chain_relative) and ok; + + // decode in passes of c.batch and of every tile: both equal the staged tiles assembled, bit for bit + const height = c.rows * side; + const width = c.cols * side; + const staged = try assemble(a, t, gpu_tiles, 3 * height * width); + const theirs_f = try assemble(a, t, ref_tiles, staged.len); + const decoded = try a.alloc(f32, staged.len); + for ([_]usize{ c.batch, tiles }, 0..) |b, i| { + if (i == 1 and b == c.batch) continue; + _ = try d.decode(a, config, latent, c.rows, c.cols, checked, b, decoded); + const same = std.mem.eql(u32, @ptrCast(staged), @ptrCast(decoded)); + std.debug.print(" decode in passes of {d}: {s} the staged tiles assembled\n", .{ b, if (same) "bit-identical to" else "DIFFERENT from" }); + ok = ok and same; + } + const ours = try a.alloc(u8, 3 * height * width); + const theirs = try a.alloc(u8, ours.len); + try vae.pixels(decoded, height, width, ours); + try vae.pixels(theirs_f, height, width, theirs); + var same: usize = 0; + var most: u8 = 0; + for (ours, theirs) |x, y| { + same += @intFromBool(x == y); + most = @max(most, if (x > y) x - y else y - x); + } + const fraction = @as(f64, @floatFromInt(same)) / @as(f64, @floatFromInt(ours.len)); + const bytes_ok = picturePass(fraction, most); + std.debug.print(" picture bytes: {d:.3}% identical, at most {d} apart ({s})\n", .{ 100 * fraction, most, if (bytes_ok) "pass" else "FAIL" }); + ok = ok and bytes_ok; + if (c.deep) ok = try deep(a, d, model, latent, c, t, origins, cos, sin, scratch) and ok; + return ok; +} + +fn assemble(a: std.mem.Allocator, t: host.Tiles, tiles: []const f32, len: usize) ![]f32 { + const out = try a.alloc(f32, len); + var assembly = try vae.Assembler.init(a, t.rows, t.cols, 3, out); + const pixels = tiles.len / t.total(); + for (0..t.total()) |k| { + const at = t.at(k); + try assembly.place(at.r, at.c, tiles[k * pixels ..][0..pixels]); + } + return out; +} + +/// Block `i` on the GPU's own input `stream` (bf16 bits, left as the block's output) against the reference. +fn block(d: *dec.Decoder, model: ref.Model, scratch: ref.Scratch, origins: []const [2]u32, i: usize, stream: []u16, input: []f32, cos: []const u16, sin: []const u16) !bool { + for (input, stream) |*o, b| o.* = rounding.value(b); + _ = try d.pass(origins, .{ .embed = false, .from = i, .to = i + 1, .final = false }); + @memcpy(stream, try d.stream()); + const per = input.len / origins.len; + for (0..origins.len) |k| try ref.layer(model, scratch, i, input[k * per ..][0..per], d.tokens, cos, sin); + var s: Stat = .{}; + s.add(stream, input, W); + var name: [32]u8 = undefined; + return s.report(try std.fmt.bufPrint(&name, "block {d}", .{i}), bounds.block_ulps, bounds.block_same, bounds.block_relative); +} + +/// All 24 blocks chained, the GPU from the latent in one pass and the reference beside it; then each block alone. +fn deep(a: std.mem.Allocator, d: *dec.Decoder, model: ref.Model, latent: []const f32, c: Case, t: host.Tiles, origins: []const [2]u32, cos: []const u16, sin: []const u16, scratch: ref.Scratch) !bool { + try d.prepare(latent, c.rows, c.cols, t.h, t.w, t.total()); + _ = try d.pass(origins, .{ .to = vae.layers }); + const gpu_rows = try a.alloc(u16, t.total() * d.tokens * host.patch); + @memcpy(gpu_rows, try d.projected()); + const cells = t.h * t.w; + const per = d.tokens * W; + const x = try a.alloc(f32, t.total() * per); + try embedAll(a, model, latent, c, t, x); + const want = try a.alloc(f32, cells * host.patch); + var s: Stat = .{}; + for (0..t.total()) |k| { + for (0..vae.layers) |i| try ref.layer(model, scratch, i, x[k * per ..][0..per], d.tokens, cos, sin); + try ref.final(model, scratch, x[k * per ..][0..per], cells, want); + s.add(gpu_rows[k * d.tokens * host.patch ..][0 .. cells * host.patch], want, host.patch); + } + var ok = s.report("output after 24 blocks", std.math.inf(f64), 0, bounds.deep_relative); + _ = try d.pass(origins, .{ .to = 0, .final = false }); + const stream = try a.alloc(u16, x.len); + @memcpy(stream, try d.stream()); + for (0..vae.layers) |i| ok = try block(d, model, scratch, origins, i, stream, x, cos, sin) and ok; + return ok; +} + +/// All 24 blocks on a 1024 x 1024 canvas (64 x 64 cells, 5 x 5 tiles of 16 x 16), passes of 16 tiles. +fn timing(a: std.mem.Allocator, d: *dec.Decoder, config: *const vae.Config) !void { + const cells = 64; + const latent = try synthetic(a, cells, cells); + const out = try a.alloc(f32, 3 * cells * cells * side * side); + const tiles = (try host.tiles(a, config, cells, cells)).total(); + const took = try d.decode(a, config, latent, cells, cells, vae.layers, 16, out); + std.debug.print("timing: {d} tiles of 16 x 16, 24 blocks: {d:.2} s in passes, {d:.2} s on the GPU, {d:.1} ms a tile\n", .{ tiles, took.wall, took.gpu, 1000 * took.gpu / @as(f64, @floatFromInt(tiles)) }); +} diff --git a/zig/src/families/h3/image_decoder_host.zig b/zig/src/families/h3/image_decoder_host.zig new file mode 100644 index 00000000000..66b5052b23e --- /dev/null +++ b/zig/src/families/h3/image_decoder_host.zig @@ -0,0 +1,167 @@ +//! MiniMax-H3-Image's image decoder on the host: the reference decoder over every tile, all cores, no GPU. +const std = @import("std"); +const rounding = @import("bf16_round"); +const writer = @import("picture_writer"); +pub const host = @import("image_decoder.zig"); +pub const vae = @import("picture_vae.zig"); +pub const reference = @import("image_decoder_reference.zig"); + +const W = host.width; + +/// A file's bytes, or why they cannot be read. +pub fn read(io: std.Io, a: std.mem.Allocator, path: []const u8, most: usize) ![]u8 { + return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(most)) catch |err| { + std.debug.print("cannot read {s}: {s}\n", .{ path, @errorName(err) }); + return err; + }; +} + +/// `MODEL_DIR/vae/config.json` as a checked `Config`. +pub fn config(io: std.Io, a: std.mem.Allocator, model_dir: []const u8) !vae.Config { + const json = try std.fs.path.join(a, &.{ model_dir, "vae", "config.json" }); + return vae.config(a, try read(io, a, json, 1 << 20)); +} + +/// The decoded picture to RGB bytes and a PNG at `path`, LANCZOS-resized to `want_width` x `want_height` when needed. +pub fn write(io: std.Io, a: std.mem.Allocator, decoded: []const f32, height: usize, width: usize, want_width: usize, want_height: usize, path: []const u8) !void { + const rgb = try a.alloc(u8, 3 * width * height); + try vae.pixels(decoded, height, width, rgb); + const picture = if (want_width == width and want_height == height) rgb else try writer.resample.resizeWith(a, .pillow, .lanczos, writer.resample.View.of(rgb, width, height), want_width, want_height); + const file = try writer.png.encode(a, picture, want_width, want_height); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = file }); +} + +/// The decoder on the host: every parameter in bf16 as `plan` says, tiles decoded across every core. +pub const Decoder = struct { + gpa: std.mem.Allocator, + plan: host.Plan, + weights: []u16, + + /// `layers` blocks; fill `weights` with `load` or `synthetic` before `decode`. + pub fn init(gpa: std.mem.Allocator, layers: usize) !Decoder { + return .{ .gpa = gpa, .plan = try host.Plan.init(layers), .weights = try gpa.alloc(u16, 0) }; + } + + pub fn deinit(d: *Decoder) void { + d.gpa.free(d.weights); + } + + /// The decoder's tensors of `MODEL_DIR/vae/diffusion_pytorch_model.safetensors`, checked, rounded to bf16. + pub fn load(d: *Decoder, io: std.Io, a: std.mem.Allocator, model_dir: []const u8) !void { + const path = try std.fs.path.join(a, &.{ model_dir, "vae", "diffusion_pytorch_model.safetensors" }); + const bytes = try read(io, a, path, 8 << 30); + const w = try host.weights(a, bytes, d.plan); + d.weights = try d.gpa.realloc(d.weights, d.plan.total()); + host.read(w, d.weights); + } + + /// Synthetic weights from `seed` for a test, in the decoder's own buffer. + pub fn synthetic(d: *Decoder, a: std.mem.Allocator, seed: u64) !void { + d.weights = try d.gpa.realloc(d.weights, d.plan.total()); + try host.synthetic(a, d.plan, seed, d.weights); + } + + /// The raw latent [24, rows, cols] decoded to `out` [3, 16 rows, 16 cols]: a tile a worker, blended in fp32. + pub fn decode(d: *Decoder, a: std.mem.Allocator, c: *const vae.Config, raw: []const f32, rows: usize, cols: usize, layers: usize, out: []f32) !void { + return d.decodeWith(a, c, raw, rows, cols, layers, out, std.Thread, std.Thread.getCpuCount() catch 1); + } + + /// `decode` with up to `workers` workers (64 at most) from `Thread`, which a test swaps for one whose spawn fails. + pub fn decodeWith(d: *Decoder, a: std.mem.Allocator, c: *const vae.Config, raw: []const f32, rows: usize, cols: usize, layers: usize, out: []f32, comptime Thread: type, workers: usize) !void { + if (raw.len != try host.latentLength(rows, cols)) return error.H3BadLatentLength; + const t = try host.tiles(a, c, rows, cols); + if (layers > d.plan.layers) return error.H3BadTiles; + const height = rows * vae.cell_pixels; + const width = cols * vae.cell_pixels; + if (out.len != 3 * height * width) return error.H3BadLatentLength; + const model: reference.Model = .{ .w = d.weights, .plan = d.plan }; + const n = try host.tokens(t.h, t.w); + const cells = t.h * t.w; + const cos = try a.alloc(u16, n * vae.rotated); + const sin = try a.alloc(u16, cos.len); + try host.rotary(t.h, t.w, c.rope_theta, cos, sin); + const pixels = 3 * t.rows[0].len * t.cols[0].len; + const count = @min(t.total(), 64, @max(workers, 1)); + const stream = try a.alloc([]f32, count); + const proj = try a.alloc([]f32, count); + const bits = try a.alloc([]u16, count); + const tile = try a.alloc([]f32, count); + const picture = try a.alloc(f32, t.total() * pixels); // a slot a tile: a worker may not overwrite another's + const scratches = try a.alloc(reference.Scratch, count); + for (0..count) |me| { + stream[me] = try a.alloc(f32, n * W); + proj[me] = try a.alloc(f32, cells * host.patch); + bits[me] = try a.alloc(u16, cells * host.patch); + tile[me] = try a.alloc(f32, host.channels * cells); + scratches[me] = try reference.Scratch.init(a, n); + scratches[me].workers = 1; // the tiles already take every core + } + var w = Work{ .model = model, .raw = raw, .rows = rows, .cols = cols, .layers = layers, .tiles = t, .tokens = n, .cos = cos, .sin = sin, .stream = stream, .proj = proj, .bits = bits, .tile = tile, .picture = picture, .pixels = pixels, .scratches = scratches }; + const Job = struct { + /// Worker `me`'s tiles: me, me + count, ...; worker 0 is this thread. + fn run(work: *Work, me: usize, of: usize) void { + var k = me; + while (k < work.tiles.total()) : (k += of) work.one(me, k); + } + }; + { + var threads: [64]Thread = undefined; + var made: usize = 0; + defer for (threads[0..made]) |th| th.join(); // every picture slot settled before the assembly blends them + for (1..count) |me| { + threads[made] = Thread.spawn(.{}, Job.run, .{ &w, me, count }) catch |err| { + w.stop(); + return err; + }; + made += 1; + } + Job.run(&w, 0, count); + } + if (w.failed.load(.monotonic)) return error.H3BadTiles; + var assembly = try vae.Assembler.init(a, t.rows, t.cols, 3, out); + for (0..t.total()) |k| { + const at = t.at(k); + try assembly.place(at.r, at.c, picture[k * pixels ..][0..pixels]); + } + } + + /// What a decoding worker needs: the model, the latent, one slot of every scratch buffer. + const Work = struct { + model: reference.Model, + raw: []const f32, + rows: usize, + cols: usize, + layers: usize, + tiles: host.Tiles, + tokens: usize, + cos: []const u16, + sin: []const u16, + stream: [][]f32, + proj: [][]f32, + bits: [][]u16, + tile: [][]f32, + picture: []f32, + pixels: usize, + scratches: []reference.Scratch, + failed: std.atomic.Value(bool) = .init(false), + + /// Tile `k`: crop, embed, the blocks, proj_out, then unpatchify into `k`'s picture slot. + pub fn one(w: *Work, me: usize, k: usize) void { + if (w.failed.load(.monotonic)) return; + const at = w.tiles.at(k); + const h = w.tiles.h; + const ww = w.tiles.w; + const cells = h * ww; + reference.crop(w.raw, w.rows, w.cols, at.row, at.col, h, ww, w.tile[me]); + reference.embed(w.model, w.tile[me], h, ww, w.stream[me]) catch return w.stop(); + for (0..w.layers) |i| reference.layer(w.model, w.scratches[me], i, w.stream[me], w.tokens, w.cos, w.sin) catch return w.stop(); + reference.final(w.model, w.scratches[me], w.stream[me], cells, w.proj[me]) catch return w.stop(); + for (w.bits[me], w.proj[me]) |*o, v| o.* = rounding.bits(v); + host.unpatchify(w.bits[me], h, ww, w.picture[k * w.pixels ..][0..w.pixels]) catch return w.stop(); + } + + fn stop(w: *Work) void { + w.failed.store(true, .monotonic); + } + }; +}; diff --git a/zig/src/families/h3/image_decoder_host_test.zig b/zig/src/families/h3/image_decoder_host_test.zig new file mode 100644 index 00000000000..836cf2dafbf --- /dev/null +++ b/zig/src/families/h3/image_decoder_host_test.zig @@ -0,0 +1,85 @@ +//! The host image decoder (image_decoder_host.zig): tiles across cores, blended as the reference chain does. +const std = @import("std"); +const rounding = @import("bf16_round"); +const d = @import("image_decoder_host.zig"); + +const host = d.host; +const vae = d.vae; +const ref = d.reference; + +test "the host image decoder: tiles across cores, the reference chain tile by tile, bit for bit" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // 7 x 7 cells as 2 x 2 tiles of 4 x 4 cells overlapping one cell: both blends exercised + const c: vae.Config = .{ .mean = @splat(0), .std = @splat(1), .tile = 64, .overlap = 16, .rope_theta = 100 }; + var decoder = try d.Decoder.init(std.testing.allocator, 2); + defer decoder.deinit(); + try decoder.synthetic(a, 0x5eed); + var prng = std.Random.DefaultPrng.init(0x9); + const latent = try a.alloc(f32, try host.latentLength(7, 7)); + for (latent) |*v| v.* = (prng.random().float(f32) * 2 - 1) * 2; + const t = try host.tiles(a, &c, 7, 7); + try std.testing.expectEqual(@as(usize, 4), t.total()); + // the serial chain the self-test runs beside the GPU: crop, embed, the blocks, proj_out, unpatchify + const model: ref.Model = .{ .w = decoder.weights, .plan = decoder.plan }; + const n = try host.tokens(t.h, t.w); + const cells = t.h * t.w; + const cos = try a.alloc(u16, n * vae.rotated); + const sin = try a.alloc(u16, cos.len); + try host.rotary(t.h, t.w, c.rope_theta, cos, sin); + const scratch = try ref.Scratch.init(a, n); + const x = try a.alloc(f32, n * host.width); + const proj = try a.alloc(f32, cells * host.patch); + const bits = try a.alloc(u16, proj.len); + const tile_latent = try a.alloc(f32, host.channels * cells); + const tile = try a.alloc(f32, 3 * t.rows[0].len * t.cols[0].len); + const want = try a.alloc(f32, 3 * 112 * 112); + var assembly = try vae.Assembler.init(a, t.rows, t.cols, 3, want); + for (0..t.total()) |k| { + const at = t.at(k); + ref.crop(latent, 7, 7, at.row, at.col, t.h, t.w, tile_latent); + try ref.embed(model, tile_latent, t.h, t.w, x); + for (0..2) |i| try ref.layer(model, scratch, i, x, n, cos, sin); + try ref.final(model, scratch, x, cells, proj); + for (bits, proj) |*o, v| o.* = rounding.bits(v); + try host.unpatchify(bits, t.h, t.w, tile); + try assembly.place(at.r, at.c, tile); + } + const got = try a.alloc(f32, want.len); + try decoder.decode(a, &c, latent, 7, 7, 2, got); + try std.testing.expectEqualSlices(f32, want, got); +} + +/// std.Thread whose second spawn fails, as when the process runs out of threads. +const Exhausted = struct { + inner: std.Thread, + var spawned: usize = 0; + + pub fn spawn(config: std.Thread.SpawnConfig, comptime f: anytype, args: anytype) std.Thread.SpawnError!Exhausted { + spawned += 1; + if (spawned > 1) return error.ThreadQuotaExceeded; + return .{ .inner = try std.Thread.spawn(config, f, args) }; + } + + pub fn join(self: Exhausted) void { + self.inner.join(); + } +}; + +test "the host image decoder fails, not a partial picture, when a worker cannot be spawned" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const c: vae.Config = .{ .mean = @splat(0), .std = @splat(1), .tile = 64, .overlap = 16, .rope_theta = 100 }; + var decoder = try d.Decoder.init(std.testing.allocator, 2); + defer decoder.deinit(); + try decoder.synthetic(a, 0x5eed); + const latent = try a.alloc(f32, try host.latentLength(7, 7)); + @memset(latent, 0.5); + const got = try a.alloc(f32, 3 * 112 * 112); + @memset(got, -7); + try std.testing.expectError(error.ThreadQuotaExceeded, decoder.decodeWith(a, &c, latent, 7, 7, 2, got, Exhausted, 4)); + try std.testing.expectEqual(@as(usize, 2), Exhausted.spawned); + for (got) |v| try std.testing.expectEqual(@as(f32, -7), v); +} diff --git a/zig/src/families/h3/image_decoder_metal.zig b/zig/src/families/h3/image_decoder_metal.zig index 34c62531630..8eb9db17aa1 100644 --- a/zig/src/families/h3/image_decoder_metal.zig +++ b/zig/src/families/h3/image_decoder_metal.zig @@ -1,8 +1,6 @@ //! MiniMax-H3-Image's image decoder on Metal: the VAE's 2D ViT decoder in bf16 on any Apple GPU, tiles in batches. const std = @import("std"); const mtl = @import("metal"); -const st = @import("core").safetensors; -const rounding = @import("bf16_round"); const kernels = @import("h3_image_decoder_kernels"); const gpu_turn = @import("gpu_turn"); pub const host = @import("image_decoder.zig"); @@ -107,48 +105,16 @@ pub const Decoder = struct { pub fn load(d: *Decoder, path: [*:0]const u8) !void { const map = try mtl.MappedFile.open(path); defer map.deinit(); - const len = try st.headerSize(std.mem.readInt(u64, map.bytes[0..8], .little), map.size); var arena = std.heap.ArenaAllocator.init(d.gpa); defer arena.deinit(); - const a = arena.allocator(); - const header = try st.parseHeader(a, map.bytes[8..][0..len], map.size - 8 - len); - const items = try d.plan.items(a); - var culprit: []const u8 = ""; - host.check(a, &header, items, &culprit) catch |err| { - std.log.err("h3 image decoder: {s}: {s} (the decoder reads F32 tensors at the released shapes)", .{ culprit, @errorName(err) }); - return err; - }; - const data = map.bytes[8 + len ..]; - const out = d.params(); - for (items) |it| { - const e = header.get(it.name).?; - const src = data[e.begin..e.end]; - for (out[it.offset..][0..host.count(it.part)], 0..) |*o, i| { - o.* = rounding.bits(@bitCast(std.mem.readInt(u32, src[4 * i ..][0..4], .little))); - } - } + host.read(try host.weights(arena.allocator(), map.bytes[0..map.size], d.plan), d.params()); } /// Synthetic weights from `seed` for the self-test: matrices by their fan-in, gains near 1, small biases. pub fn synthetic(d: *Decoder, seed: u64) !void { var arena = std.heap.ArenaAllocator.init(d.gpa); defer arena.deinit(); - const out = d.params(); - for (try d.plan.items(arena.allocator()), 0..) |it, i| { - var prng = std.Random.DefaultPrng.init(seed +% i *% 0x9e3779b97f4a7c15); - const r = prng.random(); - const fan: f32 = @floatFromInt(if (it.part.shape.len > 1) it.part.shape[1] else 1); - for (out[it.offset..][0..host.count(it.part)]) |*o| { - const u = r.float(f32) * 2 - 1; - o.* = rounding.bits(switch (it.part.fill) { - .matrix => u * @sqrt(3.0 / fan), - .bias => u * 0.1, - .gain => 1 + u * 0.25, - .layer_scale => 0.3 + u * 0.2, - .tokens => u * 1.5, - }); - } - } + try host.synthetic(arena.allocator(), d.plan, seed, d.params()); } /// The raw latent [24, rows, cols] in, and scratch for passes of up to `batch` tiles of h x w cells. diff --git a/zig/src/families/h3/image_decoder_reference.zig b/zig/src/families/h3/image_decoder_reference.zig index 58257a5355d..3ce2a60bddd 100644 --- a/zig/src/families/h3/image_decoder_reference.zig +++ b/zig/src/families/h3/image_decoder_reference.zig @@ -1,4 +1,4 @@ -//! The image decoder on the host for the self-test: the Metal kernels' bf16 rounding points, float64 sums. +//! The image decoder on the host: the Metal kernels' bf16 rounding points and float64 sums, one tile at a time. const std = @import("std"); const rounding = @import("bf16_round"); const host = @import("image_decoder.zig"); @@ -54,8 +54,8 @@ fn dot(a: []const f32, b: []const f32) f64 { return s; } -/// y [rows, n] = bf16(x w^T + b) for x [rows, k] bf16-exact and w [n, k], b [n] in bf16; outputs split over threads. -pub fn linear(x: []const f32, w: []const u16, b: []const u16, rows: usize, n: usize, k: usize, y: []f32) !void { +/// y [rows, n] = bf16(x w^T + b), x [rows, k] bf16-exact, w [n, k] b [n] bf16; `workers` threads (0: up to 16 cores). +pub fn linearIn(x: []const f32, w: []const u16, b: []const u16, rows: usize, n: usize, k: usize, workers: usize, y: []f32) !void { std.debug.assert(x.len == rows * k and w.len == n * k and b.len == n and y.len == rows * n and k <= 8192); const Job = struct { fn run(xs: []const f32, ws: []const u16, bs: []const u16, r: usize, nn: usize, kk: usize, ys: []f32, from: usize, to: usize) void { @@ -67,19 +67,25 @@ pub fn linear(x: []const f32, w: []const u16, b: []const u16, rows: usize, n: us } }; var threads: [16]std.Thread = undefined; - const workers = @min(threads.len, std.Thread.getCpuCount() catch 1, n); + const count = @min(threads.len, if (workers == 0) threads.len else workers, std.Thread.getCpuCount() catch 1, n); + if (count <= 1) return Job.run(x, w, b, rows, n, k, y, 0, n); var made: usize = 0; defer for (threads[0..made]) |t| t.join(); - for (0..workers) |t| { - const from = n * t / workers; - const to = n * (t + 1) / workers; + for (0..count) |t| { + const from = n * t / count; + const to = n * (t + 1) / count; threads[t] = try std.Thread.spawn(.{}, Job.run, .{ x, w, b, rows, n, k, y, from, to }); made += 1; } } +/// `linearIn` over every core: the self-test's whole-tile calls. +pub fn linear(x: []const f32, w: []const u16, b: []const u16, rows: usize, n: usize, k: usize, y: []f32) !void { + return linearIn(x, w, b, rows, n, k, 0, y); +} + /// RMSNorm a row of 1,024: bf16((x * rsqrt(mean(x^2) + eps)) * g), the products in fp32. -fn rms(x: []const f32, g: []const u16, y: []f32) void { +pub fn rms(x: []const f32, g: []const u16, y: []f32) void { var s: f64 = 0; for (x) |v| s += @as(f64, v) * v; const ms: f32 = @floatCast(s / @as(f64, @floatFromInt(x.len))); @@ -123,7 +129,7 @@ pub fn embed(m: Model, latent: []const f32, h: usize, w: usize, x: []f32) !void } /// q and k of one head RMS-normed to bf16 and rotated over their first 32 dims, as the heads kernel does. -fn turn(src: []const f32, cos: []const u16, sin: []const u16, out: []f32) void { +pub fn turn(src: []const f32, cos: []const u16, sin: []const u16, out: []f32) void { var s: f64 = 0; for (src) |v| s += @as(f64, v) * v; const ms: f32 = @floatCast(s / D); @@ -138,7 +144,7 @@ fn turn(src: []const f32, cos: []const u16, sin: []const u16, out: []f32) void { @memcpy(out[vae.rotated..D], n[vae.rotated..D]); } -/// Scratch for one tile's layer. +/// Scratch for one tile's layer; `workers` threads a linear runs (0: every core), for one tile a thread. pub const Scratch = struct { xn: []f32, qkv: []f32, @@ -149,9 +155,11 @@ pub const Scratch = struct { y: []f32, wide: []f32, act: []f32, + workers: usize = 0, pub fn init(a: std.mem.Allocator, n: usize) !Scratch { var s: Scratch = undefined; + s.workers = 0; inline for (.{ .{ "xn", W }, .{ "qkv", 3 * W }, .{ "q", W }, .{ "k", W }, .{ "v", W }, .{ "o", W }, .{ "y", W }, .{ "wide", 2 * F }, .{ "act", F } }) |kv| { @field(s, kv[0]) = try a.alloc(f32, n * kv[1]); } @@ -163,7 +171,7 @@ pub const Scratch = struct { pub fn layer(m: Model, s: Scratch, index: usize, x: []f32, n: usize, cos: []const u16, sin: []const u16) !void { if (x.len != n * W or cos.len != n * vae.rotated or sin.len != cos.len) return error.H3BadLatentLength; for (0..n) |t| rms(x[t * W ..][0..W], m.block(index, .norm1), s.xn[t * W ..][0..W]); - try linear(s.xn[0 .. n * W], m.block(index, .qkv_w), m.block(index, .qkv_b), n, 3 * W, W, s.qkv[0 .. n * 3 * W]); + try linearIn(s.xn[0 .. n * W], m.block(index, .qkv_w), m.block(index, .qkv_b), n, 3 * W, W, s.workers, s.qkv[0 .. n * 3 * W]); // per head: q and k normed and turned, v as it is; stored [head, token, 64] for (0..n) |t| for (0..host.heads) |hd| { const src = s.qkv[t * 3 * W + hd * 3 * D ..][0 .. 3 * D]; @@ -193,23 +201,23 @@ pub fn layer(m: Model, s: Scratch, index: usize, x: []f32, n: usize, cos: []cons s.o[t * W + hd * D + d] = r64(acc / total); } }; - try linear(s.o[0 .. n * W], m.block(index, .out_w), m.block(index, .out_b), n, W, W, s.y[0 .. n * W]); + try linearIn(s.o[0 .. n * W], m.block(index, .out_w), m.block(index, .out_b), n, W, W, s.workers, s.y[0 .. n * W]); residual(x, s.y[0 .. n * W], m.block(index, .scale1)); for (0..n) |t| rms(x[t * W ..][0..W], m.block(index, .norm2), s.xn[t * W ..][0..W]); - try linear(s.xn[0 .. n * W], m.block(index, .w1_w), m.block(index, .w1_b), n, 2 * F, W, s.wide[0 .. n * 2 * F]); + try linearIn(s.xn[0 .. n * W], m.block(index, .w1_w), m.block(index, .w1_b), n, 2 * F, W, s.workers, s.wide[0 .. n * 2 * F]); for (0..n) |t| for (0..F) |j| { const g = s.wide[t * 2 * F + j]; const silu = r32(g / (1.0 + @exp(-g))); s.act[t * F + j] = r32(silu * s.wide[t * 2 * F + F + j]); }; - try linear(s.act[0 .. n * F], m.block(index, .w2_w), m.block(index, .w2_b), n, W, F, s.y[0 .. n * W]); + try linearIn(s.act[0 .. n * F], m.block(index, .w2_w), m.block(index, .w2_b), n, W, F, s.workers, s.y[0 .. n * W]); residual(x, s.y[0 .. n * W], m.block(index, .scale2)); } const scale: f64 = host.scale; /// x = bf16(x + bf16(y * s)) per channel, the LayerScale residual in bf16 elementwise. -fn residual(x: []f32, y: []const f32, s: []const u16) void { +pub fn residual(x: []f32, y: []const f32, s: []const u16) void { for (x, y, 0..) |*o, v, i| o.* = r32(o.* + r32(v * val(s[i % W]))); } @@ -228,7 +236,7 @@ pub fn final(m: Model, s: Scratch, x: []const f32, cells: usize, out: []f32) !vo const rstd = 1.0 / @sqrt(sq / W + eps); for (s.xn[t * W ..][0..W], row, g, b) |*o, v, gv, bv| o.* = r64((v - mean) * rstd * val(gv) + val(bv)); } - try linear(s.xn[0 .. cells * W], m.tail(.proj_w), m.tail(.proj_b), cells, host.patch, W, out); + try linearIn(s.xn[0 .. cells * W], m.tail(.proj_w), m.tail(.proj_b), cells, host.patch, W, s.workers, out); } /// A tile's raw latent [24, h, w] at cell (row, col) of a latent [24, rows, cols]. diff --git a/zig/src/families/h3/prompt.zig b/zig/src/families/h3/prompt.zig index c7fb5f5a821..fc054f7deb0 100644 --- a/zig/src/families/h3/prompt.zig +++ b/zig/src/families/h3/prompt.zig @@ -7,6 +7,7 @@ pub const picture = @import("picture.zig"); pub const tensors = @import("tensors.zig"); pub const weights = @import("prompt_weights.zig"); pub const reference = @import("prompt_reference.zig"); +pub const case = @import("prompt_case.zig"); pub const kernels = @import("prompt_kernels.zig"); const Ref = tensors.Ref; diff --git a/zig/src/families/h3/prompt_case.zig b/zig/src/families/h3/prompt_case.zig new file mode 100644 index 00000000000..b9bb0f00163 --- /dev/null +++ b/zig/src/families/h3/prompt_case.zig @@ -0,0 +1,41 @@ +//! The prompt stage's host case file: the command-line request and the picture case's tensors, tf-h3-image's layout. +const std = @import("std"); +const picture = @import("picture.zig"); +const rules = @import("picture_prompt.zig"); +const fixture = @import("checkpoint_fixture"); + +/// A text-to-image request: the size asked for, the seed and the smallest area drawn. +pub const Request = struct { size: picture.Size, seed: u64, min_area: u64 }; + +/// `WIDTHxHEIGHT` on the command line. +pub fn size(text: []const u8) !picture.Size { + const x = std.mem.indexOfScalar(u8, text, 'x') orelse return error.BadSize; + return .{ .width = try std.fmt.parseInt(usize, text[0..x], 10), .height = try std.fmt.parseInt(usize, text[x + 1 ..], 10) }; +} + +/// A presentation as a case file: the request, size and seed rows, `extra` tensors, ids, text rows; data at 16 bytes. +pub fn write(a: std.mem.Allocator, hidden: usize, p: rules.Presentation, text: []const u16, request: ?Request, draw: *const fn (u64, []f32) void, extra: []const fixture.Entry) ![]u8 { + const T = p.ids.len; + const ids = try a.alloc(i32, T); + for (ids, p.ids) |*o, id| o.* = @intCast(id); + var entries: std.ArrayList(fixture.Entry) = .empty; + if (request) |r| { + // the canvas and the seed's starting rows, ahead of the two-byte text so every tensor stays aligned + const canvas = try picture.canvas(r.size.width, r.size.height, r.min_area); + const grid = try picture.gridOf(canvas); + const start = try picture.startRows(a, grid, r.seed, draw); + const dims = try a.dupe(i32, &.{ @intCast(canvas.width), @intCast(canvas.height), @intCast(r.size.width), @intCast(r.size.height) }); + try entries.appendSlice(a, &.{ + .{ .name = "canvas", .dtype = "I32", .shape = &.{2}, .bytes = std.mem.sliceAsBytes(dims[0..2]) }, + .{ .name = "requested", .dtype = "I32", .shape = &.{2}, .bytes = std.mem.sliceAsBytes(dims[2..4]) }, + .{ .name = "noise", .dtype = "F32", .shape = try a.dupe(usize, &.{ start.len / picture.row_width, picture.row_width }), .bytes = std.mem.sliceAsBytes(start) }, + }); + } + try entries.appendSlice(a, extra); + try entries.appendSlice(a, &.{ + .{ .name = "text_tags", .dtype = "I32", .shape = &.{T}, .bytes = std.mem.sliceAsBytes(p.tags) }, + .{ .name = "ids", .dtype = "I32", .shape = &.{T}, .bytes = std.mem.sliceAsBytes(ids) }, + .{ .name = "text", .dtype = "BF16", .shape = &.{ T, hidden }, .bytes = std.mem.sliceAsBytes(text) }, + }); + return fixture.aligned(a, entries.items); +} diff --git a/zig/src/families/h3/prompt_case_test.zig b/zig/src/families/h3/prompt_case_test.zig new file mode 100644 index 00000000000..7c537a1106a --- /dev/null +++ b/zig/src/families/h3/prompt_case_test.zig @@ -0,0 +1,68 @@ +//! The prompt stage's case writer against the layout tf-h3-image-prompt wrote before it moved to the host. +const std = @import("std"); +const fixture = @import("checkpoint_fixture"); +const noise = @import("moss_noise"); +const picture = @import("picture.zig"); +const rules = @import("picture_prompt.zig"); +const case = @import("prompt_case.zig"); + +/// One id per byte, below the vision marks. +const Bytes = struct { + pub fn encode(_: Bytes, a: std.mem.Allocator, text: []const u8) ![]u32 { + const out = try a.alloc(u32, text.len); + for (out, text) |*o, c| o.* = c; + return out; + } +}; + +/// The case the Metal tool built before the writer moved: the same tensors in the same order, the fixture's own image. +fn was(a: std.mem.Allocator, hidden: usize, p: rules.Presentation, text: []const u16, request: case.Request, extra: []const fixture.Entry) ![]u8 { + const canvas = try picture.canvas(request.size.width, request.size.height, request.min_area); + const start = try picture.startRows(a, try picture.gridOf(canvas), request.seed, &noise.randn); + const dims = try a.dupe(i32, &.{ @intCast(canvas.width), @intCast(canvas.height), @intCast(request.size.width), @intCast(request.size.height) }); + const ids = try a.alloc(i32, p.ids.len); + for (ids, p.ids) |*o, id| o.* = @intCast(id); + const T = p.ids.len; + var entries: std.ArrayList(fixture.Entry) = .empty; + try entries.appendSlice(a, &.{ + .{ .name = "canvas", .dtype = "I32", .shape = &.{2}, .bytes = std.mem.sliceAsBytes(dims[0..2]) }, + .{ .name = "requested", .dtype = "I32", .shape = &.{2}, .bytes = std.mem.sliceAsBytes(dims[2..4]) }, + .{ .name = "noise", .dtype = "F32", .shape = try a.dupe(usize, &.{ start.len / picture.row_width, picture.row_width }), .bytes = std.mem.sliceAsBytes(start) }, + }); + try entries.appendSlice(a, extra); + try entries.appendSlice(a, &.{ + .{ .name = "text_tags", .dtype = "I32", .shape = &.{T}, .bytes = std.mem.sliceAsBytes(p.tags) }, + .{ .name = "ids", .dtype = "I32", .shape = &.{T}, .bytes = std.mem.sliceAsBytes(ids) }, + .{ .name = "text", .dtype = "BF16", .shape = &.{ T, hidden }, .bytes = std.mem.sliceAsBytes(text) }, + }); + const plain = try fixture.image(a, entries.items); + const header: usize = @intCast(std.mem.readInt(u64, plain[0..8], .little)); + const pad = (16 - (8 + header) % 16) % 16; + const out = try a.alloc(u8, plain.len + pad); + std.mem.writeInt(u64, out[0..8], header + pad, .little); + @memcpy(out[8..][0..header], plain[8..][0..header]); + @memset(out[8 + header ..][0..pad], ' '); + @memcpy(out[8 + header + pad ..], plain[8 + header ..]); + return out; +} + +test "the case file is byte for byte the Metal tool's: canvas, noise, anchors, tags, ids, text" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const a = arena_state.allocator(); + const marks: rules.Marks = .{ .start = 90, .image = 91, .end = 92 }; + const p = try rules.present(a, Bytes{}, marks, &.{}, "a tiny prompt"); + const hidden = 8; + const text = try a.alloc(u16, p.ids.len * hidden); + for (text, 0..) |*t, i| t.* = @intCast(0x3800 + i % 5); + const request: case.Request = .{ .size = .{ .width = 64, .height = 64 }, .seed = 42, .min_area = 64 * 64 }; + const grids = [_]i32{ 4, 4 }; + const extra = [_]fixture.Entry{.{ .name = "anchors", .dtype = "I32", .shape = &.{ 1, 2 }, .bytes = std.mem.sliceAsBytes(&grids) }}; + try std.testing.expectEqualSlices(u8, try was(a, hidden, p, text, request, &extra), try case.write(a, hidden, p, text, request, &noise.randn, &extra)); +} + +test "a WIDTHxHEIGHT size parses; anything else is refused" { + try std.testing.expectEqual(picture.Size{ .width = 2048, .height = 1536 }, try case.size("2048x1536")); + try std.testing.expectError(error.BadSize, case.size("2048")); + try std.testing.expectError(error.InvalidCharacter, case.size("axb")); +} diff --git a/zig/src/families/h3/prompt_cuda.zig b/zig/src/families/h3/prompt_cuda.zig new file mode 100644 index 00000000000..ab49511c7b7 --- /dev/null +++ b/zig/src/families/h3/prompt_cuda.zig @@ -0,0 +1,548 @@ +//! MiniMax-H3-Image's prompt stage on CUDA: Qwen3-VL text to layer 50, refiner; ~85 GiB streams via two pinned windows. +const std = @import("std"); +pub const seconds = @import("clock.zig").seconds; +const cuda = @import("cuda"); +pub const rules = @import("picture_prompt.zig"); +pub const reference = @import("prompt_reference.zig"); +pub const case = @import("prompt_case.zig"); +pub const picture = @import("picture.zig"); +pub const checkpoint = @import("checkpoint.zig"); +pub const read_ahead = @import("read_ahead.zig"); +const report = @import("report.zig"); +const bf16_round = @import("bf16_round"); + +const D = rules.head_dim; +const mode_qwen: c_int = 0; +const mode_h3: c_int = 1; + +const image align(16) = @embedFile("fatbin_h3_image_prompt").*; +const kernel_names = [_][:0]const u8{ "h3p_norm", "h3p_heads", "h3p_attention", "h3p_glu", "h3p_add", "h3p_scatter_add", "h3p_embed", "h3p_splice", "h3p_linear", "h3p_round" }; + +/// A presentation's vision rows, as prompt.Vision: the tower's merged bf16 rows at the pads and DeepStack's blocks. +pub const Vision = struct { + pads: []const u32, + rows: []const u16, + deepstack: [3][]const u16, + + fn check(v: Vision, T: usize, H: usize) !usize { + const n = v.pads.len; + for (v.pads, 0..) |at, i| if (at >= T or (i > 0 and at <= v.pads[i - 1])) return error.H3BadVisionRows; + if (v.rows.len != n * H) return error.H3BadVisionRows; + for (v.deepstack) |d| if (d.len != n * H) return error.H3BadVisionRows; + return n; + } +}; + +/// A checked weight tensor's bf16 bytes, read in place from a mapped shard. +pub const Tensor = []const u8; +/// A text layer's tensors in rules.Layer field order. +pub const LayerSet = rules.Layer(Tensor); +/// A refiner block's tensors in rules.Block field order. +pub const BlockSet = rules.Block(Tensor); + +/// Device scratch parts, 256-aligned: products write shared fp32 `p` one at a time, h3p_round to bf16 out of place. +const EncodePart = enum { x, xn, p, qb, kb, vb, att, gb, ub, act, cos, sin, idx, vision, deep }; +const RefinePart = enum { x, xn, p, qkv, att, wide, act }; + +fn Scratch(comptime Part: type) type { + return struct { + buf: cuda.DeviceBuffer, + offs: [std.enums.values(Part).len]usize, + + fn make(d: *const cuda.Driver, sizes: std.enums.EnumArray(Part, usize)) !@This() { + var s: @This() = .{ .buf = undefined, .offs = undefined }; + var total: usize = 0; + for (std.enums.values(Part), 0..) |p, i| { + s.offs[i] = total; + total += std.mem.alignForward(usize, @max(sizes.get(p), 1), 256); + } + s.buf = try cuda.DeviceBuffer.alloc(d, total); + return s; + } + + fn at(s: @This(), p: Part) u64 { + return s.buf.ptr + s.offs[@backingInt(p)]; + } + }; +} + +/// One buffered device tensor: uploaded through the runner's stages, freed by `free`. +const Dev = struct { + buf: cuda.DeviceBuffer, + + /// `bytes` into the slot kept for it, allocated on the first layer and reused. + fn into(r: *Runner, slot: *?cuda.DeviceBuffer, bytes: []const u8) !void { + if (slot.*) |*buf| { + if (buf.len < bytes.len) return error.H3UnexpectedTensor; + try r.copy(bytes, buf.ptr); + } else { + var buf = try cuda.DeviceBuffer.alloc(&r.driver, bytes.len); + errdefer { + // a staged copy can still run: drain before the destination leaves the device + cuda.completion.drain(&r.driver, r.stream, "h3 prompt cuda: an upload did not drain"); + buf.free(); + } + try r.copy(bytes, buf.ptr); + slot.* = buf; + } + } + /// The bf16 `bytes` as fp32 values, on the allocator's lifetime until the call returns. + fn asF32(a: std.mem.Allocator, bytes: []const u8) ![]f32 { + if (bytes.len % 2 != 0) return error.H3UnexpectedTensor; + const bits = std.mem.bytesAsSlice(u16, bytes); + const f = try a.alloc(f32, bits.len); + for (f, bits) |*o, b| o.* = bf16_round.value(b); + return f; + } + + fn upload(r: *Runner, bytes: []const u8) !Dev { + var d: Dev = .{ .buf = try cuda.DeviceBuffer.alloc(&r.driver, bytes.len) }; + errdefer { + // a staged copy can still run: drain before the destination leaves the device + cuda.completion.drain(&r.driver, r.stream, "h3 prompt cuda: an upload did not drain"); + d.buf.free(); + } + try r.copy(bytes, d.buf.ptr); + return d; + } + + /// The bf16 tensor converted once to fp32 on the host, for the fp32 norm-weight inputs. + fn uploadF32(r: *Runner, a: std.mem.Allocator, bytes: []const u8) !Dev { + const f = try asF32(a, bytes); + defer a.free(f); + return upload(r, std.mem.sliceAsBytes(f)); + } +}; + +/// One product's plan (cuBLASLt bf16 in, fp32 sums and out); the separate bias plan gives fused epilogues a bias only. +const Products = struct { + lt: cuda.cublaslt.Library, + workspace: cuda.DeviceBuffer, + gpa: std.mem.Allocator, + /// (rows, n, k, bias) to its plan. + plans: std.AutoHashMapUnmanaged([4]u64, cuda.cublaslt.Linear) = .empty, + + const workspace_bytes = 32 << 20; + const canonical_rows = 16384; + + fn init(gpa: std.mem.Allocator, d: *const cuda.Driver) !Products { + var lt = try cuda.cublaslt.Library.open(); + errdefer lt.close(); + return .{ .lt = lt, .gpa = gpa, .workspace = try cuda.DeviceBuffer.alloc(d, workspace_bytes) }; + } + + fn deinit(p: *Products) void { + var it = p.plans.valueIterator(); + while (it.next()) |l| l.deinit(); + p.plans.deinit(p.gpa); + p.workspace.free(); + p.lt.close(); + } + + /// y (rows, n) fp32 = x (rows, k) bf16 . w (n, k) bf16^T; bias [n] fp32 fused when nonzero. + fn run(p: *Products, stream: cuda.Stream, x: u64, w: u64, bias: u64, y: u64, rows: usize, n: usize, k: usize) !void { + const key = [4]u64{ rows, n, k, @intFromBool(bias != 0) }; + const got = try p.plans.getOrPut(p.gpa, key); + if (!got.found_existing) { + errdefer p.plans.removeByPtr(got.key_ptr); + // Prefer the canonical algorithm, but short prompts must use an algorithm valid at their own shape. + var probe = try cuda.cublaslt.Linear.initEpilogue(&p.lt, canonical_rows, n, k, .f32, workspace_bytes, if (bias != 0) .bias else .none); + defer probe.deinit(); + var l = try cuda.cublaslt.Linear.initEpilogue(&p.lt, rows, n, k, .f32, workspace_bytes, if (bias != 0) .bias else .none); + errdefer l.deinit(); + if (bias != 0) { + const epilogue: u32 = @backingInt(cuda.cublaslt.Epilogue.bias); + try p.lt.check(p.lt.api.cublasLtMatmulDescSetAttribute(l.desc, cuda.cublaslt.desc_epilogue, &epilogue, @sizeOf(u32)), "set H3 condition bias"); + } + var checked: cuda.cublaslt.Heuristic = undefined; + const s = p.lt.api.cublasLtMatmulAlgoCheck(l.handle, l.desc, l.a, l.b, l.c, l.c, &probe.algo, &checked); + if (s == 0 and checked.state == 0 and checked.workspace_size <= workspace_bytes) { + l.algo = probe.algo; + } else { + const actual = p.lt.api.cublasLtMatmulAlgoCheck(l.handle, l.desc, l.a, l.b, l.c, l.c, &l.algo, &checked); + if (actual != 0 or checked.state != 0 or checked.workspace_size > workspace_bytes) return error.NoAlgorithm; + } + l.workspace_need = checked.workspace_size; + if (bias != 0) l.epilogue = .bias; + got.value_ptr.* = l; + } + if (bias != 0) return got.value_ptr.runBias(x, w, bias, y, p.workspace.ptr, workspace_bytes, stream.handle); + try got.value_ptr.run(x, w, y, p.workspace.ptr, workspace_bytes, stream.handle); + } +}; + +pub const Runner = struct { + gpa: std.mem.Allocator, + driver: cuda.Driver, + ctx: cuda.Context, + module: cuda.Module, + functions: [kernel_names.len]cuda.Function, + stream: cuda.Stream, + products: Products, + /// Two pinned windows: a chunk's copy runs while the next is being filled. + stages: [2]cuda.copy_source.Stage = .{ .{}, .{} }, + /// GPU seconds of the last encode or refine. + gpu: f64 = 0, + + fn function(r: *const Runner, comptime name: []const u8) cuda.Function { + inline for (kernel_names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return r.functions[i]; + @compileError("no kernel " ++ name); + } + + /// A launch whose failure leaves the device drained before buffers owned by the caller are freed. + fn launch(r: *const Runner, comptime name: []const u8, grid: cuda.Dim3, threads: u32, args: *cuda.Args) !void { + errdefer cuda.completion.drain(&r.driver, r.stream, "h3 prompt cuda: a launch did not drain"); + try cuda.launch.launch(r.function(name), .{ .grid = grid, .block = .{ .x = threads } }, r.stream, args); + } + + /// The driver, context, kernels and cuBLASLt plans; heap-made: members hold `&r.driver`, which a copy would move. + pub fn init(gpa: std.mem.Allocator) !*Runner { + const r = try gpa.create(Runner); + errdefer gpa.destroy(r); + r.gpa = gpa; + r.stages = .{ .{}, .{} }; + r.gpu = 0; + r.driver = try cuda.Driver.open(); + errdefer r.driver.close(); + r.ctx = try cuda.Context.shared(&r.driver); + errdefer r.ctx.deinit(); + r.module = try cuda.Module.load(&r.driver, &image); + errdefer r.module.unload(); + inline for (kernel_names, 0..) |name, i| r.functions[i] = try r.module.function(name); + r.stream = try cuda.Stream.init(&r.driver, true); + errdefer r.stream.deinit(); + r.products = try Products.init(gpa, &r.driver); + return r; + } + + pub fn deinit(r: *Runner) void { + r.stream.synchronize() catch |e| report.say("h3 prompt cuda: work still queued at close: {t}", .{e}); + for (&r.stages) |*stage| stage.deinit(); + r.products.deinit(); + r.stream.deinit(); + r.module.unload(); + _ = r.driver.api.cuDevicePrimaryCtxRelease_v2(r.ctx.device); + r.driver.close(); + r.gpa.destroy(r); + } + + /// `bytes` to `dst` in 64 MiB windows via two pinned stages, each waited when its turn returns; stream-ordered. + fn copy(r: *Runner, bytes: []const u8, dst: u64) !void { + var done: usize = 0; + var turn: usize = 0; + while (done < bytes.len) { + const n = @min(bytes.len - done, 64 << 20); + const window = try r.stages[turn].take(&r.driver, n); + @memcpy(window, bytes[done..][0..n]); + try r.stages[turn].copyRangeTo(.{ .d = &r.driver, .ptr = dst + done, .len = n }, 0, 0, n, r.stream); + done += n; + turn ^= 1; + } + } + + fn linear(r: *const Runner, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { + var args: cuda.Args = .{}; + for ([_]u64{ x, w, y }) |p| args.add(p); + for ([_]usize{ rows, n, k }) |v| args.add(@as(c_int, @intCast(v))); + try r.launch("h3p_linear", .{ .x = @intCast((rows * n + 255) / 256) }, 256, &args); + } + + fn norm(r: *const Runner, x: u64, w: u64, y: u64, rows: usize, width: usize, eps: f32, mode: c_int) !void { + var args: cuda.Args = .{}; + for ([_]u64{ x, w, y }) |p| args.add(p); + for ([_]usize{ width, @intCast(mode) }) |v| args.add(@as(c_int, @intCast(v))); + args.add(eps); + try r.launch("h3p_norm", .{ .x = @intCast(rows) }, 256, &args); + } + + /// The text model's heads: q, k bf16 in place, normed, rotated by the [rows, 64] tables `rot` (cos, sin pointers). + fn heads(r: *const Runner, q: u64, k: u64, wq: u64, wk: u64, rot: ?[2]u64, count: usize, kv_count: usize, q_row: usize, k_row: usize, head: usize, rows: usize, eps: f32, mode: c_int) !void { + var args: cuda.Args = .{}; + for ([_]u64{ q, k, wq, wk, if (rot) |t| t[0] else 0, if (rot) |t| t[1] else 0 }) |p| args.add(p); + for ([_]usize{ count, kv_count, q_row, k_row, head, @intCast(mode), @intFromBool(rot != null) }) |v| args.add(@as(c_int, @intCast(v))); + args.add(eps); + try r.launch("h3p_heads", .{ .x = @intCast(rows), .y = @intCast((count + kv_count + 7) / 8) }, 256, &args); + } + + fn attention(r: *const Runner, q: u64, k: u64, v: u64, o: u64, rows: usize, count: usize, kv_count: usize, q_row: usize, k_row: usize, v_row: usize, head: usize, causal: bool) !void { + var args: cuda.Args = .{}; + for ([_]u64{ q, k, v, o }) |p| args.add(p); + for ([_]usize{ rows, count, kv_count, q_row, k_row, v_row, head, @intFromBool(causal) }) |n| args.add(@as(c_int, @intCast(n))); + args.add(@as(f32, 1.0 / @sqrt(@as(f32, D)))); + try r.launch("h3p_attention", .{ .x = @intCast(rows), .y = @intCast((count + 7) / 8) }, 256, &args); + } + + fn glu(r: *const Runner, g: u64, v: u64, o: u64, rows: usize, width: usize, g_row: usize, v_row: usize, mode: c_int) !void { + var args: cuda.Args = .{}; + for ([_]u64{ g, v, o }) |p| args.add(p); + for ([_]usize{ width, g_row, v_row, @intCast(mode) }) |n| args.add(@as(c_int, @intCast(n))); + try r.launch("h3p_glu", .{ .x = @intCast((width + 255) / 256), .y = @intCast(rows) }, 256, &args); + } + + fn add(r: *const Runner, x: u64, y: u64, n: usize) !void { + var args: cuda.Args = .{}; + for ([_]u64{ x, y }) |p| args.add(p); + args.add(@as(c_int, @intCast(n))); + try r.launch("h3p_add", .{ .x = @intCast((n + 255) / 256) }, 256, &args); + } + + fn round(r: *const Runner, x: u64, y: u64, n: usize) !void { + var args: cuda.Args = .{}; + for ([_]u64{ x, y }) |p| args.add(p); + args.add(@as(c_int, @intCast(n))); + try r.launch("h3p_round", .{ .x = @intCast((n + 255) / 256) }, 256, &args); + } + + fn indexed(r: *const Runner, comptime name: []const u8, a_ptr: u64, b_ptr: u64, idx: u64, rows: usize, width: usize) !void { + var args: cuda.Args = .{}; + for ([_]u64{ a_ptr, b_ptr, idx }) |p| args.add(p); + args.add(@as(c_int, @intCast(width))); + try r.launch(name, .{ .x = @intCast((width + 255) / 256), .y = @intCast(rows) }, 256, &args); + } + + /// Last-layer rows [T, hidden] bf16 for `ids` at M-RoPE `pos`, vision spliced at pads; `layer` live till return. + pub fn encode( + r: *Runner, + a: std.mem.Allocator, + g: rules.Text, + embed: Tensor, + ids: []const u32, + pos: []const [3]i32, + vision: ?Vision, + layer: *const fn (ctx: *anyopaque, li: usize) anyerror!LayerSet, + ctx: *anyopaque, + out: []u16, + ) !void { + const T = ids.len; + const H = g.hidden; + const qh = g.heads * D; + const kvh = g.kv_heads * D; + if (T == 0 or pos.len != T or out.len != T * H or g.layers == 0 or embed.len != g.vocab * H * 2) return error.H3PromptRows; + const n = if (vision) |v| try v.check(T, H) else 0; + var sizes = std.enums.EnumArray(EncodePart, usize).initFill(T * H * 2); + // `p` holds one product's fp32 rows at a time; the rest are bf16 buffers at their width + sizes.set(.p, T * @max(H, @max(qh, g.ffn)) * 4); + sizes.set(.qb, T * qh * 2); + sizes.set(.kb, T * kvh * 2); + sizes.set(.vb, T * kvh * 2); + sizes.set(.att, T * qh * 2); + sizes.set(.gb, T * g.ffn * 2); + sizes.set(.ub, T * g.ffn * 2); + sizes.set(.act, T * g.ffn * 2); + sizes.set(.cos, T * 64 * 4); + sizes.set(.sin, T * 64 * 4); + sizes.set(.idx, (T + n) * 4); + sizes.set(.vision, n * H * 2); + sizes.set(.deep, 3 * n * H * 2); + var s = try Scratch(EncodePart).make(&r.driver, sizes); + defer s.buf.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 prompt encode did not drain"); + + // the rotary tables on the host, as picture_prompt.rotary writes them + const cs = try a.alloc(f32, T * 64); + defer a.free(cs); + const sn = try a.alloc(f32, T * 64); + defer a.free(sn); + rules.rotary(cs, sn, pos, g.theta, g.sections); + try r.copy(std.mem.sliceAsBytes(cs), s.at(.cos)); + try r.copy(std.mem.sliceAsBytes(sn), s.at(.sin)); + { + const idx = try a.alloc(u32, T + n); + defer a.free(idx); + @memcpy(idx[0..T], ids); + if (vision) |v| @memcpy(idx[T..], v.pads); + try r.copy(std.mem.sliceAsBytes(idx), s.at(.idx)); + if (vision) |v| { + try r.copy(std.mem.sliceAsBytes(v.rows), s.at(.vision)); + for (v.deepstack, 0..) |d, i| try r.copy(std.mem.sliceAsBytes(d), s.at(.deep) + i * n * H * 2); + } + } + { + var table = try Dev.upload(r, embed); + defer table.buf.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 prompt embedding did not drain"); + try r.indexed("h3p_embed", table.buf.ptr, s.at(.idx), s.at(.x), T, H); + if (vision) |_| try r.indexed("h3p_splice", s.at(.x), s.at(.vision), s.at(.idx) + T * 4, n, H); + // the table leaves the device once the gather and splice have run + try r.stream.synchronize(); + } + + var begun = try cuda.Event.init(&r.driver, true); + defer begun.deinit(); + var ended = try cuda.Event.init(&r.driver, true); + defer ended.deinit(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 prompt timing did not drain"); + try begun.record(r.stream); + // one set of layer buffers for the run, each layer's tensors copied into it + var w: LayerDev = .{ .bufs = @splat(null), .ptrs = undefined }; + defer w.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 prompt layer did not drain"); + for (0..g.layers) |li| { + const set = try layer(ctx, li); + try uploadLayer(r, a, &w, set); + try r.norm(s.at(.x), w.ptrs.norm1, s.at(.xn), T, H, g.eps, mode_qwen); + try r.linear(s.at(.xn), w.ptrs.q, s.at(.p), T, qh, H); + try r.round(s.at(.p), s.at(.qb), T * qh); + try r.linear(s.at(.xn), w.ptrs.k, s.at(.p), T, kvh, H); + try r.round(s.at(.p), s.at(.kb), T * kvh); + try r.linear(s.at(.xn), w.ptrs.v, s.at(.p), T, kvh, H); + try r.round(s.at(.p), s.at(.vb), T * kvh); + try r.heads(s.at(.qb), s.at(.kb), w.ptrs.q_norm, w.ptrs.k_norm, .{ s.at(.cos), s.at(.sin) }, g.heads, g.kv_heads, qh, kvh, D, T, g.eps, mode_qwen); + try r.attention(s.at(.qb), s.at(.kb), s.at(.vb), s.at(.att), T, g.heads, g.kv_heads, qh, kvh, kvh, D, true); + try r.linear(s.at(.att), w.ptrs.o, s.at(.p), T, H, qh); + try r.add(s.at(.x), s.at(.p), T * H); + try r.norm(s.at(.x), w.ptrs.norm2, s.at(.xn), T, H, g.eps, mode_qwen); + try r.linear(s.at(.xn), w.ptrs.gate, s.at(.p), T, g.ffn, H); + try r.round(s.at(.p), s.at(.gb), T * g.ffn); + try r.linear(s.at(.xn), w.ptrs.up, s.at(.p), T, g.ffn, H); + try r.round(s.at(.p), s.at(.ub), T * g.ffn); + try r.glu(s.at(.gb), s.at(.ub), s.at(.act), T, g.ffn, g.ffn, g.ffn, mode_qwen); + try r.linear(s.at(.act), w.ptrs.down, s.at(.p), T, H, g.ffn); + try r.add(s.at(.x), s.at(.p), T * H); + if (n > 0 and li < 3) try r.indexed("h3p_scatter_add", s.at(.x), s.at(.deep) + li * n * H * 2, s.at(.idx) + T * 4, n, H); + } + try ended.record(r.stream); + try ended.synchronize(); + r.gpu = @as(f64, try cuda.Event.elapsedMs(begun, ended)) / 1000; + var dst: cuda.DeviceBuffer = .{ .d = &r.driver, .ptr = s.at(.x), .len = out.len * 2 }; + try dst.download(0, std.mem.sliceAsBytes(out)); + } + + /// A layer's 11 device buffers held for the run; a later tensor of another size is refused rather than reallocated. + const LayerDev = struct { + bufs: [11]?cuda.DeviceBuffer, + ptrs: rules.Layer(u64), + + fn free(w: *LayerDev) void { + for (&w.bufs) |*b| if (b.*) |*held| held.free(); + } + }; + + fn uploadLayer(r: *Runner, a: std.mem.Allocator, w: *LayerDev, set: LayerSet) !void { + inline for (comptime std.meta.fieldNames(LayerSet), 0..) |field, i| { + const t = @field(set, field); + if (t.len % 2 != 0) return error.H3UnexpectedTensor; + const is_norm = comptime std.mem.indexOf(u8, field, "norm") != null; + if (is_norm) { + const f = try Dev.asF32(a, t); + defer a.free(f); + try Dev.into(r, &w.bufs[i], std.mem.sliceAsBytes(f)); + } else try Dev.into(r, &w.bufs[i], t); + @field(w.ptrs, field) = w.bufs[i].?.ptr; + } + } + + /// condition_proj, refiner blocks, final norm: rows [T, text] bf16 to `out` [T, hidden]; `block` live till return. + pub fn refine( + r: *Runner, + a: std.mem.Allocator, + g: rules.Refiner, + cond_w: Tensor, + cond_b: Tensor, + final_norm: Tensor, + block: *const fn (ctx: *anyopaque, bi: usize) anyerror!BlockSet, + ctx: *anyopaque, + rows: []const u16, + out: []u16, + ) !void { + const H = g.hidden; + const inner = g.heads * D; + const T = rows.len / g.text; + if (T == 0 or rows.len != T * g.text or out.len != T * H or g.blocks == 0) return error.H3PromptRows; + var sizes = std.enums.EnumArray(RefinePart, usize).initFill(T * @max(g.text, H) * 2); + sizes.set(.p, T * @max(H, @max(3 * inner, 2 * g.mlp)) * 4); + sizes.set(.qkv, T * 3 * inner * 2); + sizes.set(.att, T * inner * 2); + sizes.set(.wide, T * 2 * g.mlp * 2); + sizes.set(.act, T * g.mlp * 2); + var s = try Scratch(RefinePart).make(&r.driver, sizes); + defer s.buf.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 refiner did not drain"); + try r.copy(std.mem.sliceAsBytes(rows), s.at(.x)); + + var begun = try cuda.Event.init(&r.driver, true); + defer begun.deinit(); + var ended = try cuda.Event.init(&r.driver, true); + defer ended.deinit(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 refiner timing did not drain"); + try begun.record(r.stream); + // condition_proj: its bias fused in fp32 into the product, then the reference's one rounding + { + var cw = try Dev.upload(r, cond_w); + defer cw.buf.free(); + var cb = try Dev.uploadF32(r, a, cond_b); + defer cb.buf.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 condition projection did not drain"); + try r.products.run(r.stream, s.at(.x), cw.buf.ptr, cb.buf.ptr, s.at(.p), T, H, g.text); + try r.round(s.at(.p), s.at(.x), T * H); + try r.stream.synchronize(); + } + const fused_row = 3 * inner; + // one set of block buffers for the run, each block's tensors copied into it + var b: BlockDev = .{ .bufs = @splat(null), .ptrs = undefined }; + defer b.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 refiner block did not drain"); + for (0..g.blocks) |bi| { + const set = try block(ctx, bi); + try uploadBlock(r, a, &b, set); + try r.norm(s.at(.x), b.get("norm1"), s.at(.xn), T, H, g.eps, mode_h3); + try r.products.run(r.stream, s.at(.xn), b.get("qkv"), 0, s.at(.p), T, 3 * inner, H); + try r.round(s.at(.p), s.at(.qkv), T * 3 * inner); + // the fused rows' q and k heads normed in place, no rotary; v sits `head` = 384 apart + try r.heads(s.at(.qkv), s.at(.qkv) + D * 2, b.get("q_norm"), b.get("k_norm"), null, g.heads, g.heads, fused_row, fused_row, 3 * D, T, g.qk_eps, mode_h3); + try r.attention(s.at(.qkv), s.at(.qkv) + D * 2, s.at(.qkv) + 2 * D * 2, s.at(.att), T, g.heads, g.heads, fused_row, fused_row, fused_row, 3 * D, false); + try r.products.run(r.stream, s.at(.att), b.get("out"), 0, s.at(.p), T, H, inner); + try r.add(s.at(.x), s.at(.p), T * H); + try r.norm(s.at(.x), b.get("norm2"), s.at(.xn), T, H, g.eps, mode_h3); + try r.products.run(r.stream, s.at(.xn), b.get("fc1"), 0, s.at(.p), T, 2 * g.mlp, H); + try r.round(s.at(.p), s.at(.wide), T * 2 * g.mlp); + try r.glu(s.at(.wide), s.at(.wide) + g.mlp * 2, s.at(.act), T, g.mlp, 2 * g.mlp, 2 * g.mlp, mode_h3); + try r.products.run(r.stream, s.at(.act), b.get("fc2"), 0, s.at(.p), T, H, g.mlp); + try r.add(s.at(.x), s.at(.p), T * H); + } + { + var fw = try Dev.uploadF32(r, a, final_norm); + defer fw.buf.free(); + errdefer cuda.completion.drain(&r.driver, r.stream, "H3 refiner norm did not drain"); + try r.norm(s.at(.x), fw.buf.ptr, s.at(.xn), T, H, g.final_eps, mode_h3); + try r.stream.synchronize(); + } + try ended.record(r.stream); + try ended.synchronize(); + r.gpu = @as(f64, try cuda.Event.elapsedMs(begun, ended)) / 1000; + // the final norm wrote bf16 rows straight to `out`'s shape + var dst: cuda.DeviceBuffer = .{ .d = &r.driver, .ptr = s.at(.xn), .len = out.len * 2 }; + try dst.download(0, std.mem.sliceAsBytes(out)); + } + + /// A refiner block's 8 tensors' device buffers, held for the run as the encoder's layer buffers are. + const BlockDev = struct { + bufs: [8]?cuda.DeviceBuffer, + ptrs: rules.Block(u64), + + fn free(b: *BlockDev) void { + for (&b.bufs) |*d| if (d.*) |*held| held.free(); + } + fn get(b: *const BlockDev, comptime field: []const u8) u64 { + return @field(b.ptrs, field); + } + }; + + fn uploadBlock(r: *Runner, a: std.mem.Allocator, b: *BlockDev, set: BlockSet) !void { + inline for (comptime std.meta.fieldNames(BlockSet), 0..) |field, i| { + const t = @field(set, field); + if (t.len % 2 != 0) return error.H3UnexpectedTensor; + const is_norm = comptime std.mem.indexOf(u8, field, "norm") != null; + if (is_norm) { + const f = try Dev.asF32(a, t); + defer a.free(f); + try Dev.into(r, &b.bufs[i], std.mem.sliceAsBytes(f)); + } else try Dev.into(r, &b.bufs[i], t); + @field(b.ptrs, field) = b.bufs[i].?.ptr; + } + } +}; + +test "condition projection keeps bias when the actual-row heuristic cannot fuse it" { + try @import("prompt_cuda_products_test.zig").check(Products, Products.run); +} diff --git a/zig/src/families/h3/prompt_cuda_products_test.zig b/zig/src/families/h3/prompt_cuda_products_test.zig new file mode 100644 index 00000000000..f1d463c57da --- /dev/null +++ b/zig/src/families/h3/prompt_cuda_products_test.zig @@ -0,0 +1,261 @@ +//! Exercise prompt plan compatibility and fused bias across canonical and actual row counts. +const std = @import("std"); +const cuda = @import("cuda"); +const bf = @import("bf16_round"); + +const cublaslt = cuda.cublaslt; +const abi = cuda.abi; +const S = cublaslt.Status; +const canonical: u64 = 16384; // Products.canonical_rows +const bias_tag: u32 = @backingInt(cublaslt.Epilogue.bias); + +const Desc = struct { epilogue: u32, bias: u64 }; +const Lay = struct { rows: u64, cols: u64 }; + +var bias_capable = false; +var matmul_calls: usize = 0; +var canonical_rejection: enum { none, status, state, workspace } = .none; +var actual_rejected = false; +var heuristic_calls: usize = 0; +var last_epilogue: u32 = 0; +var last_bias: u64 = 0; +var descs: [16]Desc = undefined; +var ndescs: usize = 0; +var lays: [48]Lay = undefined; +var nlays: usize = 0; +var lt_obj: u8 = 0; +var pref_obj: u8 = 0; + +fn reset(capable: bool) void { + bias_capable = capable; + canonical_rejection = .none; + actual_rejected = false; + matmul_calls = 0; + heuristic_calls = 0; + last_epilogue = 0; + last_bias = 0; + ndescs = 0; + nlays = 0; +} + +fn descOf(d: cublaslt.MatmulDesc) *Desc { + return @ptrCast(@alignCast(d.?)); +} + +fn layOf(l: cublaslt.Layout) *const Lay { + return @ptrCast(@alignCast(l.?)); +} + +fn ltCreate(out: *cublaslt.Handle) callconv(.c) S { + out.* = @ptrCast(<_obj); + return 0; +} + +fn ltDestroy(_: cublaslt.Handle) callconv(.c) S { + return 0; +} + +fn ltStatusName(_: S) callconv(.c) ?[*:0]const u8 { + return null; +} + +fn descCreate(out: *cublaslt.MatmulDesc, _: c_int, _: cublaslt.DataType) callconv(.c) S { + descs[ndescs] = .{ .epilogue = @backingInt(cublaslt.Epilogue.none), .bias = 0 }; + out.* = @ptrCast(&descs[ndescs]); + ndescs += 1; + return 0; +} + +fn descDestroy(_: cublaslt.MatmulDesc) callconv(.c) S { + return 0; +} + +fn descSet(desc: cublaslt.MatmulDesc, attr: c_int, value: ?*const anyopaque, _: usize) callconv(.c) S { + const d = descOf(desc); + switch (attr) { + cublaslt.desc_epilogue => d.epilogue = @as(*const u32, @ptrCast(@alignCast(value.?))).*, + cublaslt.desc_bias_pointer => d.bias = @as(*const u64, @ptrCast(@alignCast(value.?))).*, + else => {}, + } + return 0; +} + +fn layoutCreate(out: *cublaslt.Layout, _: cublaslt.DataType, rows: u64, cols: u64, _: i64) callconv(.c) S { + lays[nlays] = .{ .rows = rows, .cols = cols }; + out.* = @ptrCast(&lays[nlays]); + nlays += 1; + return 0; +} + +fn layoutDestroy(_: cublaslt.Layout) callconv(.c) S { + return 0; +} + +fn prefCreate(out: *cublaslt.Preference) callconv(.c) S { + out.* = @ptrCast(&pref_obj); + return 0; +} + +fn prefDestroy(_: cublaslt.Preference) callconv(.c) S { + return 0; +} + +fn prefSet(_: cublaslt.Preference, _: c_int, _: ?*const anyopaque, _: usize) callconv(.c) S { + return 0; +} + +/// Tag algorithms by row count so only the canonical shape can support bias. +fn getHeuristic(_: cublaslt.Handle, _: cublaslt.MatmulDesc, _: cublaslt.Layout, _: cublaslt.Layout, _: cublaslt.Layout, d: cublaslt.Layout, _: cublaslt.Preference, _: c_int, out: [*]cublaslt.Heuristic, count: *c_int) callconv(.c) S { + heuristic_calls += 1; + out[0] = std.mem.zeroes(cublaslt.Heuristic); + out[0].algo.data[0] = layOf(d).cols; + count.* = 1; + return 0; +} + +fn algoCheck(_: cublaslt.Handle, desc: cublaslt.MatmulDesc, _: cublaslt.Layout, _: cublaslt.Layout, _: cublaslt.Layout, d: cublaslt.Layout, algo: *const cublaslt.Algo, out: *cublaslt.Heuristic) callconv(.c) S { + const short = layOf(d).cols == 24; + if (short and algo.data[0] == canonical) { + out.* = std.mem.zeroes(cublaslt.Heuristic); + switch (canonical_rejection) { + .none => {}, + .status => return 7, + .state => { + out.state = 7; + return 0; + }, + .workspace => { + out.workspace_size = (32 << 20) + 1; + return 0; + }, + } + } + if (short and actual_rejected and algo.data[0] != canonical) return 7; + if (descOf(desc).epilogue == bias_tag and !(bias_capable and (algo.data[0] == canonical or short))) return 7; + out.* = std.mem.zeroes(cublaslt.Heuristic); + out.*.algo = algo.*; + return 0; +} + +/// Evaluate the selected descriptor's product and optional bias on host buffers. +fn matmul(_: cublaslt.Handle, desc: cublaslt.MatmulDesc, alpha: ?*const anyopaque, a_dev: abi.DevicePtr, a_lay: cublaslt.Layout, x_dev: abi.DevicePtr, _: cublaslt.Layout, beta: ?*const anyopaque, _: abi.DevicePtr, _: cublaslt.Layout, d_dev: abi.DevicePtr, d_lay: cublaslt.Layout, algo: ?*const cublaslt.Algo, _: abi.DevicePtr, _: usize, _: abi.Stream) callconv(.c) S { + const d = descOf(desc); + const selected = algo orelse return 7; + const expected: u64 = if (layOf(d_lay).cols == 24 and canonical_rejection != .none) 24 else canonical; + if (selected.data[0] != expected) return 7; + matmul_calls += 1; + last_epilogue = d.epilogue; + last_bias = d.bias; + const k = layOf(a_lay).rows; + const n = layOf(d_lay).rows; + const m = layOf(d_lay).cols; + const al = @as(*const f32, @ptrCast(@alignCast(alpha.?))).*; + const be = @as(*const f32, @ptrCast(@alignCast(beta.?))).*; + const w = @as([*]const u16, @ptrFromInt(a_dev)); + const x = @as([*]const u16, @ptrFromInt(x_dev)); + const y = @as([*]f32, @ptrFromInt(d_dev)); + for (0..m) |i| for (0..n) |j| { + var sum: f32 = 0; + for (0..k) |l| sum += bf.value(x[i * k + l]) * bf.value(w[j * k + l]); + if (d.epilogue == bias_tag) sum += @as([*]const f32, @ptrFromInt(d.bias))[j]; + y[i * n + j] = al * sum + be * y[i * n + j]; + }; + return 0; +} + +fn api() cublaslt.Api { + var a: cublaslt.Api = undefined; + a.cublasLtCreate = ltCreate; + a.cublasLtDestroy = ltDestroy; + a.cublasLtGetStatusName = ltStatusName; + a.cublasLtMatmulDescCreate = descCreate; + a.cublasLtMatmulDescDestroy = descDestroy; + a.cublasLtMatmulDescSetAttribute = descSet; + a.cublasLtMatrixLayoutCreate = layoutCreate; + a.cublasLtMatrixLayoutDestroy = layoutDestroy; + a.cublasLtMatmulPreferenceCreate = prefCreate; + a.cublasLtMatmulPreferenceDestroy = prefDestroy; + a.cublasLtMatmulPreferenceSetAttribute = prefSet; + a.cublasLtMatmulAlgoGetHeuristic = getHeuristic; + a.cublasLtMatmulAlgoCheck = algoCheck; + a.cublasLtMatmul = matmul; + return a; +} + +fn dev(v: anytype) u64 { + return @intCast(@intFromPtr(v)); +} + +fn drain(comptime Products: type, p: *Products) void { + var it = p.plans.valueIterator(); + while (it.next()) |l| l.deinit(); + p.plans.deinit(p.gpa); +} + +pub fn check(comptime Products: type, comptime run: anytype) !void { + const a = std.testing.allocator; + const stream: cuda.Stream = .{ .d = undefined, .handle = null }; + var ws: [64]u8 align(256) = undefined; + const x = [_]u16{ bf.bits(1), bf.bits(2), bf.bits(-1), bf.bits(0.5), bf.bits(0), bf.bits(1), bf.bits(0.25), bf.bits(-2) }; + const w = [_]u16{ bf.bits(1), 0, 0, 0, bf.bits(0.5), bf.bits(1), bf.bits(-1), bf.bits(2), bf.bits(-1), bf.bits(0.5), bf.bits(0.5), bf.bits(1) }; + const bias = [_]f32{ 10, -0.5, 0.25 }; + var y: [6]f32 = @splat(0); + const xp = dev(&x); + const wp = dev(&w); + const bp = dev(&bias); + const yp = dev(&y); + // The actual-row algorithm declines bias; the canonical algorithm accepts it only on a bias descriptor. + reset(true); + var p: Products = .{ .lt = .{ .lib = undefined, .api = api() }, .gpa = a, .workspace = .{ .d = undefined, .ptr = dev(&ws), .len = ws.len, .borrowed = true } }; + defer drain(Products, &p); + try run(&p, stream, xp, wp, bp, yp, 2, 3, 4); + try std.testing.expectEqual(@as(usize, 1), matmul_calls); + try std.testing.expectEqual(bias_tag, last_epilogue); + try std.testing.expectEqual(bp, last_bias); + try std.testing.expectEqualSlices(f32, &.{ 11, 4, 0.25, 10, -3.75, -1.125 }, &y); + const calls = heuristic_calls; + y = @splat(0); + try run(&p, stream, xp, wp, bp, yp, 2, 3, 4); + try std.testing.expectEqual(calls, heuristic_calls); // the cached plan, still fused + try std.testing.expectEqual(bias_tag, last_epilogue); + try std.testing.expectEqualSlices(f32, &.{ 11, 4, 0.25, 10, -3.75, -1.125 }, &y); + try run(&p, stream, xp, wp, 0, yp, 2, 3, 4); // no bias: the same shape unfused + try std.testing.expectEqual(@as(u32, @backingInt(cublaslt.Epilogue.none)), last_epilogue); + try std.testing.expectEqualSlices(f32, &.{ 1, 4.5, 0, 0, -3.25, -1.375 }, &y); + // the canonical algorithm not supporting .bias either: refused, nothing cached, nothing run + reset(false); + var q: Products = .{ .lt = .{ .lib = undefined, .api = api() }, .gpa = a, .workspace = .{ .d = undefined, .ptr = dev(&ws), .len = ws.len, .borrowed = true } }; + defer drain(Products, &q); + try std.testing.expectError(error.NoAlgorithm, run(&q, stream, xp, wp, bp, yp, 2, 3, 4)); + try std.testing.expectEqual(@as(u32, 0), q.plans.count()); + try std.testing.expectEqual(@as(usize, 0), matmul_calls); + // A long-row algorithm can be illegal for the real 24-token prompt; keep the checked short-row plan. + var xs: [24 * 4]u16 = undefined; + for (0..12) |i| @memcpy(xs[i * 8 ..][0..8], &x); + var ys: [24 * 3]f32 = @splat(0); + for ([_]@TypeOf(canonical_rejection){ .status, .state, .workspace }) |rejection| { + reset(true); + canonical_rejection = rejection; + var short: Products = .{ .lt = .{ .lib = undefined, .api = api() }, .gpa = a, .workspace = .{ .d = undefined, .ptr = dev(&ws), .len = ws.len, .borrowed = true } }; + defer drain(Products, &short); + for ([_]u64{ 0, bp }) |bias_ptr| { + try run(&short, stream, dev(&xs), wp, bias_ptr, dev(&ys), 24, 3, 4); + const expected: []const f32 = if (bias_ptr == 0) &.{ 1, 4.5, 0, 0, -3.25, -1.375 } else &.{ 11, 4, 0.25, 10, -3.75, -1.125 }; + for (0..12) |i| try std.testing.expectEqualSlices(f32, expected, ys[i * 6 ..][0..6]); + } + const selected = heuristic_calls; + try run(&short, stream, dev(&xs), wp, bp, dev(&ys), 24, 3, 4); + try std.testing.expectEqual(selected, heuristic_calls); + } + reset(true); + canonical_rejection = .status; + actual_rejected = true; + var rejected: Products = .{ .lt = .{ .lib = undefined, .api = api() }, .gpa = a, .workspace = .{ .d = undefined, .ptr = dev(&ws), .len = ws.len, .borrowed = true } }; + defer drain(Products, &rejected); + try std.testing.expectError(error.NoAlgorithm, run(&rejected, stream, dev(&xs), wp, bp, dev(&ys), 24, 3, 4)); + try std.testing.expectEqual(@as(u32, 0), rejected.plans.count()); + try std.testing.expectEqual(@as(usize, 0), matmul_calls); + actual_rejected = false; + try run(&rejected, stream, dev(&xs), wp, bp, dev(&ys), 24, 3, 4); + for (0..12) |i| try std.testing.expectEqualSlices(f32, &.{ 11, 4, 0.25, 10, -3.75, -1.125 }, ys[i * 6 ..][0..6]); +} diff --git a/zig/src/families/h3/prompt_reference.zig b/zig/src/families/h3/prompt_reference.zig index 219e77fd0c0..4e2f5caf4ec 100644 --- a/zig/src/families/h3/prompt_reference.zig +++ b/zig/src/families/h3/prompt_reference.zig @@ -17,7 +17,7 @@ fn bf(v: anytype) f32 { return @floatCast(bf16_round.bf16(v)); } -/// y [M, N] = bf16(x [M, K] w [N, K]^T (+ b)). +/// y [M, N] = bf16(x [M, K] w [N, K]^T (+ b)), each element's sum in order: the oracle the GPU is gated against. pub fn gemm(comptime S: type, x: []const f32, w: []const f32, b: ?[]const f32, y: []f32, M: usize, N: usize, K: usize) void { for (0..M) |m| for (0..N) |n| { var s: S = 0; @@ -114,46 +114,65 @@ pub fn add(x: []f32, y: []const f32) void { for (x, y) |*p, q| p.* = bf(@as(f64, p.*) + q); } +/// The encode pass's scratch, one buffer per activation, shared by every layer. +pub const Scratch = struct { + xn: []f32, + y: []f32, + q: []f32, + k: []f32, + v: []f32, + att: []f32, + gate: []f32, + up: []f32, + act: []f32, + + pub fn init(a: std.mem.Allocator, g: rules.Text, T: usize) !Scratch { + var s: Scratch = undefined; + inline for (.{ "xn", "y" }) |f| @field(s, f) = try a.alloc(f32, T * g.hidden); + inline for (.{ "gate", "up", "act" }) |f| @field(s, f) = try a.alloc(f32, T * g.ffn); + inline for (.{ "q", "att" }) |f| @field(s, f) = try a.alloc(f32, T * g.heads * D); + inline for (.{ "k", "v" }) |f| @field(s, f) = try a.alloc(f32, T * g.kv_heads * D); + return s; + } +}; + +/// One text layer over x [T, hidden] in place: attention, MLP, DeepStack rows after layers 0-2; callers stream weights. +pub fn encodeLayer(comptime S: type, a: std.mem.Allocator, g: rules.Text, l: Layer, li: usize, x: []f32, cos: []const f32, sin: []const f32, vision: ?Vision, s: Scratch) !void { + const T = x.len / g.hidden; + const H = g.hidden; + const qn = g.heads * D; + const kvn = g.kv_heads * D; + norm(S, x, l.norm1, s.xn, H, g.eps, .qwen); + gemm(S, s.xn, l.q, null, s.q, T, qn, H); + gemm(S, s.xn, l.k, null, s.k, T, kvn, H); + gemm(S, s.xn, l.v, null, s.v, T, kvn, H); + heads(S, s.q, g.heads, qn, D, l.q_norm, .{ cos, sin }, T, g.eps, .qwen); + heads(S, s.k, g.kv_heads, kvn, D, l.k_norm, .{ cos, sin }, T, g.eps, .qwen); + try attention(S, a, s.q, .{ .count = g.heads, .row = qn, .head = D }, s.k, s.v, .{ .count = g.kv_heads, .row = kvn, .head = D }, s.att, T, true); + gemm(S, s.att, l.o, null, s.y, T, H, qn); + add(x, s.y); + norm(S, x, l.norm2, s.xn, H, g.eps, .qwen); + gemm(S, s.xn, l.gate, null, s.gate, T, g.ffn, H); + gemm(S, s.xn, l.up, null, s.up, T, g.ffn, H); + glu(S, s.gate, s.up, s.act, T, g.ffn, g.ffn, g.ffn, .qwen); + gemm(S, s.act, l.down, null, s.y, T, H, g.ffn); + add(x, s.y); + const seen = vision orelse return; + if (li < 3) for (seen.pads, 0..) |at, i| add(x[at * H ..][0..H], seen.deepstack[li][i * H ..][0..H]); +} + /// The text model's rows leaving its last layer [T, hidden] for `ids`, cos and sin [T, 64]. pub fn encode(comptime S: type, a: std.mem.Allocator, g: rules.Text, w: Text, ids: []const u32, cos: []const f32, sin: []const f32, vision: ?Vision, out: []f32) !void { const T = ids.len; const H = g.hidden; - const qn = g.heads * D; - const kvn = g.kv_heads * D; var arena_state = std.heap.ArenaAllocator.init(a); defer arena_state.deinit(); const ar = arena_state.allocator(); const x = out; for (ids, 0..) |id, r| @memcpy(x[r * H ..][0..H], w.embed[id * H ..][0..H]); if (vision) |v| for (v.pads, 0..) |at, i| @memcpy(x[at * H ..][0..H], v.rows[i * H ..][0..H]); - const xn = try ar.alloc(f32, T * H); - const y = try ar.alloc(f32, T * H); - const q = try ar.alloc(f32, T * qn); - const k = try ar.alloc(f32, T * kvn); - const v = try ar.alloc(f32, T * kvn); - const att = try ar.alloc(f32, T * qn); - const gate = try ar.alloc(f32, T * g.ffn); - const up = try ar.alloc(f32, T * g.ffn); - const act = try ar.alloc(f32, T * g.ffn); - for (w.layers[0..g.layers], 0..) |l, li| { - norm(S, x, l.norm1, xn, H, g.eps, .qwen); - gemm(S, xn, l.q, null, q, T, qn, H); - gemm(S, xn, l.k, null, k, T, kvn, H); - gemm(S, xn, l.v, null, v, T, kvn, H); - heads(S, q, g.heads, qn, D, l.q_norm, .{ cos, sin }, T, g.eps, .qwen); - heads(S, k, g.kv_heads, kvn, D, l.k_norm, .{ cos, sin }, T, g.eps, .qwen); - try attention(S, ar, q, .{ .count = g.heads, .row = qn, .head = D }, k, v, .{ .count = g.kv_heads, .row = kvn, .head = D }, att, T, true); - gemm(S, att, l.o, null, y, T, H, qn); - add(x, y); - norm(S, x, l.norm2, xn, H, g.eps, .qwen); - gemm(S, xn, l.gate, null, gate, T, g.ffn, H); - gemm(S, xn, l.up, null, up, T, g.ffn, H); - glu(S, gate, up, act, T, g.ffn, g.ffn, g.ffn, .qwen); - gemm(S, act, l.down, null, y, T, H, g.ffn); - add(x, y); - const seen = vision orelse continue; - if (li < 3) for (seen.pads, 0..) |at, i| add(x[at * H ..][0..H], seen.deepstack[li][i * H ..][0..H]); - } + const s = try Scratch.init(ar, g, T); + for (w.layers[0..g.layers], 0..) |l, li| try encodeLayer(S, ar, g, l, li, x, cos, sin, vision, s); } /// condition_proj, the refiner's blocks over every row and its final norm: rows [T, text] to out [T, hidden]. diff --git a/zig/src/families/h3/qwen_copy.zig b/zig/src/families/h3/qwen_copy.zig new file mode 100644 index 00000000000..74cf2a7d47c --- /dev/null +++ b/zig/src/families/h3/qwen_copy.zig @@ -0,0 +1,48 @@ +//! MiniMax-H3-Image's Qwen copy of a reference: its size, the processor's size for it, and its LANCZOS pixels. +const std = @import("std"); +const picture = @import("picture"); + +/// The Qwen copy of a reference: its short edge exactly this, both sides multiples of `qwen_factor`. +pub const qwen_edge = 1024; +/// Patch 16 times merge 2: the processor's side unit, and one vision token per 2 x 2 patches. +pub const qwen_factor = 32; +pub const merge = 2; + +pub const Size = struct { width: usize, height: usize }; + +/// x rounded to the nearest integer, ties to even, as Python's round() does on a float64. +fn roundEven(x: f64) f64 { + const f = @floor(x); + const d = x - f; + if (d > 0.5) return f + 1; + if (d < 0.5) return f; + return if (@mod(f, 2) == 0) f else f + 1; +} + +/// The Qwen copy's size: a 1,024 short edge kept, else both sides times 1024 / short edge, snapped to 32 (half even). +pub fn qwenBound(width: usize, height: usize) !Size { + if (width < qwen_factor or height < qwen_factor) return error.H3ReferenceTooSmall; + const short = @min(width, height); + if (short == qwen_edge) return .{ .width = width, .height = height }; + const scale = @as(f64, qwen_edge) / @as(f64, @floatFromInt(short)); + const snap = struct { + fn side(v: f64) usize { + return @as(usize, @intFromFloat(@max(1.0, roundEven(v / qwen_factor)))) * qwen_factor; + } + }; + return .{ .width = snap.side(@as(f64, @floatFromInt(width)) * scale), .height = snap.side(@as(f64, @floatFromInt(height)) * scale) }; +} + +/// The processor's size for a Qwen copy: smart resize to multiples of 32 in its pixel bounds, a no-op when snapped. +pub fn qwenProcessed(s: Size, min_pixels: u64, max_pixels: u64) !Size { + const r = picture.patches.smartResize(@intCast(s.height), @intCast(s.width), qwen_factor, min_pixels, max_pixels) catch return error.H3ReferenceAspect; + return .{ .width = r.w, .height = r.h }; +} + +/// The Qwen copy's RGB pixels: the original when its short edge is 1,024, else Pillow's LANCZOS to `qwenBound`. +pub fn qwenCopy(a: std.mem.Allocator, rgb: picture.Rgb) !picture.Rgb { + const s = try qwenBound(rgb.width, rgb.height); + if (s.width == rgb.width and s.height == rgb.height) return .{ .width = s.width, .height = s.height, .pixels = try a.dupe(u8, rgb.pixels) }; + const view = picture.resample.View.of(rgb.pixels, rgb.width, rgb.height); + return .{ .width = s.width, .height = s.height, .pixels = try picture.resample.resizeWith(a, .pillow, .lanczos, view, s.width, s.height) }; +} diff --git a/zig/src/families/h3/read_ahead.zig b/zig/src/families/h3/read_ahead.zig index 1fcee119144..c49fa146ed7 100644 --- a/zig/src/families/h3/read_ahead.zig +++ b/zig/src/families/h3/read_ahead.zig @@ -1,49 +1,53 @@ -//! H3's shards read into the page cache ahead of their Metal mappings, through the shared reader. +//! Weight bytes read into the page cache before the GPU or a loader faults their mapping, via core's checked reader. const std = @import("std"); const core = @import("core"); +const ahead = core.checkpoint_read_ahead; -/// One shard's path and whole-file size. -pub const Shard = struct { path: [:0]const u8, size: u64 }; +/// A byte range of one file; its path outlives the read. +pub const Span = ahead.Span; -/// Every shard's bytes in `checkpoint_read_ahead.chunk` spans, read with `TF_LOAD_PREFETCH` readers. -pub fn read(gpa: std.mem.Allocator, io: std.Io, shards: []const Shard) !u64 { - const readers = try core.checkpoint_read_ahead.readers(); +/// Every span's bytes, cut into `chunk` pieces, with `TF_LOAD_PREFETCH` readers; missing or short files fail. +pub fn read(gpa: std.mem.Allocator, io: std.Io, spans: []const Span) !u64 { + const readers = try ahead.readers(); if (readers == 0) return 0; - var spans: std.ArrayList(core.checkpoint_read_ahead.Span) = .empty; - errdefer spans.deinit(gpa); - for (shards) |shard| { - var lo: u64 = 0; - while (lo < shard.size) { - const hi = lo + @min(core.checkpoint_read_ahead.chunk, shard.size - lo); - try spans.append(gpa, .{ .path = shard.path.ptr, .lo = lo, .hi = hi }); + var pieces: std.ArrayList(Span) = .empty; + errdefer pieces.deinit(gpa); + for (spans) |s| { + var lo = s.lo; + while (lo < s.hi) { + const hi = lo + @min(ahead.chunk, s.hi - lo); + try pieces.append(gpa, .{ .path = s.path, .lo = lo, .hi = hi }); lo = hi; } } - var reader = try core.checkpoint_read_ahead.start(gpa, io, try spans.toOwnedSlice(gpa), readers); + var reader = try ahead.start(gpa, io, try pieces.toOwnedSlice(gpa), readers); defer reader.deinit(); return reader.check(); } -test "h3 read ahead: complete shards, short or missing files refused, disabled reads skipped" { +test "h3 read ahead: every span's bytes across pieces and files, short or missing files refused, disabled reads skipped" { const gpa = std.testing.allocator; + const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - const big = try gpa.alloc(u8, core.checkpoint_read_ahead.chunk + 5); + const big = try gpa.alloc(u8, ahead.chunk + 5); defer gpa.free(big); @memset(big, 1); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a", .data = big }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b", .data = big[0..100] }); + try tmp.dir.writeFile(io, .{ .sub_path = "a", .data = big }); + try tmp.dir.writeFile(io, .{ .sub_path = "b", .data = big[0..100] }); const a = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/a", .{tmp.sub_path}, 0); defer gpa.free(a); const b = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/b", .{tmp.sub_path}, 0); defer gpa.free(b); - if (try core.checkpoint_read_ahead.readers() == 0) { - try std.testing.expectEqual(0, try read(gpa, std.testing.io, &.{.{ .path = a, .size = big.len + 1 }})); + if (try ahead.readers() == 0) { + try std.testing.expectEqual(0, try read(gpa, io, &.{.{ .path = b, .lo = 0, .hi = 101 }})); return; } - try std.testing.expectEqual(big.len + 100, try read(gpa, std.testing.io, &.{ .{ .path = a, .size = big.len }, .{ .path = b, .size = 100 } })); - try std.testing.expectEqual(0, try read(gpa, std.testing.io, &.{})); - try std.testing.expectError(error.LoadPrefetchRead, read(gpa, std.testing.io, &.{.{ .path = a, .size = big.len + 1 }})); - try tmp.dir.deleteFile(std.testing.io, "b"); - try std.testing.expectError(error.LoadPrefetchRead, read(gpa, std.testing.io, &.{.{ .path = b, .size = 1 }})); + // a's span crosses a piece boundary: two pieces; b's is one; an empty span reads nothing + const spans = [_]Span{ .{ .path = a, .lo = 3, .hi = ahead.chunk + 5 }, .{ .path = b, .lo = 0, .hi = 100 }, .{ .path = b, .lo = 7, .hi = 7 } }; + try std.testing.expectEqual(ahead.chunk + 2 + 100, try read(gpa, io, &spans)); + try std.testing.expectEqual(0, try read(gpa, io, &.{})); + try std.testing.expectError(error.LoadPrefetchRead, read(gpa, io, &.{.{ .path = b, .lo = 0, .hi = 101 }})); + try tmp.dir.deleteFile(io, "b"); + try std.testing.expectError(error.LoadPrefetchRead, read(gpa, io, &.{.{ .path = b, .lo = 0, .hi = 1 }})); } diff --git a/zig/src/families/h3/tensors.zig b/zig/src/families/h3/tensors.zig index 22ccc63d497..ec4d2be7d86 100644 --- a/zig/src/families/h3/tensors.zig +++ b/zig/src/families/h3/tensors.zig @@ -27,6 +27,11 @@ pub const Tensors = struct { return .{ .map = map, .buffer = buffer, .data = 8 + header_len, .names = names, .arena = arena, .path = owned }; } + /// The bytes of tensor `e` in the file, for `read_ahead`. + pub fn span(self: *const Tensors, e: st.Entry) read_ahead.Span { + return .{ .path = self.path, .lo = self.data + e.begin, .hi = self.data + e.end }; + } + pub fn deinit(self: *Tensors) void { self.buffer.deinit(); self.arena.deinit(); @@ -97,10 +102,10 @@ pub const Checkpoint = struct { /// Every shard's whole file into the page cache, ahead of the first forward's faults. pub fn readAhead(self: *const Checkpoint, gpa: std.mem.Allocator, io: std.Io) !void { - const shards = try gpa.alloc(read_ahead.Shard, self.shards.len); - defer gpa.free(shards); - for (shards, self.shards) |*s, *shard| s.* = .{ .path = shard.path, .size = shard.map.size }; - _ = try read_ahead.read(gpa, io, shards); + const whole = try gpa.alloc(read_ahead.Span, self.shards.len); + defer gpa.free(whole); + for (whole, self.shards) |*s, *shard| s.* = .{ .path = shard.path, .lo = 0, .hi = shard.map.size }; + _ = try read_ahead.read(gpa, io, whole); } pub fn entry(self: *const Checkpoint, name: []const u8) ?st.Entry { diff --git a/zig/tests/cuda/contract_h3_image_decoder.zig b/zig/tests/cuda/contract_h3_image_decoder.zig new file mode 100644 index 00000000000..9259b02dfcf --- /dev/null +++ b/zig/tests/cuda/contract_h3_image_decoder.zig @@ -0,0 +1,415 @@ +//! MiniMax-H3-Image's decoder CUDA kernels under the contract, each against its float64 formula. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_h3_image_ref.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; + +/// The decoder's kernels: each symbol once, h3d_finish at both modes. +pub const Which = enum { post_quant, embed, rms_norm, layer_norm, linear, finish_bias, finish_scale, heads, attention, swiglu }; + +/// h3_image_decoder.cu's H3dShape, the trailing argument every decoder kernel takes. +const Shape64 = extern struct { + tiles: u32 = 0, + h: u32 = 0, + w: u32 = 0, + tokens: u32 = 0, + rows: u32 = 0, + cols: u32 = 0, + m: u32 = 0, + n: u32 = 0, + k: u32 = 0, + mode: u32 = 0, + eps: f32 = 1e-5, + scale: f32 = 0.125, +}; + +/// A dot of 24 (post_quant, embed). +fn dot24(_: c.Shape) usize { + return 24; +} +/// The norms' row of 1024: 4 terms a thread's chain, then 5 warp levels and 8 partials serial. +fn normChain(_: c.Shape) usize { + return 4 + 5 + 8; +} +/// heads' 64 squares: 2 terms a lane, then the 5 warp levels. +fn headChain(_: c.Shape) usize { + return 2 + 5 + 2; +} +/// attention's key dots of 64 in a lane's chain, then the value sum over every key. +fn attnChain(s: c.Shape) usize { + return 64 + s.n + 8; +} +fn none(_: c.Shape) usize { + return 0; +} + +const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +/// h3d_linear's dot over k, in increasing K. +fn dotK(s: c.Shape) usize { + return s.k; +} + +pub fn spec(w: Which) c.Spec { + return switch (w) { + .post_quant => .{ .name = "cuda h3 image decoder h3d_post_quant", .accum = .f32, .depth = dot24, .ops = 1, .out = .bf16, .served = &.{ .{ .rows = 1, .n = 256, .k = 24 }, .{ .rows = 4, .n = 256, .k = 24 }, .{ .rows = 2, .n = 64, .k = 24 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = "the 24-term dot's bf16 output hides a bf16 sum's error" } }, + .embed => .{ .name = "cuda h3 image decoder h3d_embed", .accum = .f32, .depth = dot24, .ops = 1, .out = .bf16, .served = &.{ .{ .rows = 1, .n = 256, .k = 24 }, .{ .rows = 2, .n = 64, .k = 24 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = "the 24-term dot's bf16 output hides a bf16 sum's error" } }, + .rms_norm => .{ .name = "cuda h3 image decoder h3d_rms_norm", .accum = .f32, .depth = normChain, .ops = 8, .mids = 0, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 1024, .k = 1024 }, .{ .rows = 261, .n = 1024, .k = 1024 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .layer_norm => .{ .name = "cuda h3 image decoder h3d_layer_norm", .accum = .f32, .depth = normChain, .ops = 10, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 1024, .k = 1024 }, .{ .rows = 261, .n = 1024, .k = 1024 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .linear => .{ .name = "cuda h3 image decoder h3d_linear", .accum = .f32, .depth = dotK, .ops = 0, .out = .f32, .served = &.{ .{ .rows = 4, .n = 128, .k = 256 }, .{ .rows = 8, .n = 256, .k = 1024 }, .{ .rows = 8, .n = 128, .k = 4096 }, .{ .rows = 136, .n = 200, .k = 1000 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = "each output sums K in increasing order with individually rounded fp32 multiplies and adds" } }, + .finish_bias => .{ .name = "cuda h3 image decoder h3d_finish bias", .accum = .none, .depth = none, .ops = 1, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 1024, .k = 1 }, .{ .rows = 16, .n = 768, .k = 1 } } }, + .finish_scale => .{ .name = "cuda h3 image decoder h3d_finish layerscale", .accum = .none, .depth = none, .ops = 1, .mids = 2, .out = .bf16, .in_place = true, .served = &.{ .{ .rows = 8, .n = 1024, .k = 1 }, .{ .rows = 16, .n = 768, .k = 1 } } }, + .heads => .{ .name = "cuda h3 image decoder h3d_heads", .accum = .f32, .depth = headChain, .ops = 8, .mids = 4, .out = .bf16, .served = &.{ .{ .rows = 1, .n = 261, .k = 3072 }, .{ .rows = 2, .n = 64, .k = 3072 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .attention => .{ .name = "cuda h3 image decoder h3d_attention", .accum = .f32, .depth = attnChain, .ops = 8, .mids = 0, .out = .bf16, .served = &.{ .{ .rows = 1, .n = 261, .k = 64 }, .{ .rows = 2, .n = 64, .k = 64 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = "softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error" } }, + .swiglu => .{ .name = "cuda h3 image decoder h3d_swiglu", .accum = .none, .depth = none, .ops = 4, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 4096, .k = 8192 }, .{ .rows = 65, .n = 4096, .k = 8192 } } }, + }; +} + +pub fn symbol(w: Which) [:0]const u8 { + return switch (w) { + .post_quant => "h3d_post_quant", + .embed => "h3d_embed", + .rms_norm => "h3d_rms_norm", + .layer_norm => "h3d_layer_norm", + .linear => "h3d_linear", + .finish_bias, .finish_scale => "h3d_finish", + .heads => "h3d_heads", + .attention => "h3d_attention", + .swiglu => "h3d_swiglu", + }; +} + +pub const Dec = struct { + rig: rig_.Rig, + which: Which, + f: cuda.Function, + shape: c.Shape = undefined, + arena: std.heap.ArenaAllocator, + in: ref.In = .{}, + bufs: [8]u64 = undefined, + nbufs: usize = 0, + /// In-place buffers' starting bytes, re-uploaded before every launch (the same order as `bufs`). + fresh: []const u8 = &.{}, + outs: usize = 0, + /// Grid geometry the launch derives from the prepared inputs. + p: Shape64 = .{}, + + pub fn deinit(self: *Dec) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn kernel(self: *Dec) g.Kernel { + return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Dec); + + /// `n` values uniform in [lo, hi), bf16-valued when `half`, some planted non-finite when `plant`. + fn values(self: *Dec, n: usize, lo: f64, hi: f64, fill: g.Fill, rng: std.Random, half: bool, plant: bool) ![]f64 { + const v = try self.arena.allocator().alloc(f64, n); + for (v, 0..) |*x, i| { + const r = lo + (hi - lo) * rng.float(f64); + x.* = switch (fill) { + .stress => @floatFromInt(@as(i64, @intFromFloat(@round(r * 8)))), + else => r, + }; + if (i % 61 == 7 and fill != .stress) x.* *= 6; + x.* = if (half) ref.bf(x.*) else @as(f32, @floatCast(x.*)); + } + if (fill == .nonfinite and plant) { + const at = [_]usize{ n / 3, n / 2, n - 1 }; + const put = [_]f64{ std.math.nan(f64), std.math.inf(f64), -std.math.inf(f64) }; + for (at, put) |at_, x| v[at_] = x; + } + return v; + } + + /// Upload `v` as bf16 (half) or fp32, as an input; returns the slot pointer. + fn upload(self: *Dec, v: []const f64, half: bool) !u64 { + return self.bytes(try self.encode(v, half)); + } + + fn encode(self: *Dec, v: []const f64, half: bool) ![]const u8 { + const al = self.arena.allocator(); + if (half) { + const h = try al.alloc(u16, v.len); + for (h, v) |*o, x| o.* = c.toBf16(@floatCast(x)); + return std.mem.sliceAsBytes(h); + } + const f = try al.alloc(f32, v.len); + for (f, v) |*o, x| o.* = @floatCast(x); + return std.mem.sliceAsBytes(f); + } + + fn bytes(self: *Dec, b: []const u8) !u64 { + self.bufs[self.nbufs] = try self.rig.input(b); + self.nbufs += 1; + return self.bufs[self.nbufs - 1]; + } + + fn ints(self: *Dec, v: []const u32) !u64 { + return self.bytes(std.mem.sliceAsBytes(v)); + } + + fn output(self: *Dec, len: usize) !u64 { + self.bufs[self.nbufs] = try self.rig.output(len); + self.nbufs += 1; + return self.bufs[self.nbufs - 1]; + } + + /// An in-place buffer: an output slot whose starting bytes are restored before every launch. + fn inPlace(self: *Dec, v: []const f64, half: bool) !u64 { + const bytes_ = try self.encode(v, half); + self.bufs[self.nbufs] = try self.rig.output(bytes_.len); + self.nbufs += 1; + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.bufs[self.nbufs - 1], .len = bytes_.len }; + try b.upload(0, bytes_); + return self.bufs[self.nbufs - 1]; + } + + /// The latent tile origins: tile i crops at ((i % 3) * 4, (i % 5) * 4) of a 48x48 plane. + fn origins(self: *Dec, tiles: usize) ![]u32 { + const v = try self.arena.allocator().alloc(u32, 2 * tiles); + for (0..tiles) |i| { + v[2 * i] = @intCast(i % 3 * @as(usize, 4)); + v[2 * i + 1] = @intCast(i % 5 * @as(usize, 4)); + } + return v; + } + + pub fn prepare(self: *Dec, s: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.nbufs = 0; + self.shape = s; + self.p = .{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + switch (self.which) { + .post_quant => { + // s.rows tiles of h*w cells over a 48x48 latent plane; cells = s.n needs h*w = s.n. + if (s.n != 256 and s.n != 64) return false; + const h: usize = if (s.n == 256) 16 else 8; + const w: usize = s.n / h; + const tiles = s.rows; + const plane = 48 * 48; + const lat = try self.values(24 * plane, -2, 2, fill, rng, false, true); + const pw = try self.values(24 * 24, -0.5, 0.5, .random, rng, true, false); + const pb = try self.values(24, -0.5, 0.5, .random, rng, true, false); + self.in = .{ .a = lat, .b = pw, .d = pb, .rows = 48, .n = 48, .k = 24, .tiles = tiles, .h = h, .w = w, .ints = try self.origins(tiles) }; + _ = try self.upload(lat, false); + _ = try self.ints(self.in.ints); + _ = try self.upload(pw, true); + _ = try self.upload(pb, true); + _ = try self.output(tiles * s.n * 24 * 2); + self.outs = tiles * s.n * 24; + self.p = .{ .tiles = @intCast(tiles), .h = @intCast(h), .w = @intCast(w), .rows = 48, .cols = 48 }; + }, + .embed => { + if (s.n != 256 and s.n != 64) return false; + const h: usize = if (s.n == 256) 16 else 8; + const w: usize = s.n / h; + const cells = s.n; + const tokens = cells + 5; + const tiles = s.rows; + const tok = try self.values(tiles * cells * 24, -2, 2, fill, rng, true, true); + const ew = try self.values(1024 * 24, -0.5, 0.5, .random, rng, true, false); + const eb = try self.values(1024, -0.5, 0.5, .random, rng, true, false); + const regs = try self.values(4 * 1024, -1, 1, .random, rng, true, false); + self.in = .{ .a = tok, .b = ew, .d = eb, .e = regs, .k = 24, .tiles = tiles, .tokens = tokens, .h = h, .w = w }; + _ = try self.upload(tok, true); + _ = try self.upload(ew, true); + _ = try self.upload(eb, true); + _ = try self.upload(regs, true); + _ = try self.output(tiles * tokens * 1024 * 2); + self.outs = tiles * tokens * 1024; + self.p = .{ .tiles = @intCast(tiles), .h = @intCast(h), .w = @intCast(w), .tokens = @intCast(tokens) }; + }, + .rms_norm, .layer_norm => { + if (s.n != 1024 or s.k != 1024) return false; + const x = try self.values(s.rows * 1024, -2, 2, fill, rng, true, true); + // layer norm's stress rows mirror their first half: the mean is 0 and both fp32 passes are exact + if (fill == .stress and self.which == .layer_norm) for (0..s.rows) |r| for (0..512) |i| { + x[r * 1024 + 512 + i] = -x[r * 1024 + i]; + }; + const gg = try self.values(1024, 0.5, 1.5, .random, rng, true, false); + const bb = if (self.which == .layer_norm) try self.values(1024, -1, 1, .random, rng, true, false) else gg; + self.in = .{ .a = x, .b = gg, .d = bb, .rows = s.rows, .n = 1024, .k = 1024, .eps = 1e-5 }; + _ = try self.upload(x, true); + _ = try self.upload(gg, true); + if (self.which == .layer_norm) _ = try self.upload(bb, true); + _ = try self.output(s.rows * 1024 * 2); + self.outs = s.rows * 1024; + self.p = .{ .m = @intCast(s.rows), .eps = 1e-5 }; + }, + .linear => { + if (s.k > 8192) return false; + const x = try self.values(s.rows * s.k, -1, 1, fill, rng, true, true); + const w = try self.values(s.n * s.k, -1, 1, .random, rng, true, false); + self.in = .{ .a = x, .b = w, .rows = s.rows, .n = s.n, .k = s.k }; + _ = try self.upload(x, true); + _ = try self.upload(w, true); + _ = try self.output(s.rows * s.n * 4); + self.outs = s.rows * s.n; + self.p = .{ .m = @intCast(s.rows), .n = @intCast(s.n), .k = @intCast(s.k) }; + }, + .finish_bias, .finish_scale => { + const acc = try self.values(s.rows * s.n, -2, 2, fill, rng, false, true); + const bias = try self.values(s.n, -0.5, 0.5, .random, rng, true, false); + const scale = try self.values(s.n, 0.5, 1.5, .random, rng, true, false); + const y0 = if (self.which == .finish_scale) try self.values(s.rows * s.n, -1, 1, .random, rng, true, false) else acc; + const mode: u32 = if (self.which == .finish_scale) 1 else 0; + self.in = .{ .a = acc, .b = bias, .d = scale, .e = y0, .rows = s.rows, .n = s.n, .k = 1, .mode = mode }; + _ = try self.upload(acc, false); + _ = try self.upload(bias, true); + _ = try self.upload(scale, true); + if (self.which == .finish_scale) { + _ = try self.inPlace(y0, true); + self.fresh = try self.encode(y0, true); + } else _ = try self.output(s.rows * s.n * 2); + self.outs = s.rows * s.n; + self.p = .{ .m = @intCast(s.rows), .n = @intCast(s.n), .mode = mode }; + }, + .heads => { + // s.rows tiles of s.n tokens; the qkv product's rows [tiles*tokens, 3072]. + if (s.k != 3072 or s.n > 288) return false; + const tiles = s.rows; + const tokens = s.n; + const rows = tiles * tokens; + const qkv = try self.values(rows * 3072, 1, 2, fill, rng, true, true); + const cs = try self.values(tokens * 32, 0.9, 1.0, .random, rng, true, false); + const sn = try self.values(tokens * 32, 0, 0.01, .random, rng, true, false); + self.in = .{ .a = qkv, .b = cs, .d = sn, .rows = rows, .k = 3072, .tiles = tiles, .tokens = tokens, .eps = 1e-5 }; + _ = try self.upload(qkv, true); + _ = try self.upload(cs, true); + _ = try self.upload(sn, true); + for (0..3) |_| _ = try self.output(tiles * 16 * tokens * 64 * 2); + self.outs = 3 * tiles * 16 * tokens * 64; + self.p = .{ .tiles = @intCast(tiles), .tokens = @intCast(tokens), .eps = 1e-5 }; + }, + .attention => { + if (s.k != 64 or s.n > 288) return false; + const tiles = s.rows; + const tokens = s.n; + const n = tiles * 16 * tokens * 64; + const q = try self.values(n, -2, 2, fill, rng, true, true); + const k = try self.values(n, -2, 2, .random, rng, true, false); + const v = try self.values(n, 0, 2, .random, rng, true, false); + self.in = .{ .a = q, .b = k, .d = v, .rows = tiles * tokens, .n = s.n, .k = 64, .tiles = tiles, .tokens = tokens, .scale = 0.125 }; + _ = try self.upload(q, true); + _ = try self.upload(k, true); + _ = try self.upload(v, true); + _ = try self.output(tiles * tokens * 1024 * 2); + self.outs = tiles * tokens * 1024; + self.p = .{ .tiles = @intCast(tiles), .tokens = @intCast(tokens), .scale = 0.125 }; + }, + .swiglu => { + if (s.n != 4096 or s.k != 8192) return false; + const wide = try self.values(s.rows * 8192, -4, 4, fill, rng, true, true); + self.in = .{ .a = wide, .rows = s.rows, .n = 4096, .k = 8192 }; + _ = try self.upload(wide, true); + _ = try self.output(s.rows * 4096 * 2); + self.outs = s.rows * 4096; + self.p = .{ .m = @intCast(s.rows) }; + }, + } + return true; + } + + pub fn run(self: *Dec) !void { + if (self.fresh.len > 0) { + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.bufs[self.nbufs - 1], .len = self.fresh.len }; + try b.upload(0, self.fresh); + } + const s = self.shape; + const b = self.bufs; + var a: cuda.Args = .{}; + switch (self.which) { + .post_quant => { + for (b[0..5]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = 1, .y = @intCast((self.p.tiles * self.p.h * self.p.w + 7) / 8), .z = 1 }, .{ .x = 32, .y = 8 }, &a); + }, + .embed => { + for (b[0..5]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = 4, .y = @intCast(self.p.tiles * self.p.tokens), .z = 1 }, .{ .x = 256 }, &a); + }, + .rms_norm => { + for (b[0..3]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = @intCast(s.rows) }, .{ .x = 256 }, &a); + }, + .layer_norm => { + for (b[0..4]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = @intCast(s.rows) }, .{ .x = 256 }, &a); + }, + .linear => { + for (b[0..3]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = @intCast((self.p.n + 127) / 128), .y = @intCast((self.p.m + 127) / 128), .z = 1 }, .{ .x = 256 }, &a); + }, + .finish_bias, .finish_scale => { + for (b[0..4]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = @intCast((self.p.n + 31) / 32), .y = @intCast((self.p.m + 7) / 8), .z = 1 }, .{ .x = 32, .y = 8 }, &a); + }, + .heads => { + for (b[0..6]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = @intCast(self.p.tiles * self.p.tokens), .y = 16, .z = 1 }, .{ .x = 32 }, &a); + }, + .attention => { + for (b[0..4]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = @intCast((self.p.tokens + 7) / 8), .y = 16, .z = @intCast(self.p.tiles) }, .{ .x = 256 }, &a); + }, + .swiglu => { + for (b[0..2]) |p| a.add(p); + a.add(self.p); + try self.go(.{ .x = 4096 / 32, .y = @intCast((self.p.m + 7) / 8), .z = 1 }, .{ .x = 32, .y = 8 }, &a); + }, + } + try self.rig.s.synchronize(); + } + + fn go(self: *Dec, grid: cuda.Dim3, block: cuda.Dim3, args: *cuda.Args) !void { + try cuda.launch.launch(self.f, .{ .grid = grid, .block = block }, self.rig.s, args); + } + + pub fn count(self: *Dec) usize { + return self.outs; + } + + fn compute(self: *Dec, s: ref.Sum, want: []f64, mag: []f64) !void { + switch (self.which) { + .post_quant => ref.postQuant(self.in, s, want, mag), + .embed => ref.embed(self.in, s, want, mag), + .rms_norm => ref.rmsNorm(self.in, s, want, mag), + .layer_norm => ref.layerNorm(self.in, s, want, mag), + .linear => ref.linear(self.in, s, want, mag), + .finish_bias, .finish_scale => ref.finish(self.in, want, mag), + .heads => ref.heads(self.in, s, want, mag), + .attention => ref.attention(self.in, s, want, mag), + .swiglu => ref.swiglu(self.in, want, mag), + } + } + + pub fn reference(self: *Dec, want: []f64, mag: []f64) !void { + return self.compute(.{}, want, mag); + } + + pub fn simulate(self: *Dec, acc: c.Accum, order: g.Order, out: []f64) !void { + const a = self.rig.gpu.gpa; + const mag = try a.alloc(f64, out.len); + defer a.free(mag); + return self.compute(.{ .acc = acc, .order = order }, out, mag); + } +}; diff --git a/zig/tests/cuda/contract_h3_image_prompt.zig b/zig/tests/cuda/contract_h3_image_prompt.zig new file mode 100644 index 00000000000..a75a98c9271 --- /dev/null +++ b/zig/tests/cuda/contract_h3_image_prompt.zig @@ -0,0 +1,470 @@ +//! MiniMax-H3-Image's prompt CUDA kernels under the contract, each against its float64 formula. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_h3_image_ref.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; + +/// The prompt kernels: each served form — Qwen (mode 0) and H3 (mode 1) rounding where both run. +pub const Which = enum { + norm_qwen, + norm_h3, + heads_rotary, + heads_fused, + attention_causal, + attention_fused, + glu_qwen, + glu_h3, + add, + scatter_add, + embed, + splice, + linear, + round, +}; + +/// norm's row sum of squares, sequential over the width. +fn rowChain(s: c.Shape) usize { + return s.k + 2; +} +/// heads' 128 squares, sequential. +fn headChain(_: c.Shape) usize { + return 128 + 2; +} +/// attention's sequential key dots of 128, then the weight and value sums over the keys in order. +fn attnChain(s: c.Shape) usize { + return 128 + s.k + 2; +} +/// linear's sequential dot over k. +fn dotK(s: c.Shape) usize { + return s.k; +} +fn none(_: c.Shape) usize { + return 0; +} + +const norm_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; +const att_why = "softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error"; + +pub fn spec(w: Which) c.Spec { + return switch (w) { + .norm_qwen => .{ .name = "cuda h3 image prompt h3p_norm qwen", .accum = .f32, .depth = rowChain, .ops = 6, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 256, .k = 256 }, .{ .rows = 77, .n = 1024, .k = 1024 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .norm_h3 => .{ .name = "cuda h3 image prompt h3p_norm h3", .accum = .f32, .depth = rowChain, .ops = 6, .mids = 0, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 256, .k = 256 }, .{ .rows = 77, .n = 1024, .k = 1024 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .heads_rotary => .{ .name = "cuda h3 image prompt h3p_heads rotary", .accum = .f32, .depth = headChain, .ops = 8, .mids = 3, .out = .bf16, .in_place = true, .served = &.{ .{ .rows = 8, .n = 128, .k = 128 }, .{ .rows = 77, .n = 128, .k = 128 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .heads_fused => .{ .name = "cuda h3 image prompt h3p_heads fused qkv", .accum = .f32, .depth = headChain, .ops = 8, .mids = 1, .out = .bf16, .in_place = true, .served = &.{ .{ .rows = 8, .n = 128, .k = 128 }, .{ .rows = 77, .n = 128, .k = 128 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = norm_why } }, + .attention_causal => .{ .name = "cuda h3 image prompt h3p_attention causal", .accum = .f32, .depth = attnChain, .ops = 8, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 128, .k = 8 }, .{ .rows = 77, .n = 128, .k = 77 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = att_why } }, + .attention_fused => .{ .name = "cuda h3 image prompt h3p_attention all rows", .accum = .f32, .depth = attnChain, .ops = 8, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 128, .k = 8 }, .{ .rows = 77, .n = 128, .k = 77 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = att_why } }, + .glu_qwen => .{ .name = "cuda h3 image prompt h3p_glu qwen", .accum = .none, .depth = none, .ops = 4, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 256, .k = 1 }, .{ .rows = 77, .n = 1024, .k = 1 } } }, + .glu_h3 => .{ .name = "cuda h3 image prompt h3p_glu h3", .accum = .none, .depth = none, .ops = 5, .mids = 2, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 256, .k = 1 }, .{ .rows = 77, .n = 1024, .k = 1 } } }, + .add => .{ .name = "cuda h3 image prompt h3p_add", .accum = .none, .depth = none, .ops = 1, .mids = 1, .out = .bf16, .in_place = true, .served = &.{ .{ .rows = 8, .n = 1024, .k = 1 }, .{ .rows = 77, .n = 1024, .k = 1 } } }, + .scatter_add => .{ .name = "cuda h3 image prompt h3p_scatter_add", .accum = .none, .depth = none, .ops = 1, .out = .bf16, .in_place = true, .served = &.{ .{ .rows = 4, .n = 256, .k = 8 }, .{ .rows = 8, .n = 1024, .k = 16 } } }, + .embed => .{ .name = "cuda h3 image prompt h3p_embed", .accum = .none, .depth = none, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 256, .k = 32 }, .{ .rows = 77, .n = 1024, .k = 128 } } }, + .splice => .{ .name = "cuda h3 image prompt h3p_splice", .accum = .none, .depth = none, .out = .bf16, .in_place = true, .served = &.{ .{ .rows = 4, .n = 256, .k = 8 }, .{ .rows = 8, .n = 1024, .k = 16 } } }, + .linear => .{ .name = "cuda h3 image prompt h3p_linear", .accum = .f32, .depth = dotK, .ops = 0, .out = .f32, .served = &.{ .{ .rows = 4, .n = 128, .k = 256 }, .{ .rows = 8, .n = 256, .k = 1024 } }, .sums = .{ .bf16 = 0, .f16 = 0, .exact = false, .why = "a k-length sequential fp32 dot is the reference's own order" } }, + .round => .{ .name = "cuda h3 image prompt h3p_round", .accum = .none, .depth = none, .out = .bf16, .served = &.{ .{ .rows = 8, .n = 1024, .k = 1 }, .{ .rows = 77, .n = 1024, .k = 1 } } }, + }; +} + +pub fn symbol(w: Which) [:0]const u8 { + return switch (w) { + .norm_qwen, .norm_h3 => "h3p_norm", + .heads_rotary, .heads_fused => "h3p_heads", + .attention_causal, .attention_fused => "h3p_attention", + .glu_qwen, .glu_h3 => "h3p_glu", + .add => "h3p_add", + .scatter_add => "h3p_scatter_add", + .embed => "h3p_embed", + .splice => "h3p_splice", + .linear => "h3p_linear", + .round => "h3p_round", + }; +} + +pub const Prm = struct { + rig: rig_.Rig, + which: Which, + f: cuda.Function, + shape: c.Shape = undefined, + arena: std.heap.ArenaAllocator, + in: ref.In = .{}, + bufs: [10]u64 = undefined, + nbufs: usize = 0, + /// In-place starting bytes: buffer index and payload, re-uploaded before every launch. + fresh: [2]struct { at: usize, bytes: []const u8 } = .{ .{ .at = 0, .bytes = &.{} }, .{ .at = 0, .bytes = &.{} } }, + nfresh: usize = 0, + outs: usize = 0, + /// Launch geometry the prepared inputs imply. + rows: usize = 0, + heads: usize = 0, + kv_heads: usize = 0, + width: usize = 0, + q_row: usize = 0, + k_row: usize = 0, + fused: bool = false, + + pub fn deinit(self: *Prm) void { + self.rig.deinit(); + self.arena.deinit(); + } + + pub fn kernel(self: *Prm) g.Kernel { + return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Prm); + + fn values(self: *Prm, n: usize, lo: f64, hi: f64, fill: g.Fill, rng: std.Random, half: bool, plant: bool) ![]f64 { + const v = try self.arena.allocator().alloc(f64, n); + for (v, 0..) |*x, i| { + const r = lo + (hi - lo) * rng.float(f64); + x.* = switch (fill) { + .stress => @floatFromInt(@as(i64, @intFromFloat(@round(r * 8)))), + else => r, + }; + if (i % 61 == 7 and fill != .stress) x.* *= 6; + x.* = if (half) ref.bf(x.*) else @as(f32, @floatCast(x.*)); + } + if (fill == .nonfinite and plant) { + const at = [_]usize{ n / 3, n / 2, n - 1 }; + const put = [_]f64{ std.math.nan(f64), std.math.inf(f64), -std.math.inf(f64) }; + for (at, put) |at_, x| v[at_] = x; + } + return v; + } + + fn upload(self: *Prm, v: []const f64, half: bool) !u64 { + return self.bytes(try self.encode(v, half)); + } + + fn encode(self: *Prm, v: []const f64, half: bool) ![]const u8 { + const al = self.arena.allocator(); + if (half) { + const h = try al.alloc(u16, v.len); + for (h, v) |*o, x| o.* = c.toBf16(@floatCast(x)); + return std.mem.sliceAsBytes(h); + } + const f = try al.alloc(f32, v.len); + for (f, v) |*o, x| o.* = @floatCast(x); + return std.mem.sliceAsBytes(f); + } + + fn bytes(self: *Prm, b: []const u8) !u64 { + self.bufs[self.nbufs] = try self.rig.input(b); + self.nbufs += 1; + return self.bufs[self.nbufs - 1]; + } + + fn ints(self: *Prm, v: []const u32) !u64 { + return self.bytes(std.mem.sliceAsBytes(v)); + } + + fn output(self: *Prm, len: usize) !u64 { + self.bufs[self.nbufs] = try self.rig.output(len); + self.nbufs += 1; + return self.bufs[self.nbufs - 1]; + } + + /// An in-place buffer: an output slot whose starting bytes are restored before every launch. + fn inPlace(self: *Prm, v: []const f64, half: bool) !u64 { + const enc = try self.encode(v, half); + self.bufs[self.nbufs] = try self.rig.output(enc.len); + const ptr = self.bufs[self.nbufs]; + self.fresh[self.nfresh] = .{ .at = self.nbufs, .bytes = enc }; + self.nfresh += 1; + self.nbufs += 1; + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = ptr, .len = enc.len }; + try b.upload(0, enc); + return ptr; + } + + pub fn prepare(self: *Prm, s: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.nbufs = 0; + self.nfresh = 0; + self.shape = s; + self.fused = false; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const al = self.arena.allocator(); + switch (self.which) { + .norm_qwen, .norm_h3 => { + if (s.n != s.k or s.n > 4096) return false; + const mode: u32 = if (self.which == .norm_qwen) 0 else 1; + const x = try self.values(s.rows * s.n, -2, 2, fill, rng, true, true); + const w = try self.values(s.n, 0.5, 1.5, .random, rng, false, false); + self.in = .{ .a = x, .b = w, .rows = s.rows, .n = s.n, .k = s.n, .mode = mode, .eps = 1e-5 }; + self.width = s.n; + _ = try self.upload(x, true); + _ = try self.upload(w, false); + _ = try self.output(s.rows * s.n * 2); + self.outs = s.rows * s.n; + }, + .heads_rotary => { + // The text model: q [rows, 8*128], k [rows, 2*128], rotated by cos/sin [rows, 64]; mode 0. + const heads = 8; + const kv = 2; + const q = try self.values(s.rows * heads * 128, -2, 2, fill, rng, true, true); + const k = try self.values(s.rows * kv * 128, -2, 2, .random, rng, true, false); + const wq = try self.values(128, 0.5, 1.5, .random, rng, false, false); + const wk = try self.values(128, 0.5, 1.5, .random, rng, false, false); + // The served tables: row r's angle for channel pair i is r / 10000^(i/64), so sine spans [-1, 1]. + const cs = try al.alloc(f64, s.rows * 64); + const sn = try al.alloc(f64, s.rows * 64); + for (cs, sn, 0..) |*co, *si, at| { + const angle: f32 = @floatCast(@as(f64, @floatFromInt(at / 64)) / std.math.pow(f64, 10000, @as(f64, @floatFromInt(at % 64)) / 64)); + co.* = @cos(angle); + si.* = @sin(angle); + } + self.in = .{ .a = q, .b = k, .d = wq, .e = wk, .f = cs, .g = sn, .rows = s.rows, .n = s.n, .k = s.k, .heads = heads, .kv_heads = kv, .head = 128, .q_row = heads * 128, .k_row = kv * 128, .mode = 0, .eps = 1e-5, .rotary = true }; + self.rows = s.rows; + self.heads = heads; + self.kv_heads = kv; + self.q_row = heads * 128; + self.k_row = kv * 128; + _ = try self.inPlace(q, true); + _ = try self.inPlace(k, true); + _ = try self.upload(wq, false); + _ = try self.upload(wk, false); + _ = try self.upload(cs, false); + _ = try self.upload(sn, false); + self.outs = s.rows * (heads + kv) * 128; + }, + .heads_fused => { + // The refiner: qkv rows of 3 * 128 (one q, k, v triple), no rotary; mode 1. + const heads = 1; + const kv = 1; + const q_row = 3 * 128; + const qkv = try self.values(s.rows * q_row, -2, 2, fill, rng, true, true); + const wq = try self.values(128, 0.5, 1.5, .random, rng, false, false); + const wk = try self.values(128, 0.5, 1.5, .random, rng, false, false); + self.in = .{ .a = qkv, .d = wq, .e = wk, .rows = s.rows, .n = s.n, .k = s.k, .heads = heads, .kv_heads = kv, .head = 128, .stride = 3 * 128, .q_row = q_row, .k_row = q_row, .mode = 1, .eps = 1e-5 }; + self.rows = s.rows; + self.heads = heads; + self.kv_heads = kv; + self.q_row = q_row; + self.k_row = q_row; + self.fused = true; + _ = try self.inPlace(qkv, true); + _ = try self.upload(wq, false); + _ = try self.upload(wk, false); + self.outs = s.rows * q_row; + }, + .attention_causal, .attention_fused => { + // q [k, 4*128], k/v [k, 2*128]: s.k rows; causal for the text model, all rows for the refiner. + const n = s.k; + const heads = 4; + const kv = 2; + const causal = self.which == .attention_causal; + const q = try self.values(n * heads * 128, -2, 2, fill, rng, true, true); + const k = try self.values(n * kv * 128, -2, 2, .random, rng, true, false); + const v = try self.values(n * kv * 128, 0, 2, .random, rng, true, false); + self.in = .{ .a = q, .b = k, .d = v, .rows = n, .n = s.n, .k = n, .heads = heads, .kv_heads = kv, .head = 128, .q_row = heads * 128, .k_row = kv * 128, .scale = 1.0 / @sqrt(128.0), .causal = causal }; + self.rows = n; + self.heads = heads; + self.kv_heads = kv; + self.q_row = heads * 128; + self.k_row = kv * 128; + _ = try self.upload(q, true); + _ = try self.upload(k, true); + _ = try self.upload(v, true); + _ = try self.output(n * heads * 128 * 2); + self.outs = n * heads * 128; + }, + .glu_qwen, .glu_h3 => { + const mode: u32 = if (self.which == .glu_qwen) 0 else 1; + const gg = try self.values(s.rows * s.n, -4, 4, fill, rng, true, true); + const v = try self.values(s.rows * s.n, -2, 2, .random, rng, true, false); + self.in = .{ .a = gg, .b = v, .rows = s.rows, .n = s.n, .mode = mode }; + self.width = s.n; + _ = try self.upload(gg, true); + _ = try self.upload(v, true); + _ = try self.output(s.rows * s.n * 2); + self.outs = s.rows * s.n; + }, + .add => { + const x = try self.values(s.rows * s.n, -2, 2, fill, rng, true, true); + const y = try self.values(s.rows * s.n, -2, 2, .random, rng, false, false); + self.in = .{ .a = x, .b = y, .rows = s.rows, .n = s.n }; + _ = try self.inPlace(x, true); + _ = try self.upload(y, false); + self.outs = s.rows * s.n; + }, + .scatter_add => { + // s.rows scattered rows of width s.n into an x buffer of s.k rows. + if (s.k < s.rows or s.rows == 0) return false; + const x = try self.values(s.k * s.n, -2, 2, fill, rng, true, true); + const y = try self.values(s.rows * s.n, -2, 2, .random, rng, true, false); + const idx = try al.alloc(u32, s.rows); + for (idx, 0..) |*v, i| v.* = @intCast((i * s.k) / s.rows); + rng.shuffle(u32, idx); + self.in = .{ .a = x, .b = y, .ints = idx, .rows = s.k, .n = s.n, .k = s.rows }; + _ = try self.inPlace(x, true); + _ = try self.upload(y, true); + _ = try self.ints(idx); + self.outs = s.k * s.n; + }, + .embed => { + // s.rows gathered rows of width s.n from a table of s.k rows. + const table = try self.values(s.k * s.n, -2, 2, fill, rng, true, true); + const ids = try al.alloc(u32, s.rows); + for (ids, 0..) |*v, i| v.* = @intCast((i * s.k) / s.rows); + rng.shuffle(u32, ids); + self.in = .{ .a = table, .ints = ids, .rows = s.rows, .n = s.n, .k = s.k }; + _ = try self.upload(table, true); + _ = try self.ints(ids); + _ = try self.output(s.rows * s.n * 2); + self.outs = s.rows * s.n; + }, + .splice => { + // s.rows replacement rows spliced into an x buffer of s.k rows. + if (s.k < s.rows or s.rows == 0) return false; + const x = try self.values(s.k * s.n, -2, 2, fill, rng, true, true); + const rows_ = try self.values(s.rows * s.n, -2, 2, .random, rng, true, false); + const pads = try al.alloc(u32, s.rows); + for (pads, 0..) |*v, i| v.* = @intCast((i * s.k) / s.rows); + rng.shuffle(u32, pads); + self.in = .{ .a = x, .b = rows_, .ints = pads, .rows = s.k, .n = s.n, .k = s.rows }; + _ = try self.inPlace(x, true); + _ = try self.upload(rows_, true); + _ = try self.ints(pads); + self.outs = s.k * s.n; + }, + .linear => { + if (s.k > 8192) return false; + const x = try self.values(s.rows * s.k, -1, 1, fill, rng, true, true); + const w = try self.values(s.n * s.k, -1, 1, .random, rng, true, false); + self.in = .{ .a = x, .b = w, .rows = s.rows, .n = s.n, .k = s.k }; + _ = try self.upload(x, true); + _ = try self.upload(w, true); + _ = try self.output(s.rows * s.n * 4); + self.outs = s.rows * s.n; + }, + .round => { + const x = try self.values(s.rows * s.n, -8, 8, fill, rng, false, true); + self.in = .{ .a = x, .rows = s.rows, .n = s.n }; + _ = try self.upload(x, false); + _ = try self.output(s.rows * s.n * 2); + self.outs = s.rows * s.n; + }, + } + return true; + } + + pub fn run(self: *Prm) !void { + for (self.fresh[0..self.nfresh]) |f| { + const b: cuda.DeviceBuffer = .{ .d = self.rig.gpu.d, .ptr = self.bufs[f.at], .len = f.bytes.len }; + try b.upload(0, f.bytes); + } + const s = self.shape; + const b = self.bufs; + var a: cuda.Args = .{}; + const ci = struct { + fn of(n: usize) c_int { + return @intCast(n); + } + }.of; + switch (self.which) { + .norm_qwen, .norm_h3 => { + for (b[0..3]) |p| a.add(p); + a.add(ci(s.n)); + a.add(@as(c_int, @intCast(self.in.mode))); + a.add(@as(f32, 1e-5)); + try self.go(.{ .x = @intCast(s.rows) }, &a); + }, + .heads_rotary => { + for (b[0..6]) |p| a.add(p); + for ([_]usize{ self.heads, self.kv_heads, self.q_row, self.k_row, 128, 0, 1 }) |v| a.add(ci(v)); + a.add(@as(f32, 1e-5)); + try self.go(.{ .x = @intCast(self.rows), .y = @intCast((self.heads + self.kv_heads + 7) / 8) }, &a); + }, + .heads_fused => { + // q and k point into the one qkv buffer (k at +128 elements). + for ([_]u64{ b[0], b[0] + 128 * 2, b[1], b[2], 0, 0 }) |p| a.add(p); + for ([_]usize{ self.heads, self.kv_heads, self.q_row, self.k_row, 3 * 128, 1, 0 }) |v| a.add(ci(v)); + a.add(@as(f32, 1e-5)); + try self.go(.{ .x = @intCast(self.rows), .y = @intCast((self.heads + self.kv_heads + 7) / 8) }, &a); + }, + .attention_causal, .attention_fused => { + for (b[0..4]) |p| a.add(p); + for ([_]usize{ self.rows, self.heads, self.kv_heads, self.q_row, self.k_row, self.k_row, 128, @intFromBool(self.in.causal) }) |v| a.add(ci(v)); + a.add(@as(f32, 1.0 / @sqrt(128.0))); + try self.go(.{ .x = @intCast(self.rows), .y = @intCast((self.heads + 7) / 8) }, &a); + }, + .glu_qwen, .glu_h3 => { + for (b[0..3]) |p| a.add(p); + for ([_]usize{ self.width, self.width, self.width, self.in.mode }) |v| a.add(ci(v)); + try self.go(.{ .x = @intCast((self.width + 255) / 256), .y = @intCast(s.rows) }, &a); + }, + .add => { + for (b[0..2]) |p| a.add(p); + a.add(ci(s.rows * s.n)); + try self.go(.{ .x = @intCast((s.rows * s.n + 255) / 256) }, &a); + }, + .scatter_add => { + for (b[0..3]) |p| a.add(p); + a.add(ci(s.n)); + try self.go(.{ .x = @intCast((s.n + 255) / 256), .y = @intCast(s.rows) }, &a); + }, + .embed => { + for (b[0..3]) |p| a.add(p); + a.add(ci(s.n)); + try self.go(.{ .x = @intCast((s.n + 255) / 256), .y = @intCast(s.rows) }, &a); + }, + .splice => { + for (b[0..3]) |p| a.add(p); + a.add(ci(s.n)); + try self.go(.{ .x = @intCast((s.n + 255) / 256), .y = @intCast(s.rows) }, &a); + }, + .linear => { + for (b[0..3]) |p| a.add(p); + for ([_]usize{ s.rows, s.n, s.k }) |v| a.add(ci(v)); + try self.go(.{ .x = @intCast((s.rows * s.n + 255) / 256) }, &a); + }, + .round => { + for (b[0..2]) |p| a.add(p); + a.add(ci(s.rows * s.n)); + try self.go(.{ .x = @intCast((s.rows * s.n + 255) / 256) }, &a); + }, + } + try self.rig.s.synchronize(); + } + + fn go(self: *Prm, grid: cuda.Dim3, args: *cuda.Args) !void { + try cuda.launch.launch(self.f, .{ .grid = grid, .block = .{ .x = 256 } }, self.rig.s, args); + } + + pub fn count(self: *Prm) usize { + return self.outs; + } + + fn compute(self: *Prm, s_: ref.Sum, want: []f64, mag: []f64) !void { + switch (self.which) { + .norm_qwen, .norm_h3 => ref.norm(self.in, s_, want, mag), + .heads_rotary, .heads_fused => ref.pheads(self.in, s_, want, mag, self.fused), + .attention_causal, .attention_fused => ref.pattention(self.in, s_, want, mag), + .glu_qwen, .glu_h3 => ref.glu(self.in, want, mag), + .add => ref.add(self.in, want, mag), + .scatter_add => ref.scatterAdd(self.in, want, mag), + .embed => ref.gather(self.in, want, mag), + .splice => ref.splice(self.in, want, mag), + .linear => ref.linear(self.in, s_, want, mag), + .round => ref.round(self.in, want, mag), + } + } + + pub fn reference(self: *Prm, want: []f64, mag: []f64) !void { + return self.compute(.{}, want, mag); + } + + pub fn simulate(self: *Prm, acc: c.Accum, order: g.Order, out: []f64) !void { + const a = self.rig.gpu.gpa; + const mag = try a.alloc(f64, out.len); + defer a.free(mag); + return self.compute(.{ .acc = acc, .order = order }, out, mag); + } +}; diff --git a/zig/tests/cuda/contract_h3_image_ref.zig b/zig/tests/cuda/contract_h3_image_ref.zig new file mode 100644 index 00000000000..c25e5ebc684 --- /dev/null +++ b/zig/tests/cuda/contract_h3_image_ref.zig @@ -0,0 +1,366 @@ +//! MiniMax-H3-Image's CUDA kernels in float64 with their bf16 mid-roundings, before each output's store rounding. +const std = @import("std"); +const core = @import("core"); + +const contract = core.contract; +const c = contract.spec; +const Order = contract.gates.Order; +const sumIn = contract.rows.sumIn; + +/// fp32 to bf16 and back, as the kernels' __float2bfloat16 (round to nearest even); NaN and infinities kept. +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +/// How the sums are taken: in float64 (the reference) or in an accumulator and order (gate 4's simulation). +pub const Sum = struct { + acc: c.Accum = .none, + order: Order = .sequential, + + pub fn of(s: Sum, t: []const f64) f64 { + if (s.acc == .none) { + var x: f64 = 0; + for (t) |v| x += v; + return x; + } + return sumIn(s.acc, s.order, t); + } +}; + +/// What the references read: every input as float64 values (bf16 inputs already hold bf16 values) and the sizes. +pub const In = struct { + a: []const f64 = &.{}, // primary activation (lat, tok, x, q, acc, g, times...) + b: []const f64 = &.{}, // second input or first weight (pw, ew, g, k, w, bias...) + d: []const f64 = &.{}, // third (pb, eb, v, sn, s-table...) + e: []const f64 = &.{}, // fourth (reg, cs, residual y...) + f: []const f64 = &.{}, // fifth (sn, value rows...) + g: []const f64 = &.{}, // sixth (layer-norm bias) + ints: []const u32 = &.{}, // origins (pairs), ids, idx, pads + rows: usize = 0, + n: usize = 0, + k: usize = 0, + tiles: usize = 0, + tokens: usize = 0, + h: usize = 0, + w: usize = 0, + heads: usize = 1, + kv_heads: usize = 1, + head: usize = 128, + q_row: usize = 0, + k_row: usize = 0, + eps: f64 = 1e-5, + scale: f64 = 0.125, + mode: u32 = 0, + causal: bool = false, + rotary: bool = false, + stride: usize = 0, // heads' spacing in a row; 0 = head (tightly packed) +}; + +fn magOf(terms: []const f64) f64 { + var m: f64 = 0; + for (terms) |t| m += @abs(t); + return m; +} + +/// h3d_post_quant: per tile cell, bf16(pw . bf16(lat) + pb); a lat, ints origin, b pw, d pb; out tiles*cells*24. +pub fn postQuant(in: In, s: Sum, want: []f64, mag: []f64) void { + const cells = in.h * in.w; + const plane = in.rows * in.n; + var terms: [24]f64 = undefined; + for (0..in.tiles * cells) |y| { + const tile = y / cells; + const i = y % cells; + const r = in.ints[2 * tile] + i / in.w; + const col = in.ints[2 * tile + 1] + i % in.w; + for (0..24) |x| { + for (&terms, 0..) |*t, k| t.* = in.b[x * 24 + k] * bf(in.a[k * plane + r * in.n + col]); + want[y * 24 + x] = s.of(&terms) + in.d[x]; + mag[y * 24 + x] = magOf(&terms); + } + } +} + +/// h3d_embed: cells tokens from ew . tok + eb to bf16, 4 register rows and one zero; a tok, b ew, d eb, e reg. +pub fn embed(in: In, s: Sum, want: []f64, mag: []f64) void { + const cells = in.h * in.w; + var terms: [24]f64 = undefined; + for (0..in.tiles * in.tokens) |y| { + const tile = y / in.tokens; + const t = y % in.tokens; + const out = want[y * 1024 ..][0..1024]; + const om = mag[y * 1024 ..][0..1024]; + if (t < cells) { + for (out, om, 0..) |*o, *m, j| { + for (&terms, 0..) |*v, k| v.* = in.b[j * 24 + k] * in.a[(tile * cells + t) * 24 + k]; + o.* = s.of(&terms) + in.d[j]; + m.* = magOf(&terms); + } + } else if (t < cells + 4) { + for (out, om, in.e[(t - cells) * 1024 ..][0..1024]) |*o, *m, v| { + o.* = v; + m.* = 0; + } + } else { + @memset(out, 0); + @memset(om, 0); + } + } +} + +/// h3d_rms_norm: bf16(x * rsqrt(mean(x^2) + eps) * g), the squares summed in fp32; a x [m, 1024], b g [1024]. +pub fn rmsNorm(in: In, s: Sum, want: []f64, mag: []f64) void { + var terms: [1024]f64 = undefined; + for (0..in.rows) |r| { + const xr = in.a[r * 1024 ..][0..1024]; + for (&terms, xr) |*t, v| t.* = v * v; + const inv = 1.0 / @sqrt(s.of(&terms) / 1024.0 + in.eps); + for (0..1024) |i| { + want[r * 1024 + i] = xr[i] * inv * in.b[i]; + mag[r * 1024 + i] = xr[i] * xr[i]; + } + } +} + +/// h3d_layer_norm: bf16((x - mean) * rstd * g + b), mean and rstd from fp32 sums; a x, b g, d b. +pub fn layerNorm(in: In, s: Sum, want: []f64, mag: []f64) void { + var terms: [1024]f64 = undefined; + for (0..in.rows) |r| { + const xr = in.a[r * 1024 ..][0..1024]; + for (&terms, xr) |*t, v| t.* = v; + const mean = s.of(&terms) / 1024.0; + const abs = magOf(&terms); + for (&terms, xr) |*t, v| t.* = (v - mean) * (v - mean); + const rstd = 1.0 / @sqrt(s.of(&terms) / 1024.0 + in.eps); + for (0..1024) |i| { + const d = xr[i] - mean; + want[r * 1024 + i] = d * rstd * in.b[i] + in.d[i]; + // the mean's sum moves every d by its error; the variance's moves rstd by half its relative error + mag[r * 1024 + i] = @abs(in.b[i]) * rstd * (abs / 1024.0 + @abs(d)); + } + } +} + +/// h3d_finish: mode 0 bf16(acc + b); mode 1 bf16(y + bf16(bf16(acc + b) * s)); a acc, b bias, d scale, e y. +pub fn finish(in: In, want: []f64, mag: []f64) void { + for (0..in.rows * in.n) |i| { + const cix = i % in.n; + const out = in.a[i] + in.b[cix]; + want[i] = if (in.mode == 0) out else in.e[i] + bf(bf(out) * in.d[cix]); + mag[i] = 0; + } +} + +/// h3d_heads: q and k RMS-normed to bf16, their first 32 dims half-turned by cs/sn, v copied; a qkv, b cs, d sn. +pub fn heads(in: In, s: Sum, want: []f64, mag: []f64) void { + const T = in.tokens; + const block = in.tiles * 16 * T * 64; // elements of one of q, k, v + var terms: [64]f64 = undefined; + for (0..in.tiles) |tile| for (0..T) |t| for (0..16) |head| { + const row = tile * T + t; + const src = in.a[row * 3072 + head * 192 ..][0..192]; + const to = ((tile * 16 + head) * T + t) * 64; + for (0..2) |part| { + const x = src[part * 64 ..][0..64]; + for (&terms, x) |*q, v| q.* = v * v; + const inv = 1.0 / @sqrt(s.of(&terms) / 64.0 + in.eps); + var na: [64]f64 = undefined; + for (&na, x) |*o, v| o.* = bf(v * inv); + for (0..32) |lane| { + const other = if (lane < 16) -na[lane + 16] else na[lane - 16]; + want[part * block + to + lane] = bf(na[lane] * in.b[t * 32 + lane]) + bf(other * in.d[t * 32 + lane]); + want[part * block + to + 32 + lane] = x[32 + lane] * inv; + mag[part * block + to + lane] = @abs(na[lane] * in.b[t * 32 + lane]) + @abs(other * in.d[t * 32 + lane]); + mag[part * block + to + 32 + lane] = terms[32 + lane]; + } + } + for (0..64) |i| { + want[2 * block + to + i] = src[128 + i]; + mag[2 * block + to + i] = 0; + } + }; +} + +/// h3d_attention: softmax(q k^T * scale) v per (tile, head, query); a q, b k, d v; NaN scores drop as warp_max. +pub fn attention(in: In, s: Sum, want: []f64, mag: []f64) void { + const T = in.tokens; + var sc: [288]f64 = undefined; + var terms: [64]f64 = undefined; + var vt: [288]f64 = undefined; + for (0..in.tiles) |tile| for (0..16) |head| for (0..T) |query| { + const base = ((tile * 16 + head) * T) * 64; + const qr = in.a[base + query * 64 ..][0..64]; + var top: f64 = -std.math.inf(f64); + for (0..T) |key| { + const kr = in.b[base + key * 64 ..][0..64]; + for (&terms, qr, kr) |*t, q, kv| t.* = q * kv; + sc[key] = s.of(&terms) * in.scale; + if (!std.math.isNan(sc[key])) top = @max(top, sc[key]); + } + var total: f64 = 0; + for (0..T) |key| { + sc[key] = @exp(sc[key] - top); + total += sc[key]; + } + const at = ((tile * T + query) * 16 + head) * 64; + for (0..64) |ch| { + for (vt[0..T], 0..) |*t, key| t.* = sc[key] * in.d[base + key * 64 + ch]; + want[at + ch] = s.of(vt[0..T]) / total; + mag[at + ch] = magOf(vt[0..T]); + } + }; +} + +/// h3d_swiglu: act [m, 4096] = bf16(bf16(silu(gate)) * value); a wide [m, 8192]. +pub fn swiglu(in: In, want: []f64, mag: []f64) void { + for (0..in.rows) |r| for (0..4096) |x| { + const g = in.a[r * 8192 + x]; + const silu = bf(g / (1.0 + @exp(-g))); + want[r * 4096 + x] = silu * in.a[r * 8192 + 4096 + x]; + mag[r * 4096 + x] = 0; + }; +} + +/// h3p_norm: RMSNorm(x) by w, mode 0 bf16(w * bf16(x * r)) (Qwen), mode 1 bf16(x * r * w) (H3); a x, b w. +pub fn norm(in: In, s: Sum, want: []f64, mag: []f64) void { + const width = in.n; + var terms: [4096]f64 = undefined; + for (0..in.rows) |r| { + const xr = in.a[r * width ..][0..width]; + for (terms[0..width], xr) |*t, v| t.* = v * v; + const inv = 1.0 / @sqrt(s.of(terms[0..width]) / @as(f64, @floatFromInt(width)) + in.eps); + for (0..width) |i| { + want[r * width + i] = if (in.mode == 0) in.b[i] * bf(xr[i] * inv) else xr[i] * inv * in.b[i]; + mag[r * width + i] = xr[i] * xr[i]; + } + } +} + +/// h3p_heads: q and k normed (mode as h3p_norm), turned by cos/sin when rotary; fused qkv's slices rewritten. +pub fn pheads(in: In, s: Sum, want: []f64, mag: []f64, fused: bool) void { + const D = in.head; + const stride = if (in.stride == 0) D else in.stride; + var terms: [128]f64 = undefined; + if (fused) @memcpy(want, in.a) else { + @memcpy(want[0..in.a.len], in.a); + @memcpy(want[in.a.len..], in.b); + } + @memset(mag, 0); + for (0..in.rows) |r| for (0..in.heads + in.kv_heads) |hh| { + const is_q = hh < in.heads; + const at = if (fused) + r * in.q_row + (if (is_q) @as(usize, 0) else D) + else if (is_q) + r * in.q_row + hh * stride + else + in.rows * in.q_row + r * in.k_row + (hh - in.heads) * stride; + const src = if (is_q or fused) in.a[at..][0..D] else in.b[r * in.k_row + (hh - in.heads) * stride ..][0..D]; + const w = if (is_q) in.d else in.e; + for (&terms, src) |*t, v| t.* = v * v; + const inv = 1.0 / @sqrt(s.of(&terms) / @as(f64, @floatFromInt(D)) + in.eps); + var v: [128]f64 = undefined; + for (&v, src, w) |*o, xv, wv| o.* = if (in.mode == 0) wv * bf(xv * inv) else xv * inv * wv; + var o = v; + if (in.rotary) for (0..D) |ch| { + const table_at = r * 64 + ch % 64; + const other = if (ch < 64) -bf(v[ch + 64]) else bf(v[ch - 64]); + o[ch] = bf(bf(v[ch]) * in.f[table_at]) + bf(other * in.g[table_at]); + }; + for (0..D) |i| { + want[at + i] = o[i]; + mag[at + i] = terms[i]; + } + }; +} + +/// h3p_attention: softmax(q k^T scale) v, two-pass (the top score, then weight and value sums); a q, b k, d v. +pub fn pattention(in: In, s: Sum, want: []f64, mag: []f64) void { + const D = in.head; + const group = in.heads / in.kv_heads; + var p: [1032]f64 = undefined; + var vt: [1032]f64 = undefined; + var terms: [128]f64 = undefined; + for (0..in.rows) |r| for (0..in.heads) |h| { + const qr = in.a[r * in.q_row + h * in.head ..][0..D]; + const kv = h / group; + const end = if (in.causal) r + 1 else in.rows; + var top: f64 = -std.math.inf(f64); + for (0..end) |j| { + const kr = in.b[j * in.k_row + kv * in.head ..][0..D]; + for (&terms, qr, kr) |*t, q, kv2| t.* = q * kv2; + p[j] = s.of(&terms) * in.scale; + if (!std.math.isNan(p[j])) top = @max(top, p[j]); + } + var l: f64 = 0; + for (p[0..end]) |*e| { + e.* = @exp(e.* - top); + l += e.*; + } + for (0..D) |ch| { + for (vt[0..end], 0..) |*t, j| t.* = p[j] * in.d[j * in.k_row + kv * in.head + ch]; + want[(r * in.heads + h) * D + ch] = s.of(vt[0..end]) / l; + mag[(r * in.heads + h) * D + ch] = magOf(vt[0..end]); + } + }; +} + +/// h3p_glu: silu(g) * v, mode 0 bf16(bf16(g/e) v), mode 1 bf16(bf16(g * bf16(1/e)) v); a g, b v. +pub fn glu(in: In, want: []f64, mag: []f64) void { + for (0..in.rows * in.n) |i| { + const x = in.a[i]; + const e = 1.0 + @exp(-x); + const sv = if (in.mode == 0) bf(x / e) else bf(x * bf(1.0 / e)); + want[i] = sv * in.b[i]; + mag[i] = 0; + } +} + +/// h3p_add: x = bf16(x + bf16(y)) in place; a x (bf16-valued), b y fp32. +pub fn add(in: In, want: []f64, mag: []f64) void { + for (want, mag, in.a, in.b) |*o, *m, x, y| { + o.* = x + bf(y); + m.* = 0; + } +} + +/// h3p_scatter_add: rows idx[i] = bf16(x + y[i]); a x in place, b y [k*n], ints idx [k]; want is all of x. +pub fn scatterAdd(in: In, want: []f64, mag: []f64) void { + @memcpy(want, in.a); + @memset(mag, 0); + for (0..in.k) |i| for (0..in.n) |ch| { + const to = @as(usize, in.ints[i]) * in.n + ch; + want[to] = want[to] + in.b[i * in.n + ch]; + }; +} + +/// h3p_embed: x rows = table rows ids[i]; a table [k*n], ints ids [rows]. +pub fn gather(in: In, want: []f64, mag: []f64) void { + for (0..in.rows) |i| { + @memcpy(want[i * in.n ..][0..in.n], in.a[@as(usize, in.ints[i]) * in.n ..][0..in.n]); + @memset(mag[i * in.n ..][0..in.n], 0); + } +} + +/// h3p_splice: x rows pads[i] = rows[i]; a x [rows*n] in place, b rows [k*n], ints pads [k]. +pub fn splice(in: In, want: []f64, mag: []f64) void { + @memcpy(want, in.a); + @memset(mag, 0); + for (0..in.k) |i| @memcpy(want[@as(usize, in.ints[i]) * in.n ..][0..in.n], in.b[i * in.n ..][0..in.n]); +} + +/// y [rows, n] fp32 = x [rows, k] bf16 . w [n, k] bf16^T, each K sum sequential in fp32. +pub fn linear(in: In, s: Sum, want: []f64, mag: []f64) void { + var row: [8192]f64 = undefined; + for (0..in.rows) |r| for (0..in.n) |o| { + for (row[0..in.k], in.a[r * in.k ..][0..in.k], in.b[o * in.k ..][0..in.k]) |*t, x, w| t.* = x * w; + want[r * in.n + o] = s.of(row[0..in.k]); + mag[r * in.n + o] = magOf(row[0..in.k]); + }; +} + +/// h3p_round: y = bf16(x) elementwise; a x fp32. +pub fn round(in: In, want: []f64, mag: []f64) void { + for (want, mag, in.a) |*o, *m, v| { + o.* = bf(v); + m.* = 0; + } +} diff --git a/zig/tests/cuda/contract_h3_register.zig b/zig/tests/cuda/contract_h3_register.zig new file mode 100644 index 00000000000..e30baf6dbcb --- /dev/null +++ b/zig/tests/cuda/contract_h3_register.zig @@ -0,0 +1,66 @@ +//! MiniMax-H3's CUDA kernels: the video transformer's, the image decoder's and the prompt's, on the contract. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const h3_k = @import("contract_h3.zig"); +const h3_prep = @import("contract_h3_prep.zig"); +const h3_topk_k = @import("contract_h3_topk.zig"); +const h3d_k = @import("contract_h3_image_decoder.zig"); +const h3p_k = @import("contract_h3_image_prompt.zig"); + +const g = core.contract.gates; + +const images = struct { + pub const h3 align(16) = @embedFile("fatbin_h3").*; + pub const decoder align(16) = @embedFile("fatbin_h3_image_decoder").*; + pub const prompt align(16) = @embedFile("fatbin_h3_image_prompt").*; +}; + +/// H3's loaded images and kernel rigs: the gates point into it, so it lives in the caller's frame until `deinit`. +pub const Loaded = struct { + h3_mod: cuda.Module, + h3d_mod: cuda.Module, + h3p_mod: cuda.Module, + h3_list: [std.enums.values(h3_k.Which).len]h3_k.H3, + h3_topk: h3_topk_k.TopK, + h3d_list: [std.enums.values(h3d_k.Which).len]h3d_k.Dec, + h3p_list: [std.enums.values(h3p_k.Which).len]h3p_k.Prm, + + /// Frees every rig's arena and unloads the three images; call once the gates are done. + pub fn deinit(l: *Loaded) void { + for (&l.h3_list) |*m| m.deinit(); + l.h3_topk.deinit(); + for (&l.h3d_list) |*m| m.deinit(); + for (&l.h3p_list) |*m| m.deinit(); + l.h3p_mod.unload(); + l.h3d_mod.unload(); + l.h3_mod.unload(); + } +}; + +/// Loads H3's three images and appends every kernel they register; `l` must outlive the gates. +pub fn append(l: *Loaded, a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, kernels: *std.ArrayList(g.Kernel)) !void { + l.h3_mod = try cuda.Module.load(gpu.d, &images.h3); + const h3_which = comptime std.enums.values(h3_k.Which); + for (h3_which, &l.h3_list) |w, *m| { + const f = try l.h3_mod.function(h3_k.symbol(w)); + if (w == .attention) try f.allowDynamicShared(h3_prep.attention_shared); + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = f, .arena = std.heap.ArenaAllocator.init(a) }; + } + for (&l.h3_list) |*m| try kernels.append(a, m.kernel()); + l.h3_topk = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try l.h3_mod.function("h3_topk") }; + try kernels.append(a, l.h3_topk.kernel()); + l.h3d_mod = try cuda.Module.load(gpu.d, &images.decoder); + const h3d_which = comptime std.enums.values(h3d_k.Which); + for (h3d_which, &l.h3d_list) |w, *m| { + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3d_mod.function(h3d_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a) }; + } + for (&l.h3d_list) |*m| try kernels.append(a, m.kernel()); + l.h3p_mod = try cuda.Module.load(gpu.d, &images.prompt); + const h3p_which = comptime std.enums.values(h3p_k.Which); + for (h3p_which, &l.h3p_list) |w, *m| { + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3p_mod.function(h3p_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a) }; + } + for (&l.h3p_list) |*m| try kernels.append(a, m.kernel()); +} diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 18778dd193f..9bf7718cffa 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -18,6 +18,14 @@ const h3_image = struct { pub const bytes align(16) = @embedFile("fatbin_h3").*; }; +const h3_image_decoder = struct { + pub const bytes align(16) = @embedFile("fatbin_h3_image_decoder").*; +}; + +const h3_image_prompt = struct { + pub const bytes align(16) = @embedFile("fatbin_h3_image_prompt").*; +}; + /// The named embedded image; only contract_controls may select the planted controls. pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (@import("contract_deepseek_images.zig").image(name)) |bytes| return bytes; @@ -29,6 +37,8 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "mla")) return kk.mla; if (std.mem.eql(u8, name, "h3")) return &h3_image.bytes; if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; + if (std.mem.eql(u8, name, "h3_image_decoder")) return &h3_image_decoder.bytes; + if (std.mem.eql(u8, name, "h3_image_prompt")) return &h3_image_prompt.bytes; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "glm_vision", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index bcaa8adb0ee..8a3b0ebf499 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -25,9 +25,7 @@ const hcmix_k = @import("contract_hc_mix.zig"); const utility_k = @import("contract_utility.zig"); const best_k = @import("contract_row_best.zig"); const qsa_k = @import("contract_qsa_select.zig"); -const h3_k = @import("contract_h3.zig"); -const h3_prep = @import("contract_h3_prep.zig"); -const h3_topk_k = @import("contract_h3_topk.zig"); +const h3_register = @import("contract_h3_register.zig"); const drama3_k = @import("contract_drama3.zig"); const ck_k = @import("contract_ck.zig"); const q35_bf16_k = @import("contract_qwen_bf16.zig"); @@ -68,7 +66,6 @@ const kk = cuda.kernels; const images = struct { pub const controls align(16) = @embedFile("fatbin_contract_controls").*; - pub const h3 align(16) = @embedFile("fatbin_h3").*; }; /// Gates 1-4 on every registered CUDA kernel and each control at its own gate, then gate 5; `only`: contract_after.zig. @@ -303,20 +300,9 @@ fn registered(gpu: check.Gpu, only: []const []const u8, t0: *i96) !g.Tally { selection.* = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try batch.function("fn_qsa_select"), .padded = padded }; defer for (&selections) |*selection| selection.deinit(); for (&selections) |*selection| try kernels.append(a, selection.kernel()); - var h3_mod = try cuda.Module.load(gpu.d, &images.h3); - defer h3_mod.unload(); - const h3_which = comptime std.enums.values(h3_k.Which); - var h3_list: [h3_which.len]h3_k.H3 = undefined; - for (h3_which, &h3_list) |w, *m| { - const f = try h3_mod.function(h3_k.symbol(w)); - if (w == .attention) try f.allowDynamicShared(h3_prep.attention_shared); - m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = f, .arena = std.heap.ArenaAllocator.init(a) }; - } - defer for (&h3_list) |*m| m.deinit(); - for (&h3_list) |*m| try kernels.append(a, m.kernel()); - var h3_topk = h3_topk_k.TopK{ .rig = .{ .gpu = gpu, .s = s }, .f = try h3_mod.function("h3_topk") }; - defer h3_topk.deinit(); - try kernels.append(a, h3_topk.kernel()); + var h3: h3_register.Loaded = undefined; + try h3_register.append(&h3, a, gpu, s, &kernels); + defer h3.deinit(); const d3 = try drama3_k.Group.create(a, gpu, s, &kernels); defer d3.destroy(); var ck: ?cuda.ck.Ck = null; diff --git a/zig/tests/h3_image_decoder_cuda.zig b/zig/tests/h3_image_decoder_cuda.zig new file mode 100644 index 00000000000..6d20cb78a28 --- /dev/null +++ b/zig/tests/h3_image_decoder_cuda.zig @@ -0,0 +1,155 @@ +//! tf-h3-image-decoder-cuda: MiniMax-H3-Image's image decoder on CUDA, a latent to a PNG, or its self-test. +const std = @import("std"); +const dec = @import("h3_image_decoder_cuda"); +const hostdec = dec.host_decoder; +const selftest = dec.selftest; + +const vae = dec.vae; + +const usage = + \\usage: tf-h3-image-decoder-cuda MODEL_DIR latent.f32 ROWS COLUMNS out.png [WIDTHxHEIGHT] + \\ tf-h3-image-decoder-cuda reference MODEL_DIR latent.f32 ROWS COLUMNS gpu.png host.png [WIDTHxHEIGHT] + \\ tf-h3-image-decoder-cuda selftest + \\ MODEL_DIR the MiniMax-H3-Image folder: vae/config.json and vae/diffusion_pytorch_model.safetensors + \\ latent.f32 the normalised latent [24, ROWS, COLUMNS] in float32, as tf-h3-image writes it + \\ WIDTHxHEIGHT the requested size: the 16 COLUMNS x 16 ROWS canvas is resized to it (Pillow's LANCZOS) + \\reference decodes the same latent on the GPU and on the host's reference decoder, writes both PNGs and compares + \\the pictures against the selftest's full-chain relative bound; it exits 1 past it. + \\selftest runs the kernels on synthetic weights against a float64 host reference; it exits 1 past a bound. + \\ +; + +/// Tiles a pass decodes at most. +const batch = 16; + +/// The image decoder loaded once: its config and weights, its kernels and cuBLASLt plans. +pub const Vae = struct { + config: vae.Config, + d: *dec.Decoder, + + pub fn load(init: std.process.Init, a: std.mem.Allocator, model_dir: []const u8) !Vae { + const vae_dir = try std.fs.path.join(a, &.{ model_dir, "vae" }); + const config = try vae.config(a, try hostdec.read(init.io, a, try std.fs.path.join(a, &.{ vae_dir, "config.json" }), 1 << 20)); + const loading = dec.seconds(); + const d = try dec.Decoder.init(init.gpa, vae.layers, config.rope_theta); + errdefer d.deinit(); + try d.load(init.io, a, try std.fmt.allocPrint(a, "{s}/diffusion_pytorch_model.safetensors", .{vae_dir})); + std.debug.print("decoder weights in bf16 in {d:.1} s\n", .{dec.seconds() - loading}); + return .{ .config = config, .d = d }; + } + + /// The normalised `latent` [24, rows, cols] decoded and written to `path` as a PNG of `want` (default the canvas). + pub fn png(v: *const Vae, init: std.process.Init, a: std.mem.Allocator, latent: []f32, rows: usize, cols: usize, want: ?dec.host.Size, path: []const u8) !void { + if (latent.len != try dec.host.latentLength(rows, cols)) return error.H3BadLatentLength; + const tiles = try dec.host.tiles(a, &v.config, rows, cols); + const width = cols * vae.cell_pixels; + const height = rows * vae.cell_pixels; + const size = want orelse dec.host.Size{ .width = width, .height = height }; + try vae.denormalize(&v.config, latent); + const started = dec.seconds(); + const decoded = try a.alloc(f32, 3 * width * height); + const took = try v.d.decode(a, &v.config, latent, rows, cols, vae.layers, batch, decoded); + try hostdec.write(init.io, a, decoded, height, width, size.width, size.height, path); + std.debug.print("{d}x{d} canvas: decoded {d} tiles in {d:.2} s ({d:.2} s on the GPU), {d:.2} s in all; wrote {s} at {d}x{d}\n", .{ width, height, tiles.total(), took.wall, took.gpu, dec.seconds() - started, path, size.width, size.height }); + } +}; + +/// The latent file's [24, rows, cols] float32 values. +fn latentOf(init: std.process.Init, a: std.mem.Allocator, path: []const u8, rows: usize, cols: usize) ![]f32 { + const n = try dec.host.latentLength(rows, cols); + const bytes = try hostdec.read(init.io, a, path, n * 4 + 1); + if (bytes.len != n * 4) { + std.debug.print("{s} holds {d} bytes; a [24, {d}, {d}] float32 latent is {d}\n", .{ path, bytes.len, rows, cols, n * 4 }); + return error.H3BadLatentLength; + } + const latent = try a.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(latent), bytes); + return latent; +} + +/// `latent` decoded on the GPU and on the host reference decoder, both written as PNGs and the pictures compared. +fn reference(init: std.process.Init, a: std.mem.Allocator, model_dir: []const u8, latent: []f32, rows: usize, cols: usize, gpu_path: []const u8, host_path: []const u8, want: ?dec.host.Size) !bool { + const v = try Vae.load(init, a, model_dir); + defer v.d.deinit(); + const width = cols * vae.cell_pixels; + const height = rows * vae.cell_pixels; + const size = want orelse dec.host.Size{ .width = width, .height = height }; + try vae.denormalize(&v.config, latent); + const ours = try a.alloc(f32, 3 * width * height); + const started = dec.seconds(); + const took = try v.d.decode(a, &v.config, latent, rows, cols, vae.layers, batch, ours); + try hostdec.write(init.io, a, ours, height, width, size.width, size.height, gpu_path); + std.debug.print("{d}x{d} canvas: GPU decoder {d:.2} s in all ({d:.2} s on the GPU); wrote {s} at {d}x{d}\n", .{ width, height, dec.seconds() - started, took.gpu, gpu_path, size.width, size.height }); + var h = try hostdec.Decoder.init(init.gpa, vae.layers); + defer h.deinit(); + const loading = dec.seconds(); + try h.load(init.io, a, model_dir); + const theirs = try a.alloc(f32, ours.len); + const host_started = dec.seconds(); + try h.decode(a, &v.config, latent, rows, cols, vae.layers, theirs); + try hostdec.write(init.io, a, theirs, height, width, size.width, size.height, host_path); + std.debug.print("reference decoder: weights in {d:.1} s, {d:.2} s in all; wrote {s} at {d}x{d}\n", .{ host_started - loading, dec.seconds() - host_started, host_path, size.width, size.height }); + return compare(a, ours, theirs, height, width); +} + +/// The two decoded pictures: bytes' share identical and within 1, the largest difference, PSNR, the relative error. +fn compare(a: std.mem.Allocator, ours: []const f32, theirs: []const f32, height: usize, width: usize) !bool { + var dd: f64 = 0; + var norm: f64 = 0; + for (ours, theirs) |x, y| { + dd += (@as(f64, x) - y) * (@as(f64, x) - y); + norm += @as(f64, y) * y; + } + const relative = @sqrt(dd / @max(norm, 1e-300)); + const ours_rgb = try a.alloc(u8, ours.len); + const theirs_rgb = try a.alloc(u8, theirs.len); + try vae.pixels(ours, height, width, ours_rgb); + try vae.pixels(theirs, height, width, theirs_rgb); + var same: usize = 0; + var within: usize = 0; + var most: u8 = 0; + var squares: f64 = 0; + for (ours_rgb, theirs_rgb) |x, y| { + const d = if (x > y) x - y else y - x; + same += @intFromBool(d == 0); + within += @intFromBool(d <= 1); + most = @max(most, d); + squares += @as(f64, @floatFromInt(d)) * @as(f64, @floatFromInt(d)); + } + const count: f64 = @floatFromInt(ours_rgb.len); + const psnr = if (squares == 0) std.math.inf(f64) else 10 * @log10(255 * 255 / (squares / count)); + const ok = relative <= selftest.bounds.deep_relative; + std.debug.print("picture: {d:.3}% bytes identical, {d:.3}% within 1, at most {d} apart, PSNR {d:.2} dB; relative error {e:.2} (bound {e:.2}) ({s})\n", .{ 100 * @as(f64, @floatFromInt(same)) / count, 100 * @as(f64, @floatFromInt(within)) / count, most, psnr, relative, selftest.bounds.deep_relative, if (ok) "pass" else "FAIL" }); + return ok; +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len == 2 and (std.mem.eql(u8, args[1], "selftest") or std.mem.eql(u8, args[1], "--self-test"))) { + if (!try selftest.run(init.gpa, a)) std.process.exit(1); + return; + } + if (args.len >= 2 and std.mem.eql(u8, args[1], "reference")) { + if (args.len != 8 and args.len != 9) { + std.debug.print("{s}", .{usage}); + std.process.exit(2); + } + const rows = std.fmt.parseInt(usize, args[4], 10) catch return error.H3BadPictureGrid; + const cols = std.fmt.parseInt(usize, args[5], 10) catch return error.H3BadPictureGrid; + const latent = try latentOf(init, a, args[3], rows, cols); + const ok = try reference(init, a, args[2], latent, rows, cols, args[6], args[7], if (args.len == 9) try dec.host.size(args[8]) else null); + if (!ok) std.process.exit(1); + return; + } + if (args.len != 6 and args.len != 7) { + std.debug.print("{s}", .{usage}); + std.process.exit(2); + } + const rows = std.fmt.parseInt(usize, args[3], 10) catch return error.H3BadPictureGrid; + const cols = std.fmt.parseInt(usize, args[4], 10) catch return error.H3BadPictureGrid; + const latent = try latentOf(init, a, args[2], rows, cols); + const v = try Vae.load(init, a, args[1]); + defer v.d.deinit(); + try v.png(init, a, latent, rows, cols, if (args.len == 7) try dec.host.size(args[6]) else null, args[5]); +} diff --git a/zig/tests/h3_image_decoder_host.zig b/zig/tests/h3_image_decoder_host.zig new file mode 100644 index 00000000000..72b8dcb9b7c --- /dev/null +++ b/zig/tests/h3_image_decoder_host.zig @@ -0,0 +1,54 @@ +//! tf-h3-image-decoder-host: MiniMax-H3-Image's image decoder on the CPU, a latent to a PNG, no GPU. +const std = @import("std"); +const dec = @import("h3_image_decoder_host"); + +const host = dec.host; +const vae = dec.vae; + +const usage = + \\usage: tf-h3-image-decoder-host MODEL_DIR latent.f32 ROWS COLUMNS out.png [WIDTHxHEIGHT] + \\ MODEL_DIR the MiniMax-H3-Image folder: vae/config.json and vae/diffusion_pytorch_model.safetensors + \\ latent.f32 the normalised latent [24, ROWS, COLUMNS] in float32, as tf-h3-image writes it + \\ WIDTHxHEIGHT the requested size: the 16 COLUMNS x 16 ROWS canvas is resized to it (Pillow's LANCZOS) + \\ +; + +fn seconds(io: std.Io, since: std.Io.Timestamp) f64 { + return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds() - since.toNanoseconds())) / 1e9; +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len != 6 and args.len != 7) { + std.debug.print("{s}", .{usage}); + std.process.exit(2); + } + const rows = std.fmt.parseInt(usize, args[3], 10) catch return error.H3BadPictureGrid; + const cols = std.fmt.parseInt(usize, args[4], 10) catch return error.H3BadPictureGrid; + const n = try host.latentLength(rows, cols); + const bytes = try dec.read(init.io, a, args[2], n * 4 + 1); + if (bytes.len != n * 4) { + std.debug.print("{s} holds {d} bytes; a [24, {d}, {d}] float32 latent is {d}\n", .{ args[2], bytes.len, rows, cols, n * 4 }); + return error.H3BadLatentLength; + } + const latent = try a.alloc(f32, n); + @memcpy(std.mem.sliceAsBytes(latent), bytes); + const c = try dec.config(init.io, a, args[1]); + try vae.denormalize(&c, latent); + var d = try dec.Decoder.init(init.gpa, vae.layers); + defer d.deinit(); + const loading = std.Io.Clock.awake.now(init.io); + try d.load(init.io, a, args[1]); + std.debug.print("decoder weights in bf16 in {d:.1} s\n", .{seconds(init.io, loading)}); + const tiles = try host.tiles(a, &c, rows, cols); + const height = rows * vae.cell_pixels; + const width = cols * vae.cell_pixels; + const decoded = try a.alloc(f32, 3 * width * height); + const started = std.Io.Clock.awake.now(init.io); + try d.decode(a, &c, latent, rows, cols, vae.layers, decoded); + std.debug.print("decoder: {d:.2} s\n", .{seconds(init.io, started)}); + const size = if (args.len == 7) try host.size(args[6]) else host.Size{ .width = width, .height = height }; + try dec.write(init.io, a, decoded, height, width, size.width, size.height, args[5]); + std.debug.print("{d}x{d} canvas: decoded {d} tiles; wrote {s} at {d}x{d}\n", .{ width, height, tiles.total(), args[5], size.width, size.height }); +} diff --git a/zig/tests/h3_image_encoder.zig b/zig/tests/h3_image_encoder.zig index 324bca21261..9a605fe959b 100644 --- a/zig/tests/h3_image_encoder.zig +++ b/zig/tests/h3_image_encoder.zig @@ -2,7 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const he = @import("h3_image_encoder"); -const codec = @import("core").picture; +const codec = @import("picture_codec"); const noise = @import("torch_noise"); const selftest = @import("h3_image_encoder_selftest.zig"); diff --git a/zig/tests/h3_image_files.zig b/zig/tests/h3_image_files.zig new file mode 100644 index 00000000000..b68686ef56c --- /dev/null +++ b/zig/tests/h3_image_files.zig @@ -0,0 +1,71 @@ +//! The H3-Image tools' safetensors files: aligned images, a one-shard checkpoint and index, the selftests' scratch dir. +const std = @import("std"); +const fixture = @import("checkpoint_fixture"); + +/// A safetensors image whose data starts on 16 bytes: the fixture's aligned writer. +pub fn image(a: std.mem.Allocator, entries: []const fixture.Entry) ![]u8 { + return fixture.aligned(a, entries); +} + +/// `entries` as `dir`'s one shard, with the index naming it for every tensor. +pub fn checkpoint(io: std.Io, a: std.mem.Allocator, dir: []const u8, entries: []const fixture.Entry) !void { + try std.Io.Dir.cwd().createDirPath(io, dir); + const file = "model-00001-of-00001.safetensors"; + var index: std.ArrayList(u8) = .empty; + try index.appendSlice(a, "{\"weight_map\": {"); + for (entries, 0..) |e, i| try index.print(a, "{s}\"{s}\": \"{s}\"", .{ if (i == 0) "" else ", ", e.name, file }); + try index.appendSlice(a, "}}"); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }), .data = index.items }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ dir, file }), .data = try image(a, entries) }); +} + +/// A folder made new under `parent` for one selftest run: `deinit` removes it alone, never what `parent` already held. +pub const Scratch = struct { + path: []const u8, + + pub fn init(io: std.Io, a: std.mem.Allocator, parent: []const u8) !Scratch { + try std.Io.Dir.cwd().createDirPath(io, parent); + var bytes: [9]u8 = undefined; + io.random(&bytes); + var name: [12]u8 = undefined; + _ = std.base64.url_safe.Encoder.encode(&name, &bytes); + const path = try std.fs.path.join(a, &.{ parent, &name }); + try std.Io.Dir.cwd().createDir(io, path, .default_dir); // fails on an existing name, so it is ours alone + return .{ .path = path }; + } + + pub fn deinit(s: Scratch, io: std.Io) void { + std.Io.Dir.cwd().deleteTree(io, s.path) catch {}; + } +}; + +/// A selftest's shape: a checkpoint written into its scratch, then a step that may fail. +fn run(io: std.Io, a: std.mem.Allocator, parent: []const u8, fail: bool) !void { + const scratch = try Scratch.init(io, a, parent); + defer scratch.deinit(io); + try checkpoint(io, a, try std.fs.path.join(a, &.{ scratch.path, "text_encoder" }), &.{}); + if (fail) return error.GateFailed; +} + +test "selftest scratch: a run, passing or failing, removes its own folder and keeps what WORK_DIR held" { + const io = std.testing.io; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const parent = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + try tmp.dir.writeFile(io, .{ .sub_path = "sentinel", .data = "keep" }); + try tmp.dir.createDirPath(io, "text_encoder"); + try tmp.dir.writeFile(io, .{ .sub_path = "text_encoder/config.json", .data = "{}" }); + try run(io, a, parent, false); + try std.testing.expectError(error.GateFailed, run(io, a, parent, true)); + try std.testing.expectEqualStrings("keep", try tmp.dir.readFileAlloc(io, "sentinel", a, .limited(16))); + try std.testing.expectEqualStrings("{}", try tmp.dir.readFileAlloc(io, "text_encoder/config.json", a, .limited(16))); + var dir = try std.Io.Dir.cwd().openDir(io, parent, .{ .iterate = true }); + defer dir.close(io); + var it = dir.iterate(); + var left: usize = 0; + while (try it.next(io)) |_| left += 1; + try std.testing.expectEqual(2, left); +} diff --git a/zig/tests/h3_image_match.zig b/zig/tests/h3_image_match.zig new file mode 100644 index 00000000000..52e47d6438f --- /dev/null +++ b/zig/tests/h3_image_match.zig @@ -0,0 +1,48 @@ +//! The H3-Image selftests' comparison of a GPU run's bf16 values against a float64 host reference. +const std = @import("std"); +const bf16_round = @import("bf16_round"); + +/// Ours against the float64 reference: cosine, relative error, the share bit-equal, the worst value by its row's RMS. +pub const Match = struct { cosine: f64, relative: f64, equal: f64, worst: f64 }; + +pub fn match(ours: []const u16, theirs: []const f32, width: usize) Match { + var dot: f64 = 0; + var aa: f64 = 0; + var bb: f64 = 0; + var dd: f64 = 0; + var equal: usize = 0; + var worst: f64 = 0; + var row: usize = 0; + while (row < ours.len) : (row += width) { + var rb: f64 = 0; + var rd: f64 = 0; + for (ours[row..][0..width], theirs[row..][0..width]) |o, t| { + const x: f64 = bf16_round.value(o); + dot += x * t; + aa += x * x; + rb += @as(f64, t) * t; + rd = @max(rd, @abs(x - t)); + dd += (x - t) * (x - t); + equal += @intFromBool(o == bf16_round.bits(t)); + } + bb += rb; + worst = @max(worst, rd / @sqrt(@max(rb / @as(f64, @floatFromInt(width)), 1e-300))); + } + return .{ .cosine = dot / @sqrt(@max(aa * bb, 1e-300)), .relative = @sqrt(dd / @max(bb, 1e-300)), .equal = @as(f64, @floatFromInt(equal)) / @as(f64, @floatFromInt(ours.len)), .worst = worst }; +} + +pub fn report(label: []const u8, m: Match, pass: bool) void { + std.debug.print("{s}: cosine {d:.7}, relative error {e:.2}, {d:.4} bit-equal, worst value {e:.2} of its row's RMS ({s})\n", .{ label, m.cosine, m.relative, m.equal, m.worst, if (pass) "pass" else "FAIL" }); +} + +/// A whole run `m` beside the float32-sum host run's `noise`: within `factor` of its distance, cosine at `floor`. +pub fn within(m: Match, noise: Match, factor: f64, floor: f64) bool { + return m.cosine >= floor and 1 - m.cosine <= factor * (1 - noise.cosine) and m.relative <= factor * noise.relative; +} + +/// `vals` (bf16 values held in fp32) as their bf16 bits. +pub fn bf16s(a: std.mem.Allocator, vals: []const f32) ![]u16 { + const out = try a.alloc(u16, vals.len); + for (out, vals) |*o, v| o.* = bf16_round.bits(v); + return out; +} diff --git a/zig/tests/h3_image_prompt_cuda.zig b/zig/tests/h3_image_prompt_cuda.zig new file mode 100644 index 00000000000..e074c74e7fa --- /dev/null +++ b/zig/tests/h3_image_prompt_cuda.zig @@ -0,0 +1,532 @@ +//! tf-h3-image-prompt-cuda: H3-Image's prompt stage on CUDA, the tf-h3-image-prompt case or the float64 selftest. +const std = @import("std"); +const hp = @import("h3_prompt_cuda"); +const tokenizer = @import("tokenizer"); +const fixture = @import("checkpoint_fixture"); +const bf16_round = @import("bf16_round"); +const noise = @import("moss_noise"); + +const rules = hp.rules; +const ref = hp.reference; +const stage = hp.case; +const picture = hp.picture; +const ck = hp.checkpoint; +const files = @import("h3_image_files.zig"); +const match = @import("h3_image_match.zig"); + +const usage = + \\usage: tf-h3-image-prompt-cuda TEXT_ENCODER_DIR MODEL_DIR prompt.txt out.safetensors [WIDTHxHEIGHT [SEED [MIN_AREA]]] + \\ tf-h3-image-prompt-cuda selftest [WORK_DIR] + \\ TEXT_ENCODER_DIR MiniMax-H3's text_encoder/ (Qwen3-VL): config.json, its index and shards + \\ MODEL_DIR the MiniMax-H3-Image folder: model_index.json, tokenizer/, transformer/ + \\ prompt.txt the prompt, verbatim but for one trailing line ending + \\ out text BF16 [rows, 5376] and text_tags I32 [rows], as tf-h3-image's picture case reads them, + \\ and ids I32 [rows] + \\ WIDTHxHEIGHT a text-to-image case: the canvas (grown to MIN_AREA, default 2048 x 2048, at the size's + \\ ratio, sides snapped to 32), its starting rows from SEED (default 0) as torch's CPU randn + \\ draws them, and the requested size + \\ selftest the GPU kernels on a tiny synthetic checkpoint against the float64 host reference; + \\ WORK_DIR (default under TMPDIR) holds a new folder with the checkpoint while it runs + \\Exit 0: done or every gate passed; 1: a gate failed. + \\ +; + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const gpa = init.gpa; + const args = try init.minimal.args.toSlice(a); + if (args.len >= 2 and std.mem.eql(u8, args[1], "selftest") and args.len <= 3) { + const tmp = init.environ_map.get("TMPDIR") orelse "/tmp"; + const dir = if (args.len == 3) args[2] else try std.fs.path.join(a, &.{ tmp, "tf-h3-image-prompt-cuda-selftest" }); + return selftest(init, a, gpa, dir); + } + if (args.len < 5 or args.len > 8) { + std.debug.print("{s}", .{usage}); + return 2; + } + const request: ?stage.Request = if (args.len >= 6) .{ + .size = try stage.size(args[5]), + .seed = if (args.len >= 7) try std.fmt.parseInt(u64, args[6], 10) else 0, + .min_area = if (args.len == 8) try std.fmt.parseInt(u64, args[7], 10) else picture.default_min_area, + } else null; + const started = seconds(); + + // the folder and its tokenizer, checked as the host prompt path checks them + const io = init.io; + const enc = try rules.checkEncoder(a, try read(io, a, &.{ args[1], "config.json" })); + _ = try picture.checkIndex(a, try read(io, a, &.{ args[2], "model_index.json" })); + const transformer = try std.fs.path.join(a, &.{ args[2], "transformer" }); + const front = try rules.checkRefiner(a, try read(io, a, &.{ transformer, "config.json" })); + var tok = try tokenizer.loadTokenizer(io, a, try std.fs.path.join(a, &.{ args[2], "tokenizer" })); + defer tok.deinit(); + var prompt: []const u8 = try std.Io.Dir.cwd().readFileAlloc(io, args[3], a, .limited(16 << 20)); + if (std.mem.endsWith(u8, prompt, "\n")) prompt = prompt[0 .. prompt.len - 1]; + if (std.mem.endsWith(u8, prompt, "\r")) prompt = prompt[0 .. prompt.len - 1]; + + const p = try rules.present(a, &tok, enc.marks, &.{}, prompt); + const pos = try rules.positions(a, p, enc.marks, &.{}); + const T = p.ids.len; + + var runner = try hp.Runner.init(gpa); + defer runner.deinit(); + + // the text model, one layer's tensors read from the shards at a time + var shards = try Shards.open(io, a, gpa, args[1]); + defer shards.deinit(gpa); + const prefix = try rules.textPrefix(shards.where.keys()); + const embed = try shards.tensorBytes(try std.fmt.allocPrint(a, "{s}embed_tokens.weight", .{prefix}), .{ enc.text.vocab, enc.text.hidden }); + // the mapped bytes into the page cache before the uploads fault them in mid-copy + try shards.readAhead(io, a, TextNames{ .prefix = prefix, .layers = enc.text.layers }); + const enc_rows = try a.alloc(u16, T * enc.text.hidden); + var gpu_started = seconds(); + var layer_ctx: LayerCtx = .{ .shards = &shards, .g = enc.text, .prefix = prefix }; + try runner.encode(a, enc.text, embed, p.ids, pos, null, layerOf, &layer_ctx, enc_rows); + std.debug.print("{d} tokens; text encoder, {d} layers: {d:.2} s wall, {d:.2} s GPU\n", .{ T, enc.text.layers, seconds() - gpu_started, runner.gpu }); + + // condition_proj and the two-block refiner, their tensors read in order + var front_shards = try Shards.open(io, a, gpa, transformer); + defer front_shards.deinit(gpa); + const front_w = try frontTensors(&front_shards, front); + try front_shards.readAhead(io, a, struct { + fn accepts(_: @This(), name: []const u8) bool { + return std.mem.startsWith(u8, name, "condition_proj.") or std.mem.startsWith(u8, name, "token_refiner."); + } + }{}); + const text = try a.alloc(u16, T * front.hidden); + gpu_started = seconds(); + var block_ctx: BlockCtx = .{ .shards = &front_shards, .g = front }; + try runner.refine(a, front, front_w.cond_w, front_w.cond_b, front_w.final_norm, blockOf, &block_ctx, enc_rows, text); + std.debug.print("condition_proj and the token refiner: {d:.2} s wall, {d:.2} s GPU\n", .{ seconds() - gpu_started, runner.gpu }); + + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[4], .data = try stage.write(a, front.hidden, p, text, request, &noise.randn, &.{}) }); + std.debug.print("wrote {s}: text [{d}, {d}] bf16, text_tags and ids\n", .{ args[4], T, front.hidden }); + std.debug.print("prompt: {d:.2} s\n", .{seconds() - started}); + return 0; +} + +fn read(io: std.Io, a: std.mem.Allocator, parts: []const []const u8) ![]u8 { + const path = try std.fs.path.join(a, parts); + return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(64 << 20)) catch |err| { + std.debug.print("cannot read {s}: {s}\n", .{ path, @errorName(err) }); + return err; + }; +} + +const seconds = hp.seconds; + +/// A host checkpoint folder, as tf-h3-image-prompt-host's: the index's name-to-shard map, shards mapped on first use. +const Shards = struct { + gpa: std.mem.Allocator, + /// Tensor name to shard file, both in the caller's arena. + where: std.StringArrayHashMapUnmanaged([]const u8) = .empty, + folder: ck.Folder, + + fn open(io: std.Io, a: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8) !Shards { + const text = try read(io, a, &.{ dir, "model.safetensors.index.json" }); + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch return error.H3BadShardIndex; + if (doc != .object) return error.H3BadShardIndex; + const map = doc.object.get("weight_map") orelse return error.H3BadShardIndex; + if (map != .object or map.object.count() == 0) return error.H3BadShardIndex; + var s: Shards = .{ .gpa = gpa, .folder = .{ .dir = try a.dupe(u8, dir) } }; + var it = map.object.iterator(); + while (it.next()) |e| { + if (e.value_ptr.* != .string or std.mem.indexOf(u8, e.value_ptr.string, "/") != null) return error.H3BadShardIndex; + try s.where.put(a, e.key_ptr.*, e.value_ptr.string); + } + return s; + } + + fn deinit(s: *Shards, gpa: std.mem.Allocator) void { + s.folder.deinit(gpa); + } + + /// The shard holding `name`. + fn shard(s: *Shards, name: []const u8) !*ck.Checkpoint { + const file = s.where.get(name) orelse { + std.debug.print("no tensor {s}\n", .{name}); + return error.MissingTensor; + }; + return s.folder.shard(s.gpa, file); + } + + /// The mapped bytes of tensors `accepts` into the page cache before the GPU faults them, as `h3/read_ahead.zig`. + fn readAhead(s: *Shards, io: std.Io, a: std.mem.Allocator, accepts: anytype) !void { + var spans: std.ArrayList(hp.read_ahead.Span) = .empty; + defer spans.deinit(a); + var done: std.StringHashMapUnmanaged(void) = .empty; + defer done.deinit(a); + var it = s.where.iterator(); + while (it.next()) |e| { + if (!accepts.accepts(e.key_ptr.*)) continue; + const gop = try done.getOrPut(a, e.value_ptr.*); + if (gop.found_existing) continue; + const file = try s.shard(e.key_ptr.*); + const path = try std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ s.folder.dir, e.value_ptr.* }, 0); + var names = file.names.iterator(); + while (names.next()) |n| if (accepts.accepts(n.key_ptr.*)) { + const entry = n.value_ptr.*; + try spans.append(a, .{ .path = path, .lo = file.data + entry.begin, .hi = file.data + entry.end }); + }; + } + _ = try hp.read_ahead.read(a, io, spans.items); + } + + /// The bf16 tensor `name` at `shape` as stored bytes (columns 0: a vector of `rows` values). + fn tensorBytes(s: *Shards, name: []const u8, shape: rules.Shape) !hp.Tensor { + const e = try (try s.shard(name)).bf16(name); + const rows_: usize = if (shape[1] == 0) 1 else shape[0]; + const cols: usize = if (shape[1] == 0) shape[0] else shape[1]; + if (e.rows != rows_ or e.cols != cols) { + std.debug.print("{s} is [{d}, {d}]; the prompt path reads [{d}, {d}]\n", .{ name, e.rows, e.cols, rows_, cols }); + return error.H3UnexpectedTensor; + } + return e.bytes; + } +}; + +/// The text model's embedding and its first `layers` layers under `prefix`, the prompt path's set. +const TextNames = struct { + prefix: []const u8, + layers: usize, + + fn accepts(t: TextNames, name: []const u8) bool { + if (!std.mem.startsWith(u8, name, t.prefix)) return false; + const rest = name[t.prefix.len..]; + if (std.mem.eql(u8, rest, "embed_tokens.weight")) return true; + if (!std.mem.startsWith(u8, rest, "layers.")) return false; + const tail = rest["layers.".len..]; + const dot = std.mem.indexOfScalar(u8, tail, '.') orelse return false; + const i = std.fmt.parseInt(usize, tail[0..dot], 10) catch return false; + return i < t.layers; + } +}; + +/// `encode`'s layer callback: layer `li`'s 11 bf16 tensors from the mapped shards. +const LayerCtx = struct { shards: *Shards, g: rules.Text, prefix: []const u8 }; + +fn layerOf(ctx: *anyopaque, li: usize) anyerror!hp.LayerSet { + const c: *LayerCtx = @ptrCast(@alignCast(ctx)); + var set: hp.LayerSet = undefined; + var name: [176]u8 = undefined; + inline for (comptime std.meta.fieldNames(hp.LayerSet), rules.layerTensors(c.g)) |field, spec| { + std.debug.assert(std.mem.eql(u8, field, spec[0])); + @field(set, field) = try c.shards.tensorBytes(try std.fmt.bufPrint(&name, "{s}layers.{d}.{s}", .{ c.prefix, li, spec[1] }), spec[2]); + } + return set; +} + +/// `refine`'s block callback: block `bi`'s 8 bf16 tensors from the transformer's shards. +const BlockCtx = struct { shards: *Shards, g: rules.Refiner }; + +fn blockOf(ctx: *anyopaque, bi: usize) anyerror!hp.BlockSet { + const c: *BlockCtx = @ptrCast(@alignCast(ctx)); + var set: hp.BlockSet = undefined; + var name: [96]u8 = undefined; + inline for (comptime std.meta.fieldNames(hp.BlockSet), rules.blockTensors(c.g)) |field, spec| { + std.debug.assert(std.mem.eql(u8, field, spec[0])); + @field(set, field) = try c.shards.tensorBytes(try std.fmt.bufPrint(&name, "token_refiner.blocks.{d}.{s}", .{ bi, spec[1] }), spec[2]); + } + return set; +} + +/// condition_proj's weight and bias and the final norm, checked at the refiner's shapes. +fn frontTensors(s: *Shards, g: rules.Refiner) !struct { cond_w: hp.Tensor, cond_b: hp.Tensor, final_norm: hp.Tensor } { + var w: struct { cond_w: hp.Tensor, cond_b: hp.Tensor, final_norm: hp.Tensor } = undefined; + inline for (.{ "cond_w", "cond_b", "final_norm" }, rules.frontTensors(g)) |field, spec| { + std.debug.assert(std.mem.eql(u8, field, spec[0])); + @field(w, field) = try s.tensorBytes(spec[1], spec[2]); + } + return .{ .cond_w = w.cond_w, .cond_b = w.cond_b, .final_norm = w.final_norm }; +} + +/// The selftest's geometry, as tf-h3-image-prompt's: 2-layer 256-wide text (4+2 KV heads), 384-wide refiner, 70 rows. +const tiny_text: rules.Text = .{ .hidden = 256, .heads = 4, .kv_heads = 2, .ffn = 512, .vocab = 96, .layers = 2, .eps = 1e-6, .theta = 1e4, .sections = .{ 24, 20, 20 } }; +const tiny_front: rules.Refiner = .{ .text = 256, .hidden = 384, .heads = 2, .mlp = 512, .blocks = 2, .eps = 1e-5, .qk_eps = 1e-5, .final_eps = 1e-5 }; +const tiny_rows = 70; +/// The tiny checkpoint's stored bf16 bytes for `name`, missing ones refused rather than unwrapped. +fn bitsOf(tiny: *const Tiny, name: []const u8) !hp.Tensor { + return tiny.bits.get(name) orelse return error.MissingTensor; +} + +/// A synthetic checkpoint folder: bf16 tensors drawn uniformly, one shard and its index. +const Synth = struct { + a: std.mem.Allocator, + rand: std.Random, + entries: std.ArrayList(fixture.Entry) = .empty, + + /// A tensor `name` of `shape` drawn in center +- spread, kept in the shard; its values as fp32. + fn tensor(s: *Synth, name: []const u8, shape: rules.Shape, center: f32, spread: f32) ![]const f32 { + const n = shape[0] * @max(shape[1], 1); + const vals = try s.a.alloc(f32, n); + const bits = try s.a.alloc(u16, n); + for (vals, bits) |*v, *b| { + b.* = bf16_round.bits(center + spread * (2 * s.rand.float(f32) - 1)); + v.* = bf16_round.value(b.*); + } + const dims: []const usize = if (shape[1] == 0) try s.a.dupe(usize, shape[0..1]) else try s.a.dupe(usize, &shape); + try s.entries.append(s.a, .{ .name = try s.a.dupe(u8, name), .dtype = "BF16", .shape = dims, .bytes = std.mem.sliceAsBytes(bits) }); + return vals; + } + + /// A weight by its field: norms near 1, projections of unit gain, biases small. + fn weight(s: *Synth, name: []const u8, field: []const u8, shape: rules.Shape) ![]const f32 { + if (std.mem.indexOf(u8, field, "norm") != null) return s.tensor(name, shape, 1, 0.2); + if (shape[1] == 0) return s.tensor(name, shape, 0, 0.1); + return s.tensor(name, shape, 0, @sqrt(3.0 / @as(f32, @floatFromInt(shape[1])))); + } + + fn write(s: *Synth, io: std.Io, dir: []const u8) !void { + try files.checkpoint(io, s.a, dir, s.entries.items); + } +}; + +/// The tiny text model and refiner under `dir` (text_encoder/, transformer/), float64 host copies, bf16 for the GPU. +const Tiny = struct { + text_dir: []const u8, + front_dir: []const u8, + host: ref.Text, + front: ref.Refiner, + /// The stored bf16 tensors, keyed as the checkpoint names them. + bits: std.StringArrayHashMapUnmanaged([]const u8), + + fn write(io: std.Io, a: std.mem.Allocator, rand: std.Random, dir: []const u8) !Tiny { + const g = tiny_text; + const f = tiny_front; + var tiny: Tiny = .{ .text_dir = try std.fs.path.join(a, &.{ dir, "text_encoder" }), .front_dir = try std.fs.path.join(a, &.{ dir, "transformer" }), .host = undefined, .front = undefined, .bits = .empty }; + // the text model: three layers written, two run, beside a vision tensor the loader must leave alone + var text = Synth{ .a = a, .rand = rand }; + const prefix = "model.language_model."; + const embed = try text.tensor(prefix ++ "embed_tokens.weight", .{ g.vocab, g.hidden }, 0, 1); + try tiny.bits.put(a, prefix ++ "embed_tokens.weight", text.entries.items[text.entries.items.len - 1].bytes); + _ = try text.tensor("model.visual.blocks.0.norm1.weight", .{ 128, 0 }, 1, 0.2); + const layers = try a.alloc(ref.Layer, g.layers + 1); + for (layers, 0..) |*l, i| inline for (comptime std.meta.fieldNames(ref.Layer), rules.layerTensors(g)) |field, s| { + const name = try std.fmt.allocPrint(a, "{s}layers.{d}.{s}", .{ prefix, i, s[1] }); + @field(l, field) = try text.weight(name, field, s[2]); + try tiny.bits.put(a, name, text.entries.items[text.entries.items.len - 1].bytes); + }; + var front = Synth{ .a = a, .rand = rand }; + inline for (.{ "cond_w", "cond_b", "final_norm" }, rules.frontTensors(f)) |field, s| { + @field(tiny.front, field) = try front.weight(s[1], field, s[2]); + try tiny.bits.put(a, try a.dupe(u8, s[1]), front.entries.items[front.entries.items.len - 1].bytes); + } + const blocks = try a.alloc(ref.Block, f.blocks); + for (blocks, 0..) |*b, i| inline for (comptime std.meta.fieldNames(ref.Block), rules.blockTensors(f)) |field, s| { + const name = try std.fmt.allocPrint(a, "token_refiner.blocks.{d}.{s}", .{ i, s[1] }); + @field(b, field) = try front.weight(name, field, s[2]); + try tiny.bits.put(a, name, front.entries.items[front.entries.items.len - 1].bytes); + }; + tiny.front.blocks = blocks; + tiny.host = .{ .embed = embed, .layers = layers }; + try text.write(io, tiny.text_dir); + try front.write(io, tiny.front_dir); + return tiny; + } +}; + +/// A run's rows vs float64, gated by the fp32 host run's distance: cosine and relative error at most twice it. +fn whole(a: std.mem.Allocator, label: []const u8, ours: []const u16, sum32: []const f32, exact: []const f32, width: usize) !bool { + const host_noise = match.match(try match.bf16s(a, sum32), exact, width); + const m = match.match(ours, exact, width); + const pass = match.within(m, host_noise, 2, 0.999); + match.report(label, m, pass); + std.debug.print(" the float32-sum host run: cosine {d:.7}, relative error {e:.2}, {d:.4} bit-equal\n", .{ host_noise.cosine, host_noise.relative, host_noise.equal }); + return pass; +} + +fn selftest(init: std.process.Init, a: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8) !u8 { + const io = init.io; + var prng = std.Random.DefaultPrng.init(0x5133); + const rand = prng.random(); + const g = tiny_text; + const f = tiny_front; + const scratch = try files.Scratch.init(io, a, dir); + defer scratch.deinit(io); + const tiny = try Tiny.write(io, a, rand, scratch.path); + + var runner = try hp.Runner.init(gpa); + defer runner.deinit(); + std.debug.print("synthetic text model {d} wide ({d} layers run of {d}), refiner {d} wide, {d} rows\n", .{ g.hidden, g.layers, g.layers + 1, f.hidden, tiny_rows }); + var failed = false; + + const T = tiny_rows; + const ids = try a.alloc(u32, T); + for (ids) |*id| id.* = rand.uintLessThan(u32, @intCast(g.vocab)); + const pos = try a.alloc([3]i32, T); + for (pos, 0..) |*p, i| p.* = @splat(@intCast(i)); + + // the GPU run's weight callbacks answer from the tiny checkpoint's stored bf16 bytes + const prefix = "model.language_model."; + var bits_layer: Ctx = .{ .tiny = &tiny, .a = a, .g = g }; + const enc = try a.alloc(u16, T * g.hidden); + const started = seconds(); + try runner.encode(a, g, try bitsOf(&tiny, try std.fmt.allocPrint(a, "{s}embed_tokens.weight", .{prefix})), ids, pos, null, bitsLayer, &bits_layer, enc); + const enc_s = seconds() - started; + var bits_front: Ctx = .{ .tiny = &tiny, .a = a, .g = g }; + const out = try a.alloc(u16, T * f.hidden); + try runner.refine(a, f, try bitsOf(&tiny, "condition_proj.weight"), try bitsOf(&tiny, "condition_proj.bias"), try bitsOf(&tiny, "token_refiner.final_norm.weight"), bitsBlock, &bits_front, enc, out); + + // the float64 oracle and the float32-sum host run over the same weights + const cs = try a.alloc(f32, T * 64); + const sn = try a.alloc(f32, T * 64); + rules.rotary(cs, sn, pos, g.theta, g.sections); + const host = tiny.host; + const enc_ref = try a.alloc(f32, T * g.hidden); + try ref.encode(f64, a, g, host, ids, cs, sn, null, enc_ref); + const enc_32 = try a.alloc(f32, T * g.hidden); + try ref.encode(f32, a, g, host, ids, cs, sn, null, enc_32); + failed = !try whole(a, "text encoder rows, a text prompt", enc, enc_32, enc_ref, g.hidden) or failed; + const enc_f = try a.alloc(f32, enc.len); + for (enc_f, enc) |*o, v| o.* = bf16_round.value(v); + const out_ref = try a.alloc(f32, T * f.hidden); + try ref.refine(f64, a, f, tiny.front, enc_f, out_ref); + const out_32 = try a.alloc(f32, T * f.hidden); + try ref.refine(f32, a, f, tiny.front, enc_f, out_32); + failed = !try whole(a, "condition_proj, refiner and final norm on the GPU's encoder rows", out, out_32, out_ref, f.hidden) or failed; + + // a second run, byte for byte the same + const again = try a.alloc(u16, enc.len); + try runner.encode(a, g, try bitsOf(&tiny, try std.fmt.allocPrint(a, "{s}embed_tokens.weight", .{prefix})), ids, pos, null, bitsLayer, &bits_layer, again); + const out_again = try a.alloc(u16, out.len); + try runner.refine(a, f, try bitsOf(&tiny, "condition_proj.weight"), try bitsOf(&tiny, "condition_proj.bias"), try bitsOf(&tiny, "token_refiner.final_norm.weight"), bitsBlock, &bits_front, again, out_again); + const same = std.mem.eql(u16, enc, again) and std.mem.eql(u16, out, out_again); + std.debug.print("encoded in {d:.3} s; again, byte for byte the same: {}\n", .{ enc_s, same }); + failed = failed or !same; + + // an edit's rows: a 6-pad vision block spliced at the marks, DeepStack after layers 0-2, each part checked alone. + failed = !try withPicture(runner, a, rand, tiny) or failed; + std.debug.print("{s}\n", .{if (failed) "FAIL" else "PASS every gate"}); + return @intFromBool(failed); +} + +/// Preserve the failing full vision case, then separate no-op writes, layer growth, splice and DeepStack. +fn withPicture(runner: *hp.Runner, a: std.mem.Allocator, rand: std.Random, tiny: Tiny) !bool { + const g = tiny_text; + const H = g.hidden; + const n = 6; + var blocks: [4][]f32 = undefined; + const bits = try a.alloc(u16, 4 * n * H); + for (&blocks, 0..) |*v, j| { + v.* = try a.alloc(f32, n * H); + for (v.*, bits[j * n * H ..][0 .. n * H]) |*x, *b| { + b.* = bf16_round.bits(2 * rand.float(f32) - 1); + x.* = bf16_round.value(b.*); + } + } + // the presentation the pads land in: 62 text rows, the vision block's start mark, 6 pads, its end + const T = 62 + 1 + n + 1; + const ids = try a.alloc(u32, T); + for (ids, 0..) |*id, i| id.* = if (i < 62) @intCast(i % 80) else if (i < 62 + n) 91 else 92; + const pads = try a.alloc(u32, n); + for (pads, 0..) |*p, i| p.* = @intCast(63 + i); + const pos = try a.alloc([3]i32, T); + for (pos, 0..) |*p, i| p.* = @splat(@intCast(i)); + const cs = try a.alloc(f32, T * 64); + const sn = try a.alloc(f32, T * 64); + rules.rotary(cs, sn, pos, g.theta, g.sections); + var layer_ctx: Ctx = .{ .tiny = &tiny, .a = a, .g = g }; + const embed = try bitsOf(&tiny, "model.language_model.embed_tokens.weight"); + + // Preserve embedding rows for no-op splices; zero DeepStack blocks separate the two vision operations. + const zeros = try a.alloc(u16, n * H); + @memset(zeros, 0); + const zeros_f = try a.alloc(f32, n * H); + @memset(zeros_f, 0); + const keep = try a.alloc(u16, n * H); + const keep_f = try a.alloc(f32, n * H); + for (0..n) |i| { + const row = ids[pads[i]]; + @memcpy(std.mem.sliceAsBytes(keep[i * H ..][0..H]), embed[row * H * 2 ..][0 .. H * 2]); + @memcpy(keep_f[i * H ..][0..H], tiny.host.embed[row * H ..][0..H]); + } + const vision: hp.Vision = .{ .pads = pads, .rows = bits[0 .. n * H], .deepstack = .{ bits[n * H ..][0 .. n * H], bits[2 * n * H ..][0 .. n * H], bits[3 * n * H ..][0 .. n * H] } }; + const oracle: ref.Vision = .{ .pads = pads, .rows = blocks[0], .deepstack = blocks[1..4].* }; + + // Equal inputs must retain the same arithmetic with the vision copy/add path enabled. + const plain = try a.alloc(u16, T * H); + try runner.encode(a, g, embed, ids, pos, null, bitsLayer, &layer_ctx, plain); + const noop = try a.alloc(u16, T * H); + const noop_vision: hp.Vision = .{ .pads = pads, .rows = keep, .deepstack = .{ zeros, zeros, zeros } }; + try runner.encode(a, g, embed, ids, pos, noop_vision, bitsLayer, &layer_ctx, noop); + const noop_same = std.mem.eql(u16, plain, noop); + std.debug.print("a no-op vision (embedding rows spliced back, DeepStack zero) byte for byte the text-only run: {}\n", .{noop_same}); + + // one layer alone: the probes below separate its growth from splice and DeepStack + var first_layer = g; + first_layer.layers = 1; + + const Probe = struct { label: []const u8, geometry: rules.Text, gpu: hp.Vision, host: ref.Vision }; + const probes = [_]Probe{ + .{ .label = "text encoder rows, a reference's vision and DeepStack rows at equal-axis positions", .geometry = g, .gpu = vision, .host = oracle }, + .{ .label = "text encoder rows after layer 0 only, vision and DeepStack", .geometry = first_layer, .gpu = vision, .host = oracle }, + .{ + .label = "text encoder rows, vision spliced and DeepStack zero", + .geometry = g, + .gpu = .{ .pads = pads, .rows = vision.rows, .deepstack = .{ zeros, zeros, zeros } }, + .host = .{ .pads = pads, .rows = oracle.rows, .deepstack = .{ zeros_f, zeros_f, zeros_f } }, + }, + .{ + .label = "text encoder rows, DeepStack on embedding-row pads", + .geometry = g, + .gpu = .{ .pads = pads, .rows = keep, .deepstack = vision.deepstack }, + .host = .{ .pads = pads, .rows = keep_f, .deepstack = oracle.deepstack }, + }, + }; + const enc = try a.alloc(u16, T * H); + const exact = try a.alloc(f32, T * H); + const sum32 = try a.alloc(f32, T * H); + var ok = noop_same; + for (probes) |probe| { + try runner.encode(a, probe.geometry, embed, ids, pos, probe.gpu, bitsLayer, &layer_ctx, enc); + try ref.encode(f64, a, probe.geometry, tiny.host, ids, cs, sn, probe.host, exact); + try ref.encode(f32, a, probe.geometry, tiny.host, ids, cs, sn, probe.host, sum32); + ok = try whole(a, probe.label, enc, sum32, exact, H) and ok; + } + return ok; +} + +/// The selftest's weight callbacks' context: the tiny checkpoint's stored bf16 bytes by name. +const Ctx = struct { tiny: *const Tiny, a: std.mem.Allocator, g: rules.Text }; + +fn bitsLayer(ctx: *anyopaque, li: usize) anyerror!hp.LayerSet { + const c: *Ctx = @ptrCast(@alignCast(ctx)); + var set: hp.LayerSet = undefined; + inline for (comptime std.meta.fieldNames(hp.LayerSet), rules.layerTensors(c.g)) |field, spec| { + const name = try std.fmt.allocPrint(c.a, "model.language_model.layers.{d}.{s}", .{ li, spec[1] }); + @field(set, field) = try bitsOf(c.tiny, name); + } + return set; +} + +fn bitsBlock(ctx: *anyopaque, bi: usize) anyerror!hp.BlockSet { + const c: *Ctx = @ptrCast(@alignCast(ctx)); + var set: hp.BlockSet = undefined; + inline for (comptime std.meta.fieldNames(hp.BlockSet), rules.blockTensors(tiny_front)) |field, spec| { + const name = try std.fmt.allocPrint(c.a, "token_refiner.blocks.{d}.{s}", .{ bi, spec[1] }); + @field(set, field) = try bitsOf(c.tiny, name); + } + return set; +} + +test "the CUDA selftest exposes its checkpoint embedding to the encoder" { + const io = std.testing.io; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var prng = std.Random.DefaultPrng.init(0x5133); + const rand = prng.random(); + const scratch = try files.Scratch.init(io, a, try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path})); + defer scratch.deinit(io); + const tiny = try Tiny.write(io, a, rand, scratch.path); + const g = tiny_text; + + // the written text shard: the embedding the GPU path feeds, read back and checked byte for byte + var shards = try Shards.open(io, a, a, tiny.text_dir); + defer shards.deinit(a); + const embed = try shards.tensorBytes("model.language_model.embed_tokens.weight", .{ g.vocab, g.hidden }); + try std.testing.expectEqual(2 * g.vocab * g.hidden, embed.len); + try std.testing.expectEqualSlices(u8, embed, try bitsOf(&tiny, "model.language_model.embed_tokens.weight")); + try std.testing.expectError(error.MissingTensor, bitsOf(&tiny, "model.language_model.embed_tokens.weight.missing")); +} diff --git a/zig/tests/h3_image_prompt_host.zig b/zig/tests/h3_image_prompt_host.zig new file mode 100644 index 00000000000..4a9731e2794 --- /dev/null +++ b/zig/tests/h3_image_prompt_host.zig @@ -0,0 +1,207 @@ +//! tf-h3-image-prompt-host: H3-Image's prompt stage on the CPU, the tf-h3-image-prompt case on the host reference. +const std = @import("std"); +const hp = @import("h3_prompt"); +const ck = @import("h3_checkpoint"); +const tokenizer = @import("tokenizer"); +const noise = @import("moss_noise"); +const bf16_round = @import("bf16_round"); + +const rules = hp.rules; +const picture = hp.picture; +const ref = hp.reference; +const stage = hp.case; + +const usage = + \\usage: tf-h3-image-prompt-host TEXT_ENCODER_DIR MODEL_DIR prompt.txt out.safetensors [WIDTHxHEIGHT [SEED [MIN_AREA]]] + \\ TEXT_ENCODER_DIR MiniMax-H3's text_encoder/ (Qwen3-VL): config.json, its index and shards + \\ MODEL_DIR the MiniMax-H3-Image folder: model_index.json, tokenizer/, transformer/ + \\ prompt.txt the prompt, verbatim but for one trailing line ending + \\ out text BF16 [rows, 5376] and text_tags I32 [rows], as tf-h3-image's picture case reads them, + \\ and ids I32 [rows] + \\ WIDTHxHEIGHT a text-to-image case: the canvas (grown to MIN_AREA, default 2048 x 2048, at the size's + \\ ratio, sides snapped to 32), its starting rows from SEED (default 0) as torch's CPU randn + \\ draws them, and the requested size + \\ +; + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const gpa = init.gpa; + const args = try init.minimal.args.toSlice(a); + if (args.len < 5 or args.len > 8) { + std.debug.print("{s}", .{usage}); + return 2; + } + const request: ?stage.Request = if (args.len >= 6) .{ + .size = try stage.size(args[5]), + .seed = if (args.len >= 7) try std.fmt.parseInt(u64, args[6], 10) else 0, + .min_area = if (args.len == 8) try std.fmt.parseInt(u64, args[7], 10) else picture.default_min_area, + } else null; + const started = seconds(); + + // the folder and its tokenizer, checked as the Metal prompt path checks them + const io = init.io; + const enc = try rules.checkEncoder(a, try read(io, a, &.{ args[1], "config.json" })); + _ = try picture.checkIndex(a, try read(io, a, &.{ args[2], "model_index.json" })); + const transformer = try std.fs.path.join(a, &.{ args[2], "transformer" }); + const front = try rules.checkRefiner(a, try read(io, a, &.{ transformer, "config.json" })); + var tok = try tokenizer.loadTokenizer(io, a, try std.fs.path.join(a, &.{ args[2], "tokenizer" })); + defer tok.deinit(); + var prompt: []const u8 = try std.Io.Dir.cwd().readFileAlloc(io, args[3], a, .limited(16 << 20)); + if (std.mem.endsWith(u8, prompt, "\n")) prompt = prompt[0 .. prompt.len - 1]; + if (std.mem.endsWith(u8, prompt, "\r")) prompt = prompt[0 .. prompt.len - 1]; + + const p = try rules.present(a, &tok, enc.marks, &.{}, prompt); + const pos = try rules.positions(a, p, enc.marks, &.{}); + const T = p.ids.len; + const cos = try a.alloc(f32, T * 64); + const sin = try a.alloc(f32, T * 64); + rules.rotary(cos, sin, pos, enc.text.theta, enc.text.sections); + + // the text model, one layer's weights in memory at a time: its layers do not fit beside the transformer's + var shards = try Shards.open(io, a, gpa, args[1]); + defer shards.deinit(gpa); + const prefix = try rules.textPrefix(shards.where.keys()); + const x = try a.alloc(f32, T * enc.text.hidden); + try shards.embed(enc.text, prefix, p.ids, x); + const scratch = try ref.Scratch.init(a, enc.text, T); + var held = std.heap.ArenaAllocator.init(gpa); + defer held.deinit(); + for (0..enc.text.layers) |li| { + const layer = try shards.layer(held.allocator(), enc.text, prefix, li); + try ref.encodeLayer(f32, gpa, enc.text, layer, li, x, cos, sin, null, scratch); + _ = held.reset(.free_all); + } + + // condition_proj and the two-block refiner, their weights together + var front_shards = try Shards.open(io, a, gpa, transformer); + defer front_shards.deinit(gpa); + const text = try a.alloc(u16, T * front.hidden); + { + const w = try front_shards.refiner(held.allocator(), front); + const rows = try a.alloc(f32, T * front.hidden); + try ref.refine(f32, gpa, front, w, x, rows); + for (text, rows) |*o, v| o.* = bf16_round.bits(v); // every value is bf16-exact, so this only re-codes it + } + _ = held.reset(.free_all); + + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[4], .data = try stage.write(a, front.hidden, p, text, request, &noise.randn, &.{}) }); + std.debug.print("wrote {s}: text [{d}, {d}] bf16, text_tags and ids\n", .{ args[4], T, front.hidden }); + std.debug.print("prompt: {d:.2} s\n", .{seconds() - started}); + return 0; +} + +fn read(io: std.Io, a: std.mem.Allocator, parts: []const []const u8) ![]u8 { + const path = try std.fs.path.join(a, parts); + return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(64 << 20)) catch |err| { + std.debug.print("cannot read {s}: {s}\n", .{ path, @errorName(err) }); + return err; + }; +} + +/// Wall seconds on the monotonic clock: mtl.clock.seconds without Metal. +fn seconds() f64 { + var t: std.c.timespec = undefined; + _ = std.c.clock_gettime(std.c.CLOCK.MONOTONIC, &t); + return @as(f64, @floatFromInt(t.sec)) + @as(f64, @floatFromInt(t.nsec)) / 1e9; +} + +/// One bf16 pair as the fp32 value it holds exactly. +fn value(pair: []const u8) f32 { + return @bitCast(@as(u32, std.mem.readInt(u16, pair[0..2], .little)) << 16); +} + +/// A host checkpoint folder: the index's name-to-shard map, shards mapped on first use; callers free what they convert. +const Shards = struct { + gpa: std.mem.Allocator, + /// Tensor name to shard file, both in the caller's arena. + where: std.StringArrayHashMapUnmanaged([]const u8) = .empty, + folder: ck.Folder, + + fn open(io: std.Io, a: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8) !Shards { + const text = try read(io, a, &.{ dir, "model.safetensors.index.json" }); + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch return error.H3BadShardIndex; + if (doc != .object) return error.H3BadShardIndex; + const map = doc.object.get("weight_map") orelse return error.H3BadShardIndex; + if (map != .object or map.object.count() == 0) return error.H3BadShardIndex; + var s: Shards = .{ .gpa = gpa, .folder = .{ .dir = try a.dupe(u8, dir) } }; + var it = map.object.iterator(); + while (it.next()) |e| { + if (e.value_ptr.* != .string or std.mem.indexOf(u8, e.value_ptr.string, "/") != null) return error.H3BadShardIndex; + try s.where.put(a, e.key_ptr.*, e.value_ptr.string); + } + return s; + } + + fn deinit(s: *Shards, gpa: std.mem.Allocator) void { + s.folder.deinit(gpa); + } + + /// The shard holding `name`. + fn shard(s: *Shards, name: []const u8) !*ck.Checkpoint { + const file = s.where.get(name) orelse { + std.debug.print("no tensor {s}\n", .{name}); + return error.MissingTensor; + }; + return s.folder.shard(s.gpa, file); + } + + /// The bf16 tensor `name` at `shape` (columns 0: a vector of `rows` values). + fn tensor(s: *Shards, name: []const u8, shape: rules.Shape) !ck.Checkpoint.Entry { + const e = try (try s.shard(name)).bf16(name); + const rows: usize = if (shape[1] == 0) 1 else shape[0]; + const cols: usize = if (shape[1] == 0) shape[0] else shape[1]; + if (e.rows != rows or e.cols != cols) { + std.debug.print("{s} is [{d}, {d}]; the prompt path reads [{d}, {d}]\n", .{ name, e.rows, e.cols, rows, cols }); + return error.H3UnexpectedTensor; + } + return e; + } + + /// The bf16 tensor `name` at `shape` as fp32 values, exactly bf16's. + fn floats(s: *Shards, a: std.mem.Allocator, name: []const u8, shape: rules.Shape) ![]f32 { + const e = try s.tensor(name, shape); + const out = try a.alloc(f32, e.rows * e.cols); + for (out, 0..) |*o, i| o.* = value(e.bytes[2 * i ..]); + return out; + } + + /// The embedding rows of `ids`, converted from the mapped bf16 table: the table is never held in fp32. + fn embed(s: *Shards, g: rules.Text, prefix: []const u8, ids: []const u32, x: []f32) !void { + var name: [160]u8 = undefined; + const table = try s.tensor(try std.fmt.bufPrint(&name, "{s}embed_tokens.weight", .{prefix}), .{ g.vocab, g.hidden }); + for (ids, 0..) |id, r| { + if (id >= g.vocab) return error.H3TokenOutOfRange; + const row = table.bytes[@as(usize, id) * g.hidden * 2 ..][0 .. g.hidden * 2]; + for (x[r * g.hidden ..][0..g.hidden], 0..) |*o, i| o.* = value(row[2 * i ..]); + } + } + + /// Text layer `i`'s weights as fp32. + fn layer(s: *Shards, a: std.mem.Allocator, g: rules.Text, prefix: []const u8, i: usize) !ref.Layer { + var l: ref.Layer = undefined; + var name: [176]u8 = undefined; + inline for (comptime std.meta.fieldNames(ref.Layer), rules.layerTensors(g)) |field, spec| { + @field(l, field) = try s.floats(a, try std.fmt.bufPrint(&name, "{s}layers.{d}.{s}", .{ prefix, i, spec[1] }), spec[2]); + } + return l; + } + + /// The refiner's weights as fp32: condition_proj, its blocks and the final norm. + fn refiner(s: *Shards, a: std.mem.Allocator, g: rules.Refiner) !ref.Refiner { + var w: ref.Refiner = undefined; + inline for (.{ "cond_w", "cond_b", "final_norm" }, rules.frontTensors(g)) |field, spec| { + std.debug.assert(std.mem.eql(u8, field, spec[0])); + @field(w, field) = try s.floats(a, spec[1], spec[2]); + } + const blocks = try a.alloc(ref.Block, g.blocks); + for (blocks, 0..) |*b, i| { + var name: [96]u8 = undefined; + inline for (comptime std.meta.fieldNames(ref.Block), rules.blockTensors(g)) |field, spec| { + @field(b, field) = try s.floats(a, try std.fmt.bufPrint(&name, "token_refiner.blocks.{d}.{s}", .{ i, spec[1] }), spec[2]); + } + } + w.blocks = blocks; + return w; + } +}; From 485d4a0152f0c95ee4fa3f19e2afaf5aba73f98f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:57:13 +0000 Subject: [PATCH 166/361] adapt: join the H3 CUDA registry records to main s list --- zig/src/core/contract/registry_joins.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index c23eccd9b53..8389f3ec6ec 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -62,7 +62,7 @@ pub const cuda_pending = @import("qwen_whole_records.zig").records ++ @import("ricursive_cuda_records.zig").cuda ++ @import("ricursive_prep_records.zig").cuda ++ @import("ricursive_attn_records.zig").cuda ++ - @import("registry_media.zig").cuda_pending; + @import("registry_media.zig").cuda_pending ++ @import("h3_image_cuda_records.zig").records; pub const metal_before = @import("fsr_records.zig").metal ++ @import("scale_index_records.zig").metal ++ From c1e5dea44c2aeda5b7be3eba409d4597a42097a0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:26:13 +0000 Subject: [PATCH 167/361] adapt: register the H3 picture tools once, without duplicate Metal steps --- zig/build/h3_image_metal.zig | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) diff --git a/zig/build/h3_image_metal.zig b/zig/build/h3_image_metal.zig index 9361607853a..7dee69f8a75 100644 --- a/zig/build/h3_image_metal.zig +++ b/zig/build/h3_image_metal.zig @@ -1,27 +1,9 @@ -//! MiniMax-H3-Image's Metal tools: the transformer on a case file, a picture case, the edit encoder, the prompt tool +//! MiniMax-H3-Image's Metal tools: the edit encoder, the prompt tool and the image decoder. const std = @import("std"); -/// The picture tools on `metal`; `sources` is the Metal kernels' source module. +/// The picture tools on `metal`; `sources` is the Metal kernels' source module, used by the maintained H3 tool. pub fn tools(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, sources: *std.Build.Module) void { - const h3_kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") }); - const h3_core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); - const h3_mod = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = h3_core }, .{ .name = "h3_kernels", .module = h3_kernels }, .{ .name = "kernel_sources", .module = sources } } }); - const h3_dit = b.addExecutable(.{ .name = "tf-h3-dit", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/tests/h3_dit.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod } }, - }) }); - b.step("tf-h3-dit", "FastH3's Metal transformer against a case file: velocities, every step, timings").dependOn(&b.addInstallArtifact(h3_dit, .{}).step); - const h3_image = b.addExecutable(.{ .name = "tf-h3-image", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/tests/h3_image.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3", .module = h3_mod }, .{ .name = "core", .module = h3_core } }, - }) }); - b.step("tf-h3-image", "MiniMax-H3-Image's Metal transformer on a picture case: six distilled steps, teacher-forced and gated").dependOn(&b.addInstallArtifact(h3_image, .{}).step); + _ = sources; @import("h3_image_encoder.zig").tool(b, target, optimize, metal); @import("h3_image_prompt.zig").install(b, target, optimize, metal); @import("h3_image_decoder.zig").tool(b, target, optimize, metal); From bb475a7a84fd94a47b9a07a69b426134ad090e8a Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:34:58 +0800 Subject: [PATCH 168/361] Merge ashhart main: keep main's H3 picture stack, the CUDA prompt and decoder on core/root.zig Main's Metal image tools, recipe, h3_image_prompt.zig and tests win every add/add conflict. The separate h3_core module is gone: every H3 tool takes core/root.zig, which owns picture, picture_writer's resample and qwen_vl.rope; checkpoint_fixture comes from core too. The decoder's weights/read/synthetic helpers live once in image_decoder.zig, shared by Metal, CPU and CUDA. Unused qwen_copy.zig, h3_image_metal.zig and Tensors.span dropped. --- zig/build/h3_host.zig | 14 ++----- zig/build/h3_image_decoder_cuda.zig | 5 +-- zig/build/h3_image_encoder.zig | 5 +-- zig/build/h3_image_metal.zig | 10 ----- zig/build/h3_image_prompt_cuda.zig | 6 +-- zig/build/h3_image_prompt_host.zig | 13 +------ zig/src/core/h3_core.zig | 4 -- zig/src/families/h3/prompt_case.zig | 2 +- zig/src/families/h3/prompt_case_test.zig | 2 +- zig/src/families/h3/qwen_copy.zig | 48 ------------------------ zig/src/families/h3/tensors.zig | 5 --- zig/tests/h3_image_encoder.zig | 2 +- zig/tests/h3_image_files.zig | 2 +- zig/tests/h3_image_prompt_cuda.zig | 2 +- 14 files changed, 16 insertions(+), 104 deletions(-) delete mode 100644 zig/build/h3_image_metal.zig delete mode 100644 zig/src/core/h3_core.zig delete mode 100644 zig/src/families/h3/qwen_copy.zig diff --git a/zig/build/h3_host.zig b/zig/build/h3_host.zig index 385fef383ce..532f422a9ea 100644 --- a/zig/build/h3_host.zig +++ b/zig/build/h3_host.zig @@ -2,7 +2,7 @@ const std = @import("std"); pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { - const core = coreModule(b, target); + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = .Debug, .link_libc = true }); const root = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/geometry_test.zig"), .target = target, .imports = &.{.{ .name = "core", .module = core }} }); const filter = b.option([]const u8, "h3-filter", "Run one H3 host regression"); const cases = b.addTest(.{ .root_module = root, .filters = if (filter) |f| &.{f} else &.{} }); @@ -21,7 +21,7 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels }, .{ .name = "gpu_turn", .module = b.createModule(.{ .root_source_file = b.path("zig/src/server/gpu_turn.zig"), .target = target, .optimize = .Debug }) } }; const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports }); const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) }); - const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "checkpoint_fixture", .module = fixture(b, core) } } }) }); + const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core } } }) }); const compile = b.step("compile-h3-host", "Compile the actual H3 tools (tf-h3-dit, tf-h3-image) without compiling or executing shaders"); compile.dependOn(&tool.step); compile.dependOn(&picture_tool.step); @@ -95,15 +95,9 @@ pub fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu step.dependOn(&b.addInstallArtifact(lib, .{}).step); } -/// The core files H3 reads, for every H3 module (core/h3_core.zig). +/// The core module for the CUDA side's checkpoint (h3/checkpoint.zig). pub fn coreModule(b: *std.Build, target: std.Build.ResolvedTarget) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/core/h3_core.zig"), .target = target, .link_libc = true }); -} - -/// `checkpoint_fixture` for a tool that also holds `core`, which owns the fixture's file. -pub fn fixture(b: *std.Build, core: *std.Build.Module) *std.Build.Module { - const file = b.addWriteFiles().add("h3_fixture_alias.zig", "pub const Entry = f.Entry;\npub const image = f.image;\npub const aligned = f.aligned;\npub const write = f.write;\nconst f = @import(\"core\").checkpoint_fixture;\n"); - return b.createModule(.{ .root_source_file = file, .imports = &.{.{ .name = "core", .module = core }} }); + return b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .link_libc = true }); } /// H3's clip and picture tools share the maintained Metal family and core checkpoint reader. diff --git a/zig/build/h3_image_decoder_cuda.zig b/zig/build/h3_image_decoder_cuda.zig index 884e83f5d30..5550a24a721 100644 --- a/zig/build/h3_image_decoder_cuda.zig +++ b/zig/build/h3_image_decoder_cuda.zig @@ -5,9 +5,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil // no FMA contraction: the norms', attention's and SwiGLU's fp32 multiply-adds round as the host reference's do const image = if (opts.nvcc) |nvcc| @import("cuda_fatbin.zig").fatbin(b, nvcc, b.addSystemCommand(&.{ nvcc, "--version" }).captureStdOut(.{}), .{ .name = "h3_image_decoder", .flags = &.{ "-O3", "--fmad=false" }, .min_sm = 80 }, opts.sms) else b.addWriteFiles().add("h3-image-decoder-compile-only.fatbin", ""); const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); - const core = @import("h3_host.zig").coreModule(b, target); - const writer = b.createModule(.{ .root_source_file = b.path("zig/src/picture_writer.zig"), .target = target, .optimize = optimize }); - const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "picture_writer", .module = writer } } }); + const host = @import("h3_image_decoder.zig").hostImports(b, target, optimize); + const decoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, host[0], host[1] } }); decoder.addAnonymousImport("fatbin_h3_image_decoder", .{ .root_source_file = image }); const exe = b.addExecutable(.{ .name = "tf-h3-image-decoder-cuda", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_decoder_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "h3_image_decoder_cuda", .module = decoder }, diff --git a/zig/build/h3_image_encoder.zig b/zig/build/h3_image_encoder.zig index e55dfbd6dbc..a280f2b9a59 100644 --- a/zig/build/h3_image_encoder.zig +++ b/zig/build/h3_image_encoder.zig @@ -2,12 +2,11 @@ const std = @import("std"); fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module) *std.Build.Module { - const core = @import("h3_host.zig").coreModule(b, target); + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/image_encoder.zig") }); const encoder = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "h3_image_encoder_kernels", .module = kernels } } }); - const codec = b.createModule(.{ .root_source_file = b.path("zig/src/core/picture/picture.zig"), .target = target, .optimize = optimize, .link_libc = true }); const noise = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); - return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "picture_codec", .module = codec }, .{ .name = "torch_noise", .module = noise } } }); + return b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image_encoder.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "h3_image_encoder", .module = encoder }, .{ .name = "core", .module = core }, .{ .name = "torch_noise", .module = noise } } }); } /// `zig build tf-h3-image-encoder`: a reference picture to its clean rows, or `selftest`; needs no Metal compiler. diff --git a/zig/build/h3_image_metal.zig b/zig/build/h3_image_metal.zig deleted file mode 100644 index 7dee69f8a75..00000000000 --- a/zig/build/h3_image_metal.zig +++ /dev/null @@ -1,10 +0,0 @@ -//! MiniMax-H3-Image's Metal tools: the edit encoder, the prompt tool and the image decoder. -const std = @import("std"); - -/// The picture tools on `metal`; `sources` is the Metal kernels' source module, used by the maintained H3 tool. -pub fn tools(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, sources: *std.Build.Module) void { - _ = sources; - @import("h3_image_encoder.zig").tool(b, target, optimize, metal); - @import("h3_image_prompt.zig").install(b, target, optimize, metal); - @import("h3_image_decoder.zig").tool(b, target, optimize, metal); -} diff --git a/zig/build/h3_image_prompt_cuda.zig b/zig/build/h3_image_prompt_cuda.zig index a469a46b696..01bd44acd0f 100644 --- a/zig/build/h3_image_prompt_cuda.zig +++ b/zig/build/h3_image_prompt_cuda.zig @@ -9,8 +9,6 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil b.addWriteFiles().add("h3-image-prompt-compile-only.fatbin", ""); const cuda = @import("cuda.zig").runtime(b, target, optimize, &.{}); const core = @import("h3_host.zig").coreModule(b, target); - const fixture = @import("h3_host.zig").fixture(b, core); - const rope = @import("h3_image_prompt.zig").rope(b, target); const prompt = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/prompt_cuda.zig"), .target = target, @@ -19,8 +17,6 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, - .{ .name = "qwen_vl_rope", .module = rope }, - .{ .name = "checkpoint_fixture", .module = fixture }, }, }); prompt.addAnonymousImport("fatbin_h3_image_prompt", .{ .root_source_file = image }); @@ -32,7 +28,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .imports = &.{ .{ .name = "h3_prompt_cuda", .module = prompt }, .{ .name = "tokenizer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }) }, - .{ .name = "checkpoint_fixture", .module = fixture }, + .{ .name = "core", .module = core }, .{ .name = "moss_noise", .module = b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }) }, }, }); diff --git a/zig/build/h3_image_prompt_host.zig b/zig/build/h3_image_prompt_host.zig index 200322ce509..f09753d196c 100644 --- a/zig/build/h3_image_prompt_host.zig +++ b/zig/build/h3_image_prompt_host.zig @@ -1,6 +1,5 @@ //! tf-h3-image-prompt-host: the prompt stage on the CPU, Mac or the Spark alike — no Metal. const std = @import("std"); -const prompt = @import("h3_image_prompt.zig"); /// `zig build tf-h3-image-prompt-host` (any -Dtarget, among them aarch64-linux-gnu for the Spark) and pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, test_step: *std.Build.Step) void { @@ -13,9 +12,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .target = target, .link_libc = true, .imports = &.{ - .{ .name = "checkpoint_fixture", .module = fixture(b, target, optimize) }, + .{ .name = "core", .module = @import("h3_host.zig").coreModule(b, target) }, .{ .name = "moss_noise", .module = noise(b, target, optimize) }, - .{ .name = "qwen_vl_rope", .module = prompt.rope(b, target) }, }, }) })); const tests = b.step("test-h3-image-prompt-host", "The prompt stage's case writer: byte for byte the Metal tool's layout, and torch's CPU randn"); @@ -31,10 +29,7 @@ fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.O .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ - .{ .name = "qwen_vl_rope", .module = prompt.rope(b, target) }, - .{ .name = "checkpoint_fixture", .module = @import("h3_host.zig").fixture(b, core) }, - }, + .imports = &.{.{ .name = "core", .module = core }}, }); const checkpoint = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/checkpoint.zig"), @@ -57,10 +52,6 @@ fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.O }); } -fn fixture(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/core/checkpoint_fixture.zig"), .target = target, .optimize = optimize }); -} - fn noise(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { return b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/noise.zig"), .target = target, .optimize = optimize }); } diff --git a/zig/src/core/h3_core.zig b/zig/src/core/h3_core.zig deleted file mode 100644 index bac9f71a465..00000000000 --- a/zig/src/core/h3_core.zig +++ /dev/null @@ -1,4 +0,0 @@ -//! The core files H3 reads (safetensors, checked read-ahead, its fixture); image tools' pictures are their own module. -pub const safetensors = @import("safetensors.zig"); -pub const checkpoint_read_ahead = @import("checkpoint_read_ahead.zig"); -pub const checkpoint_fixture = @import("checkpoint_fixture.zig"); diff --git a/zig/src/families/h3/prompt_case.zig b/zig/src/families/h3/prompt_case.zig index b9bb0f00163..7104c67ab04 100644 --- a/zig/src/families/h3/prompt_case.zig +++ b/zig/src/families/h3/prompt_case.zig @@ -2,7 +2,7 @@ const std = @import("std"); const picture = @import("picture.zig"); const rules = @import("picture_prompt.zig"); -const fixture = @import("checkpoint_fixture"); +const fixture = @import("core").checkpoint_fixture; /// A text-to-image request: the size asked for, the seed and the smallest area drawn. pub const Request = struct { size: picture.Size, seed: u64, min_area: u64 }; diff --git a/zig/src/families/h3/prompt_case_test.zig b/zig/src/families/h3/prompt_case_test.zig index 7c537a1106a..839fab2fa97 100644 --- a/zig/src/families/h3/prompt_case_test.zig +++ b/zig/src/families/h3/prompt_case_test.zig @@ -1,6 +1,6 @@ //! The prompt stage's case writer against the layout tf-h3-image-prompt wrote before it moved to the host. const std = @import("std"); -const fixture = @import("checkpoint_fixture"); +const fixture = @import("core").checkpoint_fixture; const noise = @import("moss_noise"); const picture = @import("picture.zig"); const rules = @import("picture_prompt.zig"); diff --git a/zig/src/families/h3/qwen_copy.zig b/zig/src/families/h3/qwen_copy.zig deleted file mode 100644 index 74cf2a7d47c..00000000000 --- a/zig/src/families/h3/qwen_copy.zig +++ /dev/null @@ -1,48 +0,0 @@ -//! MiniMax-H3-Image's Qwen copy of a reference: its size, the processor's size for it, and its LANCZOS pixels. -const std = @import("std"); -const picture = @import("picture"); - -/// The Qwen copy of a reference: its short edge exactly this, both sides multiples of `qwen_factor`. -pub const qwen_edge = 1024; -/// Patch 16 times merge 2: the processor's side unit, and one vision token per 2 x 2 patches. -pub const qwen_factor = 32; -pub const merge = 2; - -pub const Size = struct { width: usize, height: usize }; - -/// x rounded to the nearest integer, ties to even, as Python's round() does on a float64. -fn roundEven(x: f64) f64 { - const f = @floor(x); - const d = x - f; - if (d > 0.5) return f + 1; - if (d < 0.5) return f; - return if (@mod(f, 2) == 0) f else f + 1; -} - -/// The Qwen copy's size: a 1,024 short edge kept, else both sides times 1024 / short edge, snapped to 32 (half even). -pub fn qwenBound(width: usize, height: usize) !Size { - if (width < qwen_factor or height < qwen_factor) return error.H3ReferenceTooSmall; - const short = @min(width, height); - if (short == qwen_edge) return .{ .width = width, .height = height }; - const scale = @as(f64, qwen_edge) / @as(f64, @floatFromInt(short)); - const snap = struct { - fn side(v: f64) usize { - return @as(usize, @intFromFloat(@max(1.0, roundEven(v / qwen_factor)))) * qwen_factor; - } - }; - return .{ .width = snap.side(@as(f64, @floatFromInt(width)) * scale), .height = snap.side(@as(f64, @floatFromInt(height)) * scale) }; -} - -/// The processor's size for a Qwen copy: smart resize to multiples of 32 in its pixel bounds, a no-op when snapped. -pub fn qwenProcessed(s: Size, min_pixels: u64, max_pixels: u64) !Size { - const r = picture.patches.smartResize(@intCast(s.height), @intCast(s.width), qwen_factor, min_pixels, max_pixels) catch return error.H3ReferenceAspect; - return .{ .width = r.w, .height = r.h }; -} - -/// The Qwen copy's RGB pixels: the original when its short edge is 1,024, else Pillow's LANCZOS to `qwenBound`. -pub fn qwenCopy(a: std.mem.Allocator, rgb: picture.Rgb) !picture.Rgb { - const s = try qwenBound(rgb.width, rgb.height); - if (s.width == rgb.width and s.height == rgb.height) return .{ .width = s.width, .height = s.height, .pixels = try a.dupe(u8, rgb.pixels) }; - const view = picture.resample.View.of(rgb.pixels, rgb.width, rgb.height); - return .{ .width = s.width, .height = s.height, .pixels = try picture.resample.resizeWith(a, .pillow, .lanczos, view, s.width, s.height) }; -} diff --git a/zig/src/families/h3/tensors.zig b/zig/src/families/h3/tensors.zig index ec4d2be7d86..59c29a1f77f 100644 --- a/zig/src/families/h3/tensors.zig +++ b/zig/src/families/h3/tensors.zig @@ -27,11 +27,6 @@ pub const Tensors = struct { return .{ .map = map, .buffer = buffer, .data = 8 + header_len, .names = names, .arena = arena, .path = owned }; } - /// The bytes of tensor `e` in the file, for `read_ahead`. - pub fn span(self: *const Tensors, e: st.Entry) read_ahead.Span { - return .{ .path = self.path, .lo = self.data + e.begin, .hi = self.data + e.end }; - } - pub fn deinit(self: *Tensors) void { self.buffer.deinit(); self.arena.deinit(); diff --git a/zig/tests/h3_image_encoder.zig b/zig/tests/h3_image_encoder.zig index 9a605fe959b..324bca21261 100644 --- a/zig/tests/h3_image_encoder.zig +++ b/zig/tests/h3_image_encoder.zig @@ -2,7 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const he = @import("h3_image_encoder"); -const codec = @import("picture_codec"); +const codec = @import("core").picture; const noise = @import("torch_noise"); const selftest = @import("h3_image_encoder_selftest.zig"); diff --git a/zig/tests/h3_image_files.zig b/zig/tests/h3_image_files.zig index b68686ef56c..cd0ba9ca165 100644 --- a/zig/tests/h3_image_files.zig +++ b/zig/tests/h3_image_files.zig @@ -1,6 +1,6 @@ //! The H3-Image tools' safetensors files: aligned images, a one-shard checkpoint and index, the selftests' scratch dir. const std = @import("std"); -const fixture = @import("checkpoint_fixture"); +const fixture = @import("core").checkpoint_fixture; /// A safetensors image whose data starts on 16 bytes: the fixture's aligned writer. pub fn image(a: std.mem.Allocator, entries: []const fixture.Entry) ![]u8 { diff --git a/zig/tests/h3_image_prompt_cuda.zig b/zig/tests/h3_image_prompt_cuda.zig index e074c74e7fa..cfc87715b5c 100644 --- a/zig/tests/h3_image_prompt_cuda.zig +++ b/zig/tests/h3_image_prompt_cuda.zig @@ -2,7 +2,7 @@ const std = @import("std"); const hp = @import("h3_prompt_cuda"); const tokenizer = @import("tokenizer"); -const fixture = @import("checkpoint_fixture"); +const fixture = @import("core").checkpoint_fixture; const bf16_round = @import("bf16_round"); const noise = @import("moss_noise"); From c13c597157b8c8e86400e1e40bbffd970771e5d0 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:43:31 +0800 Subject: [PATCH 169/361] h3 contract: a planted first-block control for every image decoder and prompt kernel --- zig/tests/cuda/contract_h3_image_decoder.zig | 14 ++++++++++++-- zig/tests/cuda/contract_h3_image_prompt.zig | 14 ++++++++++++-- zig/tests/cuda/contract_h3_register.zig | 15 +++++++++------ 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/zig/tests/cuda/contract_h3_image_decoder.zig b/zig/tests/cuda/contract_h3_image_decoder.zig index 9259b02dfcf..953250f0d57 100644 --- a/zig/tests/cuda/contract_h3_image_decoder.zig +++ b/zig/tests/cuda/contract_h3_image_decoder.zig @@ -98,6 +98,8 @@ pub const Dec = struct { outs: usize = 0, /// Grid geometry the launch derives from the prepared inputs. p: Shape64 = .{}, + /// A planted control: the same launch cut to its first block, so the outputs past it stay poisoned (gate 3 fails). + planted: bool = false, pub fn deinit(self: *Dec) void { self.rig.deinit(); @@ -105,9 +107,17 @@ pub const Dec = struct { } pub fn kernel(self: *Dec) g.Kernel { - return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + var sp = spec(self.which); + if (self.planted) sp.name = control_names.get(self.which); + return .{ .spec = sp, .ctx = self, .vt = &vt, .control = if (self.planted) .shapes else null }; } + const control_names = blk: { + var n = std.enums.EnumArray(Which, []const u8).initUndefined(); + for (std.enums.values(Which)) |w| n.set(w, spec(w).name ++ " control: first block only"); + break :blk n; + }; + const vt = g.hooks(Dec); /// `n` values uniform in [lo, hi), bf16-valued when `half`, some planted non-finite when `plant`. @@ -381,7 +391,7 @@ pub const Dec = struct { } fn go(self: *Dec, grid: cuda.Dim3, block: cuda.Dim3, args: *cuda.Args) !void { - try cuda.launch.launch(self.f, .{ .grid = grid, .block = block }, self.rig.s, args); + try cuda.launch.launch(self.f, .{ .grid = if (self.planted) .{} else grid, .block = block }, self.rig.s, args); } pub fn count(self: *Dec) usize { diff --git a/zig/tests/cuda/contract_h3_image_prompt.zig b/zig/tests/cuda/contract_h3_image_prompt.zig index a75a98c9271..85bdd47d912 100644 --- a/zig/tests/cuda/contract_h3_image_prompt.zig +++ b/zig/tests/cuda/contract_h3_image_prompt.zig @@ -105,6 +105,8 @@ pub const Prm = struct { q_row: usize = 0, k_row: usize = 0, fused: bool = false, + /// A planted control: the same launch cut to its first block, so the outputs past it stay poisoned (gate 3 fails). + planted: bool = false, pub fn deinit(self: *Prm) void { self.rig.deinit(); @@ -112,9 +114,17 @@ pub const Prm = struct { } pub fn kernel(self: *Prm) g.Kernel { - return .{ .spec = spec(self.which), .ctx = self, .vt = &vt }; + var sp = spec(self.which); + if (self.planted) sp.name = control_names.get(self.which); + return .{ .spec = sp, .ctx = self, .vt = &vt, .control = if (self.planted) .shapes else null }; } + const control_names = blk: { + var n = std.enums.EnumArray(Which, []const u8).initUndefined(); + for (std.enums.values(Which)) |w| n.set(w, spec(w).name ++ " control: first block only"); + break :blk n; + }; + const vt = g.hooks(Prm); fn values(self: *Prm, n: usize, lo: f64, hi: f64, fill: g.Fill, rng: std.Random, half: bool, plant: bool) ![]f64 { @@ -435,7 +445,7 @@ pub const Prm = struct { } fn go(self: *Prm, grid: cuda.Dim3, args: *cuda.Args) !void { - try cuda.launch.launch(self.f, .{ .grid = grid, .block = .{ .x = 256 } }, self.rig.s, args); + try cuda.launch.launch(self.f, .{ .grid = if (self.planted) .{} else grid, .block = .{ .x = 256 } }, self.rig.s, args); } pub fn count(self: *Prm) usize { diff --git a/zig/tests/cuda/contract_h3_register.zig b/zig/tests/cuda/contract_h3_register.zig index e30baf6dbcb..143fcb3b4e3 100644 --- a/zig/tests/cuda/contract_h3_register.zig +++ b/zig/tests/cuda/contract_h3_register.zig @@ -24,8 +24,9 @@ pub const Loaded = struct { h3p_mod: cuda.Module, h3_list: [std.enums.values(h3_k.Which).len]h3_k.H3, h3_topk: h3_topk_k.TopK, - h3d_list: [std.enums.values(h3d_k.Which).len]h3d_k.Dec, - h3p_list: [std.enums.values(h3p_k.Which).len]h3p_k.Prm, + /// Each decoder and prompt kernel twice: served, then its planted control. + h3d_list: [2 * std.enums.values(h3d_k.Which).len]h3d_k.Dec, + h3p_list: [2 * std.enums.values(h3p_k.Which).len]h3p_k.Prm, /// Frees every rig's arena and unloads the three images; call once the gates are done. pub fn deinit(l: *Loaded) void { @@ -53,14 +54,16 @@ pub fn append(l: *Loaded, a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, try kernels.append(a, l.h3_topk.kernel()); l.h3d_mod = try cuda.Module.load(gpu.d, &images.decoder); const h3d_which = comptime std.enums.values(h3d_k.Which); - for (h3d_which, &l.h3d_list) |w, *m| { - m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3d_mod.function(h3d_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a) }; + for (&l.h3d_list, 0..) |*m, i| { + const w = h3d_which[i % h3d_which.len]; + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3d_mod.function(h3d_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a), .planted = i >= h3d_which.len }; } for (&l.h3d_list) |*m| try kernels.append(a, m.kernel()); l.h3p_mod = try cuda.Module.load(gpu.d, &images.prompt); const h3p_which = comptime std.enums.values(h3p_k.Which); - for (h3p_which, &l.h3p_list) |w, *m| { - m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3p_mod.function(h3p_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a) }; + for (&l.h3p_list, 0..) |*m, i| { + const w = h3p_which[i % h3p_which.len]; + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3p_mod.function(h3p_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a), .planted = i >= h3p_which.len }; } for (&l.h3p_list) |*m| try kernels.append(a, m.kernel()); } From 9f178f7f2f7a2054ee922b4294dd34b95974e9c2 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:16:40 +0800 Subject: [PATCH 170/361] h3 contract: exactly one planted first-block control per decoder and prompt kernel (19) --- zig/tests/cuda/contract_h3_register.zig | 35 ++++++++++++++++++------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/zig/tests/cuda/contract_h3_register.zig b/zig/tests/cuda/contract_h3_register.zig index 143fcb3b4e3..6b66b5602e6 100644 --- a/zig/tests/cuda/contract_h3_register.zig +++ b/zig/tests/cuda/contract_h3_register.zig @@ -11,6 +11,23 @@ const h3p_k = @import("contract_h3_image_prompt.zig"); const g = core.contract.gates; +const h3d_which = std.enums.values(h3d_k.Which); +const h3p_which = std.enums.values(h3p_k.Which); +const h3d_planted = firstPerSymbol(h3d_k); +const h3p_planted = firstPerSymbol(h3p_k); + +/// The first form of each distinct kernel symbol, so every kernel gets exactly one planted control. +fn firstPerSymbol(comptime K: type) []const K.Which { + comptime { + var out: []const K.Which = &.{}; + outer: for (std.enums.values(K.Which)) |w| { + for (out) |o| if (std.mem.eql(u8, K.symbol(o), K.symbol(w))) continue :outer; + out = out ++ .{w}; + } + return out; + } +} + const images = struct { pub const h3 align(16) = @embedFile("fatbin_h3").*; pub const decoder align(16) = @embedFile("fatbin_h3_image_decoder").*; @@ -24,9 +41,9 @@ pub const Loaded = struct { h3p_mod: cuda.Module, h3_list: [std.enums.values(h3_k.Which).len]h3_k.H3, h3_topk: h3_topk_k.TopK, - /// Each decoder and prompt kernel twice: served, then its planted control. - h3d_list: [2 * std.enums.values(h3d_k.Which).len]h3d_k.Dec, - h3p_list: [2 * std.enums.values(h3p_k.Which).len]h3p_k.Prm, + /// Each decoder and prompt form served, then one planted control per kernel symbol. + h3d_list: [h3d_which.len + h3d_planted.len]h3d_k.Dec, + h3p_list: [h3p_which.len + h3p_planted.len]h3p_k.Prm, /// Frees every rig's arena and unloads the three images; call once the gates are done. pub fn deinit(l: *Loaded) void { @@ -53,17 +70,17 @@ pub fn append(l: *Loaded, a: std.mem.Allocator, gpu: check.Gpu, s: cuda.Stream, l.h3_topk = .{ .rig = .{ .gpu = gpu, .s = s }, .f = try l.h3_mod.function("h3_topk") }; try kernels.append(a, l.h3_topk.kernel()); l.h3d_mod = try cuda.Module.load(gpu.d, &images.decoder); - const h3d_which = comptime std.enums.values(h3d_k.Which); for (&l.h3d_list, 0..) |*m, i| { - const w = h3d_which[i % h3d_which.len]; - m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3d_mod.function(h3d_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a), .planted = i >= h3d_which.len }; + const planted = i >= h3d_which.len; + const w = if (planted) h3d_planted[i - h3d_which.len] else h3d_which[i]; + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3d_mod.function(h3d_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a), .planted = planted }; } for (&l.h3d_list) |*m| try kernels.append(a, m.kernel()); l.h3p_mod = try cuda.Module.load(gpu.d, &images.prompt); - const h3p_which = comptime std.enums.values(h3p_k.Which); for (&l.h3p_list, 0..) |*m, i| { - const w = h3p_which[i % h3p_which.len]; - m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3p_mod.function(h3p_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a), .planted = i >= h3p_which.len }; + const planted = i >= h3p_which.len; + const w = if (planted) h3p_planted[i - h3p_which.len] else h3p_which[i]; + m.* = .{ .rig = .{ .gpu = gpu, .s = s }, .which = w, .f = try l.h3p_mod.function(h3p_k.symbol(w)), .arena = std.heap.ArenaAllocator.init(a), .planted = planted }; } for (&l.h3p_list) |*m| try kernels.append(a, m.kernel()); } From fdbb21927df91bde06ca398fe650754909f50986 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:37:05 +0800 Subject: [PATCH 171/361] receipts: PR 3733 ask 4 (why the clip comparison can't run) and CI state --- .../h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md new file mode 100644 index 00000000000..f78d1b82764 --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -0,0 +1,21 @@ +# PR 3733 asks 3 to 5 + +## 4. An H3 clip checkpoint on main against this head + +This comparison can't be run on the Spark. Ash's main at `a6cde902d` has two tools that print H3 velocities +from a checkpoint. `tf-h3-dit` handles FastH3 clip cases and `tf-h3-image` handles picture cases (`zig/build/h3_host.zig:104-105`). +Both run only on Metal. CUDA's H3 on main is `libtf_h3.so` (`zig build tf-h3`). That library runs the transformer blocks +on rows the caller prepares. It has no case reader, no input and output projections, and no velocity output. The +clip case exporter, `tools/zig/h3_case.py`, lives on the `drowzeys/TensorFold` fork (`docs/recipes/minimax-h3-metal.md:47-49`). +It is in neither tree. The GB10 job `docs/recipes/minimax-h3-cuda/plant-203.sh` (side branch `gpu/203-plant`, `ba8ada1c7`) also lists every FastH3 checkpoint and H3 case file on that host. + +On the clip path, this head differs from main only in `checkpoint.zig`. There, `Checkpoint.open` maps the same bytes with the +same flags and keeps the fd until `deinit`. `git diff a6cde902d HEAD -- zig/src/families/h3/h3.zig +zig/src/families/h3/geometry.zig zig/src/families/h3/block.zig zig/src/families/h3/cuda*.zig` is empty. + +## CI on #3733 + +At `1ceaab3de`, every job (`fmt`, `zig`, `zig-b`, `zig-windows`, `pytest`, `release-paths`, `benchmark-clients`, +`comfyui-moss-installer`, `zig-macos-dev-tools`) is `QUEUED` and needs a maintainer's approval to run for a fork. +`host-nightly-*` is skipped. No job is red. Ash's main is not green either: its latest `No GPU` and `Zig format` runs at `75a86a0772` are +queued or pending, and the two before them, at `a6cde902d` and `924d50a9d`, were cancelled. From c43926eb3a0a139f37449e7e68c161eafc731e23 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:39:04 +0800 Subject: [PATCH 172/361] receipts: ask 4 names what the loader diff changes --- docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md index f78d1b82764..f1414b51e0a 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -7,11 +7,11 @@ from a checkpoint. `tf-h3-dit` handles FastH3 clip cases and `tf-h3-image` handl Both run only on Metal. CUDA's H3 on main is `libtf_h3.so` (`zig build tf-h3`). That library runs the transformer blocks on rows the caller prepares. It has no case reader, no input and output projections, and no velocity output. The clip case exporter, `tools/zig/h3_case.py`, lives on the `drowzeys/TensorFold` fork (`docs/recipes/minimax-h3-metal.md:47-49`). -It is in neither tree. The GB10 job `docs/recipes/minimax-h3-cuda/plant-203.sh` (side branch `gpu/203-plant`, `ba8ada1c7`) also lists every FastH3 checkpoint and H3 case file on that host. +It is in neither tree. The GB10 job `docs/recipes/minimax-h3-cuda/plant-203.sh` (side branch `gpu/203-plant`, `ba8ada1c7`) also searches that host for FastH3 checkpoints and H3 case files. -On the clip path, this head differs from main only in `checkpoint.zig`. There, `Checkpoint.open` maps the same bytes with the -same flags and keeps the fd until `deinit`. `git diff a6cde902d HEAD -- zig/src/families/h3/h3.zig -zig/src/families/h3/geometry.zig zig/src/families/h3/block.zig zig/src/families/h3/cuda*.zig` is empty. +The transformer diff against Ash's main is empty for `h3.zig`, `geometry.zig`, `block.zig` and the CUDA block sources. +The shared Metal loader does change: `tensors.zig` now uses the span-based `read_ahead.zig`, and `checkpoint.zig` is the +CUDA-side checkpoint reader. Static inspection is therefore not a substitute for the unavailable velocity comparison. ## CI on #3733 From 9d84046eb67130c462e35e16e5b8265ff56baa34 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:21:31 +0800 Subject: [PATCH 173/361] receipts: PR 3733 ask 3's 19 planted controls from TOP, CI at c203accb0 --- .../h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 28 +++++++++++--- .../controls-top-1c5bc91282e3.txt | 38 +++++++++++++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-1c5bc91282e3.txt diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md index f1414b51e0a..9b0e3135299 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -1,5 +1,22 @@ # PR 3733 asks 3 to 5 +## 3. A planted control for every new kernel + +Each of the 19 decoder and prompt kernels has a "first block only" control (`zig/tests/cuda/contract_h3_register.zig`). +TOP job `top-1c5bc91282e3` ran `tf-cuda-test kernel-contract` at `1ee412bf0` on the GB10, and every control went red at +`shapes`, the gate it is planted for. Each control's gate line and verdict are in `controls-top-1c5bc91282e3.txt`, 38 lines for +19 controls. For example: + +``` +FAIL shapes cuda h3 image decoder h3d_attention control: first block only: at 1x261x64 output 64 is -nan where float64 gives 9.543158e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_attention control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_heads rotary control: first block only: at 8x128x128 output 1024 is 3.984375e-1 where float64 gives 4.902344e-1: 11.95 of its bound +CONTROL cuda h3 image prompt h3p_heads rotary control: first block only: red at shapes, as planted +``` + +In the same log, all 122 H3 gate lines without a control are `PASS`. +The Desk stopped that job in `tf_md_conv3x3`'s float64 shapes reference, a moss kernel that is not part of H3. + ## 4. An H3 clip checkpoint on main against this head This comparison can't be run on the Spark. Ash's main at `a6cde902d` has two tools that print H3 velocities @@ -7,7 +24,7 @@ from a checkpoint. `tf-h3-dit` handles FastH3 clip cases and `tf-h3-image` handl Both run only on Metal. CUDA's H3 on main is `libtf_h3.so` (`zig build tf-h3`). That library runs the transformer blocks on rows the caller prepares. It has no case reader, no input and output projections, and no velocity output. The clip case exporter, `tools/zig/h3_case.py`, lives on the `drowzeys/TensorFold` fork (`docs/recipes/minimax-h3-metal.md:47-49`). -It is in neither tree. The GB10 job `docs/recipes/minimax-h3-cuda/plant-203.sh` (side branch `gpu/203-plant`, `ba8ada1c7`) also searches that host for FastH3 checkpoints and H3 case files. +It is in neither tree. The GB10 job `docs/recipes/minimax-h3-cuda/plant-203.sh` (side branch `gpu/203-plant-h3`, `30c9f2302`) also searches that host for FastH3 checkpoints and H3 case files. The transformer diff against Ash's main is empty for `h3.zig`, `geometry.zig`, `block.zig` and the CUDA block sources. The shared Metal loader does change: `tensors.zig` now uses the span-based `read_ahead.zig`, and `checkpoint.zig` is the @@ -15,7 +32,8 @@ CUDA-side checkpoint reader. Static inspection is therefore not a substitute for ## CI on #3733 -At `1ceaab3de`, every job (`fmt`, `zig`, `zig-b`, `zig-windows`, `pytest`, `release-paths`, `benchmark-clients`, -`comfyui-moss-installer`, `zig-macos-dev-tools`) is `QUEUED` and needs a maintainer's approval to run for a fork. -`host-nightly-*` is skipped. No job is red. Ash's main is not green either: its latest `No GPU` and `Zig format` runs at `75a86a0772` are -queued or pending, and the two before them, at `a6cde902d` and `924d50a9d`, were cancelled. +At `c203accb0` (23 Nov 05:2x): `pytest`, `release-paths` and `comfyui-moss-installer` pass. `zig` and `zig-macos-dev-tools` +were cancelled. `zig-windows` and `benchmark-clients (windows-latest)` are in progress. `fmt`, `zig-b` and +`benchmark-clients (ubuntu-latest)` are queued, and `host-nightly-*` is skipped. No job is red. Ash's main isn't green either: +`No GPU` and `Zig format` at `bdcb6e6086` are queued or pending, and every run before that at `df0f420161`, `a325f58258` +and `833d8ec465` was cancelled or is still pending. diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-1c5bc91282e3.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-1c5bc91282e3.txt new file mode 100644 index 00000000000..e7747e8f525 --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-1c5bc91282e3.txt @@ -0,0 +1,38 @@ +FAIL shapes cuda h3 image decoder h3d_post_quant control: first block only: at 1x256x24 output 192 is -nan where float64 gives 1.672110e0: nan of its bound +CONTROL cuda h3 image decoder h3d_post_quant control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_embed control: first block only: at 1x256x24 output 256 is -nan where float64 gives 3.792953e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_embed control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_rms_norm control: first block only: at 8x1024x1024 output 1024 is -nan where float64 gives 1.167831e0: nan of its bound +CONTROL cuda h3 image decoder h3d_rms_norm control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_layer_norm control: first block only: at 8x1024x1024 output 1024 is -nan where float64 gives 6.127985e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_layer_norm control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_linear control: first block only: at 8x256x1024 output 128 is -nan where float64 gives -1.251590e1: nan of its bound +CONTROL cuda h3 image decoder h3d_linear control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_finish bias control: first block only: at 8x1024x1 output 32 is -nan where float64 gives -1.045709e0: nan of its bound +CONTROL cuda h3 image decoder h3d_finish bias control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_heads control: first block only: at 1x261x3072 output 64 is -nan where float64 gives 6.727295e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_heads control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_attention control: first block only: at 1x261x64 output 64 is -nan where float64 gives 9.543158e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_attention control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_swiglu control: first block only: at 8x4096x8192 output 32 is -nan where float64 gives -1.039063e0: nan of its bound +CONTROL cuda h3 image decoder h3d_swiglu control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_norm qwen control: first block only: at 8x256x256 output 256 is -nan where float64 gives -6.471916e-1: nan of its bound +CONTROL cuda h3 image prompt h3p_norm qwen control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_heads rotary control: first block only: at 8x128x128 output 1024 is 3.984375e-1 where float64 gives 4.902344e-1: 11.95 of its bound +CONTROL cuda h3 image prompt h3p_heads rotary control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_attention causal control: first block only: at 8x128x8 output 512 is -nan where float64 gives 1.434424e0: nan of its bound +CONTROL cuda h3 image prompt h3p_attention causal control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_glu qwen control: first block only: at 8x256x1 output 256 is -nan where float64 gives -9.650574e-1: nan of its bound +CONTROL cuda h3 image prompt h3p_glu qwen control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_add control: first block only: at 8x1024x1 output 256 is 1.648438e0 where float64 gives 1.964844e0: 20.57 of its bound +CONTROL cuda h3 image prompt h3p_add control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_scatter_add control: first block only: at 4x256x8 output 0 is -5.937500e-1 where float64 gives 3.750000e-1: 661.32 of its bound +CONTROL cuda h3 image prompt h3p_scatter_add control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_embed control: first block only: at 8x256x32 output 256 is -nan where float64 gives -1.851563e0: nan of its bound +CONTROL cuda h3 image prompt h3p_embed control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_splice control: first block only: at 4x256x8 output 0 is -1.781250e0 where float64 gives -3.242188e-1: 1150.46 of its bound +CONTROL cuda h3 image prompt h3p_splice control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_linear control: first block only: at 4x128x256 output 256 is -nan where float64 gives 1.182369e0: nan of its bound +CONTROL cuda h3 image prompt h3p_linear control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_round control: first block only: at 8x1024x1 output 256 is -nan where float64 gives 6.593750e0: nan of its bound +CONTROL cuda h3 image prompt h3p_round control: first block only: red at shapes, as planted From 8d2066a0a94114ce95f5e3dca6fe7a0c454bc333 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:37:18 +0800 Subject: [PATCH 174/361] receipts: PR 3733 ask 5 from TOP job top-7c6183220113 (H3 contract clean, stale limits are main's) --- .../h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 21 +- .../contract-h3-top-7c6183220113.txt | 209 ++++++++++++++++++ .../decoder-selftest.txt | 2 +- .../limits-stale-top-7c6183220113.txt | 107 +++++++++ 4 files changed, 337 insertions(+), 2 deletions(-) create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-7c6183220113.txt create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-7c6183220113.txt diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md index 9b0e3135299..d24375d4ede 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -24,12 +24,31 @@ from a checkpoint. `tf-h3-dit` handles FastH3 clip cases and `tf-h3-image` handl Both run only on Metal. CUDA's H3 on main is `libtf_h3.so` (`zig build tf-h3`). That library runs the transformer blocks on rows the caller prepares. It has no case reader, no input and output projections, and no velocity output. The clip case exporter, `tools/zig/h3_case.py`, lives on the `drowzeys/TensorFold` fork (`docs/recipes/minimax-h3-metal.md:47-49`). -It is in neither tree. The GB10 job `docs/recipes/minimax-h3-cuda/plant-203.sh` (side branch `gpu/203-plant-h3`, `30c9f2302`) also searches that host for FastH3 checkpoints and H3 case files. +It is in neither tree. The GB10 job `plant-203.sh` also searched TOP for FastH3 checkpoints and H3 case files. That output scrolled out +of the door's 2000-line log (`job logs top-7c6183220113`), and the job's `/work/out` files don't include it. The transformer diff against Ash's main is empty for `h3.zig`, `geometry.zig`, `block.zig` and the CUDA block sources. The shared Metal loader does change: `tensors.zig` now uses the span-based `read_ahead.zig`, and `checkpoint.zig` is the CUDA-side checkpoint reader. Static inspection is therefore not a substitute for the unavailable velocity comparison. +## 5. CUDA selftests and the GB10 kernel contract + +TOP job `top-7c6183220113` ran `plant-203.sh` (side branch `gpu/203-plant-h3`, `30c9f2302`) on the GB10 and exited 0. +Both selftests pass: `decoder-selftest.txt` and `prompt-selftest.txt` end in `selftest: pass` and `PASS every gate`. +`tf-cuda-test kernel-contract h3` (`contract-h3-top-7c6183220113.txt`) runs the H3 kernels' gates, controls and live limits: + +``` +(filtered) SUMMARY 34 kernels: 34 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 8447 ms, limits 1 ms +``` + +The five-SM audit, `kernel-contract-limits` over `-Dsm=80,86,89,120,121` fatbins, reports `105 problems`. +All of them are stale records on 47 launches that aren't H3: `muse_linear` (17), `muse_glue`, `exl3_experts`, `GLM` (4 each), +`qwen35`, `flashnext_hcn`, `exl3_grouped` (3 each), `nemo_audio`, `muse_dflash2` (2 each), and `qmmf`, `qmm_prefill`, +`glm_glue`, `flashnext_mtp` and `drama3` (1 each). The list is in `limits-stale-top-7c6183220113.txt`. No H3 record is stale. +These problems already exist on Ash's main: against `bdcb6e608` this head adds only `h3_image_decoder.cu`, `h3_image_prompt.cu`, +`h3_image_cuda_records.zig` and their line in `registry_joins.zig` under `zig/kernels/cuda` and `zig/src/core/contract`. +The full unfiltered contract was not run again. The earlier run spent 75 minutes in `tf_md_conv3x3`'s float64 reference, a moss kernel. + ## CI on #3733 At `c203accb0` (23 Nov 05:2x): `pytest`, `release-paths` and `comfyui-moss-installer` pass. `zig` and `zig-macos-dev-tools` diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-7c6183220113.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-7c6183220113.txt new file mode 100644 index 00000000000..efd900ebfd2 --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-7c6183220113.txt @@ -0,0 +1,209 @@ +N/A cuda affine4 MLP128 replacement bits: cluster path needs sm_90 or newer, this GPU is sm_121 +N/A cuda affine4 MLP128 FP64: cluster path needs sm_90 or newer, this GPU is sm_121 +PASS nonfinite cuda h3 modulated norm h3_norm: 5381 non-finite and 80635 finite outputs match the float64 classes +PASS repeat cuda h3 modulated norm h3_norm: five runs byte-identical (344064 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 modulated norm h3_norm: 1 shapes within the float64 bound (worst 0.547 of the bound), 4 edges refused by the kernel +PASS sums cuda h3 modulated norm h3_norm: within its bound at k 5376; fp16 sums would miss 43x, bf16 0.0x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 gated add h3_gate_add: 3 non-finite and 43005 finite outputs match the float64 classes +PASS repeat cuda h3 gated add h3_gate_add: five runs byte-identical (172032 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 gated add h3_gate_add: 5 shapes within the float64 bound (worst 0.996 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 gated add h3_gate_add: declares none sums +PASS nonfinite cuda h3 pooled branch mix h3_gate_mix: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 pooled branch mix h3_gate_mix: five runs byte-identical (32768 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 pooled branch mix h3_gate_mix: 5 shapes within the float64 bound (worst 0.937 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 pooled branch mix h3_gate_mix: declares none sums +PASS nonfinite cuda h3 SwiGLU h3_swiglu: 3 non-finite and 114685 finite outputs match the float64 classes +PASS repeat cuda h3 SwiGLU h3_swiglu: five runs byte-identical (458752 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 SwiGLU h3_swiglu: 5 shapes within the float64 bound (worst 0.924 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 SwiGLU h3_swiglu: declares none sums +PASS nonfinite cuda h3 head layout h3_heads: 131 non-finite and 786301 finite outputs match the float64 classes +PASS repeat cuda h3 head layout h3_heads: five runs byte-identical (1572864 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 head layout h3_heads: 1 shapes within the float64 bound (worst 0.569 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 head layout h3_heads: within its bound at k 96; fp16 sums would miss 0x, bf16 0.3x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 tile means h3_pool: 1 non-finite and 6143 finite outputs match the float64 classes +PASS repeat cuda h3 tile means h3_pool: five runs byte-identical (49152 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 tile means h3_pool: 1 shapes within the float64 bound (worst 0.008 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 tile means h3_pool: within its bound at k 64; fp16 sums would miss 90x, bf16 733.3x (a mean of at most 64 bf16 values: no sum reaches past fp16's range) +PASS nonfinite cuda h3 tile scores h3_tile_scores: 24 non-finite and 104 finite outputs match the float64 classes +PASS repeat cuda h3 tile scores h3_tile_scores: five runs byte-identical (2048 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 tile scores h3_tile_scores: 5 shapes within the float64 bound (worst 0.101 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 tile scores h3_tile_scores: exact sums at k 128, where fp16 sums would miss by 932068x and bf16 by 9320675x +PASS nonfinite cuda h3 pooled branch h3_coarse: 256 non-finite and 1792 finite outputs match the float64 classes +PASS repeat cuda h3 pooled branch h3_coarse: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 pooled branch h3_coarse: 2 shapes within the float64 bound (worst 0.211 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 pooled branch h3_coarse: within its bound at k 16; fp16 sums would miss 961x, bf16 8380.3x (softmax weights in [0, 1], rounded to bf16 before the value product: the bf16 output hides the sums' error) +PASS nonfinite cuda h3 routed attention h3_attention: 128 non-finite and 94848 finite outputs match the float64 classes +PASS repeat cuda h3 routed attention h3_attention: five runs byte-identical (447488 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 routed attention h3_attention: 6 shapes within the float64 bound (worst 0.758 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 routed attention h3_attention: within its bound at k 1024; fp16 sums would miss 6x, bf16 44.5x (softmax weights in [0, 1], rounded to bf16 before the value product: the bf16 output hides the sums' error) +PASS nonfinite cuda h3 tile top-k h3_topk: the stated rule holds: a NaN score ranks as -inf, ties go to the lower tile, so every row keeps exactly n tiles +PASS repeat cuda h3 tile top-k h3_topk: five runs byte-identical (143360 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 tile top-k h3_topk: 2 shapes exact by its own check (worst 0.000 of the bound), 4 edges refused by the kernel +N/A sums cuda h3 tile top-k h3_topk: declares none sums +PASS nonfinite cuda h3 image decoder h3d_post_quant: 24 non-finite and 30696 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_post_quant: five runs byte-identical (12288 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_post_quant: 3 shapes within the float64 bound (worst 0.991 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_post_quant: within its bound at k 24; fp16 sums would miss 41x, bf16 536.8x (the 24-term dot's bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image decoder h3d_embed: 3072 non-finite and 1333248 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_embed: five runs byte-identical (534528 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_embed: 2 shapes within the float64 bound (worst 0.995 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_embed: within its bound at k 24; fp16 sums would miss 173x, bf16 1486.3x (the 24-term dot's bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image decoder h3d_rms_norm: 1026 non-finite and 7166 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_rms_norm: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_rms_norm: 2 shapes within the float64 bound (worst 0.995 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_rms_norm: within its bound at k 1024; fp16 sums would miss 256x, bf16 0.5x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image decoder h3d_layer_norm: 3072 non-finite and 5120 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_layer_norm: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_layer_norm: 2 shapes within the float64 bound (worst 0.995 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_layer_norm: within its bound at k 1024; fp16 sums would miss 374158x, bf16 223.6x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image decoder h3d_linear: 384 non-finite and 256 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_linear: five runs byte-identical (2048 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_linear: 4 shapes within the float64 bound (worst 0.012 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_linear: within its bound at k 4096; fp16 sums would miss 0x, bf16 2.3x (each output sums K in increasing order with individually rounded fp32 multiplies and adds) +PASS nonfinite cuda h3 image decoder h3d_finish bias: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_finish bias: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_finish bias: 2 shapes within the float64 bound (worst 0.996 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image decoder h3d_finish bias: declares none sums +PASS nonfinite cuda h3 image decoder h3d_finish layerscale: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_finish layerscale: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_finish layerscale: 2 shapes within the float64 bound (worst 0.331 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image decoder h3d_finish layerscale: declares none sums +PASS nonfinite cuda h3 image decoder h3d_heads: 67 non-finite and 4008893 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_heads: five runs byte-identical (1603584 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_heads: 2 shapes within the float64 bound (worst 0.199 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_heads: within its bound at k 3072; fp16 sums would miss 1x, bf16 0.6x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image decoder h3d_attention: 192 non-finite and 1336128 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_attention: five runs byte-identical (534528 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_attention: 2 shapes within the float64 bound (worst 0.992 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_attention: within its bound at k 64; fp16 sums would miss 14x, bf16 125.0x (softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image decoder h3d_swiglu: 3 non-finite and 32765 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_swiglu: five runs byte-identical (65536 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_swiglu: 2 shapes within the float64 bound (worst 0.493 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image decoder h3d_swiglu: declares none sums +FAIL shapes cuda h3 image decoder h3d_post_quant control: first block only: at 1x256x24 output 192 is -nan where float64 gives 1.672110e0: nan of its bound +CONTROL cuda h3 image decoder h3d_post_quant control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_embed control: first block only: at 1x256x24 output 256 is -nan where float64 gives 3.792953e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_embed control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_rms_norm control: first block only: at 8x1024x1024 output 1024 is -nan where float64 gives 1.167831e0: nan of its bound +CONTROL cuda h3 image decoder h3d_rms_norm control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_layer_norm control: first block only: at 8x1024x1024 output 1024 is -nan where float64 gives 6.127985e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_layer_norm control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_linear control: first block only: at 8x256x1024 output 128 is -nan where float64 gives -1.251590e1: nan of its bound +CONTROL cuda h3 image decoder h3d_linear control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_finish bias control: first block only: at 8x1024x1 output 32 is -nan where float64 gives -1.045709e0: nan of its bound +CONTROL cuda h3 image decoder h3d_finish bias control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_heads control: first block only: at 1x261x3072 output 64 is -nan where float64 gives 6.727295e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_heads control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_attention control: first block only: at 1x261x64 output 64 is -nan where float64 gives 9.543158e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_attention control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_swiglu control: first block only: at 8x4096x8192 output 32 is -nan where float64 gives -1.039063e0: nan of its bound +CONTROL cuda h3 image decoder h3d_swiglu control: first block only: red at shapes, as planted +PASS nonfinite cuda h3 image prompt h3p_norm qwen: 258 non-finite and 1790 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_norm qwen: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_norm qwen: 2 shapes within the float64 bound (worst 0.492 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_norm qwen: within its bound at k 1024; fp16 sums would miss 126x, bf16 0.8x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_norm h3: 258 non-finite and 1790 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_norm h3: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_norm h3: 2 shapes within the float64 bound (worst 0.990 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_norm h3: within its bound at k 1024; fp16 sums would miss 252x, bf16 0.7x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_heads rotary: 132 non-finite and 10108 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_heads rotary: five runs byte-identical (20480 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_heads rotary: 2 shapes within the float64 bound (worst 0.248 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_heads rotary: within its bound at k 128; fp16 sums would miss 1x, bf16 11.2x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_heads fused qkv: 3 non-finite and 3069 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_heads fused qkv: five runs byte-identical (6144 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_heads fused qkv: 2 shapes within the float64 bound (worst 0.495 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_heads fused qkv: within its bound at k 128; fp16 sums would miss 0x, bf16 0.3x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_attention causal: 384 non-finite and 3712 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_attention causal: five runs byte-identical (8192 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_attention causal: 2 shapes within the float64 bound (worst 0.495 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_attention causal: within its bound at k 77; fp16 sums would miss 5x, bf16 25.1x (softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image prompt h3p_attention all rows: 384 non-finite and 3712 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_attention all rows: five runs byte-identical (8192 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_attention all rows: 2 shapes within the float64 bound (worst 0.493 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_attention all rows: within its bound at k 77; fp16 sums would miss 5x, bf16 42.4x (softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image prompt h3p_glu qwen: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_glu qwen: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_glu qwen: 2 shapes within the float64 bound (worst 0.493 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_glu qwen: declares none sums +PASS nonfinite cuda h3 image prompt h3p_glu h3: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_glu h3: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_glu h3: 2 shapes within the float64 bound (worst 0.329 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_glu h3: declares none sums +PASS nonfinite cuda h3 image prompt h3p_add: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_add: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_add: 2 shapes within the float64 bound (worst 0.497 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_add: declares none sums +PASS nonfinite cuda h3 image prompt h3p_scatter_add: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_scatter_add: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_scatter_add: 2 shapes within the float64 bound (worst 0.996 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_scatter_add: declares none sums +PASS nonfinite cuda h3 image prompt h3p_embed: 1 non-finite and 2047 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_embed: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_embed: 2 shapes within the float64 bound (worst 0.000 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_embed: declares none sums +PASS nonfinite cuda h3 image prompt h3p_splice: 2 non-finite and 2046 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_splice: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_splice: 2 shapes within the float64 bound (worst 0.000 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_splice: declares none sums +PASS nonfinite cuda h3 image prompt h3p_linear: 384 non-finite and 256 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_linear: five runs byte-identical (2048 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_linear: 2 shapes within the float64 bound (worst 0.004 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_linear: within its bound at k 1024; fp16 sums would miss 3x, bf16 18.3x (a k-length sequential fp32 dot is the reference's own order) +PASS nonfinite cuda h3 image prompt h3p_round: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_round: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_round: 2 shapes within the float64 bound (worst 0.000 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_round: declares none sums +FAIL shapes cuda h3 image prompt h3p_norm qwen control: first block only: at 8x256x256 output 256 is -nan where float64 gives -6.471916e-1: nan of its bound +CONTROL cuda h3 image prompt h3p_norm qwen control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_heads rotary control: first block only: at 8x128x128 output 1024 is 3.984375e-1 where float64 gives 4.902344e-1: 11.95 of its bound +CONTROL cuda h3 image prompt h3p_heads rotary control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_attention causal control: first block only: at 8x128x8 output 512 is -nan where float64 gives 1.434424e0: nan of its bound +CONTROL cuda h3 image prompt h3p_attention causal control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_glu qwen control: first block only: at 8x256x1 output 256 is -nan where float64 gives -9.650574e-1: nan of its bound +CONTROL cuda h3 image prompt h3p_glu qwen control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_add control: first block only: at 8x1024x1 output 256 is 1.648438e0 where float64 gives 1.964844e0: 20.57 of its bound +CONTROL cuda h3 image prompt h3p_add control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_scatter_add control: first block only: at 4x256x8 output 0 is -5.937500e-1 where float64 gives 3.750000e-1: 661.32 of its bound +CONTROL cuda h3 image prompt h3p_scatter_add control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_embed control: first block only: at 8x256x32 output 256 is -nan where float64 gives -1.851563e0: nan of its bound +CONTROL cuda h3 image prompt h3p_embed control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_splice control: first block only: at 4x256x8 output 0 is -1.781250e0 where float64 gives -3.242188e-1: 1150.46 of its bound +CONTROL cuda h3 image prompt h3p_splice control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_linear control: first block only: at 4x128x256 output 256 is -nan where float64 gives 1.182369e0: nan of its bound +CONTROL cuda h3 image prompt h3p_linear control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_round control: first block only: at 8x1024x1 output 256 is -nan where float64 gives 6.593750e0: nan of its bound +CONTROL cuda h3 image prompt h3p_round control: first block only: red at shapes, as planted +PASS limits live sm_121 most shared bytes a block (opt-in): the driver says 101376, the table 101376 +PASS limits live sm_121 threads a block: the driver says 1024, the table 1024 +INFO limits live: images built by nvcc 13.0, checked against nvcc 13.0's records +PASS limits live h3 h3_norm: 256 threads launched, the driver allows 256; 32 registers, 128 + 0 shared bytes (recorded 32, 128) +PASS limits live h3 h3_gate_add: 256 threads launched, the driver allows 256; 22 registers, 0 + 0 shared bytes (recorded 22, 0) +PASS limits live h3 h3_gate_mix: 256 threads launched, the driver allows 256; 24 registers, 0 + 0 shared bytes (recorded 24, 0) +PASS limits live h3 h3_swiglu: 256 threads launched, the driver allows 256; 24 registers, 0 + 0 shared bytes (recorded 24, 0) +PASS limits live h3 h3_heads: 256 threads launched, the driver allows 256; 255 registers, 0 + 0 shared bytes (recorded 255, 0) +PASS limits live h3 h3_pool: 32 threads launched, the driver allows 1024; 40 registers, 0 + 0 shared bytes (recorded 40, 0) +PASS limits live h3 h3_tile_scores: 256 threads launched, the driver allows 256; 21 registers, 0 + 0 shared bytes (recorded 21, 0) +PASS limits live h3 h3_coarse: 32 threads launched, the driver allows 1024; 39 registers, 0 + 0 shared bytes (recorded 39, 0) +PASS limits live h3 h3_attention: 128 threads launched, the driver allows 128; 217 registers, 0 + 49152 shared bytes (recorded 217, 0) +PASS limits live h3 h3_topk: 32 threads launched, the driver allows 1024; 40 registers, 0 + 0 shared bytes (recorded 40, 0) +PASS limits live h3_image h3d_post_quant: 256 threads launched, the driver allows 256; 40 registers, 0 + 0 shared bytes (recorded 40, 0) +PASS limits live h3_image h3d_embed: 256 threads launched, the driver allows 256; 40 registers, 0 + 0 shared bytes (recorded 40, 0) +PASS limits live h3_image h3d_rms_norm: 256 threads launched, the driver allows 256; 32 registers, 64 + 0 shared bytes (recorded 32, 64) +PASS limits live h3_image h3d_layer_norm: 256 threads launched, the driver allows 256; 26 registers, 64 + 0 shared bytes (recorded 26, 64) +PASS limits live h3_image h3d_linear: 256 threads launched, the driver allows 256; 127 registers, 16512 + 0 shared bytes (recorded 127, 16512) +PASS limits live h3_image h3d_finish: 256 threads launched, the driver allows 256; 14 registers, 0 + 0 shared bytes (recorded 14, 0) +PASS limits live h3_image h3d_heads: 32 threads launched, the driver allows 32; 21 registers, 0 + 0 shared bytes (recorded 21, 0) +PASS limits live h3_image h3d_attention: 256 threads launched, the driver allows 256; 48 registers, 11264 + 0 shared bytes (recorded 48, 11264) +PASS limits live h3_image h3d_swiglu: 256 threads launched, the driver allows 256; 20 registers, 0 + 0 shared bytes (recorded 20, 0) +PASS limits live h3_image h3p_norm: 256 threads launched, the driver allows 256; 27 registers, 8 + 0 shared bytes (recorded 27, 8) +PASS limits live h3_image h3p_heads: 256 threads launched, the driver allows 256; 40 registers, 0 + 0 shared bytes (recorded 40, 0) +PASS limits live h3_image h3p_attention: 256 threads launched, the driver allows 256; 40 registers, 0 + 0 shared bytes (recorded 40, 0) +PASS limits live h3_image h3p_glu: 256 threads launched, the driver allows 256; 17 registers, 0 + 0 shared bytes (recorded 17, 0) +PASS limits live h3_image h3p_add: 256 threads launched, the driver allows 256; 10 registers, 0 + 0 shared bytes (recorded 10, 0) +PASS limits live h3_image h3p_scatter_add: 256 threads launched, the driver allows 256; 14 registers, 0 + 0 shared bytes (recorded 14, 0) +PASS limits live h3_image h3p_embed: 256 threads launched, the driver allows 256; 14 registers, 0 + 0 shared bytes (recorded 14, 0) +PASS limits live h3_image h3p_splice: 256 threads launched, the driver allows 256; 12 registers, 0 + 0 shared bytes (recorded 12, 0) +PASS limits live h3_image h3p_linear: 256 threads launched, the driver allows 256; 29 registers, 0 + 0 shared bytes (recorded 29, 0) +PASS limits live h3_image h3p_round: 256 threads launched, the driver allows 256; 10 registers, 0 + 0 shared bytes (recorded 10, 0) +(filtered) SUMMARY 34 kernels: 34 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 8447 ms, limits 1 ms diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt index fd51a2f9104..c16fd259e41 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt @@ -1,4 +1,4 @@ -CUDA decoder: 24 synthetic blocks made in 1.7 s +CUDA decoder: 24 synthetic blocks made in 1.9 s 6 x 10 cells: 1 tiles of 6 x 10 cells, 65 tokens each embedding: 66560 values, 99.997% identical, worst 1.00 ULP, relative 1.91e-5 (pass) block 0: 66560 values, 96.946% identical, worst 2.00 ULP, relative 5.73e-4 (pass) diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-7c6183220113.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-7c6183220113.txt new file mode 100644 index 00000000000..2c322a2e1b0 --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-7c6183220113.txt @@ -0,0 +1,107 @@ +PASS limits sm_121 qmm_prefill many bit-exact BF16 launch fusion: 130 registers, 0 static shared bytes, bound 256 (record stale) +PASS limits sm_80 glm_glue tf_glm_dsel_merge: 57 registers, 34064 static shared bytes, bound 1024 (record stale) +PASS limits sm_120 flashnext_hcn fn_hcn_down2: 161 registers, 0 static shared bytes, bound 224 (record stale) +PASS limits sm_121 flashnext_hcn fn_hcn_down2: 161 registers, 0 static shared bytes, bound 224 (record stale) +PASS limits sm_120 flashnext_hcn fn_hcn_down3: 190 registers, 0 static shared bytes, bound 224 (record stale) +PASS limits sm_121 flashnext_hcn fn_hcn_down3: 190 registers, 0 static shared bytes, bound 224 (record stale) +PASS limits sm_120 flashnext_hcn fn_hcn_up3: 128 registers, 0 static shared bytes, bound 256 (record stale) +PASS limits sm_121 flashnext_hcn fn_hcn_up3: 128 registers, 0 static shared bytes, bound 256 (record stale) +PASS limits sm_80 qmmf BF16 fp32 out 16-row tile, fused slices: 78 registers, 0 static shared bytes, bound 128 (record stale) +PASS limits sm_86 qmmf BF16 fp32 out 16-row tile, fused slices: 78 registers, 0 static shared bytes, bound 128 (record stale) +PASS limits sm_89 qmmf BF16 fp32 out 16-row tile, fused slices: 78 registers, 0 static shared bytes, bound 128 (record stale) +PASS limits sm_120 nemo_audio tf_nemo_attn64: 68 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_121 nemo_audio tf_nemo_attn64: 68 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_120 nemo_audio tf_nemo_preds: 27 registers, 0 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_glue muse_rms: 19 registers, 132 static shared bytes, bound 0 (record stale) +PASS limits sm_121 muse_glue muse_expert_sum: 28 registers, 132 static shared bytes, bound 0 (record stale) +PASS limits sm_121 muse_glue muse_softcap: 30 registers, 0 static shared bytes, bound 0 (record stale) +PASS limits sm_121 muse_glue muse_argmax: 40 registers, 2048 static shared bytes, bound 0 (record stale) +PASS limits sm_121 muse_linear muse_linear_multi_k2: 128 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k2_w4: 245 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k2_w8: 251 registers, 16 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_linear muse_linear_multi_k3: 153 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k3_w8: 252 registers, 16 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_linear muse_linear_multi_k4: 128 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k4_w4: 245 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k4_w8: 251 registers, 16 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_linear muse_linear_multi_k5: 154 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k5_w4: 253 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k5_w8: 255 registers, 16 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_linear muse_linear_multi_k6: 154 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k6_w4: 255 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k6_w8: 255 registers, 16 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_linear muse_linear_multi_k8: 141 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_linear2_k8_w4: 245 registers, 16 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_linear muse_rot_multi: 24 registers, 0 static shared bytes, bound 128 (record stale) +PASS limits sm_121 muse_dflash2 dfl_topk: 48 registers, 3072 static shared bytes, bound 256 (record stale) +PASS limits sm_121 muse_dflash2 dfl_walk: 38 registers, 196 static shared bytes, bound 512 (record stale) +PASS limits sm_80 flashnext_mtp fn_row_topk: 32 registers, 9228 static shared bytes, bound 1024 (record stale) +PASS limits sm_86 flashnext_mtp fn_row_topk: 59 registers, 9228 static shared bytes, bound 1024 (record stale) +PASS limits sm_89 flashnext_mtp fn_row_topk: 59 registers, 9228 static shared bytes, bound 1024 (record stale) +PASS limits sm_120 flashnext_mtp fn_row_topk: 34 registers, 9228 static shared bytes, bound 1024 (record stale) +PASS limits sm_121 flashnext_mtp fn_row_topk: 34 registers, 9228 static shared bytes, bound 1024 (record stale) +PASS limits sm_80 exl3_experts tf_exl3_prompt_gu: 126 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_86 exl3_experts tf_exl3_prompt_gu: 128 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_89 exl3_experts tf_exl3_prompt_gu: 128 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_120 exl3_experts tf_exl3_prompt_gu: 124 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_121 exl3_experts tf_exl3_prompt_gu: 124 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_80 exl3_experts tf_exl3_prompt_down: 126 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_86 exl3_experts tf_exl3_prompt_down: 126 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_89 exl3_experts tf_exl3_prompt_down: 126 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_120 exl3_experts tf_exl3_prompt_down: 126 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_121 exl3_experts tf_exl3_prompt_down: 126 registers, 43264 static shared bytes, bound 256 (record stale) +PASS limits sm_80 exl3_experts tf_exl3_prompt_gu_k6: 127 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_86 exl3_experts tf_exl3_prompt_gu_k6: 126 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_89 exl3_experts tf_exl3_prompt_gu_k6: 126 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_120 exl3_experts tf_exl3_prompt_gu_k6: 127 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_121 exl3_experts tf_exl3_prompt_gu_k6: 127 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_80 exl3_experts tf_exl3_prompt_down_k6: 125 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_86 exl3_experts tf_exl3_prompt_down_k6: 125 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_89 exl3_experts tf_exl3_prompt_down_k6: 125 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_120 exl3_experts tf_exl3_prompt_down_k6: 127 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_121 exl3_experts tf_exl3_prompt_down_k6: 127 registers, 40192 static shared bytes, bound 256 (record stale) +PASS limits sm_80 qwen35 tf_q35_gdn_slots_1: 80 registers, 4096 static shared bytes, bound 128 (record stale) +PASS limits sm_80 qwen35 tf_q35_gdn_slots_2: 80 registers, 8192 static shared bytes, bound 128 (record stale) +PASS limits sm_80 qwen35 tf_q35_gdn_slots_4: 80 registers, 16384 static shared bytes, bound 128 (record stale) +PASS limits sm_80 drama3 d3_router_compact: 19 registers, 592 static shared bytes, bound 0 (record stale) +PASS limits sm_86 drama3 d3_router_compact: 19 registers, 592 static shared bytes, bound 0 (record stale) +PASS limits sm_89 drama3 d3_router_compact: 19 registers, 592 static shared bytes, bound 0 (record stale) +PASS limits sm_120 drama3 d3_router_compact: 26 registers, 592 static shared bytes, bound 0 (record stale) +PASS limits sm_121 drama3 d3_router_compact: 26 registers, 592 static shared bytes, bound 0 (record stale) +PASS limits sm_80 exl3_grouped tf_ctl_exl3_grouped_old_0: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_86 exl3_grouped tf_ctl_exl3_grouped_old_0: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_89 exl3_grouped tf_ctl_exl3_grouped_old_0: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_120 exl3_grouped tf_ctl_exl3_grouped_old_0: 127 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_121 exl3_grouped tf_ctl_exl3_grouped_old_0: 127 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_80 exl3_grouped tf_ctl_exl3_grouped_old_1: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_86 exl3_grouped tf_ctl_exl3_grouped_old_1: 127 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_89 exl3_grouped tf_ctl_exl3_grouped_old_1: 127 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_120 exl3_grouped tf_ctl_exl3_grouped_old_1: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_121 exl3_grouped tf_ctl_exl3_grouped_old_1: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_80 exl3_grouped tf_ctl_exl3_grouped_old_2: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_86 exl3_grouped tf_ctl_exl3_grouped_old_2: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_89 exl3_grouped tf_ctl_exl3_grouped_old_2: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_120 exl3_grouped tf_ctl_exl3_grouped_old_2: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_121 exl3_grouped tf_ctl_exl3_grouped_old_2: 128 registers, 32896 static shared bytes, bound 0 (record stale) +PASS limits sm_80 GLM BF16 tf_ctl_glm_old_rmsnorm_512: 18 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_86 GLM BF16 tf_ctl_glm_old_rmsnorm_512: 19 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_89 GLM BF16 tf_ctl_glm_old_rmsnorm_512: 19 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_120 GLM BF16 tf_ctl_glm_old_rmsnorm_512: 22 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_121 GLM BF16 tf_ctl_glm_old_rmsnorm_512: 22 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_80 GLM BF16 tf_ctl_glm_old_rmsnorm_1536: 40 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_86 GLM BF16 tf_ctl_glm_old_rmsnorm_1536: 40 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_89 GLM BF16 tf_ctl_glm_old_rmsnorm_1536: 40 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_120 GLM BF16 tf_ctl_glm_old_rmsnorm_1536: 40 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_121 GLM BF16 tf_ctl_glm_old_rmsnorm_1536: 40 registers, 128 static shared bytes, bound 128 (record stale) +PASS limits sm_80 GLM BF16 tf_ctl_glm_old_rmsnorm_4096: 40 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_86 GLM BF16 tf_ctl_glm_old_rmsnorm_4096: 40 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_89 GLM BF16 tf_ctl_glm_old_rmsnorm_4096: 40 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_120 GLM BF16 tf_ctl_glm_old_rmsnorm_4096: 39 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_121 GLM BF16 tf_ctl_glm_old_rmsnorm_4096: 39 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_80 GLM BF16 tf_ctl_glm_old_hc_finish: 64 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_86 GLM BF16 tf_ctl_glm_old_hc_finish: 64 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_89 GLM BF16 tf_ctl_glm_old_hc_finish: 64 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_120 GLM BF16 tf_ctl_glm_old_hc_finish: 79 registers, 128 static shared bytes, bound 256 (record stale) +PASS limits sm_121 GLM BF16 tf_ctl_glm_old_hc_finish: 79 registers, 128 static shared bytes, bound 256 (record stale) +FAIL kernel-contract-limits: 105 problems +FAIL kernel-contract-limits: TestFailed From fc1a1b88806f2bb4258a942efde7ecfa9510309e Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:50:38 +0800 Subject: [PATCH 175/361] receipts: PR 3733 ask 4's checkpoint search on this Mac, the full contract's state on TOP --- docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md index d24375d4ede..650427c8a1f 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -24,8 +24,10 @@ from a checkpoint. `tf-h3-dit` handles FastH3 clip cases and `tf-h3-image` handl Both run only on Metal. CUDA's H3 on main is `libtf_h3.so` (`zig build tf-h3`). That library runs the transformer blocks on rows the caller prepares. It has no case reader, no input and output projections, and no velocity output. The clip case exporter, `tools/zig/h3_case.py`, lives on the `drowzeys/TensorFold` fork (`docs/recipes/minimax-h3-metal.md:47-49`). -It is in neither tree. The GB10 job `plant-203.sh` also searched TOP for FastH3 checkpoints and H3 case files. That output scrolled out -of the door's 2000-line log (`job logs top-7c6183220113`), and the job's `/work/out` files don't include it. +It is in neither tree. On this Mac, a search of the home directory and mounted volumes, six levels deep, matched 122 `*.h3case.safetensors` files under +`h3-image-runs/`. All of them are MiniMax-H3-Image picture cases (`text`, `video`, `video_velocity`, no `audio`). The only +models are `MiniMax-H3-Image` and `ComfyUI-MiniMax-H3-Image`; there is no FastH3 clip checkpoint. The earlier TOP search +scrolled out of the door's log. `plant-203.sh` at `42a57c64f` (side branch `gpu/203-plant-h3`) now writes it to `checkpoints.txt`. The transformer diff against Ash's main is empty for `h3.zig`, `geometry.zig`, `block.zig` and the CUDA block sources. The shared Metal loader does change: `tensors.zig` now uses the span-based `read_ahead.zig`, and `checkpoint.zig` is the @@ -47,7 +49,10 @@ All of them are stale records on 47 launches that aren't H3: `muse_linear` (17), `glm_glue`, `flashnext_mtp` and `drama3` (1 each). The list is in `limits-stale-top-7c6183220113.txt`. No H3 record is stale. These problems already exist on Ash's main: against `bdcb6e608` this head adds only `h3_image_decoder.cu`, `h3_image_prompt.cu`, `h3_image_cuda_records.zig` and their line in `registry_joins.zig` under `zig/kernels/cuda` and `zig/src/core/contract`. -The full unfiltered contract was not run again. The earlier run spent 75 minutes in `tf_md_conv3x3`'s float64 reference, a moss kernel. +Without `h3`, the full contract has never finished on TOP. Job `top-1c5bc91282e3` spent 75 minutes in moss's `tf_md_conv3x3` +float64 shapes reference, whose code is the same on Ash's main, and the Desk stopped it there. Its 3629 lines up to that +point show every H3 gate passing. `plant-203.sh` at `42a57c64f` runs the full contract for 20 minutes and keeps its log; +that job is in TOP's queue. ## CI on #3733 From a0f7530cf40454efb1f9a7e89986d315c17da3b4 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:43:38 +0800 Subject: [PATCH 176/361] cuda contract: -WORD drops kernels from gates 1-4 and keeps the run full The full GB10 contract never finishes on TOP: moss's tf_md_conv3x3 float64 shapes reference runs past 75 min. kernel-contract -tf_md_conv3x3 runs every other kernel's gates and controls, the back and after suites and every limit record. --- zig/tests/cuda/contract_after.zig | 24 ++++++++++++++++++++---- zig/tests/cuda/contract_finish.zig | 5 +++-- zig/tests/cuda/contract_limits.zig | 13 +++++++------ zig/tests/cuda/main_usage.zig | 2 +- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/zig/tests/cuda/contract_after.zig b/zig/tests/cuda/contract_after.zig index 961397f5480..8caf7b02a94 100644 --- a/zig/tests/cuda/contract_after.zig +++ b/zig/tests/cuda/contract_after.zig @@ -3,14 +3,30 @@ const std = @import("std"); const g = @import("core").contract.gates; const check = @import("check.zig"); -/// Keeps the kernels whose name holds one of `only`'s words; empty keeps every one. +/// Whether `only` names kernels to keep: without plain words (none, or only `-word`s) the run is a full one. +pub fn filtered(only: []const []const u8) bool { + for (only) |w| if (!std.mem.startsWith(u8, w, "-")) return true; + return false; +} + +/// Whether `name` holds no `-word` and, when plain words are given, one of them. +pub fn wanted(name: []const u8, only: []const []const u8) bool { + var named = !filtered(only); + for (only) |w| { + const minus = std.mem.startsWith(u8, w, "-"); + const hit = std.mem.indexOf(u8, name, if (minus) w[1..] else w) != null; + if (minus and hit) return false; + named = named or hit; + } + return named; +} + +/// Keeps the kernels `wanted` keeps; empty keeps every one. pub fn keep(kernels: *std.ArrayList(g.Kernel), only: []const []const u8) void { - if (only.len == 0) return; var kept: usize = 0; - for (kernels.items) |k| for (only) |w| if (std.mem.indexOf(u8, k.spec.name, w) != null) { + for (kernels.items) |k| if (wanted(k.spec.name, only)) { kernels.items[kept] = k; kept += 1; - break; }; kernels.shrinkRetainingCapacity(kept); } diff --git a/zig/tests/cuda/contract_finish.zig b/zig/tests/cuda/contract_finish.zig index 580e227d5a6..ef068dd87d4 100644 --- a/zig/tests/cuda/contract_finish.zig +++ b/zig/tests/cuda/contract_finish.zig @@ -5,9 +5,10 @@ const g = @import("core").contract.gates; const live = @import("contract_limits.zig").live; pub fn run(gpu: check.Gpu, only: []const []const u8, t: g.Tally, t0: i96) !void { - if (only.len == 0) try @import("contract_back_suites.zig").run(gpu); + const full = !@import("contract_after.zig").filtered(only); + if (full) try @import("contract_back_suites.zig").run(gpu); const t1 = check.now(gpu.io); - if (only.len == 0) try @import("contract_after.zig").suites(gpu); + if (full) try @import("contract_after.zig").suites(gpu); const lim = try live(gpu, only); const t2 = check.now(gpu.io); std.debug.print("{s}SUMMARY {d} kernels: {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: {d} red as planted, {d} missed; {d} limit problems; gates {d} ms, limits {d} ms\n", .{ if (only.len > 0) "(filtered) " else "", t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed, lim, @divTrunc(t1 - t0, std.time.ns_per_ms), @divTrunc(t2 - t1, std.time.ns_per_ms) }); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 9bf7718cffa..6c11c71aaab 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -48,11 +48,14 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { return error.UnknownContractImage; } -/// Gate 5 on this GPU, each record against the loaded function; `only`: the launches so named, no offline audit. +/// Gate 5 on this GPU, each record against the loaded function; plain words in `only`: the launches so named, no +/// offline audit. `-word`s leave every record in: they drop only a kernel's gates 1-4. pub fn live(gpu: check.Gpu, only: []const []const u8) !usize { + const after = @import("contract_after.zig"); + const full = !after.filtered(only); var n: usize = 0; - if (only.len == 0) n = try registry.checkCuda(gpu.gpa, ®istry.all_cuda, false); - if (only.len == 0) std.debug.print("{s} limits: {d} registered CUDA launches against sm_80/86/89/120/121, {d} problems\n", .{ if (n == 0) "PASS" else "FAIL", registry.all_cuda.len, n }); + if (full) n = try registry.checkCuda(gpu.gpa, ®istry.all_cuda, false); + if (full) std.debug.print("{s} limits: {d} registered CUDA launches against sm_80/86/89/120/121, {d} problems\n", .{ if (n == 0) "PASS" else "FAIL", registry.all_cuda.len, n }); const sm: u32 = @intCast(try gpu.ctx.capability()); const t = limits.target(sm) orelse { std.debug.print("N/A limits live: sm_{d} is not a target the records cover\n", .{sm}); @@ -73,9 +76,7 @@ pub fn live(gpu: check.Gpu, only: []const []const u8) !usize { var said: ?limits.Nvcc = null; for (registry.all_cuda ++ registry.cuda_controls) |r| { const control = std.mem.startsWith(u8, r.launch.name, "control"); - if (only.len > 0) for (only) |w| { - if (std.mem.indexOf(u8, r.launch.name, w) != null) break; - } else continue; + if (!full and !after.wanted(r.launch.name, only)) continue; if (!control and t.sm < r.launch.min_sm) continue; if (!control and at != null and registry.targetDecision(r, t, r.usage[at.?]) != .applicable) continue; const bytes = image(r.launch.image) catch |err| { diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 26f6b82fd85..8e0fed2e9f7 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -139,7 +139,7 @@ pub const usage = \\ qwen35-tp-cut PACK [STEP] the 27B's EXL3 weights cut for two ranks at the whole plan: each rank's columns, one run's bytes \\ exl3-prompt-k6 [DIR|none] [BASE] EXL3 prompt kernels at 3 and 4 bits, GLM's shapes: runSlots, FP64, row bytes, time; DIR adds a real layer, BASE (an earlier exl3_experts fatbin) its 4-bit bytes \\ train-pack MODEL EXAMPLES [COUNT] training passes holding several sequences against one a pass: differences, time - \\ kernel-contract [WORD...] the contract's gates, each planted control red (-Dnvcc); WORDs: kernels named so + \\ kernel-contract [WORD...] the contract's gates, each planted control red (-Dnvcc); WORDs: kernels named so, -WORDs: all but those \\ qmm-prefill-many-contract the GB10 bit-exact multi-projection prompt launch against separate launches \\ qmm-prefill-tile22-contract the GB10 large-prompt 2x2 tile against the default tile \\ qmmf-prompt BF16 K32 prompt staging: parent K64 bytes at current Flash Next shapes From 4a71066701e252599d94ed27f79329dbc2c8d322 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:29:50 +0800 Subject: [PATCH 177/361] receipts: PR 3733 ask 5's one TOP job without tf_md_conv3x3, CI green at 04f9ad328 --- .../h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md index 650427c8a1f..9cabdec3c1f 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -51,13 +51,13 @@ These problems already exist on Ash's main: against `bdcb6e608` this head adds o `h3_image_cuda_records.zig` and their line in `registry_joins.zig` under `zig/kernels/cuda` and `zig/src/core/contract`. Without `h3`, the full contract has never finished on TOP. Job `top-1c5bc91282e3` spent 75 minutes in moss's `tf_md_conv3x3` float64 shapes reference, whose code is the same on Ash's main, and the Desk stopped it there. Its 3629 lines up to that -point show every H3 gate passing. `plant-203.sh` at `42a57c64f` runs the full contract for 20 minutes and keeps its log; -that job is in TOP's queue. +point show every H3 gate passing. The Lead left that one non-H3 reference out of ask 5, so `kernel-contract` now takes +`-WORD`s (`c759a1372`): `kernel-contract -tf_md_conv3x3` runs every other kernel's gates and controls, the back and after +suites, and every limit record, `tf_md_conv3x3`'s included. One job at `93f592f6b` (`plant-203.sh` on `gpu/203-plant-h3`) runs +it, both selftests, the five-SM audit and ask 4's search. That job is in TOP's queue. ## CI on #3733 -At `c203accb0` (23 Nov 05:2x): `pytest`, `release-paths` and `comfyui-moss-installer` pass. `zig` and `zig-macos-dev-tools` -were cancelled. `zig-windows` and `benchmark-clients (windows-latest)` are in progress. `fmt`, `zig-b` and -`benchmark-clients (ubuntu-latest)` are queued, and `host-nightly-*` is skipped. No job is red. Ash's main isn't green either: -`No GPU` and `Zig format` at `bdcb6e6086` are queued or pending, and every run before that at `df0f420161`, `a325f58258` -and `833d8ec465` was cancelled or is still pending. +At `04f9ad328` (23 Nov), every job passes: `zig`, `zig-b`, `zig-windows`, `zig-macos-dev-tools`, `fmt`, `pytest`, +`release-paths (ubuntu-24.04)`, `comfyui-moss-installer` and `benchmark-clients` on Ubuntu and Windows. +`host-nightly-linux` and `host-nightly-macos` are skipped. No job is red. From c1ba17f0efa4d81698f32580bbe3f366a98b2c56 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:11:12 +0800 Subject: [PATCH 178/361] cuda contract: one-line doc on live's -word filter (lean check) --- zig/tests/cuda/contract_limits.zig | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 6c11c71aaab..fe54dc36ba8 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -48,8 +48,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { return error.UnknownContractImage; } -/// Gate 5 on this GPU, each record against the loaded function; plain words in `only`: the launches so named, no -/// offline audit. `-word`s leave every record in: they drop only a kernel's gates 1-4. +/// Gate 5 on this GPU, each record against the loaded function; plain words in `only` pick launches, `-word`s keep all. pub fn live(gpu: check.Gpu, only: []const []const u8) !usize { const after = @import("contract_after.zig"); const full = !after.filtered(only); From af9c217e19c04325f4536e1c4ac834d686f4dc3c Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:43:45 +0800 Subject: [PATCH 179/361] receipts: PR 3733 asks 3-5 from TOP job top-a4a49aacbcd1 (contract stopped at 45 min in window_rows) --- .../h3-image-cuda-gb10-0bfee52e/asks-3-5.md | 36 +++-- .../contract-h3-top-a4a49aacbcd1.txt | 134 ++++++++++++++++++ ...82e3.txt => controls-top-a4a49aacbcd1.txt} | 0 .../decoder-selftest.txt | 4 +- ....txt => limits-stale-top-a4a49aacbcd1.txt} | 0 5 files changed, 153 insertions(+), 21 deletions(-) create mode 100644 docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-a4a49aacbcd1.txt rename docs/receipts/h3-image-cuda-gb10-0bfee52e/{controls-top-1c5bc91282e3.txt => controls-top-a4a49aacbcd1.txt} (100%) rename docs/receipts/h3-image-cuda-gb10-0bfee52e/{limits-stale-top-7c6183220113.txt => limits-stale-top-a4a49aacbcd1.txt} (100%) diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md index 9cabdec3c1f..afa741d5e74 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/asks-3-5.md @@ -3,9 +3,9 @@ ## 3. A planted control for every new kernel Each of the 19 decoder and prompt kernels has a "first block only" control (`zig/tests/cuda/contract_h3_register.zig`). -TOP job `top-1c5bc91282e3` ran `tf-cuda-test kernel-contract` at `1ee412bf0` on the GB10, and every control went red at -`shapes`, the gate it is planted for. Each control's gate line and verdict are in `controls-top-1c5bc91282e3.txt`, 38 lines for -19 controls. For example: +TOP job `top-a4a49aacbcd1` ran `tf-cuda-test kernel-contract -tf_md_conv3x3` at `93f592f6b` on the GB10, and every control +went red at `shapes`, the gate it is planted for. Each control's gate line and verdict are in +`controls-top-a4a49aacbcd1.txt`, 38 lines for 19 controls. For example: ``` FAIL shapes cuda h3 image decoder h3d_attention control: first block only: at 1x261x64 output 64 is -nan where float64 gives 9.543158e-1: nan of its bound @@ -14,8 +14,7 @@ FAIL shapes cuda h3 image prompt h3p_heads rotary control: first block only: at CONTROL cuda h3 image prompt h3p_heads rotary control: first block only: red at shapes, as planted ``` -In the same log, all 122 H3 gate lines without a control are `PASS`. -The Desk stopped that job in `tf_md_conv3x3`'s float64 shapes reference, a moss kernel that is not part of H3. +In the same log (`contract-h3-top-a4a49aacbcd1.txt`), every H3 gate line without a control is `PASS` (86) or `N/A` (10). ## 4. An H3 clip checkpoint on main against this head @@ -26,8 +25,8 @@ on rows the caller prepares. It has no case reader, no input and output projecti clip case exporter, `tools/zig/h3_case.py`, lives on the `drowzeys/TensorFold` fork (`docs/recipes/minimax-h3-metal.md:47-49`). It is in neither tree. On this Mac, a search of the home directory and mounted volumes, six levels deep, matched 122 `*.h3case.safetensors` files under `h3-image-runs/`. All of them are MiniMax-H3-Image picture cases (`text`, `video`, `video_velocity`, no `audio`). The only -models are `MiniMax-H3-Image` and `ComfyUI-MiniMax-H3-Image`; there is no FastH3 clip checkpoint. The earlier TOP search -scrolled out of the door's log. `plant-203.sh` at `42a57c64f` (side branch `gpu/203-plant-h3`) now writes it to `checkpoints.txt`. +models are `MiniMax-H3-Image` and `ComfyUI-MiniMax-H3-Image`; there is no FastH3 clip checkpoint. On TOP, job +`top-a4a49aacbcd1`'s `find / -xdev` for `*fasth3*`, `*h3*case*`, `case.safetensors` and `*minimax*h3*` found 0 paths. The transformer diff against Ash's main is empty for `h3.zig`, `geometry.zig`, `block.zig` and the CUDA block sources. The shared Metal loader does change: `tensors.zig` now uses the span-based `read_ahead.zig`, and `checkpoint.zig` is the @@ -43,21 +42,20 @@ Both selftests pass: `decoder-selftest.txt` and `prompt-selftest.txt` end in `se (filtered) SUMMARY 34 kernels: 34 pass gates 1-4, 0 fail, 0 known findings; 19 controls: 19 red as planted, 0 missed; 0 limit problems; gates 8447 ms, limits 1 ms ``` -The five-SM audit, `kernel-contract-limits` over `-Dsm=80,86,89,120,121` fatbins, reports `105 problems`. -All of them are stale records on 47 launches that aren't H3: `muse_linear` (17), `muse_glue`, `exl3_experts`, `GLM` (4 each), -`qwen35`, `flashnext_hcn`, `exl3_grouped` (3 each), `nemo_audio`, `muse_dflash2` (2 each), and `qmmf`, `qmm_prefill`, -`glm_glue`, `flashnext_mtp` and `drama3` (1 each). The list is in `limits-stale-top-7c6183220113.txt`. No H3 record is stale. +The five-SM audit, `kernel-contract-limits` over `-Dsm=80,86,89,120,121` fatbins, reports `105 problems`, none of them H3. These problems already exist on Ash's main: against `bdcb6e608` this head adds only `h3_image_decoder.cu`, `h3_image_prompt.cu`, `h3_image_cuda_records.zig` and their line in `registry_joins.zig` under `zig/kernels/cuda` and `zig/src/core/contract`. -Without `h3`, the full contract has never finished on TOP. Job `top-1c5bc91282e3` spent 75 minutes in moss's `tf_md_conv3x3` -float64 shapes reference, whose code is the same on Ash's main, and the Desk stopped it there. Its 3629 lines up to that -point show every H3 gate passing. The Lead left that one non-H3 reference out of ask 5, so `kernel-contract` now takes -`-WORD`s (`c759a1372`): `kernel-contract -tf_md_conv3x3` runs every other kernel's gates and controls, the back and after -suites, and every limit record, `tf_md_conv3x3`'s included. One job at `93f592f6b` (`plant-203.sh` on `gpu/203-plant-h3`) runs -it, both selftests, the five-SM audit and ask 4's search. That job is in TOP's queue. +Job `top-a4a49aacbcd1` (`plant-203.sh` at `93f592f6b`) ran the full contract without `tf_md_conv3x3`'s reference, +the Lead's ask 5. Its log is `contract.log` in the job's out folder, 2176 lines. Both selftests pass again, and every H3 +line is as above. The run still hit the script's 45-minute limit (exit 124) in `window_rows`'s paged cases, before the +GLM, MLA, q35 contiguous, MTP rows, weight-only and family-set suites and the run's SUMMARY. Its only red lines outside +the controls are four `qwen35` nonfinite gates (`head 18 element 0: finite where float64 gives nan`). `qwen35`'s kernels +and `contract_q35_attn.zig` are the same as on Ash's main. The same job's five-SM audit again reports `105 problems`: +stale records on 44 launches, none H3, all in `limits-stale-top-a4a49aacbcd1.txt`. ## CI on #3733 -At `04f9ad328` (23 Nov), every job passes: `zig`, `zig-b`, `zig-windows`, `zig-macos-dev-tools`, `fmt`, `pytest`, +At `e27a4ecf4` (23 Nov), every job passes: `zig`, `zig-b`, `zig-windows`, `zig-macos-dev-tools`, `fmt`, `pytest`, `release-paths (ubuntu-24.04)`, `comfyui-moss-installer` and `benchmark-clients` on Ubuntu and Windows. -`host-nightly-linux` and `host-nightly-macos` are skipped. No job is red. +`host-nightly-linux` and `host-nightly-macos` are skipped. At `64fdb3215`, `zig` was red at lean check on a two-line +comment in `contract_limits.zig` from this branch. Ash's main is not red there, and `e27a4ecf4` fixes it. diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-a4a49aacbcd1.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-a4a49aacbcd1.txt new file mode 100644 index 00000000000..7e033e6a453 --- /dev/null +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/contract-h3-top-a4a49aacbcd1.txt @@ -0,0 +1,134 @@ +PASS nonfinite cuda h3 image decoder h3d_post_quant: 24 non-finite and 30696 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_post_quant: five runs byte-identical (12288 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_post_quant: 3 shapes within the float64 bound (worst 0.991 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_post_quant: within its bound at k 24; fp16 sums would miss 41x, bf16 536.8x (the 24-term dot's bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image decoder h3d_embed: 3072 non-finite and 1333248 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_embed: five runs byte-identical (534528 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_embed: 2 shapes within the float64 bound (worst 0.995 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_embed: within its bound at k 24; fp16 sums would miss 173x, bf16 1486.3x (the 24-term dot's bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image decoder h3d_rms_norm: 1026 non-finite and 7166 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_rms_norm: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_rms_norm: 2 shapes within the float64 bound (worst 0.995 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_rms_norm: within its bound at k 1024; fp16 sums would miss 256x, bf16 0.5x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image decoder h3d_layer_norm: 3072 non-finite and 5120 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_layer_norm: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_layer_norm: 2 shapes within the float64 bound (worst 0.995 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_layer_norm: within its bound at k 1024; fp16 sums would miss 374158x, bf16 223.6x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image decoder h3d_linear: 384 non-finite and 256 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_linear: five runs byte-identical (2048 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_linear: 4 shapes within the float64 bound (worst 0.012 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_linear: within its bound at k 4096; fp16 sums would miss 0x, bf16 2.3x (each output sums K in increasing order with individually rounded fp32 multiplies and adds) +PASS nonfinite cuda h3 image decoder h3d_finish bias: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_finish bias: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_finish bias: 2 shapes within the float64 bound (worst 0.996 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image decoder h3d_finish bias: declares none sums +PASS nonfinite cuda h3 image decoder h3d_finish layerscale: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_finish layerscale: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_finish layerscale: 2 shapes within the float64 bound (worst 0.331 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image decoder h3d_finish layerscale: declares none sums +PASS nonfinite cuda h3 image decoder h3d_heads: 67 non-finite and 4008893 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_heads: five runs byte-identical (1603584 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_heads: 2 shapes within the float64 bound (worst 0.199 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_heads: within its bound at k 3072; fp16 sums would miss 1x, bf16 0.6x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image decoder h3d_attention: 192 non-finite and 1336128 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_attention: five runs byte-identical (534528 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_attention: 2 shapes within the float64 bound (worst 0.992 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image decoder h3d_attention: within its bound at k 64; fp16 sums would miss 14x, bf16 125.0x (softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image decoder h3d_swiglu: 3 non-finite and 32765 finite outputs match the float64 classes +PASS repeat cuda h3 image decoder h3d_swiglu: five runs byte-identical (65536 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image decoder h3d_swiglu: 2 shapes within the float64 bound (worst 0.493 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image decoder h3d_swiglu: declares none sums +FAIL shapes cuda h3 image decoder h3d_post_quant control: first block only: at 1x256x24 output 192 is -nan where float64 gives 1.672110e0: nan of its bound +CONTROL cuda h3 image decoder h3d_post_quant control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_embed control: first block only: at 1x256x24 output 256 is -nan where float64 gives 3.792953e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_embed control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_rms_norm control: first block only: at 8x1024x1024 output 1024 is -nan where float64 gives 1.167831e0: nan of its bound +CONTROL cuda h3 image decoder h3d_rms_norm control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_layer_norm control: first block only: at 8x1024x1024 output 1024 is -nan where float64 gives 6.127985e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_layer_norm control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_linear control: first block only: at 8x256x1024 output 128 is -nan where float64 gives -1.251590e1: nan of its bound +CONTROL cuda h3 image decoder h3d_linear control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_finish bias control: first block only: at 8x1024x1 output 32 is -nan where float64 gives -1.045709e0: nan of its bound +CONTROL cuda h3 image decoder h3d_finish bias control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_heads control: first block only: at 1x261x3072 output 64 is -nan where float64 gives 6.727295e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_heads control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_attention control: first block only: at 1x261x64 output 64 is -nan where float64 gives 9.543158e-1: nan of its bound +CONTROL cuda h3 image decoder h3d_attention control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image decoder h3d_swiglu control: first block only: at 8x4096x8192 output 32 is -nan where float64 gives -1.039063e0: nan of its bound +CONTROL cuda h3 image decoder h3d_swiglu control: first block only: red at shapes, as planted +PASS nonfinite cuda h3 image prompt h3p_norm qwen: 258 non-finite and 1790 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_norm qwen: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_norm qwen: 2 shapes within the float64 bound (worst 0.492 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_norm qwen: within its bound at k 1024; fp16 sums would miss 126x, bf16 0.8x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_norm h3: 258 non-finite and 1790 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_norm h3: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_norm h3: 2 shapes within the float64 bound (worst 0.990 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_norm h3: within its bound at k 1024; fp16 sums would miss 252x, bf16 0.7x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_heads rotary: 132 non-finite and 10108 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_heads rotary: five runs byte-identical (20480 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_heads rotary: 2 shapes within the float64 bound (worst 0.248 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_heads rotary: within its bound at k 128; fp16 sums would miss 1x, bf16 11.2x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_heads fused qkv: 3 non-finite and 3069 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_heads fused qkv: five runs byte-identical (6144 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_heads fused qkv: 2 shapes within the float64 bound (worst 0.495 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_heads fused qkv: within its bound at k 128; fp16 sums would miss 0x, bf16 0.3x (a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps) +PASS nonfinite cuda h3 image prompt h3p_attention causal: 384 non-finite and 3712 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_attention causal: five runs byte-identical (8192 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_attention causal: 2 shapes within the float64 bound (worst 0.495 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_attention causal: within its bound at k 77; fp16 sums would miss 5x, bf16 25.1x (softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image prompt h3p_attention all rows: 384 non-finite and 3712 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_attention all rows: five runs byte-identical (8192 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_attention all rows: 2 shapes within the float64 bound (worst 0.493 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_attention all rows: within its bound at k 77; fp16 sums would miss 5x, bf16 42.4x (softmax weights in [0, 1] with fp32 scores: the bf16 output hides a bf16 sum's error) +PASS nonfinite cuda h3 image prompt h3p_glu qwen: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_glu qwen: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_glu qwen: 2 shapes within the float64 bound (worst 0.493 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_glu qwen: declares none sums +PASS nonfinite cuda h3 image prompt h3p_glu h3: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_glu h3: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_glu h3: 2 shapes within the float64 bound (worst 0.329 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_glu h3: declares none sums +PASS nonfinite cuda h3 image prompt h3p_add: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_add: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_add: 2 shapes within the float64 bound (worst 0.497 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_add: declares none sums +PASS nonfinite cuda h3 image prompt h3p_scatter_add: 3 non-finite and 2045 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_scatter_add: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_scatter_add: 2 shapes within the float64 bound (worst 0.996 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_scatter_add: declares none sums +PASS nonfinite cuda h3 image prompt h3p_embed: 1 non-finite and 2047 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_embed: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_embed: 2 shapes within the float64 bound (worst 0.000 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_embed: declares none sums +PASS nonfinite cuda h3 image prompt h3p_splice: 2 non-finite and 2046 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_splice: five runs byte-identical (4096 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_splice: 2 shapes within the float64 bound (worst 0.000 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_splice: declares none sums +PASS nonfinite cuda h3 image prompt h3p_linear: 384 non-finite and 256 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_linear: five runs byte-identical (2048 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_linear: 2 shapes within the float64 bound (worst 0.004 of the bound), 0 edges refused by the kernel +PASS sums cuda h3 image prompt h3p_linear: within its bound at k 1024; fp16 sums would miss 3x, bf16 18.3x (a k-length sequential fp32 dot is the reference's own order) +PASS nonfinite cuda h3 image prompt h3p_round: 3 non-finite and 8189 finite outputs match the float64 classes +PASS repeat cuda h3 image prompt h3p_round: five runs byte-identical (16384 bytes), inputs and guards untouched, no overlap +PASS shapes cuda h3 image prompt h3p_round: 2 shapes within the float64 bound (worst 0.000 of the bound), 0 edges refused by the kernel +N/A sums cuda h3 image prompt h3p_round: declares none sums +FAIL shapes cuda h3 image prompt h3p_norm qwen control: first block only: at 8x256x256 output 256 is -nan where float64 gives -6.471916e-1: nan of its bound +CONTROL cuda h3 image prompt h3p_norm qwen control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_heads rotary control: first block only: at 8x128x128 output 1024 is 3.984375e-1 where float64 gives 4.902344e-1: 11.95 of its bound +CONTROL cuda h3 image prompt h3p_heads rotary control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_attention causal control: first block only: at 8x128x8 output 512 is -nan where float64 gives 1.434424e0: nan of its bound +CONTROL cuda h3 image prompt h3p_attention causal control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_glu qwen control: first block only: at 8x256x1 output 256 is -nan where float64 gives -9.650574e-1: nan of its bound +CONTROL cuda h3 image prompt h3p_glu qwen control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_add control: first block only: at 8x1024x1 output 256 is 1.648438e0 where float64 gives 1.964844e0: 20.57 of its bound +CONTROL cuda h3 image prompt h3p_add control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_scatter_add control: first block only: at 4x256x8 output 0 is -5.937500e-1 where float64 gives 3.750000e-1: 661.32 of its bound +CONTROL cuda h3 image prompt h3p_scatter_add control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_embed control: first block only: at 8x256x32 output 256 is -nan where float64 gives -1.851563e0: nan of its bound +CONTROL cuda h3 image prompt h3p_embed control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_splice control: first block only: at 4x256x8 output 0 is -1.781250e0 where float64 gives -3.242188e-1: 1150.46 of its bound +CONTROL cuda h3 image prompt h3p_splice control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_linear control: first block only: at 4x128x256 output 256 is -nan where float64 gives 1.182369e0: nan of its bound +CONTROL cuda h3 image prompt h3p_linear control: first block only: red at shapes, as planted +FAIL shapes cuda h3 image prompt h3p_round control: first block only: at 8x1024x1 output 256 is -nan where float64 gives 6.593750e0: nan of its bound +CONTROL cuda h3 image prompt h3p_round control: first block only: red at shapes, as planted diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-1c5bc91282e3.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-a4a49aacbcd1.txt similarity index 100% rename from docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-1c5bc91282e3.txt rename to docs/receipts/h3-image-cuda-gb10-0bfee52e/controls-top-a4a49aacbcd1.txt diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt index c16fd259e41..68d68035461 100644 --- a/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt +++ b/docs/receipts/h3-image-cuda-gb10-0bfee52e/decoder-selftest.txt @@ -1,4 +1,4 @@ -CUDA decoder: 24 synthetic blocks made in 1.9 s +CUDA decoder: 24 synthetic blocks made in 1.8 s 6 x 10 cells: 1 tiles of 6 x 10 cells, 65 tokens each embedding: 66560 values, 99.997% identical, worst 1.00 ULP, relative 1.91e-5 (pass) block 0: 66560 values, 96.946% identical, worst 2.00 ULP, relative 5.73e-4 (pass) @@ -41,5 +41,5 @@ CUDA decoder: 24 synthetic blocks made in 1.9 s decode in passes of 3: bit-identical to the staged tiles assembled decode in passes of 4: bit-identical to the staged tiles assembled picture bytes: 92.164% identical, at most 1 apart (pass) -timing: 25 tiles of 16 x 16, 24 blocks: 1.09 s in passes, 1.09 s on the GPU, 43.6 ms a tile +timing: 25 tiles of 16 x 16, 24 blocks: 1.09 s in passes, 1.09 s on the GPU, 43.5 ms a tile selftest: pass diff --git a/docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-7c6183220113.txt b/docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-a4a49aacbcd1.txt similarity index 100% rename from docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-7c6183220113.txt rename to docs/receipts/h3-image-cuda-gb10-0bfee52e/limits-stale-top-a4a49aacbcd1.txt From fb6591d83d3f52842182a9043d07ca35ee4a589f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:58:54 +0000 Subject: [PATCH 180/361] changelog: #3733 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59f2d737f0b..d30ff23a174 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 +- MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. + - Flash Next on CUDA: the fused read-out is now the default, making prompt processing about 3-5% faster on GB10 with identical tokens; `TF_FLASHNEXT_READOUT_FUSED=0` keeps the old path (#4799). Thanks @BadAd84. - Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. From 66aa87e8a3a62efc3234b572c2970bc80f7e08a4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:58:54 +0000 Subject: [PATCH 181/361] changelog: #3733 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d30ff23a174..0b606f7ac54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. + + - Flash Next on CUDA: the fused read-out is now the default, making prompt processing about 3-5% faster on GB10 with identical tokens; `TF_FLASHNEXT_READOUT_FUSED=0` keeps the old path (#4799). Thanks @BadAd84. - Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. From 26abf607c78eb50417bf511bf2393fd499b34f31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:29:05 +0100 Subject: [PATCH 182/361] inkling2 cuda: Mini expert weights staged a warp in whole 128-byte rows, the NVFP4 factor once an expert tf_ink2moe_up and tf_ink2moe_prompt_up decoded every BF16 weight with its own byte loads (code, scale) and an FP32 division (amax / denominator), so a decode token spent 96 ms in the routed experts. Each warp now stages its 32 rows' codes 128 bytes a row (8 lanes a row) and their scale bytes in shared memory, and decodes its fragments from there; the expert's factor is computed once a unit. On decode (one row) the next tile and the next step's inputs are fetched while the current step multiplies. Each weight is the same product, rounded alike, and the mma sequence is unchanged, so the bits are unchanged. --- zig/kernels/cuda/inkling2/modelopt.cu | 170 ++++++++++++++---- .../contract/inkling2_experts_records.zig | 4 +- 2 files changed, 141 insertions(+), 33 deletions(-) diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu index 2f8a4c40bd7..f798aa003da 100644 --- a/zig/kernels/cuda/inkling2/modelopt.cu +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -35,33 +35,100 @@ __device__ __forceinline__ float e8m0(uint32_t n) { } __device__ __forceinline__ float bf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); } -__device__ __forceinline__ __nv_bfloat16 decoded(const Weight& w, long long e, long long row, long long col) { - const long long z = e * w.N * w.K + row * w.K + col; - const uint32_t nib = w.format ? w.codes[z] : ((w.codes[z / 2] >> ((col & 1) * 4)) & 15); - float v; +__device__ __forceinline__ uint32_t pair(float lo, float hi) { + return __bfloat16_as_ushort(__float2bfloat16_rn(lo)) | (uint32_t)__bfloat16_as_ushort(__float2bfloat16_rn(hi)) << 16; +} + +// An NVFP4 expert's outer factor: the same quotient every element of expert e used to recompute. +__device__ __forceinline__ float outer_of(const Weight& w, long long e) { + return w.format ? 0.f : __fdiv_rn(bf(__ldg(w.amax + e)), bf(__ldg(w.den))); +} + +// A half-fragment's stored bytes: columns col..col+3 and col+16..col+19 of one row, their two scale bytes. +struct Raw { + uint32_t lo, hi, sc; +}; + +constexpr int kRowBytes = 144; // a staged row: 128 code bytes + 16, so the 8 rows a load touches use distinct banks + +// A warp's tile in registers: up to 128 code bytes of its 32 rows (8 lanes a row), the lane's row's scales; K % 64 == 0 +struct Tile { + uint4 codes[8]; + uint32_t scales[4]; +}; + +__device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int g0, int steps, int lane, Tile& t) { + const int bytes = steps * (w.format ? 32 : 16); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int q = lane + 32 * i, lr = q >> 3, chunk = q & 7; + if (chunk * 16 >= bytes) continue; + const long long row = w.row0 + w.row_step * (cb * 32 + lr); + const long long z = (e * w.N + row) * w.K + 32LL * g0; // first element of the tile + t.codes[i] = __ldg(reinterpret_cast(w.codes + (w.format ? z : z / 2) + chunk * 16)); + } + const long long row = w.row0 + w.row_step * (cb * 32 + lane); + const long long z = (e * w.N + row) * w.K + 32LL * g0; + const int words = w.format ? 1 : (2 * steps + 3) / 4; + const uint32_t* src = reinterpret_cast(w.scales + z / w.G); +#pragma unroll + for (int i = 0; i < 4; ++i) + if (i < words) t.scales[i] = __ldg(src + i); +} + +__device__ __forceinline__ void put(const Weight& w, int steps, int lane, const Tile& t, uint8_t* __restrict__ codes, + uint8_t* __restrict__ scales) { + const int bytes = steps * (w.format ? 32 : 16); +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int q = lane + 32 * i, lr = q >> 3, chunk = q & 7; + if (chunk * 16 < bytes) *reinterpret_cast(codes + lr * kRowBytes + chunk * 16) = t.codes[i]; + } +#pragma unroll + for (int i = 0; i < 4; ++i) reinterpret_cast(scales + lane * 16)[i] = t.scales[i]; +} + +// Step gg of a staged tile, fragment rows 8j + lane / 4: the bytes ld_w used to read from global memory. +__device__ __forceinline__ Raw staged(const Weight& w, const uint8_t* codes, const uint8_t* scales, int gg, int lane, + int j) { + const int lr = 8 * j + (lane >> 2), t = lane & 3; + const uint8_t* c = codes + lr * kRowBytes; + Raw r; if (w.format) { - v = __fmul_rn(e4m3(nib), e8m0(w.scales[z / w.G])); + r.lo = *reinterpret_cast(c + gg * 32 + 4 * t); + r.hi = *reinterpret_cast(c + gg * 32 + 4 * t + 16); + r.sc = scales[lr * 16 + gg] * 0x101u; // one MXFP8 scale covers both halves } else { - const float outer = __fdiv_rn(bf(__ldg(w.amax + e)), bf(__ldg(w.den))); - v = __fmul_rn(__fmul_rn(e2m1(nib), e4m3(w.scales[z / w.G])), outer); + r.lo = *reinterpret_cast(c + gg * 16 + 2 * t); + r.hi = *reinterpret_cast(c + gg * 16 + 2 * t + 8); + r.sc = scales[lr * 16 + 2 * gg] | (uint32_t)scales[lr * 16 + 2 * gg + 1] << 8; } - return __float2bfloat16_rn(v); + return r; } -// One uint4 is eight BF16 weights in the fragment layout of experts_bf16.cu. -__device__ __forceinline__ uint4 ld_w(const Weight& w, long long e, int cb, int g, int lane, int j) { - const int row = w.row0 + w.row_step * (cb * 32 + 8 * j + (lane >> 2)), col = g * 32 + 4 * (lane & 3); - uint16_t h[8]; +// Eight BF16 weights in experts_bf16.cu's fragment layout: each the checkpoint's per-element product, rounded alike. +__device__ __forceinline__ uint4 decode(const Weight& w, const Raw& r, float outer) { + float v[8]; + if (w.format) { + const float s0 = e8m0(r.sc & 255), s1 = e8m0(r.sc >> 8); #pragma unroll - for (int i = 0; i < 8; ++i) { - const int c = col + (i & 3) + 16 * (i >> 2); - h[i] = __bfloat16_as_ushort(decoded(w, e, row, c)); + for (int i = 0; i < 4; ++i) { + v[i] = __fmul_rn(e4m3((r.lo >> (8 * i)) & 255), s0); + v[4 + i] = __fmul_rn(e4m3((r.hi >> (8 * i)) & 255), s1); + } + } else { + const float s0 = e4m3(r.sc & 255), s1 = e4m3(r.sc >> 8); +#pragma unroll + for (int i = 0; i < 4; ++i) { + v[i] = __fmul_rn(__fmul_rn(e2m1((r.lo >> (4 * i)) & 15), s0), outer); + v[4 + i] = __fmul_rn(__fmul_rn(e2m1((r.hi >> (4 * i)) & 15), s1), outer); + } } uint4 o; - o.x = h[0] | (uint32_t)h[1] << 16; - o.y = h[2] | (uint32_t)h[3] << 16; - o.z = h[4] | (uint32_t)h[5] << 16; - o.w = h[6] | (uint32_t)h[7] << 16; + o.x = pair(v[0], v[1]); + o.y = pair(v[2], v[3]); + o.z = pair(v[4], v[5]); + o.w = pair(v[6], v[7]); return o; } @@ -71,10 +138,15 @@ __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_ const int* __restrict__ members, void* __restrict__ out, int N, int skip) { const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; const int units = __ldg(item_count) * NB; + __shared__ __align__(16) uint8_t tiles[WARPS][32 * kRowBytes]; + __shared__ __align__(16) uint8_t tile_scales[WARPS][32 * 16]; + uint8_t* codes = tiles[threadIdx.x >> 5]; + uint8_t* scales = tile_scales[threadIdx.x >> 5]; for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) { const int it = unit / NB, cb = unit - it * NB; const int e = __ldg(items + 3 * it), first = __ldg(items + 3 * it + 1), cnt = __ldg(items + 3 * it + 2); if (e == skip) continue; + const float outer = outer_of(w, e); for (int r0 = 0; r0 < cnt; r0 += 16 * RT) { bool v[RT][2]; int pr[RT][2]; @@ -94,23 +166,59 @@ __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_ #pragma unroll for (int j = 0; j < NTW; ++j) acc[0][r][j][0] = acc[0][r][j][1] = acc[0][r][j][2] = acc[0][r][j][3] = 0.f; const uint2 zero = make_uint2(0u, 0u); - for (int g = 0; g < KG; ++g) { - uint4 ww[NTW]; + const int ts = w.format ? 4 : 8; // steps a staged tile + uint2 xn[2][2] = {{zero, zero}, {zero, zero}}; // decode: the next step's inputs + if constexpr (RT == 1) #pragma unroll - for (int j = 0; j < NTW; ++j) ww[j] = ld_w(w, e, cb, g, lane, j); -#pragma unroll - for (int r = 0; r < RT; ++r) { - uint2 xa[2], xb[2]; + for (int q = 0; q < 2; ++q) { + xn[0][q] = v[0][0] ? __ldg(reinterpret_cast(x[0][0] + 16 * q)) : zero; + xn[1][q] = v[0][1] ? __ldg(reinterpret_cast(x[0][1] + 16 * q)) : zero; + } + Tile next; // decode (RT 1) fetches the next tile while this one sums; prompt tiles load in place + if (RT == 1) fetch(w, e, cb, 0, KG < ts ? KG : ts, lane, next); + for (int g0 = 0; g0 < KG; g0 += ts) { + const int steps = KG - g0 < ts ? KG - g0 : ts; + __syncwarp(); + if (RT != 1) fetch(w, e, cb, g0, steps, lane, next); + put(w, steps, lane, next, codes, scales); + __syncwarp(); + if (RT == 1 && g0 + ts < KG) fetch(w, e, cb, g0 + ts, KG - g0 - ts < ts ? KG - g0 - ts : ts, lane, next); + for (int gg = 0; gg < steps; ++gg) { + const int g = g0 + gg; + uint2 cur[2][2]; // decode: this step's inputs, fetched a step early + if constexpr (RT == 1) { #pragma unroll - for (int q = 0; q < 2; ++q) { - xa[q] = v[r][0] ? __ldg(reinterpret_cast(x[r][0] + 32 * g + 16 * q)) : zero; - xb[q] = v[r][1] ? __ldg(reinterpret_cast(x[r][1] + 32 * g + 16 * q)) : zero; + for (int q = 0; q < 2; ++q) { + cur[0][q] = xn[0][q]; + cur[1][q] = xn[1][q]; + const uint2* pa = reinterpret_cast(x[0][0] + 32 * (g + 1) + 16 * q); + const uint2* pb = reinterpret_cast(x[0][1] + 32 * (g + 1) + 16 * q); + xn[0][q] = g + 1 < KG && v[0][0] ? __ldg(pa) : zero; + xn[1][q] = g + 1 < KG && v[0][1] ? __ldg(pb) : zero; + } } + uint4 ww[NTW]; #pragma unroll - for (int q = 0; q < 2; ++q) + for (int j = 0; j < NTW; ++j) ww[j] = decode(w, staged(w, codes, scales, gg, lane, j), outer); #pragma unroll - for (int j = 0; j < NTW; ++j) - mma(acc[0][r][j], xa[q].x, xb[q].x, xa[q].y, xb[q].y, q ? ww[j].z : ww[j].x, q ? ww[j].w : ww[j].y); + for (int r = 0; r < RT; ++r) { + uint2 xa[2], xb[2]; +#pragma unroll + for (int q = 0; q < 2; ++q) { + if constexpr (RT == 1) { + xa[q] = cur[0][q]; + xb[q] = cur[1][q]; + } else { + xa[q] = v[r][0] ? __ldg(reinterpret_cast(x[r][0] + 32 * g + 16 * q)) : zero; + xb[q] = v[r][1] ? __ldg(reinterpret_cast(x[r][1] + 32 * g + 16 * q)) : zero; + } + } +#pragma unroll + for (int q = 0; q < 2; ++q) +#pragma unroll + for (int j = 0; j < NTW; ++j) + mma(acc[0][r][j], xa[q].x, xb[q].x, xa[q].y, xb[q].y, q ? ww[j].z : ww[j].x, q ? ww[j].w : ww[j].y); + } } } #pragma unroll diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 092e5b4e30a..91cca080dad 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -11,8 +11,8 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 96, .static = 0, .bound = 128 }, .{ .regs = 102, .static = 0, .bound = 128 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 180, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 20480, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, From 10b93fc4fff02729c9b6fb031500717757e02a76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:18:49 +0100 Subject: [PATCH 183/361] inkling2 cuda: Mini expert scale loads stop at a row's last scale byte, K = 32 in the contract fetch read each lane's row scales as whole uint32 words, (2 steps + 3) / 4 of them for NVFP4 and one for MXFP8. The scales are unpadded, so a tile with fewer than four bytes left read past the row, and at the end of the projection past the data; at K = 32 a row's scales also start at an odd half-word, which a word load cannot read. Whole words now load only while four bytes remain and the row's start is word-aligned; the rest loads byte by byte into the same word. Mini's shapes (K 2304 and 1152) are aligned with no tail, so their path still takes whole words. The contract adds NVFP4 and MXFP8 decode cases at K = 32 (rows 1 and 16), each projection's scales in an allocation of exactly their size, so compute-sanitizer memcheck sees any byte read past them. --- zig/kernels/cuda/inkling2/modelopt.cu | 20 +++++++++++--- zig/tests/cuda/contract_inkling2_experts.zig | 9 ++++--- zig/tests/cuda/contract_inkling2_modelopt.zig | 26 +++++++++++++------ 3 files changed, 39 insertions(+), 16 deletions(-) diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu index f798aa003da..07262bcc063 100644 --- a/zig/kernels/cuda/inkling2/modelopt.cu +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -51,12 +51,21 @@ struct Raw { constexpr int kRowBytes = 144; // a staged row: 128 code bytes + 16, so the 8 rows a load touches use distinct banks -// A warp's tile in registers: up to 128 code bytes of its 32 rows (8 lanes a row), the lane's row's scales; K % 64 == 0 +// A warp's tile in registers: up to 128 code bytes of its 32 rows (8 lanes a row), the lane's row's scales; K % 32 == 0 struct Tile { uint4 codes[8]; uint32_t scales[4]; }; +// Up to four scale bytes as one little-endian word, none read past `n`: a tail or an unaligned row's scales. +__device__ __forceinline__ uint32_t scale_word(const uint8_t* p, int n) { + uint32_t v = 0; +#pragma unroll + for (int b = 0; b < 4; ++b) + if (b < n) v |= (uint32_t)__ldg(p + b) << (8 * b); + return v; +} + __device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int g0, int steps, int lane, Tile& t) { const int bytes = steps * (w.format ? 32 : 16); #pragma unroll @@ -69,11 +78,14 @@ __device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int } const long long row = w.row0 + w.row_step * (cb * 32 + lane); const long long z = (e * w.N + row) * w.K + 32LL * g0; - const int words = w.format ? 1 : (2 * steps + 3) / 4; - const uint32_t* src = reinterpret_cast(w.scales + z / w.G); + const int n = w.format ? steps : 2 * steps; // the row's scale bytes in this tile; unpadded, the last ends the data + const uint8_t* src = w.scales + z / w.G; + const bool words = (reinterpret_cast(src) & 3) == 0; #pragma unroll for (int i = 0; i < 4; ++i) - if (i < words) t.scales[i] = __ldg(src + i); + if (4 * i < n) + t.scales[i] = words && 4 * i + 4 <= n ? __ldg(reinterpret_cast(src) + i) + : scale_word(src + 4 * i, n - 4 * i); } __device__ __forceinline__ void put(const Weight& w, int steps, int lane, const Tile& t, uint8_t* __restrict__ codes, diff --git a/zig/tests/cuda/contract_inkling2_experts.zig b/zig/tests/cuda/contract_inkling2_experts.zig index 73f89cff366..13206551d54 100644 --- a/zig/tests/cuda/contract_inkling2_experts.zig +++ b/zig/tests/cuda/contract_inkling2_experts.zig @@ -19,7 +19,7 @@ pub const Set = struct { mk: ink.modelopt.Kernels = undefined, groups: [2]grouped.Group = undefined, projections: [4]grouped.Grouped = undefined, - moe: [11]modelopt.ModelOpt = undefined, + moe: [13]modelopt.ModelOpt = undefined, embeds: [2]ref.Gated(vision.Embed) = undefined, ropes: [2]ref.Gated(vision.Rope) = undefined, adds: [2]ref.Gated(vision.ScaleAdd) = undefined, @@ -37,14 +37,14 @@ pub const Set = struct { for (&set.groups, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.ek, .wrong_run = i == 1 }; const forms = [4]@import("contract_inkling2_experts_ref.zig").Form{ .rows, .rows, .wide, .wide }; for (&set.projections, forms, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = &set.ek, .form = f, .fault = if (i == 1) .short else if (i == 3) .swapped else .none }; - const prompt = [11]bool{ false, true, false, true, false, true, false, false, false, true, false }; + const prompt = [13]bool{ false, true, false, true, false, true, false, false, false, true, false, false, false }; for (&set.moe, 0..) |*x, i| x.* = .{ .rig = rig, .k = &set.mk, - .format = if (i < 4) .nvfp4 else .mxfp8, + .format = if (i < 4 or i == 11) .nvfp4 else .mxfp8, .phase = if (prompt[i]) .prompt else .decode, .fault = switch (i) { - 0, 1, 4, 5 => .none, + 0, 1, 4, 5, 11, 12 => .none, 2, 6 => .wrong_combine, 3, 9 => .wrong_prompt_up, 7 => .wrong_plan, @@ -52,6 +52,7 @@ pub const Set = struct { 10 => .wrong_act, else => unreachable, }, + .tail = i >= 11, // K = 32, the scales' last row ending its allocation }; for (&set.embeds, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .late = i == 1 } }; for (&set.ropes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = &set.vk, .swapped = i == 1 } }; diff --git a/zig/tests/cuda/contract_inkling2_modelopt.zig b/zig/tests/cuda/contract_inkling2_modelopt.zig index 5052173fd2a..1824f50caa7 100644 --- a/zig/tests/cuda/contract_inkling2_modelopt.zig +++ b/zig/tests/cuda/contract_inkling2_modelopt.zig @@ -94,7 +94,7 @@ fn mxfp8Weight(code: u8, scale: u8) u16 { const Phase = enum { decode, prompt }; const Fault = enum { none, wrong_combine, wrong_plan, wrong_up, wrong_prompt_up, wrong_act }; -fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { +fn rawSpec(format: mo.Format, phase: Phase, fault: Fault, tail: bool) c.Spec { const served = &[_]c.Shape{ .{ .rows = 1, .n = 2304, .k = 1152 }, .{ .rows = 16, .n = 2304, .k = 1152 }, @@ -102,7 +102,7 @@ fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { .{ .rows = 32, .n = 2304, .k = 1152 }, .{ .rows = 2048, .n = 2304, .k = 1152 }, }; - const name = switch (fault) { + const name = if (tail) (if (format == .nvfp4) "inkling2 Mini NVFP4 decode experts at K = 32, scales ending at their allocation" else "inkling2 Mini MXFP8 decode experts at K = 32, scales ending at their allocation") else switch (fault) { .none => if (format == .nvfp4) (if (phase == .decode) "inkling2 Mini NVFP4 decode w13/w2 tensor-core experts" else "inkling2 Mini NVFP4 prompt w13/w2 tensor-core experts") else @@ -113,7 +113,7 @@ fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { .wrong_prompt_up => if (format == .nvfp4) "control: inkling2 Mini NVFP4 prompt up projection clears the planted up-row code" else "control: inkling2 Mini MXFP8 prompt up projection clears the planted up-row code", .wrong_act => "control: inkling2 Mini MXFP8 activation uses gate cap eight", }; - const shapes = if (fault == .wrong_prompt_up or (fault == .none and phase == .prompt)) + const shapes = if (tail) &[_]c.Shape{ .{ .rows = 1, .n = 32, .k = 32 }, .{ .rows = 16, .n = 32, .k = 32 } } else if (fault == .wrong_prompt_up or (fault == .none and phase == .prompt)) served[3..] else if (fault == .none) served[0..3] @@ -130,7 +130,7 @@ fn rawSpec(format: mo.Format, phase: Phase, fault: Fault) c.Spec { .nan = .{ .stated = "a non-finite BF16 input row propagates through its selected experts" }, .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{ .size = 32 } }, .served = shapes, - .sums = .{ .f16 = 30, .bf16 = 30 }, + .sums = if (tail) .{ .f16 = 0, .bf16 = 0, .why = "K = 32 sums are too short to tell precisions apart; the Mini specs prove them" } else .{ .f16 = 30, .bf16 = 30 }, }; } fn depth(s: c.Shape) usize { @@ -143,6 +143,8 @@ pub const ModelOpt = struct { phase: Phase, shape: c.Shape = undefined, fault: Fault = .none, + tail: bool = false, // K = 32: each projection's scales in an allocation of their size, memcheck sees a read past + tight: [2]?cuda.DeviceBuffer = .{ null, null }, arena: ?std.heap.ArenaAllocator = null, x: []const u16 = &.{}, w13: []const u16 = &.{}, @@ -166,7 +168,7 @@ pub const ModelOpt = struct { baseline: ?Baseline = null, pub fn kernel(self: *ModelOpt) g.Kernel { - return .{ .spec = rawSpec(self.format, self.phase, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; + return .{ .spec = rawSpec(self.format, self.phase, self.fault, self.tail), .ctx = self, .vt = &vt, .control = if (self.fault == .none) null else .shapes }; } const vt = g.hooks(ModelOpt); @@ -184,6 +186,8 @@ pub const ModelOpt = struct { fn drop(self: *ModelOpt) void { if (self.arena) |*a| a.deinit(); self.arena = null; + for (&self.tight) |*t| if (t.*) |*b| b.free(); + self.tight = .{ null, null }; self.rig.reset(); } @@ -250,7 +254,7 @@ pub const ModelOpt = struct { pub fn prepare(self: *ModelOpt, shape: c.Shape, fill: g.Fill, seed: u64) !bool { _ = seed; if (self.phase == .prompt and shape.rows < 32 and fill != .stress and fill != .nonfinite) return false; - if (shape.n != 2304 or shape.k != 1152 or shape.rows == 0 or shape.rows > 2048) return false; + if (shape.n != @as(usize, if (self.tail) 32 else 2304) or shape.k != @as(usize, if (self.tail) 32 else 1152) or shape.rows == 0 or shape.rows > 2048) return false; self.drop(); self.shape = shape; self.stress = fill == .stress; @@ -286,9 +290,9 @@ pub const ModelOpt = struct { } break :blk try self.rig.input(wrong); } else try self.rig.input(p13.codes); - const dev13s = try self.rig.input(p13.scales); + const dev13s = try self.scaleInput(0, p13.scales); const dev2 = try self.rig.input(p2.codes); - const dev2s = try self.rig.input(p2.scales); + const dev2s = try self.scaleInput(1, p2.scales); var amax13: u64 = 0; var amax2: u64 = 0; var den13: u64 = 0; @@ -331,6 +335,12 @@ pub const ModelOpt = struct { return true; } + fn scaleInput(self: *ModelOpt, i: usize, bytes: []const u8) !u64 { + if (!self.tail) return self.rig.input(bytes); + self.tight[i] = try cuda.DeviceBuffer.fromHost(self.rig.gpu.d, bytes); + return self.tight[i].?.ptr; + } + pub fn run(self: *ModelOpt) !void { const route_weights = if (self.fault == .wrong_combine) self.pick else self.weights; const caps = if (self.fault == .wrong_act) ink.experts.Caps{ .gate = 8, .up = 25 } else ink.experts.Caps{ .gate = 4, .up = 25 }; From beaa4313860b4953272ed9640be112a0b2d38d7f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:19:35 +0000 Subject: [PATCH 184/361] inkling2 cuda: record the rewritten up launches' usage on every SM #4728 rewrites tf_ink2moe_up and tf_ink2moe_prompt_up and records their compiled usage at sm_121 only; at sm_80, sm_86, sm_89 and sm_120 the rows held zeros, so the kernel registry test failed with 8 "no compiled usage recorded" entries. The values are nvcc 13.0's, from kernel-contract-limits over fatbins built for all five SMs from this tree; each sm_121 entry equals the one the PR recorded. No kernel changes. --- zig/src/core/contract/inkling2_experts_records.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 91cca080dad..7c1568b621e 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -11,8 +11,8 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 20480, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 164, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true }, From 0d8cbb26fb2e1bc0116895897447e09792c10cf7 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:58:57 +0000 Subject: [PATCH 185/361] changelog: #4728 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b606f7ac54..575ee33d093 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 +- Inkling 2 Mini on CUDA: expert weights are staged a warp at a time in 128-byte rows with each expert's NVFP4 factor read once, so one-stream decode is about 70% faster on GB10, four streams about 60% faster and long prompts reach the first token about 25% sooner, with identical tokens (#4728). Thanks @jschmied. + - MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. From 268e4c5fb44d20696d45b9edaafa31e010690f18 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:51:47 +0000 Subject: [PATCH 186/361] feat(ocr): POST /ocr in docTR's API contract docTR's API client posts one or more files parts with options in the query and reads one OCROut a page, so POST /ocr now answers it: parts typed by their exact Content-Type in part order, each PDF page named by its file, blocks and lines from the shared estimates in relative coordinates or 8-float polygons, pydantic booleans for the options, a docTR option sent twice refused, and content options off their documented defaults refused. A body with both files and file parts is refused as ambiguous on every path, the format query included, in the chosen envelope. --- zig/src/server/ocr/doctr.zig | 331 +++++++++++++++++++++++ zig/src/server/ocr/doctr_test.zig | 365 ++++++++++++++++++++++++++ zig/src/server/ocr/liteparse.zig | 6 +- zig/src/server/ocr/liteparse_test.zig | 8 +- zig/src/server/ocr/mistral.zig | 4 +- zig/src/server/ocr/mistral_reply.zig | 2 +- zig/src/server/ocr/route.zig | 38 ++- zig/src/server/ocr/route_test.zig | 17 +- zig/src/server/ocr/run.zig | 17 +- zig/src/server/ocr/run_pdf_test.zig | 4 +- zig/src/server/ocr/run_test.zig | 24 +- zig/src/server/ocr/types.zig | 1 + zig/src/server/root.zig | 1 + 13 files changed, 761 insertions(+), 57 deletions(-) create mode 100644 zig/src/server/ocr/doctr.zig create mode 100644 zig/src/server/ocr/doctr_test.zig diff --git a/zig/src/server/ocr/doctr.zig b/zig/src/server/ocr/doctr.zig new file mode 100644 index 00000000000..4ba6edbf39b --- /dev/null +++ b/zig/src/server/ocr/doctr.zig @@ -0,0 +1,331 @@ +//! POST /ocr in the docTR API's contract: ``files`` parts and query options in (docs/api.md OCR: docTR). +const std = @import("std"); +const Allocator = std.mem.Allocator; +const api = @import("engine_api"); +const json = @import("json"); +const picture = @import("core").picture; +const multipart = @import("../multipart.zig"); +const pdf = @import("../pdf.zig"); +const query = @import("../query.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Server = @import("../server.zig").Server; +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const lines = @import("lines.zig"); +const run = @import("run.zig"); +const route = @import("route.zig"); +const Quad = api.ocr.Quad; +const Value = json.Value; +const Fault = types.Fault; +const OcrPage = types.OcrPage; +const Step = run.Step; + +/// The query options that shape the reply; every other option is ignored or refused by ``options``. +pub const Options = struct { + /// Boxes ``[xmin, ymin, xmax, ymax]``; false: 8 floats, TL, TR, BR, BL. + straight: bool = true, + /// One block a source block; false: one block a page. + blocks: bool = false, + /// One line a text line; false: one block holding one line of all the page's words. + lines: bool = true, +}; + +/// Content options TensorFold cannot honour, accepted at their documented default: off (docTR's docs, using_models). +const fixed_flags = [_]struct { []const u8, bool }{ .{ "detect_tables", false }, .{ "detect_layout", false }, .{ "straighten_pages", false } }; +/// The documented default of ``paragraph_break`` (docTR's docs: "default: 0.035"); any other value is refused. +const paragraph_break = 0.035; +/// Detector thresholds: TensorFold has no text detector, so any value is refused (docTR's docs state no API default). +const detector = [_][]const u8{ "bin_thresh", "box_thresh" }; +/// Metadata options: any boolean is accepted; ``language`` stays null and ``orientation`` 0 (the page as sent). +const metadata = [_][]const u8{ "detect_orientation", "detect_language" }; + +/// Answers one POST /ocr chosen as docTR; ``parts`` is null when ``?format=`` chose it before any multipart parse. +pub fn post(srv: *Server, conn: *Conn, a: Allocator, parts: ?[]const multipart.Part, body: []const u8, gone: anytype) void { + var fault: Fault = .{ .class = .internal, .message = "" }; + const out = handle(srv, a, conn.path, conn.header("Content-Type"), parts, body, gone, &fault) catch |e| switch (e) { + error.Faulted => return sendFault(conn, a, fault), + error.OutOfMemory => return sendFault(conn, a, .{ .class = .internal, .message = "out of memory" }), + error.Cancelled => { + conn.close = true; + return; + }, + }; + conn.sendJson(200, out); +} + +fn handle(srv: *Server, a: Allocator, path: []const u8, content_type: ?[]const u8, parts_in: ?[]const multipart.Part, body: []const u8, gone: anytype, fault: *Fault) Step![]const u8 { + try run.gate(srv, a, fault); + const o = try options(a, path, fault); + const parts = parts_in orelse try partsOf(a, content_type, body, fault); + const sources = try files(a, parts, srv.config.vision_pdf, fault); + var enc: Encoder = .{ .o = o, .geometry = srv.info.ocr.?.geometry, .sources = sources }; + try run.run(srv, a, sources, enc.sink(), fault, gone); + return json.stringify(a, .{ .array = enc.pages.items }, .{}); +} + +fn bad(a: Allocator, fault: *Fault, comptime fmt: []const u8, args: anytype) Step { + return fault.fail(a, .bad_input, fmt, args); +} + +/// The query's options: booleans as query words; content options at their documented defaults; model options unread. +pub fn options(a: Allocator, path: []const u8, fault: *Fault) Step!Options { + for (metadata) |m| _ = try boolean(a, path, m, fault); + for (fixed_flags) |f| if (try boolean(a, path, f[0], fault)) |v| if (v != f[1]) + return bad(a, fault, "{s}={} is not supported; TensorFold reads pages with {s}={}", .{ f[0], v, f[0], f[1] }); + if (try param(a, path, "paragraph_break", fault)) |text| { + const v = std.fmt.parseFloat(f64, std.mem.trim(u8, text, " ")) catch return bad(a, fault, "paragraph_break must be a number", .{}); + if (v != paragraph_break) return bad(a, fault, "paragraph_break={s} is not supported; TensorFold reads pages with paragraph_break={d}", .{ text, paragraph_break }); + } + for (detector) |name| if (try param(a, path, name, fault) != null) + return bad(a, fault, "{s} is not supported: TensorFold has no text detector to apply it to; leave it out", .{name}); + return .{ + .straight = try boolean(a, path, "assume_straight_pages", fault) orelse true, + .blocks = try boolean(a, path, "resolve_blocks", fault) orelse false, + .lines = try boolean(a, path, "resolve_lines", fault) orelse true, + }; +} + +fn boolean(a: Allocator, path: []const u8, name: []const u8, fault: *Fault) Step!?bool { + const text = try param(a, path, name, fault) orelse return null; + return query.boolean(text) orelse bad(a, fault, "{s} must be a boolean (true, false, 1, 0, yes, no, on or off)", .{name}); +} + +fn param(a: Allocator, path: []const u8, name: []const u8, fault: *Fault) Step!?[]const u8 { + return query.get(a, path, name) catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Malformed => bad(a, fault, "the {s} query parameter is malformed", .{name}), + error.Repeated => bad(a, fault, "the {s} query parameter is repeated; send it once", .{name}), + }; +} + +/// The body's multipart parts, read here when ``?format=doctr`` chose the dialect before any part was parsed. +fn partsOf(a: Allocator, content_type: ?[]const u8, body: []const u8, fault: *Fault) Step![]const multipart.Part { + const ct = std.mem.trim(u8, content_type orelse "", " \t"); + const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t"); + if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) return bad(a, fault, "a docTR request is multipart/form-data with one or more files parts", .{}); + const bound = multipart.boundary(ct) orelse return bad(a, fault, "multipart/form-data needs a boundary parameter", .{}); + return multipart.parse(a, body, bound) catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Malformed => bad(a, fault, "the multipart body is malformed", .{}), + }; +} + +/// The ``files`` parts in order as sources: the part type exactly as docTR checks it, and the file's name. +pub fn files(a: Allocator, parts: []const multipart.Part, pdf_on: bool, fault: *Fault) Step![]const types.Source { + if (route.mixed(parts)) return bad(a, fault, "{s}", .{route.mixed_parts}); + var out: std.ArrayList(types.Source) = .empty; + for (parts) |p| { + if (!std.mem.eql(u8, p.name, "files")) continue; + const mime = p.content_type orelse ""; + const name = p.filename orelse ""; // a part without a filename is read, unnamed + const is_pdf = std.mem.eql(u8, mime, "application/pdf"); + if (!is_pdf and !std.mem.eql(u8, mime, "image/jpeg") and !std.mem.eql(u8, mime, "image/png")) + return if (p.content_type) |ct| bad(a, fault, "files part \"{s}\" has type {s}; send image/jpeg, image/png or application/pdf", .{ name, ct }) else bad(a, fault, "files part \"{s}\" has no Content-Type; send image/jpeg, image/png or application/pdf", .{name}); + if (is_pdf and !pdf_on) return bad(a, fault, "{s}", .{pdf.off_message}); + const sel: pdf.Selection = .{ .all_within = if (is_pdf) std.math.maxInt(u32) else 1 }; + try out.append(a, .{ .name = name, .bytes = p.body, .kind = if (is_pdf) .pdf else .image, .sel = sel }); + } + if (out.items.len == 0) return bad(a, fault, "a docTR request needs one or more files parts", .{}); + return out.items; +} + +/// The page sink: one OCROut a page, named by the page's file. +pub const Encoder = struct { + o: Options, + geometry: api.ocr.Geometry, + sources: []const types.Source, + pages: std.ArrayList(Value) = .empty, + + pub fn sink(e: *Encoder) run.PageSink { + return .{ .ctx = e, .page = onPage }; + } + + fn onPage(ctx: *anyopaque, a: Allocator, source: u32, page: *const OcrPage, _: picture.Rgb, _: *budget.Encodes, fault: *Fault) Step!void { + const e: *Encoder = @ptrCast(@alignCast(ctx)); + const out = e.encodePage(a, e.sources[source].name, page) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.Unreadable => return fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{page.index}), + }; + try e.pages.append(a, out); + } + + /// One OCROut: name, orientation 0, unknown language, ``[height, width]``, no layout or tables, one item. + pub fn encodePage(e: *const Encoder, a: Allocator, name: []const u8, page: *const OcrPage) (Allocator.Error || error{Unreadable})!Value { + const size: Size = .{ .w = @floatFromInt(page.width), .h = @floatFromInt(page.height) }; + var built: std.ArrayList(Line) = .empty; + for (try lines.fromBlocks(a, page, e.geometry)) |l| { + const ws = try lines.words(a, l, page.width, page.height); + // a line of only Unicode whitespace has no words and no box: left out, as is a block of only such lines + if (ws.len > 0) try built.append(a, .{ .quad = l.quad, .words = ws, .block = l.block }); + } + if (!e.o.lines and built.items.len > 0) { + var all: std.ArrayList(lines.Word) = .empty; + for (built.items) |l| try all.appendSlice(a, l.words); + built.items[0] = .{ .quad = null, .words = all.items, .block = 0, .own = false }; + built.shrinkRetainingCapacity(1); + } + var blocks: std.ArrayList(Value) = .empty; + var start: usize = 0; + while (start < built.items.len) { + var end = start + 1; + if (e.o.blocks) { + while (end < built.items.len and built.items[end].block == built.items[start].block) end += 1; + } else end = built.items.len; + try blocks.append(a, try e.block(a, built.items[start..end], size)); + start = end; + } + const item = try json.newObject(a); + try item.put(a, "blocks", .{ .array = blocks.items }); + const o = try json.newObject(a); + try o.put(a, "name", .{ .string = name }); + try o.put(a, "orientation", try angle(a)); // docTR's README reply: {"value": 0, "confidence": null} + try o.put(a, "language", try unknown(a)); + try o.put(a, "dimensions", .{ .array = try a.dupe(Value, &.{ try json.intValue(a, page.height), try json.intValue(a, page.width) }) }); + try o.put(a, "layout", .{ .array = &.{} }); + try o.put(a, "tables", .{ .array = &.{} }); + try o.put(a, "items", .{ .array = try a.dupe(Value, &.{.{ .object = item }}) }); + return .{ .object = o }; + } + + fn block(e: *const Encoder, a: Allocator, ls: []const Line, size: Size) Allocator.Error!Value { + var box = empty_box; + const out = try a.alloc(Value, ls.len); + for (ls, out) |l, *v| { + const r = try e.line(a, l, size); + box = join(box, r.box); + v.* = r.value; + } + const o = try json.newObject(a); + try o.put(a, "geometry", try geometry(a, e.o.straight, box, null)); + try o.put(a, "objectness_score", .{ .float = 1.0 }); + try o.put(a, "lines", .{ .array = out }); + return .{ .object = o }; + } + + /// A line and the box that encloses its words (the block's union takes it). + fn line(e: *const Encoder, a: Allocator, l: Line, size: Size) Allocator.Error!struct { value: Value, box: Box } { + var box = empty_box; + const ws = try a.alloc(Value, l.words.len); + for (l.words, ws) |w, *v| { + const wb = boxOf(w.quad, size); + box = join(box, wb); + const o = try json.newObject(a); + try o.put(a, "value", .{ .string = w.text }); + try o.put(a, "geometry", try geometry(a, e.o.straight, wb, if (w.quad) |q| relative(q, size) else null)); + try o.put(a, "objectness_score", .{ .float = 1.0 }); + try o.put(a, "confidence", .{ .float = 1.0 }); + const crop = try json.newObject(a); + try crop.put(a, "value", try json.intValue(a, 0)); + try crop.put(a, "confidence", .null); + try o.put(a, "crop_orientation", .{ .object = crop }); + v.* = .{ .object = o }; + } + // polygon mode writes the line's own quad when it encloses its words; else, and for a merged line, their union + const own: ?[4][2]f64 = if (l.own) if (l.quad) |q| (if (encloses(q, l.words)) relative(q, size) else null) else null else null; + const o = try json.newObject(a); + try o.put(a, "geometry", try geometry(a, e.o.straight, box, own)); + try o.put(a, "objectness_score", .{ .float = 1.0 }); + try o.put(a, "words", .{ .array = ws }); + return .{ .value = .{ .object = o }, .box = box }; + } +}; + +const Size = struct { w: f64, h: f64 }; +/// ``[xmin, ymin, xmax, ymax]`` relative to the page. +const Box = [4]f64; +const empty_box: Box = .{ std.math.inf(f64), std.math.inf(f64), -std.math.inf(f64), -std.math.inf(f64) }; +/// A page line, its words, its source block, and whether polygon mode writes its own quad. +const Line = struct { quad: ?Quad, words: []const lines.Word, block: u32, own: bool = true }; + +/// The quad's points divided by the page size, not rounded (as the floats in docTR's API README reply). +fn relative(q: Quad, size: Size) [4][2]f64 { + var out: [4][2]f64 = undefined; + for (q, &out) |p, *o| o.* = .{ @as(f64, p[0]) / size.w, @as(f64, p[1]) / size.h }; + return out; +} + +/// The quad's relative min/max box; the whole page for a reader without geometry. +fn boxOf(q: ?Quad, size: Size) Box { + const r = relative(q orelse return .{ 0, 0, 1, 1 }, size); + var box = empty_box; + for (r) |p| box = join(box, .{ p[0], p[1], p[0], p[1] }); + return box; +} + +/// Whether every corner of every word lies in the convex quad ``q``, to 1e-3 px (validation widens tiny words past it). +fn encloses(q: Quad, words: []const lines.Word) bool { + var area: f64 = 0; + for (0..4) |i| area += cross(q[i], q[(i + 1) % 4], .{ 0, 0 }); + const sign: f64 = if (area < 0) -1 else 1; + for (words) |w| for (w.quad orelse return false) |p| for (0..4) |i| { + const from = q[i]; + const to = q[(i + 1) % 4]; + const len = std.math.hypot(@as(f64, to[0]) - from[0], @as(f64, to[1]) - from[1]); + if (sign * cross(from, to, p) < -1e-3 * len) return false; + }; + return true; +} + +/// The cross product of ``to - from`` and ``p - from``: its sign says which side of the edge ``p`` is on. +fn cross(from: [2]f32, to: [2]f32, p: [2]f32) f64 { + const ax = @as(f64, to[0]) - from[0]; + const ay = @as(f64, to[1]) - from[1]; + return ax * (@as(f64, p[1]) - from[1]) - ay * (@as(f64, p[0]) - from[0]); +} + +fn join(x: Box, y: Box) Box { + return .{ @min(x[0], y[0]), @min(x[1], y[1]), @max(x[2], y[2]), @max(x[3], y[3]) }; +} + +/// Box mode: the 4 box floats; polygon mode: ``quad``'s 8, or the box's corners TL, TR, BR, BL. +fn geometry(a: Allocator, straight: bool, box: Box, quad: ?[4][2]f64) Allocator.Error!Value { + if (straight) return floats(a, &box); + const q = quad orelse [4][2]f64{ .{ box[0], box[1] }, .{ box[2], box[1] }, .{ box[2], box[3] }, .{ box[0], box[3] } }; + return floats(a, &@as([8]f64, @bitCast(q))); +} + +fn floats(a: Allocator, xs: []const f64) Allocator.Error!Value { + const out = try a.alloc(Value, xs.len); + for (xs, out) |x, *v| v.* = .{ .float = x }; + return .{ .array = out }; +} + +/// ``{"value": 0, "confidence": null}``: the page as sent, no orientation estimated. +fn angle(a: Allocator) Allocator.Error!Value { + const o = try json.newObject(a); + try o.put(a, "value", try json.intValue(a, 0)); + try o.put(a, "confidence", .null); + return .{ .object = o }; +} + +fn unknown(a: Allocator) Allocator.Error!Value { + const o = try json.newObject(a); + try o.put(a, "value", .null); + try o.put(a, "confidence", .null); + return .{ .object = o }; +} + +/// The HTTP status of each fault class (docs/api.md OCR: Failures). +pub fn status(class: types.Class) u16 { + return switch (class) { + .bad_input => 400, + .unreadable => 422, + .capacity => 503, + .internal => 500, + }; +} + +/// ``{"detail": message}``, FastAPI's error body (docTR's template is a FastAPI server); capacity adds Retry-After. +pub fn sendFault(conn: *Conn, a: Allocator, fault: Fault) void { + const body = errorBody(a, fault.message) catch return conn.sendJson(500, "{\"detail\": \"out of memory\"}"); + if (fault.class != .capacity) return conn.sendJson(status(fault.class), body); + var buf: [16]u8 = undefined; + const retry = std.fmt.bufPrint(&buf, "{d}", .{fault.retry_after orelse 1}) catch unreachable; + conn.sendJsonWith(status(fault.class), body, &.{.{ "Retry-After", retry }}); +} + +pub fn errorBody(a: Allocator, message: []const u8) Allocator.Error![]const u8 { + const o = try json.newObject(a); + try o.put(a, "detail", .{ .string = message }); + return json.stringify(a, .{ .object = o }, .{}); +} diff --git a/zig/src/server/ocr/doctr_test.zig b/zig/src/server/ocr/doctr_test.zig new file mode 100644 index 00000000000..1afa6505b44 --- /dev/null +++ b/zig/src/server/ocr/doctr_test.zig @@ -0,0 +1,365 @@ +//! docTR's dialect: options, files, OCROut pages in box and polygon geometry, and whole requests through the route. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const doctr = @import("doctr.zig"); +const multipart = @import("../multipart.zig"); +const routes = @import("../routes.zig"); +const types = @import("types.zig"); +const run = @import("run.zig"); +const harness = @import("harness_test.zig"); +const Harness = harness.Harness; +const Value = json.Value; +const Allocator = std.mem.Allocator; +const t = std.testing; + +fn optionsOf(a: Allocator, path: []const u8, fault: *types.Fault) !doctr.Options { + return doctr.options(a, path, fault); +} + +test "ocr doctr: options read query booleans, ignore model choices and refuse content options off their documented defaults" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fault: types.Fault = undefined; + try t.expectEqualDeep(doctr.Options{}, try optionsOf(a, "/ocr?det_arch=db_resnet50&reco_arch=crnn_vgg16_bn&det_bs=9&x=1", &fault)); + try t.expectEqualDeep(doctr.Options{ .straight = false, .blocks = true, .lines = false }, try optionsOf(a, "/ocr?assume_straight_pages=OFF&resolve_blocks=Yes&resolve_lines=0", &fault)); + const ok = "/ocr?detect_orientation=true&detect_language=1&detect_tables=false&straighten_pages=no¶graph_break=0.035"; + try t.expectEqualDeep(doctr.Options{}, try optionsOf(a, ok, &fault)); + const Case = struct { []const u8, []const u8 }; + for ([_]Case{ + .{ "/ocr?detect_tables=true", "detect_tables=true is not supported" }, + .{ "/ocr?detect_layout=1", "detect_layout=true is not supported" }, + .{ "/ocr?straighten_pages=on", "straighten_pages=true is not supported" }, + .{ "/ocr?paragraph_break=0.01", "paragraph_break=0.01 is not supported" }, + .{ "/ocr?paragraph_break=0.0035", "paragraph_break=0.0035 is not supported" }, + .{ "/ocr?paragraph_break=x", "paragraph_break must be a number" }, + .{ "/ocr?bin_thresh=0.3", "bin_thresh is not supported: TensorFold has no text detector to apply it to; leave it out" }, + .{ "/ocr?box_thresh=0.1", "box_thresh is not supported: TensorFold has no text detector to apply it to; leave it out" }, + .{ "/ocr?resolve_blocks=maybe", "resolve_blocks must be a boolean" }, + .{ "/ocr?detect_language=2", "detect_language must be a boolean" }, + .{ "/ocr?resolve_lines=%zz", "the resolve_lines query parameter is malformed" }, + .{ "/ocr?resolve_lines=true&resolve_lines=false", "the resolve_lines query parameter is repeated; send it once" }, + }) |c| { + try t.expectError(error.Faulted, optionsOf(a, c[0], &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + try t.expect(std.mem.indexOf(u8, fault.message, c[1]) != null); + } +} + +fn part(name: []const u8, filename: ?[]const u8, content_type: ?[]const u8) multipart.Part { + return .{ .name = name, .filename = filename, .content_type = content_type, .media = null, .body = "bytes" }; +} + +test "ocr doctr: files keep part order and their names; other part types are refused as docTR words them" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fault: types.Fault = undefined; + const parts = [_]multipart.Part{ part("files", "b.png", "image/png"), part("other", "x", "text/plain"), part("files", "a.pdf", "application/pdf"), part("files", null, "image/jpeg") }; + const got = try doctr.files(a, &parts, true, &fault); + try t.expectEqual(@as(usize, 3), got.len); + try t.expectEqualStrings("b.png", got[0].name); + try t.expect(got[0].kind == .image and got[0].sel.all_within == 1); + try t.expectEqualStrings("a.pdf", got[1].name); + try t.expect(got[1].kind == .pdf and got[1].sel.all_within == std.math.maxInt(u32)); + try t.expectEqualStrings("", got[2].name); + const Case = struct { []const multipart.Part, []const u8 }; + for ([_]Case{ + .{ &.{part("files", "x.txt", "text/plain")}, "files part \"x.txt\" has type text/plain; send image/jpeg, image/png or application/pdf" }, + .{ &.{part("files", "y.png", null)}, "files part \"y.png\" has no Content-Type; send image/jpeg, image/png or application/pdf" }, + .{ &.{part("files", "z.png", "image/png; charset=binary")}, "files part \"z.png\" has type image/png; charset=binary; send image/jpeg, image/png or application/pdf" }, + .{ &.{part("files", "w.webp", "image/webp")}, "files part \"w.webp\" has type image/webp; send image/jpeg, image/png or application/pdf" }, + .{ &.{part("file", "v.png", "image/png")}, "a docTR request needs one or more files parts" }, + }) |c| { + try t.expectError(error.Faulted, doctr.files(a, c[0], true, &fault)); + try t.expectEqualStrings(c[1], fault.message); + } + try t.expectError(error.Faulted, doctr.files(a, &.{part("files", "a.pdf", "application/pdf")}, false, &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "--vision-pdf") != null); +} + +fn page(a: Allocator, w: u32, h: u32, blocks: []const api.ocr.OcrBlock) !types.OcrPage { + return .{ .index = 0, .width = w, .height = h, .dpi = 72, .blocks = try a.dupe(api.ocr.OcrBlock, blocks) }; +} + +fn rect(x0: f32, y0: f32, x1: f32, y1: f32) api.ocr.Quad { + return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } }; +} + +fn encode(a: Allocator, o: doctr.Options, geo: api.ocr.Geometry, p: *const types.OcrPage) !Value { + const e: doctr.Encoder = .{ .o = o, .geometry = geo, .sources = &.{} }; + return e.encodePage(a, "page.png", p); +} + +fn expectFloats(want: []const f64, got: Value) !void { + try t.expectEqual(want.len, got.array.len); + for (want, got.array) |w, g| try t.expectEqual(w, g.float); +} + +fn blocksOf(v: Value) []Value { + return v.get("items").?.array[0].get("blocks").?.array; +} + +const two_blocks = [_]api.ocr.OcrBlock{ + .{ .content = "Hello world", .quad = rect(10, 10, 60, 20), .kind = .text }, + .{ .content = "", .quad = rect(0, 0, 5, 5), .kind = .picture }, + .{ .content = "one\ntwo", .quad = rect(10, 30, 90, 40), .kind = .text }, +}; + +test "ocr doctr: one block a page by default, source blocks with resolve_blocks, one line with resolve_lines=false" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p = try page(a, 100, 50, &two_blocks); + const v = try encode(a, .{}, .block, &p); + try t.expectEqualStrings("page.png", v.strField("name").?); + // docTR's API README reply: orientation {"value": 0, "confidence": null}, language both null + try t.expectEqualStrings("0", v.get("orientation").?.get("value").?.int); + try t.expect(v.get("orientation").?.get("confidence").? == .null); + try t.expect(v.get("language").?.get("value").? == .null and v.get("language").?.get("confidence").? == .null); + try t.expectEqualStrings("50", v.get("dimensions").?.array[0].int); + try t.expectEqualStrings("100", v.get("dimensions").?.array[1].int); + try t.expect(v.get("layout").?.array.len == 0 and v.get("tables").?.array.len == 0); + const one = blocksOf(v); + try t.expectEqual(@as(usize, 1), one.len); + try expectFloats(&.{ 0.1, 0.2, 0.9, 0.8 }, one[0].get("geometry").?); + try t.expectEqual(@as(f64, 1.0), one[0].get("objectness_score").?.float); + const ls = one[0].get("lines").?.array; + try t.expectEqual(@as(usize, 3), ls.len); + try expectFloats(&.{ 0.1, 0.2, 0.6, 0.4 }, ls[0].get("geometry").?); + try expectFloats(&.{ 0.1, 0.7, 0.9, 0.8 }, ls[2].get("geometry").?); + const word = ls[0].get("words").?.array[0]; + try t.expectEqualStrings("Hello", word.strField("value").?); + try expectFloats(&.{ 0.1, 0.2, 0.35, 0.4 }, word.get("geometry").?); + try t.expectEqual(@as(f64, 1.0), word.get("confidence").?.float); + try t.expectEqual(@as(f64, 1.0), word.get("objectness_score").?.float); + try t.expectEqualStrings("0", word.get("crop_orientation").?.get("value").?.int); + try t.expect(word.get("crop_orientation").?.get("confidence").? == .null); + const grouped = blocksOf(try encode(a, .{ .blocks = true }, .block, &p)); + try t.expectEqual(@as(usize, 2), grouped.len); + try t.expectEqual(@as(usize, 1), grouped[0].get("lines").?.array.len); + try t.expectEqual(@as(usize, 2), grouped[1].get("lines").?.array.len); + try expectFloats(&.{ 0.1, 0.6, 0.9, 0.8 }, grouped[1].get("geometry").?); + for ([_]doctr.Options{ .{ .lines = false }, .{ .lines = false, .blocks = true } }) |o| { + const merged = blocksOf(try encode(a, o, .block, &p)); + try t.expectEqual(@as(usize, 1), merged.len); + const line = merged[0].get("lines").?.array; + try t.expectEqual(@as(usize, 1), line.len); + const ws = line[0].get("words").?.array; + try t.expectEqual(@as(usize, 4), ws.len); + for (ws, [_][]const u8{ "Hello", "world", "one", "two" }) |w, s| try t.expectEqualStrings(s, w.strField("value").?); + try expectFloats(&.{ 0.1, 0.2, 0.9, 0.8 }, line[0].get("geometry").?); + } +} + +test "ocr doctr: polygon geometry is 8 relative floats in reading order, never rounded" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // a 180-degree line: TL is at the right, so the first word starts there + const turned: api.ocr.Quad = .{ .{ 60, 20 }, .{ 10, 20 }, .{ 10, 10 }, .{ 60, 10 } }; + const p = try page(a, 100, 50, &.{.{ .content = "ab cd", .quad = turned, .kind = .text }}); + const block = blocksOf(try encode(a, .{ .straight = false }, .block, &p))[0]; + try expectFloats(&.{ 0.1, 0.2, 0.6, 0.2, 0.6, 0.4, 0.1, 0.4 }, block.get("geometry").?); + const line = block.get("lines").?.array[0]; + try expectFloats(&.{ 0.6, 0.4, 0.1, 0.4, 0.1, 0.2, 0.6, 0.2 }, line.get("geometry").?); + try expectFloats(&.{ 0.6, 0.4, 0.35, 0.4, 0.35, 0.2, 0.6, 0.2 }, line.get("words").?.array[0].get("geometry").?); + // a merged line has no quad of its own: its union's corners + const merged = blocksOf(try encode(a, .{ .straight = false, .lines = false }, .block, &p))[0].get("lines").?.array[0]; + try expectFloats(&.{ 0.1, 0.2, 0.6, 0.2, 0.6, 0.4, 0.1, 0.4 }, merged.get("geometry").?); + const third = try page(a, 30, 10, &.{.{ .content = "x", .quad = rect(10, 0, 20, 10), .kind = .text }}); + const g = blocksOf(try encode(a, .{}, .block, &third))[0].get("geometry").?; + try expectFloats(&.{ 10.0 / 30.0, 0, 20.0 / 30.0, 1 }, g); + const text = try json.stringify(a, g, .{}); + try t.expect(std.mem.indexOf(u8, text, "0.3333333333333333") != null); +} + +test "ocr doctr: an empty page has no blocks, and a reader without geometry gives whole-page boxes" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const empty = try page(a, 100, 50, &.{.{ .content = "", .quad = rect(0, 0, 5, 5), .kind = .picture }}); + for ([_]doctr.Options{ .{}, .{ .lines = false }, .{ .blocks = true } }) |o| try t.expectEqual(@as(usize, 0), blocksOf(try encode(a, o, .block, &empty)).len); + const whole = try page(a, 100, 50, &.{.{ .content = "# Title\n\nbody text", .quad = null, .kind = .page }}); + const b = blocksOf(try encode(a, .{}, .none, &whole))[0]; + try expectFloats(&.{ 0, 0, 1, 1 }, b.get("geometry").?); + const ls = b.get("lines").?.array; + try t.expectEqual(@as(usize, 2), ls.len); + try expectFloats(&.{ 0, 0, 1, 1 }, ls[1].get("words").?.array[1].get("geometry").?); + const poly = blocksOf(try encode(a, .{ .straight = false }, .none, &whole))[0]; + try expectFloats(&.{ 0, 0, 1, 0, 1, 1, 0, 1 }, poly.get("lines").?.array[0].get("geometry").?); +} + +fn noInfinity(a: Allocator, v: Value) !void { + const text = try json.stringify(a, v, .{}); + try t.expect(std.mem.indexOf(u8, text, "inf") == null and std.mem.indexOf(u8, text, "Inf") == null); +} + +test "ocr doctr: lines of only Unicode whitespace are left out, and so are blocks left without lines" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const blank = try page(a, 100, 50, &.{ + .{ .content = "\u{00A0}", .quad = rect(10, 10, 60, 20), .kind = .text }, + .{ .content = "\u{3000}", .quad = rect(10, 30, 60, 40), .kind = .text }, + }); + const all = [_]doctr.Options{ .{}, .{ .straight = false }, .{ .lines = false }, .{ .straight = false, .lines = false }, .{ .blocks = true } }; + for (all) |o| { + const v = try encode(a, o, .block, &blank); + try t.expectEqual(@as(usize, 0), blocksOf(v).len); + try noInfinity(a, v); + } + const mixed = try page(a, 100, 50, &.{ + .{ .content = "Hello", .quad = rect(10, 10, 60, 20), .kind = .text }, + .{ .content = "\u{3000}", .quad = rect(10, 20, 60, 30), .kind = .text }, + .{ .content = "world", .quad = rect(10, 30, 60, 40), .kind = .text }, + }); + for ([_]bool{ true, false }) |straight| { + const one = try encode(a, .{ .straight = straight }, .block, &mixed); + try noInfinity(a, one); + const ls = blocksOf(one)[0].get("lines").?.array; + try t.expectEqual(@as(usize, 2), ls.len); + try t.expectEqualStrings("world", ls[1].get("words").?.array[0].strField("value").?); + if (straight) try expectFloats(&.{ 0.1, 0.2, 0.6, 0.8 }, blocksOf(one)[0].get("geometry").?); + const grouped = try encode(a, .{ .straight = straight, .blocks = true }, .block, &mixed); + try noInfinity(a, grouped); + try t.expectEqual(@as(usize, 2), blocksOf(grouped).len); + const merged = try encode(a, .{ .straight = straight, .lines = false }, .block, &mixed); + try noInfinity(a, merged); + try t.expectEqual(@as(usize, 2), blocksOf(merged)[0].get("lines").?.array[0].get("words").?.array.len); + } +} + +test "ocr doctr: a line polygon encloses its words, or the words' union is written instead" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // two words under 1 px² each are widened by validation past the half-pixel-wide line quad + const thin = try page(a, 100, 50, &.{.{ .content = "a b", .quad = rect(10, 10, 10.5, 12), .kind = .text }}); + const line = blocksOf(try encode(a, .{ .straight = false }, .block, &thin))[0].get("lines").?.array[0]; + const g = line.get("geometry").?.array; + var lo: [2]f64 = .{ std.math.inf(f64), std.math.inf(f64) }; + var hi: [2]f64 = .{ -std.math.inf(f64), -std.math.inf(f64) }; + for (line.get("words").?.array) |w| for (w.get("geometry").?.array, 0..) |x, i| { + lo[i % 2] = @min(lo[i % 2], x.float); + hi[i % 2] = @max(hi[i % 2], x.float); + }; + try t.expect(hi[0] > 10.5 / 100.0); + const want = [_]f64{ lo[0], lo[1], hi[0], lo[1], hi[0], hi[1], lo[0], hi[1] }; + for (want, g) |w, x| try t.expectEqual(w, x.float); + // a line whose words lie inside it keeps its own quad + const wide = try page(a, 100, 50, &.{.{ .content = "a b", .quad = rect(10, 10, 60, 20), .kind = .text }}); + const kept = blocksOf(try encode(a, .{ .straight = false }, .block, &wide))[0].get("lines").?.array[0]; + try expectFloats(&.{ 0.1, 0.2, 0.6, 0.2, 0.6, 0.4, 0.1, 0.4 }, kept.get("geometry").?); +} + +const File = struct { filename: ?[]const u8 = "page.png", ct: ?[]const u8 = "image/png", bytes: []const u8 }; + +fn form(a: Allocator, files: []const File) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (files) |f| { + try out.appendSlice(a, "--XyZ\r\nContent-Disposition: form-data; name=\"files\""); + if (f.filename) |n| try out.print(a, "; filename=\"{s}\"", .{n}); + try out.appendSlice(a, "\r\n"); + if (f.ct) |ct| try out.print(a, "Content-Type: {s}\r\n", .{ct}); + try out.print(a, "\r\n{s}\r\n", .{f.bytes}); + } + try out.appendSlice(a, "--XyZ--\r\n"); + return out.items; +} + +/// A whole POST through the dispatcher; the reply as JSON, its status in ``status``. +fn post(a: Allocator, h: *Harness, path: []const u8, body: []const u8, status: *u16) !Value { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, path, "multipart/form-data; boundary=XyZ", body), a); + status.* = wire.status(); + try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nContent-Type: application/json\r\n") != null); + return wire.parsed(); +} + +fn serve(h: *Harness, replies: []const harness.Script) !void { + h.* = .{ .replies = replies }; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); +} + +test "ocr doctr: the README call on /ocr and /ocr/ gives one OCROut a file, in order, with docTR's field types" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: Harness = undefined; + const first = "text 10 10 60 20\nHello world"; + const second = "title 0 0 100 50\n# Second"; + try serve(&h, &.{ .{ .text = first }, .{ .text = second }, .{ .text = first }, .{ .text = second } }); + defer h.stop(); + const png = try harness.png(a, 100, 50); + const body = try form(a, &.{ .{ .filename = "a.png", .bytes = png }, .{ .filename = "b.png", .bytes = png } }); + for ([_][]const u8{ "/ocr?det_arch=db_resnet50&reco_arch=crnn_vgg16_bn", "/ocr/?det_arch=db_resnet50&reco_arch=crnn_vgg16_bn" }) |path| { + var status: u16 = 0; + const r = try post(a, &h, path, body, &status); + try t.expectEqual(@as(u16, 200), status); + try t.expectEqual(@as(usize, 2), r.array.len); + try t.expectEqualStrings("a.png", r.array[0].strField("name").?); + try t.expectEqualStrings("b.png", r.array[1].strField("name").?); + try t.expectEqualStrings("50", r.array[0].get("dimensions").?.array[0].int); + const word = blocksOf(r.array[0])[0].get("lines").?.array[0].get("words").?.array[1]; + try t.expectEqualStrings("world", word.strField("value").?); + try expectFloats(&.{ 0.35, 0.2, 0.6, 0.4 }, word.get("geometry").?); + try t.expectEqualStrings("0", word.get("crop_orientation").?.get("value").?.int); + try t.expectEqualStrings("Second", blocksOf(r.array[1])[0].get("lines").?.array[0].get("words").?.array[0].strField("value").?); + } +} + +test "ocr doctr: ?format=doctr reads the parts itself, and refusals and failures answer {detail} with their status" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: Harness = undefined; + try serve(&h, &.{ .{ .text = "text 0 0 10 10\nok" }, .{ .text = "!not the grammar" }, .{ .text = "text 0 0 1 1\nhalf", .reason = .length } }); + defer h.stop(); + const png = try harness.png(a, 100, 50); + const one = try form(a, &.{.{ .bytes = png }}); + var status: u16 = 0; + try t.expectEqual(@as(usize, 1), (try post(a, &h, "/ocr?format=doctr", one, &status)).array.len); + try t.expectEqual(@as(u16, 200), status); + var many: [17]File = undefined; + const small = try harness.png(a, 8, 8); + for (&many) |*f| f.* = .{ .bytes = small }; + const Case = struct { []const u8, []const u8, u16, []const u8 }; + for ([_]Case{ + .{ "/ocr", one, 422, "page 0: the model's output does not follow its format" }, + .{ "/ocr", one, 422, "page 0: the model's output was cut at the context limit" }, + .{ "/ocr", try form(a, &.{.{ .filename = "n.txt", .ct = "text/plain", .bytes = "x" }}), 400, "files part \"n.txt\" has type text/plain; send image/jpeg, image/png or application/pdf" }, + .{ "/ocr", try form(a, &.{.{ .ct = null, .bytes = png }}), 400, "files part \"page.png\" has no Content-Type; send image/jpeg, image/png or application/pdf" }, + .{ "/ocr?detect_tables=true", one, 400, "detect_tables=true is not supported; TensorFold reads pages with detect_tables=false" }, + .{ "/ocr", try form(a, &many), 400, "a request may read at most 16 pages (TENSORFOLD_MAX_PDF_PAGES); this one selects more" }, + .{ "/ocr?format=doctr", "{}", 400, "a docTR request is multipart/form-data with one or more files parts" }, + }) |c| { + var wire: harness.Wire = .{ .a = a }; + const ct: []const u8 = if (c[1][0] == '{') "application/json" else "multipart/form-data; boundary=XyZ"; + routes.dispatch(h.srv, try harness.request(a, &wire, c[0], ct, c[1]), a); + try t.expectEqual(c[2], wire.status()); + try t.expectEqualStrings(c[3], (try wire.parsed()).strField("detail").?); + } + h.srv.info.ocr = null; + _ = try post(a, &h, "/ocr", one, &status); + try t.expectEqual(@as(u16, 400), status); + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, "/ocr", "multipart/form-data; boundary=XyZ", one), a); + try t.expectEqualStrings(run.no_reader, (try wire.parsed()).strField("detail").?); +} + +test "ocr doctr: a capacity fault sends 503 with Retry-After, other classes their status, all as {detail}" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const Case = struct { types.Class, u16 }; + for ([_]Case{ .{ .bad_input, 400 }, .{ .unreadable, 422 }, .{ .capacity, 503 }, .{ .internal, 500 } }) |c| { + var wire: harness.Wire = .{ .a = a }; + const conn = try harness.request(a, &wire, "/ocr", null, ""); + doctr.sendFault(conn, a, .{ .class = c[0], .message = "why", .retry_after = if (c[0] == .capacity) 1 else null }); + try t.expectEqual(c[1], wire.status()); + try t.expectEqual(c[0] == .capacity, std.mem.indexOf(u8, wire.head(), "\r\nRetry-After: 1\r\n") != null); + try t.expectEqualStrings("why", (try wire.parsed()).strField("detail").?); + } +} diff --git a/zig/src/server/ocr/liteparse.zig b/zig/src/server/ocr/liteparse.zig index f3e4ec60b35..6cf785591c6 100644 --- a/zig/src/server/ocr/liteparse.zig +++ b/zig/src/server/ocr/liteparse.zig @@ -62,7 +62,7 @@ fn parseParts(a: Allocator, content_type: ?[]const u8, body: []const u8, fault: /// The one ``file`` part as an image source; ``language`` and other parts are ignored (no reader takes a hint). pub fn decode(a: Allocator, parts: []const multipart.Part, fault: *Fault) Step!types.Source { - if (route.hasFiles(parts)) return fault.fail(a, .bad_input, "{s}", .{route.files_parts}); + if (route.mixed(parts)) return fault.fail(a, .bad_input, "{s}", .{route.mixed_parts}); var file: ?multipart.Part = null; for (parts) |p| if (std.mem.eql(u8, p.name, "file")) { if (file != null) return fault.fail(a, .bad_input, "a LiteParse request has exactly one file part", .{}); @@ -78,7 +78,7 @@ pub fn decode(a: Allocator, parts: []const multipart.Part, fault: *Fault) Step!t return fault.fail(a, .bad_input, "the file is not a PNG, JPEG or WebP image", .{}); }, } - return .{ .bytes = f.body, .kind = .image, .sel = .{ .all_within = 1 } }; + return .{ .name = f.filename orelse "file", .bytes = f.body, .kind = .image, .sel = .{ .all_within = 1 } }; } /// The page sink: each line of the page as one LiteParse result. @@ -90,7 +90,7 @@ pub const Encoder = struct { return .{ .ctx = e, .page = onPage }; } - fn onPage(ctx: *anyopaque, a: Allocator, page: *const types.OcrPage, _: picture.Rgb, _: *budget.Encodes, fault: *Fault) Step!void { + fn onPage(ctx: *anyopaque, a: Allocator, _: u32, page: *const types.OcrPage, _: picture.Rgb, _: *budget.Encodes, fault: *Fault) Step!void { const e: *Encoder = @ptrCast(@alignCast(ctx)); const got = lines.fromBlocks(a, page, e.geometry) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, diff --git a/zig/src/server/ocr/liteparse_test.zig b/zig/src/server/ocr/liteparse_test.zig index 753ef2d57b1..3066bf8bf00 100644 --- a/zig/src/server/ocr/liteparse_test.zig +++ b/zig/src/server/ocr/liteparse_test.zig @@ -8,7 +8,6 @@ const types = @import("types.zig"); const budget = @import("budget.zig"); const run = @import("run.zig"); const lp = @import("liteparse.zig"); -const route = @import("route.zig"); const harness = @import("harness_test.zig"); const Harness = harness.Harness; const t = std.testing; @@ -49,15 +48,14 @@ test "ocr liteparse: the one file part is the page; a PDF, an empty or unknown f const png = try harness.png(a, 4, 3); const s = try lp.decode(a, &.{ part("language", "en"), part("file", png), part("other", "x") }, &fault); try t.expectEqual(.image, s.kind); + try t.expectEqualStrings("image.png", s.name); try t.expectEqual(png.len, s.bytes.len); const cases = [_]struct { []const multipart.Part, []const u8 }{ .{ &.{part("file", "%PDF-1.7\n...")}, lp.no_pdf }, .{ &.{part("file", "")}, "the file part is empty" }, .{ &.{part("file", "GIF89a....")}, "the file is not a PNG, JPEG or WebP image" }, .{ &.{ part("file", png), part("file", png) }, "a LiteParse request has exactly one file part" }, - // a files part is refused, never dropped: this server reads only LiteParse's file part - .{ &.{part("files", png)}, route.files_parts }, - .{ &.{ part("file", png), part("files", png) }, route.files_parts }, + .{ &.{part("files", png)}, "a LiteParse request has exactly one file part" }, }; for (cases) |c| { try t.expectError(error.Faulted, lp.decode(a, c[0], &fault)); @@ -77,7 +75,7 @@ test "ocr liteparse: a page without text gives an empty results list, and faults const page: types.OcrPage = .{ .index = 0, .width = 1, .height = 1, .dpi = 72, .blocks = &blocks }; var budget_ = budget.Encodes.init(1, 1); var fault: types.Fault = undefined; - try sink.page(sink.ctx, a, &page, .{ .width = 1, .height = 1, .pixels = &pixels }, &budget_, &fault); + try sink.page(sink.ctx, a, 0, &page, .{ .width = 1, .height = 1, .pixels = &pixels }, &budget_, &fault); try t.expectEqualStrings("{\"results\": []}", try enc.reply(a)); const want = [_]struct { types.Class, u16 }{ .{ .bad_input, 400 }, .{ .unreadable, 422 }, .{ .capacity, 503 }, .{ .internal, 500 } }; for (want) |w| try t.expectEqual(w[1], lp.status(w[0])); diff --git a/zig/src/server/ocr/mistral.zig b/zig/src/server/ocr/mistral.zig index afb590454c5..d2386207102 100644 --- a/zig/src/server/ocr/mistral.zig +++ b/zig/src/server/ocr/mistral.zig @@ -114,11 +114,11 @@ pub fn decode(a: Allocator, body: Value, facts: Facts, fault: *Fault) Step!Reque if (is_pdf) { if (!facts.pdf) return bad(a, fault, &.{ "body", "document" }, "{s}", .{pdf.off_message}); const sel: pdf.Selection = if (pages) |l| .{ .list = l } else .{ .all_within = std.math.maxInt(u32) }; - return .{ .options = o, .source = .{ .bytes = bytes, .kind = .pdf, .sel = sel }, .doc_size = bytes.len }; + return .{ .options = o, .source = .{ .name = "document", .bytes = bytes, .kind = .pdf, .sel = sel }, .doc_size = bytes.len }; } if (!image) return bad(a, fault, &.{ "body", "document" }, "the document is not a PDF, PNG, JPEG or WebP file", .{}); if (pages) |l| if (l.len != 1 or l[0] != 0) return bad(a, fault, &.{ "body", "pages" }, "an image has one page; pages may select only page 0", .{}); - return .{ .options = o, .source = .{ .bytes = bytes, .kind = .image, .sel = .{ .all_within = 1 } }, .doc_size = bytes.len }; + return .{ .options = o, .source = .{ .name = "document", .bytes = bytes, .kind = .image, .sel = .{ .all_within = 1 } }, .doc_size = bytes.len }; } fn flag(a: Allocator, fault: *Fault, body: Value, name: []const u8) Step!?bool { diff --git a/zig/src/server/ocr/mistral_reply.zig b/zig/src/server/ocr/mistral_reply.zig index fec25c381d9..a447b6c0219 100644 --- a/zig/src/server/ocr/mistral_reply.zig +++ b/zig/src/server/ocr/mistral_reply.zig @@ -48,7 +48,7 @@ pub const Encoder = struct { return .{ .ctx = e, .page = onPage }; } - fn onPage(ctx: *anyopaque, a: Allocator, page: *const OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step!void { + fn onPage(ctx: *anyopaque, a: Allocator, _: u32, page: *const OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step!void { const e: *Encoder = @ptrCast(@alignCast(ctx)); try e.pages.append(a, try e.encodePage(a, page, rgb, enc, fault)); } diff --git a/zig/src/server/ocr/route.zig b/zig/src/server/ocr/route.zig index 083aa66912a..e307041e18f 100644 --- a/zig/src/server/ocr/route.zig +++ b/zig/src/server/ocr/route.zig @@ -11,11 +11,12 @@ const Conn = @import("../http_conn.zig").Conn; const Server = @import("../server.zig").Server; const mistral = @import("mistral.zig"); const mistral_reply = @import("mistral_reply.zig"); +const doctr = @import("doctr.zig"); const liteparse = @import("liteparse.zig"); const run = @import("run.zig"); /// The client contracts POST /ocr answers in. -pub const Dialect = enum { liteparse }; +pub const Dialect = enum { doctr, liteparse }; /// A chosen dialect, with the multipart parts when choosing it parsed them. pub const Selected = struct { dialect: Dialect, parts: ?[]const multipart.Part = null }; @@ -49,6 +50,7 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator, route: []const u8) void { /// Runs the chosen dialect, which gates the request and answers in its own error shape. fn dialect(srv: *Server, conn: *Conn, a: Allocator, s: Selected, body: []const u8, gone: openai.Gone) void { switch (s.dialect) { + .doctr => doctr.post(srv, conn, a, s.parts, body, gone), .liteparse => liteparse.post(srv, conn, a, s.parts, conn.header("Content-Type"), body, gone), } } @@ -61,33 +63,43 @@ pub fn select(a: Allocator, raw_path: []const u8, content_type: ?[]const u8, bod error.Repeated => return refuse(400, "the format query parameter is repeated; send it once"), }; if (format) |f| { - const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be liteparse"); + const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be doctr or liteparse"); return .{ .ok = .{ .dialect = d } }; } const ct = std.mem.trim(u8, content_type orelse "", " \t"); - if (ct.len == 0) return refuse(415, "the request has no Content-Type; send multipart/form-data (LiteParse)"); + if (ct.len == 0) return refuse(415, "the request has no Content-Type; send multipart/form-data (docTR, LiteParse)"); const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t"); if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) - return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send multipart/form-data (LiteParse)", .{media})); + return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send multipart/form-data (docTR, LiteParse)", .{media})); const bound = multipart.boundary(ct) orelse return refuse(400, "multipart/form-data needs a boundary parameter"); const parts = multipart.parse(a, body, bound) catch |e| switch (e) { error.OutOfMemory => return error.OutOfMemory, error.Malformed => return refuse(400, "the multipart body is malformed"), }; - if (hasFiles(parts)) return refuse(400, files_parts); + if (mixed(parts)) return refuse(400, mixed_parts); + var files: usize = 0; var file: usize = 0; - for (parts) |p| file += @intFromBool(std.mem.eql(u8, p.name, "file")); + for (parts) |p| { + files += @intFromBool(std.mem.eql(u8, p.name, "files")); + file += @intFromBool(std.mem.eql(u8, p.name, "file")); + } + if (files > 0) return .{ .ok = .{ .dialect = .doctr, .parts = parts } }; if (file == 1) return .{ .ok = .{ .dialect = .liteparse, .parts = parts } }; - return refuse(400, "a multipart OCR request needs exactly one file part (LiteParse)"); + return refuse(400, "a multipart OCR request needs one or more files parts (docTR) or exactly one file part (LiteParse)"); } -/// The refusal for ``files`` parts: on /ocr this server reads only LiteParse's one ``file`` part, and drops nothing. -pub const files_parts = "a multipart OCR request has files parts, which this server does not read; LiteParse sends one file part"; +/// The refusal for parts of both dialects: docTR would drop the ``file`` part and LiteParse the ``files`` parts. +pub const mixed_parts = "a multipart OCR request has both files parts (docTR) and a file part (LiteParse); send one kind"; -/// Whether ``parts`` hold a ``files`` part; refused on every path, ``?format=`` included. -pub fn hasFiles(parts: []const multipart.Part) bool { - for (parts) |p| if (std.mem.eql(u8, p.name, "files")) return true; - return false; +/// Whether ``parts`` hold both ``files`` and ``file`` parts; refused on every path, ``?format=`` included. +pub fn mixed(parts: []const multipart.Part) bool { + var files = false; + var file = false; + for (parts) |p| { + files = files or std.mem.eql(u8, p.name, "files"); + file = file or std.mem.eql(u8, p.name, "file"); + } + return files and file; } fn refuse(status: u16, message: []const u8) Selection { diff --git a/zig/src/server/ocr/route_test.zig b/zig/src/server/ocr/route_test.zig index 95a10896b41..bfb1fe493c4 100644 --- a/zig/src/server/ocr/route_test.zig +++ b/zig/src/server/ocr/route_test.zig @@ -23,8 +23,7 @@ test "ocr route: the format query, then the media type, then the part names choo const Case = struct { path: []const u8 = "/ocr", ct: ?[]const u8, body: []const u8 = "", want: ?route.Dialect, status: u16 = 0 }; const cases = [_]Case{ .{ .path = "/ocr?format=liteparse", .ct = "application/json", .want = .liteparse }, - .{ .path = "/ocr?x=1&format=liteparse", .ct = null, .want = .liteparse }, - .{ .path = "/ocr?format=doctr", .ct = form, .want = null, .status = 400 }, + .{ .path = "/ocr?x=1&format=doctr", .ct = null, .want = .doctr }, .{ .path = "/ocr?format=tesseract", .ct = "application/json", .want = null, .status = 400 }, .{ .path = "/ocr?format=%zz", .ct = "application/json", .want = null, .status = 400 }, .{ .path = "/ocr?format=liteparse&format=liteparse", .ct = form, .want = null, .status = 400 }, @@ -32,7 +31,7 @@ test "ocr route: the format query, then the media type, then the part names choo .{ .ct = null, .body = " {\"file\": \"x\"}", .want = null, .status = 415 }, .{ .ct = null, .body = "file=x", .want = null, .status = 415 }, .{ .ct = "text/plain", .want = null, .status = 415 }, - .{ .ct = form, .body = try parts(a, &.{ "files", "files" }), .want = null, .status = 400 }, + .{ .ct = form, .body = try parts(a, &.{ "files", "files" }), .want = .doctr }, .{ .ct = form, .body = try parts(a, &.{ "file", "files" }), .want = null, .status = 400 }, .{ .ct = form, .body = try parts(a, &.{"file"}), .want = .liteparse }, .{ .ct = form, .body = try parts(a, &.{ "file", "file" }), .want = null, .status = 400 }, @@ -52,7 +51,7 @@ test "ocr route: the format query, then the media type, then the part names choo }; } -test "ocr route: files parts are refused on every path, the format query included" { +test "ocr route: files and file parts together are refused on every path, the format query included" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -61,20 +60,20 @@ test "ocr route: files parts are refused on every path, the format query include .ok => return error.TestUnexpectedResult, .refused => |r| { try t.expectEqual(@as(u16, 400), r.status); - try t.expectEqualStrings(route.files_parts, r.message); + try t.expectEqualStrings(route.mixed_parts, r.message); }, } - // the format query picks LiteParse, which refuses the same body in its own envelope rather than drop the parts + // the format query picks the dialect, which refuses the same body in its own envelope rather than drop parts var h: harness.Harness = .{}; try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); defer h.stop(); - const cases = [_]struct { []const u8, []const u8 }{ .{ "/ocr", "error" }, .{ "/ocr?format=liteparse", "error" } }; + const cases = [_]struct { []const u8, []const u8 }{ .{ "/ocr", "error" }, .{ "/ocr?format=doctr", "detail" }, .{ "/ocr?format=liteparse", "error" } }; for (cases) |c| { var wire: harness.Wire = .{ .a = a }; routes.dispatch(h.srv, try harness.request(a, &wire, c[0], form, both), a); try t.expectEqual(@as(u16, 400), wire.status()); const got = (try wire.parsed()).get(c[1]).?; - try t.expectEqualStrings(route.files_parts, if (got == .string) got.string else got.strField("message").?); + try t.expectEqualStrings(route.mixed_parts, if (got == .string) got.string else got.strField("message").?); } try t.expectEqual(@as(usize, 0), h.next); } @@ -103,7 +102,7 @@ test "ocr route: /ocr answers in the OpenAI shape until a dialect is chosen; bot try t.expectEqualStrings("the format query parameter is repeated; send it once", (try wire.parsed()).get("error").?.strField("message").?); const infer: auth_scope.Scopes = .{ .inference = true }; const read: auth_scope.Scopes = .{ .read = true }; - for ([_][]const u8{ "/ocr", "/ocr/", "/v1/ocr", "/ocr?format=liteparse" }) |p| { + for ([_][]const u8{ "/ocr", "/ocr/", "/v1/ocr", "/ocr?format=doctr" }) |p| { try t.expect(auth_scope.allows(infer, "POST", p)); try t.expect(!auth_scope.allows(read, "POST", p)); } diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig index b881c6576e5..b3fe2bba3f0 100644 --- a/zig/src/server/ocr/run.zig +++ b/zig/src/server/ocr/run.zig @@ -29,8 +29,8 @@ pub const Step = types.Faulted || error{ Cancelled, OutOfMemory }; /// The dialect's per-page encoder, called in page order. pub const PageSink = struct { ctx: *anyopaque, - /// Called once per page while its pixels live; encodes go into ``a``. - page: *const fn (ctx: *anyopaque, a: Allocator, page: *const OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step!void, + /// Called once per page while its pixels live; ``source`` indexes ``run``'s sources; encodes go into ``a``. + page: *const fn (ctx: *anyopaque, a: Allocator, source: u32, page: *const OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step!void, }; /// The gate's refusal for a model without a reader (docs/api.md OCR). @@ -54,8 +54,8 @@ pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void { /// Where a page's encoded image comes from: an image source's bytes, or a measured PDF page rendered just before use. const Origin = union(enum) { image: []const u8, pdf: struct { bytes: []const u8, width: u32, height: u32 } }; -/// One page to read: its index in its source, where its image comes from, its DPI and its pixel count. -const Planned = struct { index: u32, origin: Origin, dpi: u32, pixels: u64 }; +/// One page to read: its source, its index in that source, where its image comes from, its DPI and its pixel count. +const Planned = struct { source: u32, index: u32, origin: Origin, dpi: u32, pixels: u64 }; /// Reads every page of ``sources`` in order into ``sink``; ``a`` is the request arena, ``gone`` says the client left. pub fn run(srv: *Server, a: Allocator, sources: []const Source, sink: PageSink, fault: *Fault, gone: anytype) Step!void { @@ -87,13 +87,14 @@ fn plan(srv: *const Server, a: Allocator, sources: []const Source, fault: *Fault var used: pdf.Budget = .{}; var cx: Cx = .{ .a = a }; var out: std.ArrayList(Planned) = .empty; - for (sources) |s| { + for (sources, 0..) |s, k| { + const source: u32 = @intCast(k); switch (s.kind) { .image => { if (!left.take(1)) return overBudget(a, fault, cap); used.pdf_pages_used += 1; const px = try imagePixels(srv, a, s.bytes, fault); - try out.append(a, .{ .index = 0, .origin = .{ .image = s.bytes }, .dpi = 72, .pixels = px }); + try out.append(a, .{ .source = source, .index = 0, .origin = .{ .image = s.bytes }, .dpi = 72, .pixels = px }); }, .pdf => { if (!srv.config.vision_pdf) return fault.fail(a, .bad_input, "{s}", .{pdf.off_message}); @@ -112,7 +113,7 @@ fn plan(srv: *const Server, a: Allocator, sources: []const Source, fault: *Fault if (!left.take(@intCast(r.pages.len))) return overBudget(a, fault, cap); for (r.pages) |p| { const origin: Origin = .{ .pdf = .{ .bytes = s.bytes, .width = p.width, .height = p.height } }; - try out.append(a, .{ .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height }); + try out.append(a, .{ .source = source, .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height }); } }, } @@ -193,7 +194,7 @@ fn onePage(srv: *Server, a: Allocator, reader: api.ocr.Ocr, id: []const u8, p: P o.* = .{ .content = try a.dupe(u8, b.content), .quad = quad, .kind = b.kind }; } const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks }; - try sink.page(sink.ctx, a, &page, rgb, enc, fault); + try sink.page(sink.ctx, a, p.source, &page, rgb, enc, fault); } const Generated = struct { content: []const u8, frame: api.Size }; diff --git a/zig/src/server/ocr/run_pdf_test.zig b/zig/src/server/ocr/run_pdf_test.zig index d3b212cc902..9af320e3841 100644 --- a/zig/src/server/ocr/run_pdf_test.zig +++ b/zig/src/server/ocr/run_pdf_test.zig @@ -50,7 +50,7 @@ const Order = struct { fn sink(o: *Order) run.PageSink { return .{ .ctx = o, .page = page }; } - fn page(ctx: *anyopaque, a: Allocator, p: *const types.OcrPage, rgb: picture.Rgb, _: *budget.Encodes, _: *types.Fault) run.Step!void { + fn page(ctx: *anyopaque, a: Allocator, _: u32, p: *const types.OcrPage, rgb: picture.Rgb, _: *budget.Encodes, _: *types.Fault) run.Step!void { const o: *Order = @ptrCast(@alignCast(ctx)); const calls: u32 = blk: { // 0 when the count cannot be read, which the test then reports const text = o.dir.readFileAlloc(t.io, "calls", a, .limited(64)) catch break :blk 0; @@ -92,7 +92,7 @@ test "ocr run: PDF pages are measured first, and page k renders only after page defer h.stop(); var order: Order = .{ .dir = tmp.dir }; var fault: types.Fault = undefined; - const doc: types.Source = .{ .bytes = pdf.minimal_two_page_pdf, .kind = .pdf, .sel = .{ .all_within = 16 } }; + const doc: types.Source = .{ .name = "d", .bytes = pdf.minimal_two_page_pdf, .kind = .pdf, .sel = .{ .all_within = 16 } }; run.run(h.srv, a, &.{doc}, order.sink(), &fault, Gone{}) catch |e| { if (e == error.Faulted) std.debug.print("ocr run: {s}\n", .{fault.message}); return e; diff --git a/zig/src/server/ocr/run_test.zig b/zig/src/server/ocr/run_test.zig index 2793ea6c01b..0a8c7ff8d3f 100644 --- a/zig/src/server/ocr/run_test.zig +++ b/zig/src/server/ocr/run_test.zig @@ -46,7 +46,7 @@ const Seen = struct { fn sink(s: *Seen) run.PageSink { return .{ .ctx = s, .page = page }; } - fn page(ctx: *anyopaque, a: Allocator, p: *const types.OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, _: *types.Fault) run.Step!void { + fn page(ctx: *anyopaque, a: Allocator, _: u32, p: *const types.OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, _: *types.Fault) run.Step!void { const s: *Seen = @ptrCast(@alignCast(ctx)); try s.pages.append(a, p.*); try s.sizes.append(a, .{ rgb.width, rgb.height }); @@ -55,7 +55,7 @@ const Seen = struct { }; fn imageSource(a: Allocator, w: u32, h: u32) !types.Source { - return .{ .bytes = try harness.png(a, w, h), .kind = .image, .sel = .{ .all_within = 1 } }; + return .{ .name = "page", .bytes = try harness.png(a, w, h), .kind = .image, .sel = .{ .all_within = 1 } }; } test "ocr run: blocks scale from the frame, quads are validated, and the sink sees the live pixels" { @@ -116,29 +116,25 @@ test "ocr run: the page budget, undecodable bytes and the gate refuse before any try t.expectError(error.Faulted, run.run(h.srv, a, many, seen.sink(), &fault, Gone{})); try t.expectEqual(types.Class.bad_input, fault.class); try t.expect(std.mem.indexOf(u8, fault.message, "TENSORFOLD_MAX_PDF_PAGES") != null); - const junk: types.Source = .{ .bytes = "\x89PNG\r\n\x1a\nnope", .kind = .image, .sel = .{ .all_within = 1 } }; + const junk: types.Source = .{ .name = "x", .bytes = "\x89PNG\r\n\x1a\nnope", .kind = .image, .sel = .{ .all_within = 1 } }; try t.expectError(error.Faulted, run.run(h.srv, a, &.{junk}, seen.sink(), &fault, Gone{})); try t.expectEqual(types.Class.bad_input, fault.class); - const doc: types.Source = .{ .bytes = "%PDF-1.4\n", .kind = .pdf, .sel = .{ .all_within = 16 } }; + const doc: types.Source = .{ .name = "d", .bytes = "%PDF-1.4\n", .kind = .pdf, .sel = .{ .all_within = 16 } }; try t.expectError(error.Faulted, run.run(h.srv, a, &.{doc}, seen.sink(), &fault, Gone{})); try t.expect(std.mem.indexOf(u8, fault.message, "--vision-pdf") != null); try t.expectEqual(@as(usize, 0), h.next); } -/// Reserves five whole-page encodes on the first page of a request, as five full-page pictures would. +/// Reserves five whole-page encodes on the first page, as five full-page pictures would. const Greedy = struct { limit: u64 = 0, - first: bool = true, fn sink(g: *Greedy) run.PageSink { - g.first = true; return .{ .ctx = g, .page = page }; } - fn page(ctx: *anyopaque, _: Allocator, p: *const types.OcrPage, _: picture.Rgb, enc: *budget.Encodes, fault: *types.Fault) run.Step!void { + fn page(ctx: *anyopaque, _: Allocator, source: u32, p: *const types.OcrPage, _: picture.Rgb, enc: *budget.Encodes, fault: *types.Fault) run.Step!void { const g: *Greedy = @ptrCast(@alignCast(ctx)); - if (!g.first) return; - g.first = false; - g.limit = enc.limit_pixels; - for (0..5) |_| try enc.before(fault, p.width, p.height); + if (source == 0) g.limit = enc.limit_pixels; + if (source == 0) for (0..5) |_| try enc.before(fault, p.width, p.height); } }; @@ -200,7 +196,7 @@ test "ocr run: an image whose first header and its pixels disagree is refused be for (orders) |o| { var seen: Seen = .{}; var fault: types.Fault = undefined; - const src: types.Source = .{ .bytes = try twoHeaders(a, o[0], o[1]), .kind = .image, .sel = .{ .all_within = 1 } }; + const src: types.Source = .{ .name = "p", .bytes = try twoHeaders(a, o[0], o[1]), .kind = .image, .sel = .{ .all_within = 1 } }; try t.expectError(error.Faulted, run.run(h.srv, a, &.{src}, seen.sink(), &fault, Gone{})); try t.expectEqual(types.Class.bad_input, fault.class); try t.expectEqualStrings("page 0: the image's header and its pixels disagree", fault.message); @@ -229,7 +225,7 @@ test "ocr run: a client that left renders no PDF and generates no page" { var seen: Seen = .{}; var fault: types.Fault = undefined; // not a renderable document: a render would refuse it, so Cancelled shows no render was tried - const doc: types.Source = .{ .bytes = "%PDF-1.4\nnot a document", .kind = .pdf, .sel = .{ .all_within = 16 } }; + const doc: types.Source = .{ .name = "d", .bytes = "%PDF-1.4\nnot a document", .kind = .pdf, .sel = .{ .all_within = 16 } }; for ([_]u32{ 0, 1 }) |after| { var checks: u32 = 0; try t.expectError(error.Cancelled, run.run(h.srv, a, &.{ try imageSource(a, 8, 8), doc }, seen.sink(), &fault, LeavesAfter{ .checks = &checks, .after = after })); diff --git a/zig/src/server/ocr/types.zig b/zig/src/server/ocr/types.zig index bb9ac9f515e..6d3fd5dae4e 100644 --- a/zig/src/server/ocr/types.zig +++ b/zig/src/server/ocr/types.zig @@ -55,6 +55,7 @@ pub const Fault = struct { /// One document of a request: an image or a PDF and the pages chosen from it. pub const Source = struct { + name: []const u8, bytes: []const u8, kind: enum { image, pdf }, sel: pdf.Selection, diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index c6f5add9375..7e403bb6fc7 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -391,6 +391,7 @@ test { _ = @import("ocr/run_pdf_test.zig"); _ = @import("ocr/route_test.zig"); _ = @import("ocr/size_test.zig"); + _ = @import("ocr/doctr_test.zig"); _ = @import("ocr/liteparse_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); From ab223fc73fdde08a8b72d2e198f94b3278de25e9 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:51:53 +0000 Subject: [PATCH 187/361] docs(ocr): document POST /ocr in docTR's contract The API guide adds docTR to the /ocr contract choice, with the refusal of a body holding both files and file parts, its failure column, word estimates and scores, whole-page boxes for a reader without boxes, and the docTR section with its part types and query options, a repeated option refused; the changelog stays with the maintainer. --- docs/api.md | 64 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/docs/api.md b/docs/api.md index fda7c9f6c34..dc4b4c4f2e8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -275,12 +275,13 @@ context-window check still applies. Cohere-style requests retain the reranker's ## OCR -The native HIP engine reads pages through two OCR contracts when it serves a model with an OCR reader and -`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers LiteParse's. +The native HIP engine reads pages through three OCR contracts when it serves a model with an OCR reader and +`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers two more, chosen from the request. | Route | Contract | Request | Reply | Written for | | --- | --- | --- | --- | --- | | `POST /v1/ocr` | Mistral OCR | JSON `{"model", "document", ...}` | `{"pages", "model", "document_annotation", "usage_info"}` | the `mistralai` Python and `@mistralai/mistralai` TypeScript SDKs, with `server_url` set to the server root | +| `POST /ocr` | docTR API | multipart, one or more `files` parts, options in the query | one `OCROut` a page | the docTR API template's client | | `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` | Two families have a reader. A reader gives Markdown blocks in pixels of the page the client sent (after EXIF @@ -298,11 +299,11 @@ Embedding, reranker and readout engines refuse the OCR routes as they refuse cha `POST /ocr` picks its contract in this order: -1. `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is repeated; send - it once"), because servers differ on which copy wins. -2. `multipart/form-data`: exactly one part named `file` is LiteParse; any other set of parts is HTTP 400, and so - is a body with any `files` part ("a multipart OCR request has files parts, which this server does not read; - LiteParse sends one file part"), even when `?format=` names the contract. +1. `?format=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is + repeated; send it once", and the same for docTR's parameters), because servers differ on which copy wins. +2. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse; + any other set of parts is HTTP 400, and so is a body with both `files` and `file` parts, even when `?format=` + names the contract. 3. Any other content type, or none, is HTTP 415. Refusals made before the contract is known (415, those 400s, a drain's 503 and an admission 429 with @@ -349,13 +350,13 @@ stops on its end token and the reader can parse it. ### Failures -| Failure | Mistral | LiteParse | -| --- | --- | --- | -| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 400 | -| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | 422 | -| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | -| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | -| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"error": "..."}` | +| Failure | Mistral | docTR | LiteParse | +| --- | --- | --- | --- | +| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 400 | 400 | +| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | 422 | 422 | +| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | +| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 | +| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"detail": "..."}` | `{"error": "..."}` | A failed page fails the whole request: no reply returns some pages and drops others. An unreadable page's message names its index, and the model's raw text goes to the server log, never to the client. 422 means the @@ -364,13 +365,17 @@ stops the request before its next page or PDF render. ### Estimates -dots.mocr gives one box a block and GLM-OCR none, so LiteParse's lines estimate what the models do not give: +dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate what the models do not give: - **Lines.** A block's plain-text lines (Markdown markup removed, a table one line a row with tab-separated cells, math without its `$`) divide the block's box into equal bands along its left and right edges, first line at the top. A paragraph written without line breaks stays one line covering the block. -- **Scores.** Every score is `1.0`: LiteParse `confidence`. Mistral replies leave `confidence_scores` out. -- **No geometry.** With GLM-OCR, Mistral returns `blocks: []` and LiteParse is refused. +- **Words.** docTR's words divide a line's box along its reading direction in proportion to each word's character + count. +- **Scores.** Every score is `1.0`: docTR `confidence` and `objectness_score`, LiteParse `confidence`. Mistral + replies leave `confidence_scores` out. +- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, docTR gives each line the whole page as its box, and + LiteParse is refused. ### Mistral: `POST /v1/ocr` @@ -394,12 +399,33 @@ dots.mocr gives one box a block and GLM-OCR none, so LiteParse's lines estimate `content`, its own Markdown with its tables in the `table_format` form; image blocks add `image_id` and table blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size. +### docTR: `POST /ocr` + +Each `files` part's type must be exactly `image/jpeg`, `image/png` or `application/pdf` (the types docTR's API README names), +else HTTP 400 naming the part and its type. Files answer in part order, each PDF page with its file's name. Each page's +`OCROut` follows the reply in docTR's API README: `name`, `orientation` (`{"value": 0, "confidence": null}`: the page as +sent), `language` (`{"value": null, "confidence": null}`), `dimensions` `[height, width]`, `items` with one page of +blocks, lines and words; plus `layout` and `tables`, always `[]` (docTR's docs list both in a page's export). + +| Query option | Meaning | +| --- | --- | +| `assume_straight_pages` | Default `true`: boxes `[xmin, ymin, xmax, ymax]`; `false`: 4 points TL, TR, BR, BL. Coordinates are relative to the page and not rounded | +| `resolve_blocks` | Default `false`: one block a page; `true`: one block for each reader block | +| `resolve_lines` | Default `true`: one line for each text line; `false`: one line of all the page's words | +| `detect_orientation`, `detect_language` | Accepted; neither is estimated: `orientation` stays 0 and `language` null | +| `detect_tables`, `detect_layout`, `straighten_pages` | Accepted only when false; `layout` and `tables` are always `[]` | +| `paragraph_break` | Accepted only at its documented default, 0.035 | +| `bin_thresh`, `box_thresh` | Refused: TensorFold has no text detector to apply them to | +| `det_arch`, `reco_arch` and the batch options | Ignored: the served model reads every page | + +A boolean option takes `true`, `t`, `yes`, `y`, `on` or `1`, or `false`, `f`, `no`, `n`, `off` or `0`, in any case; another +value is HTTP 400. + ### LiteParse: `POST /ocr` The contract is LiteParse's published [OCR API specification](https://github.com/run-llama/liteparse/blob/main/OCR_API_SPEC.md). One `file` part holds a PNG, -JPEG or WebP page image; `language` and other parts are ignored, but a `files` part is HTTP 400 (above). A PDF is -HTTP 400: the specification sends an image. +JPEG or WebP page image; `language` and other parts are ignored. A PDF is HTTP 400: the specification sends an image. Each line is one result `{"text", "bbox", "confidence"}`: `bbox` is the line's axis-aligned `[x1, y1, x2, y2]` in pixels of the image received, and `confidence` is `1.0`, the value the specification asks for when the engine gives none. The specification's optional `polygon` is not sent: it gives the point order, but not how LiteParse turns a From 217055d11cebacd8e69645c46dbac5e03742b2ac Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:56:11 +0000 Subject: [PATCH 188/361] changelog: #2574 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 575ee33d093..69bb0f77698 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 +- OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. + - Inkling 2 Mini on CUDA: expert weights are staged a warp at a time in 128-byte rows with each expert's NVFP4 factor read once, so one-stream decode is about 70% faster on GB10, four streams about 60% faster and long prompts reach the first token about 25% sooner, with identical tokens (#4728). Thanks @jschmied. - MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. From 8402286dcb587b1602e23caac0bee341eb46308e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:56:11 +0000 Subject: [PATCH 189/361] changelog: #2574 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69bb0f77698..9c1ed01eae6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. + + - Inkling 2 Mini on CUDA: expert weights are staged a warp at a time in 128-byte rows with each expert's NVFP4 factor read once, so one-stream decode is about 70% faster on GB10, four streams about 60% faster and long prompts reach the first token about 25% sooner, with identical tokens (#4728). Thanks @jschmied. - MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. From 3e246951be90379898f6f7035b100f118c6635c8 Mon Sep 17 00:00:00 2001 From: atakann <17346304+atakann@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:29:33 +0300 Subject: [PATCH 190/361] hy4_flash: the NVFP4 build's quantization block and weight map, with its recipe and quality receipts (slice 1 of #3801) nvfp4_weights.zig reads hf_quant_config.json (ModelOpt NVFP4, groups of 16, no KV cache quantization; anything else is UnsupportedHy4Quant) and names every text and drafter tensor of the build with its stored type and shape: NVFP4 routed experts, shared experts and dense MLP, e4m3 Engram rows with a BF16 scale a row, the rest as Tencent released it. The host test checks the map against 344 entries of atakans/Hy4-flash-NVFP4's own safetensors headers and the full count of 253,728 tensors outside the vision tower's blocks. tools/hy4_flash/nvfp4.py and engram_fp8.py rebuild the checkpoint; docs/receipts/hy4-flash-nvfp4/ holds the build steps and GPQA Diamond and IFEval on two GB10s. --- LICENSES/Tencent-Hy-1.0.txt | 245 +++++++++++++ THIRD_PARTY_NOTICES.md | 9 + docs/receipts/hy4-flash-nvfp4/README.md | 50 +++ .../tensorfold-gpqa-ifeval.json | 1 + .../hy4-flash-nvfp4/vllm-gpqa-ifeval.json | 1 + tools/hy4_flash/engram_fp8.py | 66 ++++ tools/hy4_flash/nvfp4.py | 68 ++++ zig/src/families/hy4_flash/host_tests.zig | 1 + zig/src/families/hy4_flash/nvfp4_header.txt | 344 ++++++++++++++++++ zig/src/families/hy4_flash/nvfp4_weights.zig | 208 +++++++++++ .../families/hy4_flash/nvfp4_weights_test.zig | 97 +++++ 11 files changed, 1090 insertions(+) create mode 100644 LICENSES/Tencent-Hy-1.0.txt create mode 100644 docs/receipts/hy4-flash-nvfp4/README.md create mode 100644 docs/receipts/hy4-flash-nvfp4/tensorfold-gpqa-ifeval.json create mode 100644 docs/receipts/hy4-flash-nvfp4/vllm-gpqa-ifeval.json create mode 100644 tools/hy4_flash/engram_fp8.py create mode 100644 tools/hy4_flash/nvfp4.py create mode 100644 zig/src/families/hy4_flash/nvfp4_header.txt create mode 100644 zig/src/families/hy4_flash/nvfp4_weights.zig create mode 100644 zig/src/families/hy4_flash/nvfp4_weights_test.zig diff --git a/LICENSES/Tencent-Hy-1.0.txt b/LICENSES/Tencent-Hy-1.0.txt new file mode 100644 index 00000000000..2be6f885970 --- /dev/null +++ b/LICENSES/Tencent-Hy-1.0.txt @@ -0,0 +1,245 @@ + Tencent Hy License, Version 1.0 + + This License is derived from the Apache License, Version 2.0 + (http://www.apache.org/licenses/LICENSE-2.0), with modifications, mainly + the additional commercial terms for large Model-as-a-Service ("MaaS") + businesses in Section 10. This License is not the Apache License, + Version 2.0, and is not endorsed by or affiliated with the Apache + Software Foundation. + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 10 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). For the avoidance + of doubt, the Work includes the model weights, parameters, + configuration files, inference and training code, and documentation + made available by Licensor under this License. + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. For the avoidance of doubt, + Derivative Works include any fine-tuned, quantized, distilled, merged, + pruned, or otherwise modified versions of the model weights. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. Notwithstanding the + foregoing, any license terms You provide for the Work or any + Derivative Works must not remove, limit, or conflict with Section 10, + and Section 10 shall continue to apply to every recipient of the + Work or any Derivative Works. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + 10. Additional Commercial Terms. + + 10.1 MaaS. "MaaS" means giving third parties remote access to model + inference or fine-tuning (e.g., via API), allowing them to + submit inputs or specify parameters or training data. This + excludes (i) end-user products with model capabilities confined + to specific features or workflows, without general-purpose + model access, or (ii) merely relaying requests to an + independently operated third-party model service. + + 10.2 Separate License Required. Notwithstanding Sections 2 and 3, + and except as provided in Section 10.3, if You operate a MaaS + business, You must obtain a separate written license to use the + Work or any Derivative Works from Licensor (including by email), + in either of the following cases: + + (a) if Your aggregate worldwide gross revenue exceeds + US$50 million (or the equivalent in other currencies) in + any consecutive 12-month period, whether or not such + revenue is derived from the Work or any Derivative Works, + before using (or continuing to use) the Work or any + Derivative Works; or + + (b) before using the Work or any Derivative Works in or for any + product or service provided by You that has more than + 100 million monthly active users in any calendar month. + + 10.3 Internal Use. Section 10.2 does not apply to Your use of the + Work or any Derivative Works solely for internal purposes, + provided that neither the Work, any Derivative Works, nor their + outputs are made available to third parties. + + 10.4 Contact. For licensing requests or questions, please contact + hy_partners@tencent.com. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Tencent Hy License to your work. + + To apply this License to a Derivative Work, attach the following + notice, with the fields enclosed by brackets "[]" replaced with your + own identifying information. (Don't include the brackets!) + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Tencent Hy License, Version 1.0 (the "License"), + which is based on the Apache License, Version 2.0, with additional + commercial terms. You may not use this file except in compliance + with the License. You may obtain a copy of the License in the + LICENSE file distributed with this work. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied. See the License for the specific language governing + permissions and limitations under the License. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index bb3efe49a8f..33313e47b9b 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -608,3 +608,12 @@ arithmetic. `zig/kernels/cuda/inkling2/vision.cu` and `zig/src/families/inkling2 vision tower: `Inkling2VisionEmbeddings`, `Inkling2VisionRotaryEmbedding`, `Inkling2VisionAttention`, `Inkling2VisionMLP` and `Inkling2VisionMerger`. `zig/src/families/inkling2/image.zig` follows `Inkling2ImageProcessor` in `image_processing_inkling2.py` at the same commit for its 40-pixel patches and the tower's input tables. + +## Hy4-flash NVFP4 tensor table and build scripts + +`zig/src/families/hy4_flash/nvfp4_header.txt` lists names, types and shapes from the safetensors headers of the NVFP4 +build [atakans/Hy4-flash-NVFP4](https://huggingface.co/atakans/Hy4-flash-NVFP4) at revision +`30f201acf0b4f9ba178817bcbc04ccfa3ec473f9`, made from Tencent's Hy4-flash release +([tencent/Hy4-flash](https://huggingface.co/tencent/Hy4-flash) at revision `d88c9dfd96ba4f2e6b92adba0b8e8f1c8696f959`) +under the Tencent Hy License 1.0 (see [the license text](LICENSES/Tencent-Hy-1.0.txt)); no weights are included. +`tools/hy4_flash/nvfp4.py` and `tools/hy4_flash/engram_fp8.py` rebuild that checkpoint (`docs/receipts/hy4-flash-nvfp4/`). diff --git a/docs/receipts/hy4-flash-nvfp4/README.md b/docs/receipts/hy4-flash-nvfp4/README.md new file mode 100644 index 00000000000..e1449f9d82f --- /dev/null +++ b/docs/receipts/hy4-flash-nvfp4/README.md @@ -0,0 +1,50 @@ +# Hy4-flash NVFP4: the build and its quality + +The first Hy4-flash checkpoint of the family (#3801, answer 2) is +[atakans/Hy4-flash-NVFP4](https://huggingface.co/atakans/Hy4-flash-NVFP4) at revision +`30f201acf0b4f9ba178817bcbc04ccfa3ec473f9`: 164.7 GB, against 440 GB for Tencent's BF16 release and 287 GB for its FP8 +release. This page says how to build it again and what it scores. + +## What the build holds + +- NVFP4 (ModelOpt's default: E2M1 weights and activations, one FP8 E4M3 scale per 16 elements, one FP32 scale per tensor, + static input scales) on every MLP: the 512 routed experts of each MoE layer, the shared experts and the dense MLP. The + routed experts are stored one tensor per expert (`experts.N.gate_proj`, `up_proj`, `down_proj`). +- FP8 E4M3 rows with one BF16 scale a row on the four Engram tables (`multi_head_embedding.embedding.weight` and + `weight_scale_inv`; value = row x scale, scale = row maximum / 448), and `engram_fp8_embedding: true` in `config.json`. +- BF16 on everything else: attention, the compressed indexer, the router, the latent down and up projections, the + embeddings, the DFly layers and the vision tower. The head is stored F32. +- `config.json`, the tokenizer and the chat template are Tencent's own files; `hf_quant_config.json` is ModelOpt's. + +## Build it again + +Source: [tencent/Hy4-flash](https://huggingface.co/tencent/Hy4-flash) at revision +`d88c9dfd96ba4f2e6b92adba0b8e8f1c8696f959` (BF16). The run used NVIDIA ModelOpt 0.48.0, transformers 5.24.0.dev0 (a +source build with Hy4-flash) and 8 x RTX PRO 6000 Blackwell Max-Q; the model is spread over the 8 cards. + +```sh +python tools/hy4_flash/nvfp4.py tencent-Hy4-flash/ Hy4-flash-NVFP4/ --samples 128 +python tools/hy4_flash/engram_fp8.py Hy4-flash-NVFP4/ +``` + +- `nvfp4.py` quantizes with `NVFP4_DEFAULT_CFG` plus rules that keep the BF16 parts above, calibrates on ModelOpt's + `nemotron-post-training-v3` mix (128 samples of up to 2,048 tokens; the weight scales come from the weights alone) and + exports the checkpoint. Calibration took 42 minutes and the export 5 minutes. +- `engram_fp8.py` converts the four Engram tables in place and writes their error to `engram-fp8.json`. + +Weight-level checks of the result: the experts dequantized against BF16 (gate, up and down of three experts in layers 5, +20 and 40) have 9.5 % relative error each, the usual level for NVFP4; each Engram table has 2.6 % relative RMS error +against BF16. + +## Quality + +GPQA Diamond (198 questions) and IFEval (541 prompts) through the OpenAI chat API on two DGX Sparks (GB10) at tensor +parallel 2, thinking off (`reasoning_effort: "no_think"`), temperature 0, 16,384 tokens a reply at most. + +| Engine | GPQA Diamond | IFEval | Replies cut at the limit | +|---|---|---|---| +| TensorFold, the prototype on atakann/TensorFold `hy4-flash` (`72d3869ed`), DFly on | 72.2 % (95 % CI 65.6 to 78.0) | 84.7 % (81.4 to 87.4) | 0 and 1 | +| vLLM, the `hy4-flash` image with vllm-project/vllm#68387 | 72.7 % (66.1 to 78.5) | 83.5 % (80.2 to 86.4) | 1 and 1 | + +`tensorfold-gpqa-ifeval.json` and `vllm-gpqa-ifeval.json` hold each run's settings, its summary and the score of every +item by its id (the replies are left out). The official FP8 release on four GB10s is a later check (#3801, answer 2). diff --git a/docs/receipts/hy4-flash-nvfp4/tensorfold-gpqa-ifeval.json b/docs/receipts/hy4-flash-nvfp4/tensorfold-gpqa-ifeval.json new file mode 100644 index 00000000000..5b184b510d1 --- /dev/null +++ b/docs/receipts/hy4-flash-nvfp4/tensorfold-gpqa-ifeval.json @@ -0,0 +1 @@ +{"checkpoint":"atakans/Hy4-flash-NVFP4@30f201acf0b4f9ba178817bcbc04ccfa3ec473f9","engine":"TensorFold fork atakann/TensorFold@72d3869ed, tensorfold-native serve --tp 2","hardware":"2 x DGX Spark (GB10), RoCE","settings":{"template_kwargs":{"reasoning_effort":"no_think"},"max_tokens":16384,"temperature":0,"concurrency":1,"started":"2026-11-19T15:09:16+00:00"},"suites":{"gpqa":{"summary":{"n":198,"score":0.7222222222222222,"ci95":[0.6560557666182436,0.7799296793948676],"truncated":0,"mean_tokens":331.979797979798,"minutes":29.8},"items":[["rec06pnAkLOr2t2mp",1.0],["rec0Arme2jcXQZnAW",1.0],["rec0wZvZgiz320KRs",1.0],["rec0yTRmO1o1xCA6H",0.0],["rec1zl5LvaatzGhFt",1.0],["rec260hNUCEj109Dj",1.0],["rec2UlKqC6RFHdcro",1.0],["rec2ZTsqazBZ3LTWZ",1.0],["rec2fsnzUuvNtUYK8",1.0],["rec4JrWy7Il8ho5vk",1.0],["rec4L69T0Y1AS4AFS",1.0],["rec4UqStf9WUVif1f",1.0],["rec4r4KWNLrT7g2kR",1.0],["rec527dNeEtWJrYNl",0.0],["rec5eA17Qr1ucNLUf",1.0],["rec5rjeLsEq5Fg7Oj",1.0],["rec7C06XOB2h298ue",1.0],["rec7qmSnbud4FHSqL",0.0],["rec8nshandHARTkrg",1.0],["rec8y3ZrBOcLgNEkE",1.0],["rec9GugrngvsQR99A",0.0],["rec9ubQihAh6g9bft",0.0],["recA1i5ZAh0Uzclxp",0.0],["recAAJoHMW45Lv5je",1.0],["recBGxVySx1pkrO1i",1.0],["recBXlqrZUCR897It",0.0],["recBtVK8rBVtIlXDq",1.0],["recCJJOeBGERaHYax",1.0],["recD8oX1KevFbl7bL",1.0],["recDDxpS9s8cwkqfq",1.0],["recDj2Y2BbtV02Wv5",0.0],["recDytVnNYZe2HuUU",1.0],["recEmTBhx2hgw6tPQ",1.0],["recFaL6j8UMhutXrc",0.0],["recG1ljJQcVy6CbSl",1.0],["recGFKDUd8qgz81Zl",1.0],["recGFNRVl1qBZGwyU",0.0],["recHVUd2DkoKfedJZ",1.0],["recI1ls9OXdxatHQn",1.0],["recIDiDKKrN61Auyr",1.0],["recIIUynGGpsGEYuo",1.0],["recIMcQfaQNa6vzsT",1.0],["recINSFEYLCyyd08m",0.0],["recIOlKBsOeEcgkA1",1.0],["recIj8lR4tuDgrHou",1.0],["recIlghoOw5VbY4Zh",0.0],["recJJcOHhFeSaRpl4",1.0],["recJZ3QEfRKjYw9a7",1.0],["recK9F5aqdaybl8bb",0.0],["recKcjTwONILZqHAX",1.0],["recKm6LNWykGapmCr",1.0],["recKv4hFyNpViUXnL",1.0],["recL9MFV5zmdlle5T",1.0],["recLAgwx9vbgB5EHk",0.0],["recLSzwBUS3olCjhl",1.0],["recLrRirj7iXoB0rU",0.0],["recN4DY9Q5V03glmQ",0.0],["recNAiPUKOulQbKVP",1.0],["recNFJjE5PPTqVJGv",1.0],["recNu3MXkvWUzHZr9",1.0],["recNuT2oSnO86bxOx",1.0],["recO3hvCWRGiG0odN",1.0],["recOYsaYs6RmtlTDy",1.0],["recOkA2zsy4GSMD9R",1.0],["recOvqPKUtyy9ISA1",0.0],["recPL4ZPpVYxgMu57",1.0],["recPSTGXK3P39yNYT",1.0],["recPzW1WqRnPs57D6",1.0],["recQ8oxSY2aCwFRS8",1.0],["recQiWOxhkXRz9NVE",1.0],["recRTiyaRymerDJ4y",1.0],["recRgabRzMaEoBRcM",0.0],["recS48OsU6kVadBPW",1.0],["recSBcGLPatKb3Ygu",1.0],["recTs7qzfJs6kfLUK",1.0],["recUBgVlkKzcRPDdK",0.0],["recUOePh79cp4T2Bg",0.0],["recV1nqYQvpII94oC",1.0],["recVEXvhYxAhELVqB",0.0],["recVvpD8miVjmmyfe",0.0],["recWPMm91mGDLXONm",0.0],["recWxGU8Q4YReJ1tb",1.0],["recWzUUYBN0NuXO2k",1.0],["recXsuOHRBLcyenF2",1.0],["recXvQ6gWAmyakrpD",1.0],["recYA3LPsCvF1fTMI",0.0],["recYOzCsevNz61Lyn",1.0],["recYt8xx80OTyDsL0",1.0],["recZ13cwgDQf9jRd9",0.0],["recZSGUkn56v9kEp1",0.0],["recZWeueB7lSPR6wN",1.0],["recZbxrocrxh9YENH",1.0],["recZdZxsN0AxDx0pB",1.0],["recZt4x514UQNnsgy",1.0],["reca44yABeO2fx7UB",1.0],["recaXdGn3FAIkxLGM",1.0],["recafnH3RRnMBXEb1",1.0],["recakFKZioXUuldcd",0.0],["recb2M22zaD3tL6Qc",0.0],["recb4cGsC6BJUCU3V",1.0],["reccOKzFNmyqeJ6ry",1.0],["reccVFW11Elovnf8T",1.0],["recclFbsjbaiVVnnV",0.0],["recdya6FuYraBU5Rh",1.0],["receYQxnUBvxPcvbQ",1.0],["receo3UUzRvWCqyfA",1.0],["recf6ayQmL1SxKbvW",0.0],["recgI6tUQ7RLJRWGx",1.0],["recgM7o1tcc7tP778",1.0],["recgXxEgllSGEpELP",1.0],["rechKl68Uc6H7vU0N",1.0],["rechgQucGlrnt8KRV",1.0],["rechtUKxC6G67H7Pr",1.0],["recihePFulRgNKsIn",0.0],["reciuppdQde4FGX1z",1.0],["recjJ54TXc04enRkZ",1.0],["recjgMJaMxz4ESDF2",1.0],["reck1zKeCssmN82Ga",1.0],["reck4G4xxv3YnpbtQ",0.0],["reckYqR92oJkqJXkE",1.0],["reckl6PkaEMWM50yZ",0.0],["recl1UtgTVKishAq4",1.0],["recmI7EiLv72PxmYK",1.0],["recmkvk6EFAmqyMxR",1.0],["recmwwQJnx7ll7bqL",1.0],["recn3NhOhqAPLda16",1.0],["recnGEpF1srQpaqWq",0.0],["recnTTKdBzfuoZ7w7",1.0],["recnawZPumSCLMVgp",1.0],["recnjViFrqlZNL3fY",0.0],["reco8WSc71p8zAv4q",0.0],["recooG6bivTUJpDBz",0.0],["recoy9ZLBsc7HIRBy",1.0],["recpJmTOXx6T48nDJ",1.0],["recpki12iG9RUGrz9",1.0],["recqFDvYKKRmbnoUb",1.0],["recqGD3fxPCI59vPQ",1.0],["recqLRu4BcJvlSANc",1.0],["recr3VHM4zYf6dMFY",0.0],["recrHBEJJoDTV05JR",0.0],["recrNbtgTNoabJJi6",0.0],["recrs0kUo7Ua1xhKO",1.0],["recs3PLPUEMiqg4P8",0.0],["rect4iLrSfUwkNTno",1.0],["rectXfsCM1dj4Kv2c",0.0],["rectlyG9pCAAuWhoB",1.0],["recuYEkVjdVUwA3c0",1.0],["recuyeuT5rQ6qDt8F",0.0],["recv7GsQg3f0fvB1f",1.0],["recvZlMbpPz0yLDle",1.0],["recvlnu8BuLmXZhSX",1.0],["recw4rROcnHKNZhtK",1.0],["recxTy0x7M6T9ikc0",1.0],["recxsX66ktJ1Lwt4f",1.0],["recyPffUDqC2k7ZZO",1.0],["recyl3usDqb7ruXJx",1.0],["recypVp2NmPlBKVTp",1.0],["reczQ4I0VpENdMtIj",1.0],["reczUoM8JsxU6pYxr",1.0],["reczjcMtrB1YGS2fO",0.0],["reczzzihL7btBH7RO",1.0],["rec0VuKUjt1SZ7NYv",1.0],["rec1oj2DveQWl9Rpw",0.0],["rec32C1ZEapBnCC0E",1.0],["rec47oNPXudlTIk4y",1.0],["rec6sE2CRtD4drtHg",0.0],["rec9W28HgpEUeUN8k",0.0],["recAYkd96NNuNl1Ei",0.0],["recBhnXrUyTJ6WHIR",1.0],["recE2ihVfqEK4R9d0",1.0],["recGee5m84dg5FZkc",1.0],["recINGR1z01Fh1Z3A",1.0],["recJpyGtGIsxulevT",1.0],["recLB0EkQ54bYVhnd",1.0],["recMicVBcqy1xM1jq",0.0],["recPIzpnuYpB4yvmp",1.0],["recRZjaElf8ft7xTq",1.0],["recReg13iV2HwJTaA",1.0],["recRhwQwHijW0gCLo",1.0],["recUc29lMDBEvurYo",1.0],["recVE8cUNHpHZIAvL",1.0],["recWXwn9v4IG9ZrM6",1.0],["recXsYa3i2UhGF5fe",0.0],["recYCMJWH7IpcdqwE",1.0],["recatj4YXzbOaq3Ar",1.0],["recb80OwMgNnceA9t",0.0],["reccVBrYdwsB84fGy",0.0],["recfTlTMjZBuOducT",0.0],["recgC4GJ8wUemlUQD",1.0],["recixxJmdux0d8LZQ",1.0],["reckEnrOPFT9Ru7tW",1.0],["recoiTJPGUmzAkief",1.0],["recwW1A85nfyQpReG",0.0],["recwlwlcPvXVNPmvl",1.0],["recyrk6XBVwugG5u8",0.0],["recywRj5a8EEjj2Ib",1.0],["recz3MfYHPRhsEQkW",1.0],["reczkBiPPNrNN49Hp",1.0]]},"ifeval":{"summary":{"n":541,"score":0.8465804066543438,"ci95":[0.8137763633761538,0.8744970724261049],"truncated":1,"mean_tokens":450.70425138632163,"minutes":170.4},"items":[["1000",1.0],["1001",1.0],["1005",1.0],["1012",1.0],["1019",1.0],["102",1.0],["1021",1.0],["1040",1.0],["1051",1.0],["1069",0.0],["1072",1.0],["1075",0.0],["1082",1.0],["1087",1.0],["1092",1.0],["1094",1.0],["1098",1.0],["1107",1.0],["1108",1.0],["1122",1.0],["1127",0.0],["1128",1.0],["1129",1.0],["1130",0.0],["1131",1.0],["1132",0.0],["1137",1.0],["1139",1.0],["1147",1.0],["1148",1.0],["1153",1.0],["1154",1.0],["1162",1.0],["1174",0.0],["1180",1.0],["1187",1.0],["1203",0.0],["1216",1.0],["1217",1.0],["1219",1.0],["122",1.0],["1220",1.0],["1233",1.0],["1236",1.0],["1237",1.0],["1242",1.0],["1246",1.0],["1248",0.0],["1251",1.0],["1258",1.0],["1259",0.0],["1262",1.0],["1265",1.0],["1268",1.0],["127",0.0],["1281",1.0],["1286",1.0],["1287",1.0],["13",1.0],["1300",0.0],["1305",1.0],["1307",1.0],["1314",1.0],["1322",1.0],["1325",1.0],["1332",1.0],["1342",1.0],["1348",1.0],["136",1.0],["1361",1.0],["1367",1.0],["1372",1.0],["1375",1.0],["1377",1.0],["1379",0.0],["1381",0.0],["1389",1.0],["1392",1.0],["1393",1.0],["1402",1.0],["1418",1.0],["142",1.0],["143",1.0],["1436",1.0],["1446",1.0],["1466",1.0],["1476",1.0],["1477",1.0],["1480",1.0],["1481",0.0],["1498",0.0],["1508",1.0],["1512",1.0],["1516",1.0],["1518",1.0],["152",1.0],["1531",1.0],["1535",0.0],["1537",1.0],["1546",0.0],["1548",1.0],["1551",1.0],["1561",1.0],["1566",0.0],["1571",1.0],["1580",1.0],["1582",1.0],["1591",1.0],["1592",1.0],["1593",1.0],["16",1.0],["1601",0.0],["1609",1.0],["1619",1.0],["1620",1.0],["1627",0.0],["1629",1.0],["163",1.0],["1634",1.0],["164",1.0],["1643",1.0],["1644",1.0],["1645",0.0],["1646",1.0],["1653",1.0],["1656",1.0],["1658",1.0],["1659",1.0],["1667",0.0],["167",1.0],["1670",0.0],["1675",0.0],["168",1.0],["1686",1.0],["1691",1.0],["1705",1.0],["1713",1.0],["1730",1.0],["1733",1.0],["1738",1.0],["1739",1.0],["1746",1.0],["1759",1.0],["1773",1.0],["1776",0.0],["1779",0.0],["1781",0.0],["179",1.0],["1793",1.0],["1800",1.0],["1802",1.0],["181",0.0],["1813",0.0],["1823",0.0],["1825",1.0],["1834",1.0],["1837",1.0],["1843",0.0],["1845",1.0],["1857",1.0],["1858",1.0],["1879",0.0],["1880",0.0],["1883",0.0],["1886",1.0],["1893",1.0],["1897",1.0],["19",0.0],["1902",1.0],["1906",1.0],["1908",1.0],["1922",1.0],["1927",1.0],["1928",1.0],["1934",1.0],["1936",1.0],["1939",1.0],["1943",1.0],["1944",1.0],["1954",0.0],["1964",0.0],["1967",1.0],["1980",1.0],["1996",1.0],["1999",1.0],["201",0.0],["2010",1.0],["2015",1.0],["202",0.0],["2023",1.0],["2028",1.0],["2034",1.0],["2035",1.0],["2041",1.0],["2063",1.0],["2069",1.0],["2070",1.0],["2071",1.0],["2078",1.0],["2084",1.0],["209",1.0],["2097",1.0],["2100",1.0],["2107",1.0],["2118",0.0],["2136",1.0],["2139",1.0],["2142",1.0],["2143",1.0],["2162",1.0],["2164",1.0],["2169",1.0],["218",1.0],["2180",0.0],["219",1.0],["2192",0.0],["2195",1.0],["2207",0.0],["2209",1.0],["2215",1.0],["2216",1.0],["2225",1.0],["2229",1.0],["2230",1.0],["2239",1.0],["2243",1.0],["2245",1.0],["2246",0.0],["2247",0.0],["2250",1.0],["2253",1.0],["2265",1.0],["2266",1.0],["2268",1.0],["227",1.0],["2273",1.0],["2275",1.0],["2284",1.0],["2292",1.0],["2299",1.0],["2303",1.0],["2304",1.0],["2305",1.0],["2309",1.0],["2311",1.0],["2314",1.0],["2323",1.0],["2324",1.0],["2328",1.0],["2337",1.0],["2341",1.0],["2350",0.0],["2355",1.0],["2357",1.0],["2359",1.0],["2362",1.0],["2372",1.0],["2374",1.0],["2380",1.0],["2381",0.0],["2383",1.0],["2386",1.0],["2391",1.0],["2392",1.0],["2395",1.0],["2396",1.0],["2398",1.0],["24",1.0],["240",1.0],["2404",1.0],["2416",1.0],["2417",1.0],["2422",1.0],["2432",1.0],["2436",1.0],["2439",1.0],["2441",1.0],["2447",0.0],["2449",1.0],["2457",1.0],["2464",1.0],["2465",1.0],["2467",1.0],["247",1.0],["2471",1.0],["2475",1.0],["2482",1.0],["2485",1.0],["2497",1.0],["2505",1.0],["251",0.0],["2515",1.0],["2517",1.0],["2531",1.0],["2532",1.0],["2534",1.0],["2549",1.0],["2563",0.0],["2567",1.0],["2571",0.0],["2577",1.0],["2583",1.0],["2585",1.0],["2589",1.0],["2590",1.0],["2591",1.0],["2596",1.0],["260",1.0],["2602",1.0],["2605",1.0],["2616",0.0],["2617",1.0],["2622",1.0],["2628",1.0],["2637",1.0],["2649",1.0],["2653",0.0],["2662",0.0],["2667",1.0],["2674",1.0],["2677",1.0],["2683",1.0],["2685",1.0],["2691",1.0],["2704",1.0],["2713",1.0],["2716",0.0],["2724",1.0],["2728",1.0],["2736",0.0],["2739",1.0],["2749",1.0],["2751",1.0],["2752",1.0],["2759",1.0],["2765",0.0],["2768",1.0],["2779",1.0],["2780",1.0],["2785",1.0],["2787",1.0],["279",0.0],["2790",1.0],["2798",1.0],["2801",1.0],["2807",1.0],["281",1.0],["2811",0.0],["2817",1.0],["2820",1.0],["2825",1.0],["2828",1.0],["2829",1.0],["2832",1.0],["2844",1.0],["2849",1.0],["2853",1.0],["2857",1.0],["2859",1.0],["286",1.0],["2870",1.0],["2871",1.0],["288",1.0],["2880",1.0],["2887",1.0],["2889",1.0],["2904",1.0],["2905",1.0],["2908",1.0],["2909",1.0],["2912",1.0],["2918",1.0],["292",1.0],["2921",1.0],["2925",1.0],["2929",1.0],["2941",1.0],["2943",1.0],["295",1.0],["2957",1.0],["296",1.0],["2969",1.0],["2977",1.0],["2985",1.0],["2997",1.0],["30",1.0],["3001",1.0],["301",1.0],["3025",1.0],["3035",1.0],["3041",1.0],["3048",1.0],["3057",1.0],["3063",1.0],["3069",0.0],["3071",1.0],["3073",1.0],["3079",1.0],["3081",1.0],["3084",1.0],["3089",0.0],["3091",1.0],["3098",1.0],["3109",1.0],["3112",1.0],["3114",1.0],["3126",1.0],["3130",1.0],["3131",1.0],["3150",1.0],["3156",1.0],["3166",1.0],["3186",1.0],["3188",0.0],["3191",1.0],["3195",1.0],["3198",1.0],["32",1.0],["3203",1.0],["3204",0.0],["321",1.0],["322",1.0],["3221",1.0],["3223",1.0],["3224",1.0],["3241",1.0],["3243",1.0],["3245",1.0],["3256",0.0],["3263",1.0],["3272",1.0],["3276",1.0],["3280",1.0],["3281",1.0],["3287",0.0],["3294",1.0],["3305",1.0],["331",1.0],["3311",1.0],["3315",1.0],["332",0.0],["3323",1.0],["3324",1.0],["3326",1.0],["3327",0.0],["3329",1.0],["3335",1.0],["334",1.0],["3345",1.0],["3350",1.0],["3351",0.0],["3362",0.0],["3367",1.0],["3369",0.0],["337",1.0],["3371",0.0],["3376",1.0],["3380",1.0],["3386",1.0],["340",1.0],["3401",1.0],["3407",0.0],["3409",1.0],["3414",0.0],["3415",1.0],["3424",0.0],["3425",1.0],["3428",1.0],["3429",0.0],["343",1.0],["3434",1.0],["3439",1.0],["3442",1.0],["3445",1.0],["3453",1.0],["3455",1.0],["3456",0.0],["3478",0.0],["3479",1.0],["3484",1.0],["349",1.0],["3494",1.0],["3502",1.0],["3505",1.0],["3506",1.0],["3513",1.0],["3518",1.0],["3534",1.0],["3536",1.0],["3538",0.0],["3540",1.0],["3549",1.0],["3557",1.0],["3563",1.0],["3565",1.0],["3567",1.0],["3569",1.0],["357",1.0],["3572",0.0],["3595",1.0],["3606",1.0],["3608",1.0],["3615",1.0],["3617",0.0],["3619",1.0],["3623",1.0],["3624",1.0],["3629",1.0],["3631",1.0],["3633",1.0],["3644",1.0],["3653",1.0],["3669",1.0],["3672",1.0],["3680",1.0],["3682",1.0],["3690",1.0],["3691",1.0],["3697",1.0],["3703",1.0],["3709",1.0],["371",1.0],["3710",1.0],["3718",0.0],["3719",1.0],["3724",1.0],["3732",0.0],["3739",1.0],["374",0.0],["3743",1.0],["3744",1.0],["3748",1.0],["3749",1.0],["3750",1.0],["3751",1.0],["3752",1.0],["3753",1.0],["3754",1.0],["3755",1.0],["3756",1.0],["3757",1.0]]}}} \ No newline at end of file diff --git a/docs/receipts/hy4-flash-nvfp4/vllm-gpqa-ifeval.json b/docs/receipts/hy4-flash-nvfp4/vllm-gpqa-ifeval.json new file mode 100644 index 00000000000..88f786a38e4 --- /dev/null +++ b/docs/receipts/hy4-flash-nvfp4/vllm-gpqa-ifeval.json @@ -0,0 +1 @@ +{"checkpoint":"atakans/Hy4-flash-NVFP4@30f201acf0b4f9ba178817bcbc04ccfa3ec473f9","engine":"vLLM hy4-flash image with the six files of vllm-project/vllm#68387, TP 2 + expert parallel","hardware":"2 x DGX Spark (GB10), RoCE","settings":{"template_kwargs":{"reasoning_effort":"no_think"},"max_tokens":16384,"temperature":0,"concurrency":4,"started":"2026-11-18T12:22:17+00:00"},"suites":{"gpqa":{"summary":{"n":198,"score":0.7272727272727273,"ci95":[0.6613532621999608,0.7845409439498122],"truncated":1,"mean_tokens":432.7070707070707,"minutes":17.3},"items":[["rec06pnAkLOr2t2mp",1.0],["rec0Arme2jcXQZnAW",1.0],["rec0wZvZgiz320KRs",1.0],["rec0yTRmO1o1xCA6H",0.0],["rec1zl5LvaatzGhFt",1.0],["rec260hNUCEj109Dj",1.0],["rec2UlKqC6RFHdcro",1.0],["rec2ZTsqazBZ3LTWZ",1.0],["rec2fsnzUuvNtUYK8",1.0],["rec4JrWy7Il8ho5vk",1.0],["rec4L69T0Y1AS4AFS",1.0],["rec4UqStf9WUVif1f",1.0],["rec4r4KWNLrT7g2kR",1.0],["rec527dNeEtWJrYNl",1.0],["rec5eA17Qr1ucNLUf",1.0],["rec5rjeLsEq5Fg7Oj",1.0],["rec7C06XOB2h298ue",1.0],["rec7qmSnbud4FHSqL",0.0],["rec8nshandHARTkrg",1.0],["rec8y3ZrBOcLgNEkE",1.0],["rec9GugrngvsQR99A",0.0],["rec9ubQihAh6g9bft",0.0],["recA1i5ZAh0Uzclxp",1.0],["recAAJoHMW45Lv5je",1.0],["recBGxVySx1pkrO1i",1.0],["recBXlqrZUCR897It",1.0],["recBtVK8rBVtIlXDq",1.0],["recCJJOeBGERaHYax",0.0],["recD8oX1KevFbl7bL",1.0],["recDDxpS9s8cwkqfq",1.0],["recDj2Y2BbtV02Wv5",0.0],["recDytVnNYZe2HuUU",1.0],["recEmTBhx2hgw6tPQ",0.0],["recFaL6j8UMhutXrc",1.0],["recG1ljJQcVy6CbSl",1.0],["recGFKDUd8qgz81Zl",1.0],["recGFNRVl1qBZGwyU",0.0],["recHVUd2DkoKfedJZ",1.0],["recI1ls9OXdxatHQn",1.0],["recIDiDKKrN61Auyr",1.0],["recIIUynGGpsGEYuo",1.0],["recIMcQfaQNa6vzsT",1.0],["recINSFEYLCyyd08m",0.0],["recIOlKBsOeEcgkA1",1.0],["recIj8lR4tuDgrHou",1.0],["recIlghoOw5VbY4Zh",1.0],["recJJcOHhFeSaRpl4",1.0],["recJZ3QEfRKjYw9a7",1.0],["recK9F5aqdaybl8bb",0.0],["recKcjTwONILZqHAX",0.0],["recKm6LNWykGapmCr",1.0],["recKv4hFyNpViUXnL",1.0],["recL9MFV5zmdlle5T",1.0],["recLAgwx9vbgB5EHk",0.0],["recLSzwBUS3olCjhl",1.0],["recLrRirj7iXoB0rU",1.0],["recN4DY9Q5V03glmQ",0.0],["recNAiPUKOulQbKVP",1.0],["recNFJjE5PPTqVJGv",1.0],["recNu3MXkvWUzHZr9",1.0],["recNuT2oSnO86bxOx",1.0],["recO3hvCWRGiG0odN",0.0],["recOYsaYs6RmtlTDy",1.0],["recOkA2zsy4GSMD9R",1.0],["recOvqPKUtyy9ISA1",1.0],["recPL4ZPpVYxgMu57",1.0],["recPSTGXK3P39yNYT",1.0],["recPzW1WqRnPs57D6",1.0],["recQ8oxSY2aCwFRS8",1.0],["recQiWOxhkXRz9NVE",0.0],["recRTiyaRymerDJ4y",1.0],["recRgabRzMaEoBRcM",1.0],["recS48OsU6kVadBPW",1.0],["recSBcGLPatKb3Ygu",1.0],["recTs7qzfJs6kfLUK",1.0],["recUBgVlkKzcRPDdK",0.0],["recUOePh79cp4T2Bg",0.0],["recV1nqYQvpII94oC",1.0],["recVEXvhYxAhELVqB",1.0],["recVvpD8miVjmmyfe",0.0],["recWPMm91mGDLXONm",0.0],["recWxGU8Q4YReJ1tb",1.0],["recWzUUYBN0NuXO2k",1.0],["recXsuOHRBLcyenF2",1.0],["recXvQ6gWAmyakrpD",1.0],["recYA3LPsCvF1fTMI",0.0],["recYOzCsevNz61Lyn",1.0],["recYt8xx80OTyDsL0",1.0],["recZ13cwgDQf9jRd9",1.0],["recZSGUkn56v9kEp1",0.0],["recZWeueB7lSPR6wN",0.0],["recZbxrocrxh9YENH",0.0],["recZdZxsN0AxDx0pB",1.0],["recZt4x514UQNnsgy",1.0],["reca44yABeO2fx7UB",0.0],["recaXdGn3FAIkxLGM",1.0],["recafnH3RRnMBXEb1",1.0],["recakFKZioXUuldcd",0.0],["recb2M22zaD3tL6Qc",0.0],["recb4cGsC6BJUCU3V",1.0],["reccOKzFNmyqeJ6ry",1.0],["reccVFW11Elovnf8T",0.0],["recclFbsjbaiVVnnV",0.0],["recdya6FuYraBU5Rh",1.0],["receYQxnUBvxPcvbQ",1.0],["receo3UUzRvWCqyfA",1.0],["recf6ayQmL1SxKbvW",0.0],["recgI6tUQ7RLJRWGx",1.0],["recgM7o1tcc7tP778",1.0],["recgXxEgllSGEpELP",1.0],["rechKl68Uc6H7vU0N",1.0],["rechgQucGlrnt8KRV",1.0],["rechtUKxC6G67H7Pr",1.0],["recihePFulRgNKsIn",1.0],["reciuppdQde4FGX1z",1.0],["recjJ54TXc04enRkZ",0.0],["recjgMJaMxz4ESDF2",1.0],["reck1zKeCssmN82Ga",1.0],["reck4G4xxv3YnpbtQ",0.0],["reckYqR92oJkqJXkE",1.0],["reckl6PkaEMWM50yZ",0.0],["recl1UtgTVKishAq4",1.0],["recmI7EiLv72PxmYK",1.0],["recmkvk6EFAmqyMxR",1.0],["recmwwQJnx7ll7bqL",1.0],["recn3NhOhqAPLda16",1.0],["recnGEpF1srQpaqWq",0.0],["recnTTKdBzfuoZ7w7",1.0],["recnawZPumSCLMVgp",1.0],["recnjViFrqlZNL3fY",1.0],["reco8WSc71p8zAv4q",0.0],["recooG6bivTUJpDBz",0.0],["recoy9ZLBsc7HIRBy",1.0],["recpJmTOXx6T48nDJ",1.0],["recpki12iG9RUGrz9",1.0],["recqFDvYKKRmbnoUb",1.0],["recqGD3fxPCI59vPQ",0.0],["recqLRu4BcJvlSANc",1.0],["recr3VHM4zYf6dMFY",0.0],["recrHBEJJoDTV05JR",0.0],["recrNbtgTNoabJJi6",0.0],["recrs0kUo7Ua1xhKO",1.0],["recs3PLPUEMiqg4P8",0.0],["rect4iLrSfUwkNTno",1.0],["rectXfsCM1dj4Kv2c",0.0],["rectlyG9pCAAuWhoB",0.0],["recuYEkVjdVUwA3c0",1.0],["recuyeuT5rQ6qDt8F",0.0],["recv7GsQg3f0fvB1f",1.0],["recvZlMbpPz0yLDle",1.0],["recvlnu8BuLmXZhSX",1.0],["recw4rROcnHKNZhtK",1.0],["recxTy0x7M6T9ikc0",1.0],["recxsX66ktJ1Lwt4f",1.0],["recyPffUDqC2k7ZZO",1.0],["recyl3usDqb7ruXJx",1.0],["recypVp2NmPlBKVTp",1.0],["reczQ4I0VpENdMtIj",0.0],["reczUoM8JsxU6pYxr",1.0],["reczjcMtrB1YGS2fO",1.0],["reczzzihL7btBH7RO",0.0],["rec0VuKUjt1SZ7NYv",1.0],["rec1oj2DveQWl9Rpw",0.0],["rec32C1ZEapBnCC0E",1.0],["rec47oNPXudlTIk4y",1.0],["rec6sE2CRtD4drtHg",1.0],["rec9W28HgpEUeUN8k",0.0],["recAYkd96NNuNl1Ei",0.0],["recBhnXrUyTJ6WHIR",1.0],["recE2ihVfqEK4R9d0",1.0],["recGee5m84dg5FZkc",1.0],["recINGR1z01Fh1Z3A",1.0],["recJpyGtGIsxulevT",1.0],["recLB0EkQ54bYVhnd",1.0],["recMicVBcqy1xM1jq",0.0],["recPIzpnuYpB4yvmp",1.0],["recRZjaElf8ft7xTq",1.0],["recReg13iV2HwJTaA",1.0],["recRhwQwHijW0gCLo",1.0],["recUc29lMDBEvurYo",1.0],["recVE8cUNHpHZIAvL",0.0],["recWXwn9v4IG9ZrM6",1.0],["recXsYa3i2UhGF5fe",0.0],["recYCMJWH7IpcdqwE",1.0],["recatj4YXzbOaq3Ar",1.0],["recb80OwMgNnceA9t",0.0],["reccVBrYdwsB84fGy",0.0],["recfTlTMjZBuOducT",1.0],["recgC4GJ8wUemlUQD",1.0],["recixxJmdux0d8LZQ",1.0],["reckEnrOPFT9Ru7tW",1.0],["recoiTJPGUmzAkief",1.0],["recwW1A85nfyQpReG",0.0],["recwlwlcPvXVNPmvl",1.0],["recyrk6XBVwugG5u8",1.0],["recywRj5a8EEjj2Ib",1.0],["recz3MfYHPRhsEQkW",1.0],["reczkBiPPNrNN49Hp",1.0]]},"ifeval":{"summary":{"n":541,"score":0.8354898336414048,"ci95":[0.8019039711419572,0.8643447147146294],"truncated":1,"mean_tokens":449.2218114602588,"minutes":72.6},"items":[["1000",1.0],["1001",1.0],["1005",1.0],["1012",1.0],["1019",1.0],["102",1.0],["1021",1.0],["1040",1.0],["1051",1.0],["1069",0.0],["1072",1.0],["1075",1.0],["1082",1.0],["1087",1.0],["1092",1.0],["1094",1.0],["1098",1.0],["1107",1.0],["1108",1.0],["1122",1.0],["1127",0.0],["1128",1.0],["1129",1.0],["1130",0.0],["1131",1.0],["1132",0.0],["1137",1.0],["1139",1.0],["1147",1.0],["1148",1.0],["1153",0.0],["1154",1.0],["1162",1.0],["1174",0.0],["1180",1.0],["1187",1.0],["1203",0.0],["1216",1.0],["1217",1.0],["1219",1.0],["122",0.0],["1220",1.0],["1233",1.0],["1236",1.0],["1237",1.0],["1242",1.0],["1246",1.0],["1248",1.0],["1251",1.0],["1258",1.0],["1259",0.0],["1262",1.0],["1265",1.0],["1268",1.0],["127",1.0],["1281",1.0],["1286",1.0],["1287",1.0],["13",1.0],["1300",0.0],["1305",1.0],["1307",1.0],["1314",0.0],["1322",1.0],["1325",1.0],["1332",1.0],["1342",1.0],["1348",1.0],["136",1.0],["1361",1.0],["1367",1.0],["1372",1.0],["1375",1.0],["1377",1.0],["1379",0.0],["1381",0.0],["1389",1.0],["1392",1.0],["1393",1.0],["1402",1.0],["1418",1.0],["142",1.0],["143",1.0],["1436",1.0],["1446",1.0],["1466",1.0],["1476",1.0],["1477",1.0],["1480",1.0],["1481",1.0],["1498",0.0],["1508",1.0],["1512",1.0],["1516",1.0],["1518",1.0],["152",1.0],["1531",1.0],["1535",0.0],["1537",1.0],["1546",1.0],["1548",1.0],["1551",1.0],["1561",1.0],["1566",1.0],["1571",1.0],["1580",1.0],["1582",1.0],["1591",1.0],["1592",1.0],["1593",1.0],["16",1.0],["1601",1.0],["1609",1.0],["1619",1.0],["1620",1.0],["1627",0.0],["1629",1.0],["163",1.0],["1634",1.0],["164",1.0],["1643",1.0],["1644",1.0],["1645",1.0],["1646",1.0],["1653",1.0],["1656",1.0],["1658",1.0],["1659",1.0],["1667",1.0],["167",1.0],["1670",0.0],["1675",0.0],["168",1.0],["1686",1.0],["1691",1.0],["1705",1.0],["1713",1.0],["1730",1.0],["1733",1.0],["1738",1.0],["1739",1.0],["1746",1.0],["1759",1.0],["1773",1.0],["1776",0.0],["1779",1.0],["1781",0.0],["179",0.0],["1793",1.0],["1800",1.0],["1802",1.0],["181",0.0],["1813",1.0],["1823",0.0],["1825",1.0],["1834",0.0],["1837",1.0],["1843",0.0],["1845",1.0],["1857",1.0],["1858",1.0],["1879",0.0],["1880",0.0],["1883",0.0],["1886",1.0],["1893",1.0],["1897",1.0],["19",0.0],["1902",1.0],["1906",1.0],["1908",1.0],["1922",1.0],["1927",1.0],["1928",1.0],["1934",1.0],["1936",1.0],["1939",1.0],["1943",0.0],["1944",1.0],["1954",0.0],["1964",0.0],["1967",1.0],["1980",1.0],["1996",1.0],["1999",1.0],["201",0.0],["2010",1.0],["2015",1.0],["202",0.0],["2023",1.0],["2028",1.0],["2034",1.0],["2035",1.0],["2041",1.0],["2063",1.0],["2069",0.0],["2070",1.0],["2071",1.0],["2078",1.0],["2084",1.0],["209",1.0],["2097",1.0],["2100",1.0],["2107",1.0],["2118",0.0],["2136",1.0],["2139",1.0],["2142",1.0],["2143",0.0],["2162",1.0],["2164",1.0],["2169",1.0],["218",1.0],["2180",0.0],["219",1.0],["2192",1.0],["2195",1.0],["2207",1.0],["2209",1.0],["2215",1.0],["2216",1.0],["2225",1.0],["2229",1.0],["2230",1.0],["2239",1.0],["2243",1.0],["2245",1.0],["2246",1.0],["2247",0.0],["2250",1.0],["2253",1.0],["2265",1.0],["2266",1.0],["2268",1.0],["227",1.0],["2273",1.0],["2275",1.0],["2284",0.0],["2292",0.0],["2299",1.0],["2303",1.0],["2304",0.0],["2305",1.0],["2309",1.0],["2311",1.0],["2314",1.0],["2323",1.0],["2324",1.0],["2328",1.0],["2337",1.0],["2341",1.0],["2350",0.0],["2355",1.0],["2357",1.0],["2359",1.0],["2362",1.0],["2372",1.0],["2374",1.0],["2380",1.0],["2381",1.0],["2383",1.0],["2386",1.0],["2391",1.0],["2392",1.0],["2395",1.0],["2396",1.0],["2398",1.0],["24",1.0],["240",1.0],["2404",1.0],["2416",1.0],["2417",1.0],["2422",0.0],["2432",1.0],["2436",1.0],["2439",1.0],["2441",1.0],["2447",0.0],["2449",0.0],["2457",1.0],["2464",1.0],["2465",1.0],["2467",1.0],["247",1.0],["2471",1.0],["2475",1.0],["2482",1.0],["2485",1.0],["2497",1.0],["2505",1.0],["251",0.0],["2515",1.0],["2517",1.0],["2531",1.0],["2532",1.0],["2534",0.0],["2549",1.0],["2563",0.0],["2567",1.0],["2571",1.0],["2577",1.0],["2583",1.0],["2585",1.0],["2589",1.0],["2590",1.0],["2591",1.0],["2596",1.0],["260",1.0],["2602",1.0],["2605",1.0],["2616",1.0],["2617",1.0],["2622",1.0],["2628",1.0],["2637",1.0],["2649",1.0],["2653",0.0],["2662",0.0],["2667",1.0],["2674",0.0],["2677",0.0],["2683",1.0],["2685",1.0],["2691",1.0],["2704",1.0],["2713",0.0],["2716",0.0],["2724",1.0],["2728",1.0],["2736",0.0],["2739",0.0],["2749",1.0],["2751",1.0],["2752",1.0],["2759",1.0],["2765",1.0],["2768",1.0],["2779",0.0],["2780",1.0],["2785",0.0],["2787",1.0],["279",0.0],["2790",1.0],["2798",1.0],["2801",1.0],["2807",1.0],["281",1.0],["2811",0.0],["2817",0.0],["2820",1.0],["2825",1.0],["2828",1.0],["2829",1.0],["2832",1.0],["2844",1.0],["2849",0.0],["2853",1.0],["2857",1.0],["2859",1.0],["286",1.0],["2870",1.0],["2871",1.0],["288",1.0],["2880",1.0],["2887",1.0],["2889",1.0],["2904",1.0],["2905",1.0],["2908",1.0],["2909",1.0],["2912",1.0],["2918",1.0],["292",1.0],["2921",1.0],["2925",1.0],["2929",1.0],["2941",1.0],["2943",1.0],["295",1.0],["2957",1.0],["296",1.0],["2969",1.0],["2977",1.0],["2985",1.0],["2997",1.0],["30",1.0],["3001",1.0],["301",1.0],["3025",1.0],["3035",1.0],["3041",0.0],["3048",1.0],["3057",1.0],["3063",1.0],["3069",0.0],["3071",1.0],["3073",1.0],["3079",1.0],["3081",0.0],["3084",1.0],["3089",1.0],["3091",1.0],["3098",1.0],["3109",1.0],["3112",1.0],["3114",1.0],["3126",1.0],["3130",1.0],["3131",1.0],["3150",1.0],["3156",1.0],["3166",1.0],["3186",1.0],["3188",0.0],["3191",1.0],["3195",1.0],["3198",1.0],["32",1.0],["3203",1.0],["3204",0.0],["321",1.0],["322",1.0],["3221",1.0],["3223",1.0],["3224",1.0],["3241",1.0],["3243",1.0],["3245",1.0],["3256",0.0],["3263",1.0],["3272",1.0],["3276",1.0],["3280",1.0],["3281",1.0],["3287",0.0],["3294",1.0],["3305",1.0],["331",1.0],["3311",1.0],["3315",0.0],["332",0.0],["3323",1.0],["3324",1.0],["3326",0.0],["3327",1.0],["3329",1.0],["3335",1.0],["334",1.0],["3345",1.0],["3350",1.0],["3351",0.0],["3362",0.0],["3367",1.0],["3369",0.0],["337",1.0],["3371",0.0],["3376",1.0],["3380",1.0],["3386",1.0],["340",1.0],["3401",1.0],["3407",0.0],["3409",1.0],["3414",0.0],["3415",1.0],["3424",1.0],["3425",1.0],["3428",1.0],["3429",0.0],["343",1.0],["3434",1.0],["3439",1.0],["3442",1.0],["3445",1.0],["3453",1.0],["3455",1.0],["3456",1.0],["3478",0.0],["3479",1.0],["3484",0.0],["349",1.0],["3494",1.0],["3502",1.0],["3505",1.0],["3506",1.0],["3513",1.0],["3518",1.0],["3534",0.0],["3536",1.0],["3538",0.0],["3540",1.0],["3549",1.0],["3557",1.0],["3563",1.0],["3565",1.0],["3567",1.0],["3569",1.0],["357",1.0],["3572",0.0],["3595",1.0],["3606",1.0],["3608",0.0],["3615",1.0],["3617",0.0],["3619",1.0],["3623",1.0],["3624",1.0],["3629",1.0],["3631",1.0],["3633",1.0],["3644",1.0],["3653",1.0],["3669",1.0],["3672",1.0],["3680",1.0],["3682",1.0],["3690",1.0],["3691",1.0],["3697",1.0],["3703",1.0],["3709",1.0],["371",1.0],["3710",1.0],["3718",0.0],["3719",1.0],["3724",1.0],["3732",1.0],["3739",1.0],["374",0.0],["3743",1.0],["3744",1.0],["3748",1.0],["3749",1.0],["3750",1.0],["3751",1.0],["3752",1.0],["3753",1.0],["3754",1.0],["3755",1.0],["3756",1.0],["3757",1.0]]}}} \ No newline at end of file diff --git a/tools/hy4_flash/engram_fp8.py b/tools/hy4_flash/engram_fp8.py new file mode 100644 index 00000000000..60f2dfa4122 --- /dev/null +++ b/tools/hy4_flash/engram_fp8.py @@ -0,0 +1,66 @@ +"""engram_fp8.py : Engram tables BF16 to FP8 E4M3 rows with one BF16 scale a row, after nvfp4.py. + +Value = row x scale, scale = row max / 448; config.json gets engram_fp8_embedding: true. The run that made +atakans/Hy4-flash-NVFP4 used this file before its lint changes (context managers, imports one a line). +""" + +import json +import os +import sys + +import torch +from safetensors import safe_open +from safetensors.torch import save_file + + +def read(path): + with open(path) as f: + return json.load(f) + + +def write(value, path): + with open(path, "w") as f: + json.dump(value, f, indent=2) + + +d = sys.argv[1] +idx_path = os.path.join(d, "model.safetensors.index.json") +idx = read(idx_path) +wm = idx["weight_map"] +keys = [k for k in wm if k.endswith("multi_head_embedding.embedding.weight")] +report = {} +for shard in sorted({wm[k] for k in keys}): + path = os.path.join(d, shard) + with safe_open(path, "pt") as f: + meta = f.metadata() + tensors = {k: f.get_tensor(k) for k in f.keys()} # noqa: SIM118 (safe_open has no __iter__) + for k in [k for k in keys if wm[k] == shard]: + w = tensors[k] + q = torch.empty(w.shape, dtype=torch.float8_e4m3fn) + s = torch.empty(w.shape[0], dtype=torch.bfloat16) + err = ref = 0.0 + step = 1 << 22 + for i in range(0, w.shape[0], step): + x = w[i : i + step].cuda().float() + sc = (x.abs().amax(1) / 448).clamp(min=1e-12).to(torch.bfloat16) + y = (x / sc.float()[:, None]).clamp(-448, 448).to(torch.float8_e4m3fn) + err += (y.float() * sc.float()[:, None] - x).pow(2).sum().item() + ref += x.pow(2).sum().item() + q[i : i + len(x)] = y.cpu() + s[i : i + len(x)] = sc.cpu() + sk = k.removesuffix("weight") + "weight_scale_inv" + tensors[k], tensors[sk], wm[sk] = q, s, shard + report[k] = {"rows": w.shape[0], "rel_rms_error": (err / ref) ** 0.5} + print(k, report[k], flush=True) + save_file(tensors, path + ".tmp", metadata=meta) + os.replace(path + ".tmp", path) +idx["metadata"]["total_size"] = sum( + os.path.getsize(os.path.join(d, f)) for f in set(wm.values()) +) +write(idx, idx_path) +cfg_path = os.path.join(d, "config.json") +cfg = read(cfg_path) +(cfg.get("text_config") or cfg)["engram_fp8_embedding"] = True +write(cfg, cfg_path) +write(report, os.path.join(d, "engram-fp8.json")) +print("ENGRAM_DONE", flush=True) diff --git a/tools/hy4_flash/nvfp4.py b/tools/hy4_flash/nvfp4.py new file mode 100644 index 00000000000..13f0a8d01b6 --- /dev/null +++ b/tools/hy4_flash/nvfp4.py @@ -0,0 +1,68 @@ +"""nvfp4.py [--layers N] [--samples 512]: Hy4-flash to NVFP4 with ModelOpt 0.48. + +NVFP4 (W4A4, 16-element blocks, FP8 scales) on every MLP: the 512 routed experts (fused 3-D gate_up_proj / +down_proj, ModelOpt's @use_experts_implementation path), the shared experts and the dense MLPs. BF16 stays +on attention, the compressed indexer, the router, the latent down/up projections, embeddings, lm_head and the +vision tower. Calibration: ModelOpt's own "nemotron-post-training-v3" mix (NVIDIA's chat, science, code, +agentic, math, SWE and multilingual sets). --layers N loads only the first N layers: a smoke test of the +whole path, export included. +""" + +import argparse +import time + +import modelopt.torch.quantization as mtq +import torch +from modelopt.torch.export import export_hf_checkpoint +from modelopt.torch.utils.dataset_utils import get_dataset_dataloader +from transformers import AutoConfig, AutoModelForImageTextToText, AutoTokenizer + +ap = argparse.ArgumentParser() +ap.add_argument("src") +ap.add_argument("out") +ap.add_argument("--layers", type=int, default=0) +ap.add_argument("--samples", type=int, default=512) +ap.add_argument("--seq", type=int, default=2048) +ap.add_argument("--dataset", default="nemotron-post-training-v3") +a = ap.parse_args() + +t0 = time.time() +cfg = AutoConfig.from_pretrained(a.src) +text_cfg = getattr(cfg, "text_config", cfg) +if a.layers: + text_cfg.num_hidden_layers = a.layers +# 80 GiB a card of 95: the model spreads evenly over the 8 cards and each keeps room for calibration activations +mem = {i: "80GiB" for i in range(torch.cuda.device_count())} +model = AutoModelForImageTextToText.from_pretrained( + a.src, config=cfg, dtype=torch.bfloat16, device_map="auto", max_memory=mem +) +model.eval() +tok = AutoTokenizer.from_pretrained(a.src) +print(f"loaded in {time.time() - t0:.0f} s", flush=True) + +# ModelOpt 0.48: quant_cfg is a list of rules, a later rule wins; ours go last +q = {**mtq.NVFP4_DEFAULT_CFG, "quant_cfg": list(mtq.NVFP4_DEFAULT_CFG["quant_cfg"])} +for pat in ("*self_attn*", "*indexer*", "*router*", "*.gate.*", "*routed_expert_down_proj*", + "*routed_expert_up_proj*", "*engram*", "*lm_head*", "*visual*", "*vision*", "*embed*"): # fmt: skip + q["quant_cfg"].append({"quantizer_name": pat, "enable": False}) + +loader = get_dataset_dataloader( + dataset_name=a.dataset, tokenizer=tok, batch_size=1, num_samples=a.samples, + max_sample_length=a.seq, device=model.device, +) # fmt: skip + + +def forward(m): + for i, batch in enumerate(loader): + with torch.no_grad(): + m(input_ids=batch["input_ids"], attention_mask=batch.get("attention_mask")) + if i % 16 == 0: + print(f"calib {i}/{a.samples} at {time.time() - t0:.0f} s", flush=True) + + +model = mtq.quantize(model, q, forward) +mtq.print_quant_summary(model) +print(f"calibrated at {time.time() - t0:.0f} s", flush=True) +export_hf_checkpoint(model, export_dir=a.out) +tok.save_pretrained(a.out) +print(f"exported {a.out} at {time.time() - t0:.0f} s", flush=True) diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig index de2e65af13a..e2b765937f3 100644 --- a/zig/src/families/hy4_flash/host_tests.zig +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -16,6 +16,7 @@ test { _ = @import("forward.zig"); _ = @import("exl3_weights.zig"); _ = @import("fp8_weights_test.zig"); + _ = @import("nvfp4_weights_test.zig"); if (@import("builtin").os.tag == .linux) _ = @import("bf16_rows_test.zig"); } diff --git a/zig/src/families/hy4_flash/nvfp4_header.txt b/zig/src/families/hy4_flash/nvfp4_header.txt new file mode 100644 index 00000000000..cd26f6a966e --- /dev/null +++ b/zig/src/families/hy4_flash/nvfp4_header.txt @@ -0,0 +1,344 @@ +lm_head.weight F32 120832x3072 +model.dfly_layers.0.input_layernorm.weight BF16 3072 +model.dfly_layers.0.mlp.down_proj.weight BF16 3072x9216 +model.dfly_layers.0.mlp.gate_proj.weight BF16 9216x3072 +model.dfly_layers.0.mlp.up_proj.weight BF16 9216x3072 +model.dfly_layers.0.post_attention_layernorm.weight BF16 3072 +model.dfly_layers.0.self_attn.kv_a_layernorm.weight BF16 512 +model.dfly_layers.0.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.dfly_layers.0.self_attn.kv_b_proj.weight BF16 14336x512 +model.dfly_layers.0.self_attn.learnable_sink_param BF16 32 +model.dfly_layers.0.self_attn.linear_gate.weight BF16 8192x3072 +model.dfly_layers.0.self_attn.o_proj.weight BF16 3072x8192 +model.dfly_layers.0.self_attn.post_proj_norm.weight BF16 3072 +model.dfly_layers.0.self_attn.q_a_layernorm.weight BF16 1024 +model.dfly_layers.0.self_attn.q_a_proj.weight BF16 1024x3072 +model.dfly_layers.0.self_attn.q_b_proj.weight BF16 8192x1024 +model.dfly_layers.1.input_layernorm.weight BF16 3072 +model.dfly_layers.1.mlp.down_proj.weight BF16 3072x9216 +model.dfly_layers.1.mlp.gate_proj.weight BF16 9216x3072 +model.dfly_layers.1.mlp.up_proj.weight BF16 9216x3072 +model.dfly_layers.1.post_attention_layernorm.weight BF16 3072 +model.dfly_layers.1.self_attn.kv_a_layernorm.weight BF16 512 +model.dfly_layers.1.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.dfly_layers.1.self_attn.kv_b_proj.weight BF16 14336x512 +model.dfly_layers.1.self_attn.learnable_sink_param BF16 32 +model.dfly_layers.1.self_attn.linear_gate.weight BF16 8192x3072 +model.dfly_layers.1.self_attn.o_proj.weight BF16 3072x8192 +model.dfly_layers.1.self_attn.post_proj_norm.weight BF16 3072 +model.dfly_layers.1.self_attn.q_a_layernorm.weight BF16 1024 +model.dfly_layers.1.self_attn.q_a_proj.weight BF16 1024x3072 +model.dfly_layers.1.self_attn.q_b_proj.weight BF16 8192x1024 +model.dfly_layers.2.input_layernorm.weight BF16 3072 +model.dfly_layers.2.mlp.down_proj.weight BF16 3072x9216 +model.dfly_layers.2.mlp.gate_proj.weight BF16 9216x3072 +model.dfly_layers.2.mlp.up_proj.weight BF16 9216x3072 +model.dfly_layers.2.post_attention_layernorm.weight BF16 3072 +model.dfly_layers.2.self_attn.kv_a_layernorm.weight BF16 512 +model.dfly_layers.2.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.dfly_layers.2.self_attn.kv_b_proj.weight BF16 14336x512 +model.dfly_layers.2.self_attn.learnable_sink_param BF16 32 +model.dfly_layers.2.self_attn.linear_gate.weight BF16 8192x3072 +model.dfly_layers.2.self_attn.o_proj.weight BF16 3072x8192 +model.dfly_layers.2.self_attn.post_proj_norm.weight BF16 3072 +model.dfly_layers.2.self_attn.q_a_layernorm.weight BF16 1024 +model.dfly_layers.2.self_attn.q_a_proj.weight BF16 1024x3072 +model.dfly_layers.2.self_attn.q_b_proj.weight BF16 8192x1024 +model.dfly_layers.3.input_layernorm.weight BF16 3072 +model.dfly_layers.3.mlp.down_proj.weight BF16 3072x9216 +model.dfly_layers.3.mlp.gate_proj.weight BF16 9216x3072 +model.dfly_layers.3.mlp.up_proj.weight BF16 9216x3072 +model.dfly_layers.3.post_attention_layernorm.weight BF16 3072 +model.dfly_layers.3.self_attn.kv_a_layernorm.weight BF16 512 +model.dfly_layers.3.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.dfly_layers.3.self_attn.kv_b_proj.weight BF16 14336x512 +model.dfly_layers.3.self_attn.learnable_sink_param BF16 32 +model.dfly_layers.3.self_attn.linear_gate.weight BF16 8192x3072 +model.dfly_layers.3.self_attn.o_proj.weight BF16 3072x8192 +model.dfly_layers.3.self_attn.post_proj_norm.weight BF16 3072 +model.dfly_layers.3.self_attn.q_a_layernorm.weight BF16 1024 +model.dfly_layers.3.self_attn.q_a_proj.weight BF16 1024x3072 +model.dfly_layers.3.self_attn.q_b_proj.weight BF16 8192x1024 +model.dfly_layers.4.input_layernorm.weight BF16 3072 +model.dfly_layers.4.mlp.down_proj.weight BF16 3072x9216 +model.dfly_layers.4.mlp.gate_proj.weight BF16 9216x3072 +model.dfly_layers.4.mlp.up_proj.weight BF16 9216x3072 +model.dfly_layers.4.post_attention_layernorm.weight BF16 3072 +model.dfly_layers.4.self_attn.kv_a_layernorm.weight BF16 512 +model.dfly_layers.4.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.dfly_layers.4.self_attn.kv_b_proj.weight BF16 14336x512 +model.dfly_layers.4.self_attn.learnable_sink_param BF16 32 +model.dfly_layers.4.self_attn.linear_gate.weight BF16 8192x3072 +model.dfly_layers.4.self_attn.o_proj.weight BF16 3072x8192 +model.dfly_layers.4.self_attn.post_proj_norm.weight BF16 3072 +model.dfly_layers.4.self_attn.q_a_layernorm.weight BF16 1024 +model.dfly_layers.4.self_attn.q_a_proj.weight BF16 1024x3072 +model.dfly_layers.4.self_attn.q_b_proj.weight BF16 8192x1024 +model.dfly_layers.confidence_head.proj.bias BF16 1 +model.dfly_layers.confidence_head.proj.weight BF16 1x3072 +model.dfly_layers.final_norm.weight BF16 3072 +model.dfly_layers.hidden_correction.down_proj.weight BF16 3072x3072 +model.dfly_layers.hidden_correction.embed_norm.weight BF16 3072 +model.dfly_layers.hidden_correction.gate_proj.weight BF16 3072x6144 +model.dfly_layers.hidden_correction.hidden_norm.weight BF16 3072 +model.dfly_layers.hidden_correction.up_proj.weight BF16 3072x6144 +model.dfly_layers.mtp_fusion.eh_proj.weight BF16 3072x6144 +model.dfly_layers.mtp_fusion.enorm.weight BF16 3072 +model.dfly_layers.mtp_fusion.gate BF16 3072 +model.dfly_layers.mtp_fusion.hnorm.weight BF16 3072 +model.embed_tokens.weight BF16 120832x3072 +model.hc_head.hc_head_base F32 4 +model.hc_head.hc_head_fn F32 4x12288 +model.hc_head.hc_head_scale F32 1 +model.layers.0.hc_attn_layer.hc_pre.hc_base F32 8 +model.layers.0.hc_attn_layer.hc_pre.hc_fn F32 8x12288 +model.layers.0.hc_attn_layer.hc_pre.hc_scale F32 2 +model.layers.0.hc_mlp_layer.hc_pre.hc_base F32 8 +model.layers.0.hc_mlp_layer.hc_pre.hc_fn F32 8x12288 +model.layers.0.hc_mlp_layer.hc_pre.hc_scale F32 2 +model.layers.0.input_layernorm.weight BF16 3072 +model.layers.0.mlp.down_proj.input_scale F32 scalar +model.layers.0.mlp.down_proj.weight U8 3072x6912 +model.layers.0.mlp.down_proj.weight_scale F8_E4M3 3072x864 +model.layers.0.mlp.down_proj.weight_scale_2 F32 scalar +model.layers.0.mlp.gate_proj.input_scale F32 scalar +model.layers.0.mlp.gate_proj.weight U8 13824x1536 +model.layers.0.mlp.gate_proj.weight_scale F8_E4M3 13824x192 +model.layers.0.mlp.gate_proj.weight_scale_2 F32 scalar +model.layers.0.mlp.post_fc2_norm.weight BF16 3072 +model.layers.0.mlp.up_proj.input_scale F32 scalar +model.layers.0.mlp.up_proj.weight U8 13824x1536 +model.layers.0.mlp.up_proj.weight_scale F8_E4M3 13824x192 +model.layers.0.mlp.up_proj.weight_scale_2 F32 scalar +model.layers.0.post_attention_layernorm.weight BF16 3072 +model.layers.0.self_attn.compressed_indexer.head_weight_projection.weight BF16 16x3072 +model.layers.0.self_attn.compressed_indexer.intra_group_ape F32 4x128 +model.layers.0.self_attn.compressed_indexer.key_gate_projection.weight F32 128x128 +model.layers.0.self_attn.compressed_indexer.key_norm.weight BF16 128 +model.layers.0.self_attn.compressed_indexer.key_value_projection.weight F32 128x128 +model.layers.0.self_attn.compressed_indexer.query_projection.weight BF16 2048x1024 +model.layers.0.self_attn.compressed_indexer.token_key_norm.weight BF16 128 +model.layers.0.self_attn.compressed_indexer.token_key_projection.weight BF16 128x3072 +model.layers.0.self_attn.kv_a_layernorm.weight BF16 512 +model.layers.0.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.layers.0.self_attn.kv_b_proj.weight BF16 14336x512 +model.layers.0.self_attn.learnable_sink_param F32 32 +model.layers.0.self_attn.linear_gate.weight BF16 8192x3072 +model.layers.0.self_attn.o_proj.weight BF16 3072x8192 +model.layers.0.self_attn.post_proj_norm.weight BF16 3072 +model.layers.0.self_attn.q_a_layernorm.weight BF16 1024 +model.layers.0.self_attn.q_a_proj.weight BF16 1024x3072 +model.layers.0.self_attn.q_b_proj.weight BF16 8192x1024 +model.layers.1.engram_layer.key_projs.0.bias BF16 3072 +model.layers.1.engram_layer.key_projs.0.weight BF16 3072x1536 +model.layers.1.engram_layer.key_projs.1.bias BF16 3072 +model.layers.1.engram_layer.key_projs.1.weight BF16 3072x1536 +model.layers.1.engram_layer.key_projs.2.bias BF16 3072 +model.layers.1.engram_layer.key_projs.2.weight BF16 3072x1536 +model.layers.1.engram_layer.key_projs.3.bias BF16 3072 +model.layers.1.engram_layer.key_projs.3.weight BF16 3072x1536 +model.layers.1.engram_layer.lookup_per_head_norms.0.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.1.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.10.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.11.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.12.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.13.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.14.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.15.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.2.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.3.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.4.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.5.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.6.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.7.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.8.weight BF16 96 +model.layers.1.engram_layer.lookup_per_head_norms.9.weight BF16 96 +model.layers.1.engram_layer.lookup_table I32 120818 +model.layers.1.engram_layer.multi_head_embedding.embedding.weight F8_E4M3 164994380x96 +model.layers.1.engram_layer.multi_head_embedding.embedding.weight_scale_inv BF16 164994380 +model.layers.1.engram_layer.norm_key.0.weight BF16 3072 +model.layers.1.engram_layer.norm_key.1.weight BF16 3072 +model.layers.1.engram_layer.norm_key.2.weight BF16 3072 +model.layers.1.engram_layer.norm_key.3.weight BF16 3072 +model.layers.1.engram_layer.norm_query.0.weight BF16 3072 +model.layers.1.engram_layer.norm_query.1.weight BF16 3072 +model.layers.1.engram_layer.norm_query.2.weight BF16 3072 +model.layers.1.engram_layer.norm_query.3.weight BF16 3072 +model.layers.1.engram_layer.unified_per_hc_scales.0 BF16 3072 +model.layers.1.engram_layer.unified_per_hc_scales.1 BF16 3072 +model.layers.1.engram_layer.unified_per_hc_scales.2 BF16 3072 +model.layers.1.engram_layer.unified_per_hc_scales.3 BF16 3072 +model.layers.1.engram_layer.unified_pre_gamma BF16 3072 +model.layers.1.engram_layer.value_proj.bias BF16 3072 +model.layers.1.engram_layer.value_proj.weight BF16 3072x1536 +model.layers.1.hc_attn_layer.hc_pre.hc_base F32 8 +model.layers.1.hc_attn_layer.hc_pre.hc_fn F32 8x12288 +model.layers.1.hc_attn_layer.hc_pre.hc_scale F32 2 +model.layers.1.hc_mlp_layer.hc_pre.hc_base F32 8 +model.layers.1.hc_mlp_layer.hc_pre.hc_fn F32 8x12288 +model.layers.1.hc_mlp_layer.hc_pre.hc_scale F32 2 +model.layers.1.input_layernorm.weight BF16 3072 +model.layers.1.mlp.combine_output_norm.weight BF16 3072 +model.layers.1.mlp.experts.0.down_proj.input_scale F32 scalar +model.layers.1.mlp.experts.0.down_proj.weight U8 1536x768 +model.layers.1.mlp.experts.0.down_proj.weight_scale F8_E4M3 1536x96 +model.layers.1.mlp.experts.0.down_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.experts.0.gate_proj.input_scale F32 scalar +model.layers.1.mlp.experts.0.gate_proj.weight U8 1536x768 +model.layers.1.mlp.experts.0.gate_proj.weight_scale F8_E4M3 1536x96 +model.layers.1.mlp.experts.0.gate_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.experts.0.up_proj.input_scale F32 scalar +model.layers.1.mlp.experts.0.up_proj.weight U8 1536x768 +model.layers.1.mlp.experts.0.up_proj.weight_scale F8_E4M3 1536x96 +model.layers.1.mlp.experts.0.up_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.experts.511.down_proj.input_scale F32 scalar +model.layers.1.mlp.experts.511.down_proj.weight U8 1536x768 +model.layers.1.mlp.experts.511.down_proj.weight_scale F8_E4M3 1536x96 +model.layers.1.mlp.experts.511.down_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.experts.511.gate_proj.input_scale F32 scalar +model.layers.1.mlp.experts.511.gate_proj.weight U8 1536x768 +model.layers.1.mlp.experts.511.gate_proj.weight_scale F8_E4M3 1536x96 +model.layers.1.mlp.experts.511.gate_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.experts.511.up_proj.input_scale F32 scalar +model.layers.1.mlp.experts.511.up_proj.weight U8 1536x768 +model.layers.1.mlp.experts.511.up_proj.weight_scale F8_E4M3 1536x96 +model.layers.1.mlp.experts.511.up_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.gate.e_score_correction_bias F32 512 +model.layers.1.mlp.gate.weight BF16 512x3072 +model.layers.1.mlp.routed_expert_down_proj.weight BF16 1536x3072 +model.layers.1.mlp.routed_expert_up_proj.weight BF16 3072x1536 +model.layers.1.mlp.shared_experts.down_proj.input_scale F32 scalar +model.layers.1.mlp.shared_experts.down_proj.weight U8 3072x768 +model.layers.1.mlp.shared_experts.down_proj.weight_scale F8_E4M3 3072x96 +model.layers.1.mlp.shared_experts.down_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.shared_experts.gate_proj.input_scale F32 scalar +model.layers.1.mlp.shared_experts.gate_proj.weight U8 1536x1536 +model.layers.1.mlp.shared_experts.gate_proj.weight_scale F8_E4M3 1536x192 +model.layers.1.mlp.shared_experts.gate_proj.weight_scale_2 F32 scalar +model.layers.1.mlp.shared_experts.up_proj.input_scale F32 scalar +model.layers.1.mlp.shared_experts.up_proj.weight U8 1536x1536 +model.layers.1.mlp.shared_experts.up_proj.weight_scale F8_E4M3 1536x192 +model.layers.1.mlp.shared_experts.up_proj.weight_scale_2 F32 scalar +model.layers.1.post_attention_layernorm.weight BF16 3072 +model.layers.1.self_attn.compressed_indexer.head_weight_projection.weight BF16 16x3072 +model.layers.1.self_attn.compressed_indexer.intra_group_ape F32 4x128 +model.layers.1.self_attn.compressed_indexer.key_gate_projection.weight F32 128x128 +model.layers.1.self_attn.compressed_indexer.key_norm.weight BF16 128 +model.layers.1.self_attn.compressed_indexer.key_value_projection.weight F32 128x128 +model.layers.1.self_attn.compressed_indexer.query_projection.weight BF16 2048x1024 +model.layers.1.self_attn.compressed_indexer.token_key_norm.weight BF16 128 +model.layers.1.self_attn.compressed_indexer.token_key_projection.weight BF16 128x3072 +model.layers.1.self_attn.kv_a_layernorm.weight BF16 512 +model.layers.1.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.layers.1.self_attn.kv_b_proj.weight BF16 14336x512 +model.layers.1.self_attn.learnable_sink_param F32 32 +model.layers.1.self_attn.linear_gate.weight BF16 8192x3072 +model.layers.1.self_attn.o_proj.weight BF16 3072x8192 +model.layers.1.self_attn.post_proj_norm.weight BF16 3072 +model.layers.1.self_attn.q_a_layernorm.weight BF16 1024 +model.layers.1.self_attn.q_a_proj.weight BF16 1024x3072 +model.layers.1.self_attn.q_b_proj.weight BF16 8192x1024 +model.layers.2.hc_attn_layer.hc_pre.hc_base F32 8 +model.layers.2.hc_attn_layer.hc_pre.hc_fn F32 8x12288 +model.layers.2.hc_attn_layer.hc_pre.hc_scale F32 2 +model.layers.2.hc_mlp_layer.hc_pre.hc_base F32 8 +model.layers.2.hc_mlp_layer.hc_pre.hc_fn F32 8x12288 +model.layers.2.hc_mlp_layer.hc_pre.hc_scale F32 2 +model.layers.2.input_layernorm.weight BF16 3072 +model.layers.2.mlp.combine_output_norm.weight BF16 3072 +model.layers.2.mlp.gate.e_score_correction_bias F32 512 +model.layers.2.mlp.gate.weight BF16 512x3072 +model.layers.2.mlp.routed_expert_down_proj.weight BF16 1536x3072 +model.layers.2.mlp.routed_expert_up_proj.weight BF16 3072x1536 +model.layers.2.mlp.shared_experts.down_proj.input_scale F32 scalar +model.layers.2.mlp.shared_experts.down_proj.weight U8 3072x768 +model.layers.2.mlp.shared_experts.down_proj.weight_scale F8_E4M3 3072x96 +model.layers.2.mlp.shared_experts.down_proj.weight_scale_2 F32 scalar +model.layers.2.mlp.shared_experts.gate_proj.input_scale F32 scalar +model.layers.2.mlp.shared_experts.gate_proj.weight U8 1536x1536 +model.layers.2.mlp.shared_experts.gate_proj.weight_scale F8_E4M3 1536x192 +model.layers.2.mlp.shared_experts.gate_proj.weight_scale_2 F32 scalar +model.layers.2.mlp.shared_experts.up_proj.input_scale F32 scalar +model.layers.2.mlp.shared_experts.up_proj.weight U8 1536x1536 +model.layers.2.mlp.shared_experts.up_proj.weight_scale F8_E4M3 1536x192 +model.layers.2.mlp.shared_experts.up_proj.weight_scale_2 F32 scalar +model.layers.2.post_attention_layernorm.weight BF16 3072 +model.layers.2.self_attn.kv_a_layernorm.weight BF16 512 +model.layers.2.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.layers.2.self_attn.kv_b_proj.weight BF16 28672x512 +model.layers.2.self_attn.learnable_sink_param F32 64 +model.layers.2.self_attn.linear_gate.weight BF16 16384x3072 +model.layers.2.self_attn.o_proj.weight BF16 3072x16384 +model.layers.2.self_attn.post_proj_norm.weight BF16 3072 +model.layers.2.self_attn.q_a_layernorm.weight BF16 1024 +model.layers.2.self_attn.q_a_proj.weight BF16 1024x3072 +model.layers.2.self_attn.q_b_proj.weight BF16 16384x1024 +model.layers.41.hc_attn_layer.hc_pre.hc_base F32 8 +model.layers.41.hc_attn_layer.hc_pre.hc_fn F32 8x12288 +model.layers.41.hc_attn_layer.hc_pre.hc_scale F32 2 +model.layers.41.hc_mlp_layer.hc_pre.hc_base F32 8 +model.layers.41.hc_mlp_layer.hc_pre.hc_fn F32 8x12288 +model.layers.41.hc_mlp_layer.hc_pre.hc_scale F32 2 +model.layers.41.input_layernorm.weight BF16 3072 +model.layers.41.mlp.combine_output_norm.weight BF16 3072 +model.layers.41.mlp.experts.0.down_proj.input_scale F32 scalar +model.layers.41.mlp.experts.0.down_proj.weight U8 1536x768 +model.layers.41.mlp.experts.0.down_proj.weight_scale F8_E4M3 1536x96 +model.layers.41.mlp.experts.0.down_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.experts.0.gate_proj.input_scale F32 scalar +model.layers.41.mlp.experts.0.gate_proj.weight U8 1536x768 +model.layers.41.mlp.experts.0.gate_proj.weight_scale F8_E4M3 1536x96 +model.layers.41.mlp.experts.0.gate_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.experts.0.up_proj.input_scale F32 scalar +model.layers.41.mlp.experts.0.up_proj.weight U8 1536x768 +model.layers.41.mlp.experts.0.up_proj.weight_scale F8_E4M3 1536x96 +model.layers.41.mlp.experts.0.up_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.experts.511.down_proj.input_scale F32 scalar +model.layers.41.mlp.experts.511.down_proj.weight U8 1536x768 +model.layers.41.mlp.experts.511.down_proj.weight_scale F8_E4M3 1536x96 +model.layers.41.mlp.experts.511.down_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.experts.511.gate_proj.input_scale F32 scalar +model.layers.41.mlp.experts.511.gate_proj.weight U8 1536x768 +model.layers.41.mlp.experts.511.gate_proj.weight_scale F8_E4M3 1536x96 +model.layers.41.mlp.experts.511.gate_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.experts.511.up_proj.input_scale F32 scalar +model.layers.41.mlp.experts.511.up_proj.weight U8 1536x768 +model.layers.41.mlp.experts.511.up_proj.weight_scale F8_E4M3 1536x96 +model.layers.41.mlp.experts.511.up_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.gate.e_score_correction_bias F32 512 +model.layers.41.mlp.gate.weight BF16 512x3072 +model.layers.41.mlp.routed_expert_down_proj.weight BF16 1536x3072 +model.layers.41.mlp.routed_expert_up_proj.weight BF16 3072x1536 +model.layers.41.mlp.shared_experts.down_proj.input_scale F32 scalar +model.layers.41.mlp.shared_experts.down_proj.weight U8 3072x768 +model.layers.41.mlp.shared_experts.down_proj.weight_scale F8_E4M3 3072x96 +model.layers.41.mlp.shared_experts.down_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.shared_experts.gate_proj.input_scale F32 scalar +model.layers.41.mlp.shared_experts.gate_proj.weight U8 1536x1536 +model.layers.41.mlp.shared_experts.gate_proj.weight_scale F8_E4M3 1536x192 +model.layers.41.mlp.shared_experts.gate_proj.weight_scale_2 F32 scalar +model.layers.41.mlp.shared_experts.up_proj.input_scale F32 scalar +model.layers.41.mlp.shared_experts.up_proj.weight U8 1536x1536 +model.layers.41.mlp.shared_experts.up_proj.weight_scale F8_E4M3 1536x192 +model.layers.41.mlp.shared_experts.up_proj.weight_scale_2 F32 scalar +model.layers.41.post_attention_layernorm.weight BF16 3072 +model.layers.41.self_attn.compressed_indexer.head_weight_projection.weight BF16 16x3072 +model.layers.41.self_attn.compressed_indexer.intra_group_ape F32 4x128 +model.layers.41.self_attn.compressed_indexer.key_gate_projection.weight F32 128x128 +model.layers.41.self_attn.compressed_indexer.key_norm.weight BF16 128 +model.layers.41.self_attn.compressed_indexer.key_value_projection.weight F32 128x128 +model.layers.41.self_attn.compressed_indexer.query_projection.weight BF16 2048x1024 +model.layers.41.self_attn.compressed_indexer.token_key_norm.weight BF16 128 +model.layers.41.self_attn.compressed_indexer.token_key_projection.weight BF16 128x3072 +model.layers.41.self_attn.kv_a_layernorm.weight BF16 512 +model.layers.41.self_attn.kv_a_proj_with_mqa.weight BF16 576x3072 +model.layers.41.self_attn.kv_b_proj.weight BF16 14336x512 +model.layers.41.self_attn.learnable_sink_param F32 32 +model.layers.41.self_attn.linear_gate.weight BF16 8192x3072 +model.layers.41.self_attn.o_proj.weight BF16 3072x8192 +model.layers.41.self_attn.post_proj_norm.weight BF16 3072 +model.layers.41.self_attn.q_a_layernorm.weight BF16 1024 +model.layers.41.self_attn.q_a_proj.weight BF16 1024x3072 +model.layers.41.self_attn.q_b_proj.weight BF16 8192x1024 +model.norm.weight BF16 3072 +vit.embeddings.patch_embedding.weight BF16 1152x3x16x16 diff --git a/zig/src/families/hy4_flash/nvfp4_weights.zig b/zig/src/families/hy4_flash/nvfp4_weights.zig new file mode 100644 index 00000000000..b042676d197 --- /dev/null +++ b/zig/src/families/hy4_flash/nvfp4_weights.zig @@ -0,0 +1,208 @@ +//! ModelOpt NVFP4 builds of Hy4-flash: the quantization block they carry, and the tensor each name must be. +//! The routed experts, the shared experts and the dense MLP are NVFP4 (e2m1 codes two to a byte, an e4m3 scale +//! every 16 inputs, a per-tensor scale and an input scale). The Engram tables are e4m3 rows with one BF16 scale +//! a row. Everything else stays as Tencent released it: BF16, with the f32 tensors of the release. +const std = @import("std"); +const config = @import("config.zig"); + +pub const DType = enum { bf16, f32, i32, u8, f8_e4m3 }; + +/// The NVFP4 group: one e4m3 scale for every 16 inputs of a row. +pub const group = 16; + +/// hf_quant_config.json's "quantization" block: ModelOpt NVFP4 in groups of 16 is the one build this reads. +pub fn checkQuant(a: std.mem.Allocator, bytes: []const u8) !void { + const parsed = std.json.parseFromSlice(std.json.Value, a, bytes, .{}) catch return error.UnsupportedHy4Quant; + defer parsed.deinit(); + const root = if (parsed.value == .object) parsed.value.object else return error.UnsupportedHy4Quant; + const q = root.get("quantization") orelse return error.UnsupportedHy4Quant; + if (q != .object) return error.UnsupportedHy4Quant; + const algo = q.object.get("quant_algo") orelse return error.UnsupportedHy4Quant; + if (algo != .string or !std.mem.eql(u8, algo.string, "NVFP4")) return error.UnsupportedHy4Quant; + const size = q.object.get("group_size") orelse return error.UnsupportedHy4Quant; + if (size != .integer or size.integer != group) return error.UnsupportedHy4Quant; + if (q.object.get("kv_cache_quant_algo")) |kv| if (kv != .null) return error.UnsupportedHy4Quant; +} + +fn expect(weights: anytype, prefix: []const u8, name: []const u8, suffix: []const u8, dtype: DType, shape: []const usize) !void { + var name_buffer: [200]u8 = undefined; + const full = try std.fmt.bufPrint(&name_buffer, "{s}{s}{s}", .{ prefix, name, suffix }); + try weights.expect(full, dtype, shape); +} + +/// One NVFP4 linear of `out` rows by `in` inputs. +fn linear(weights: anytype, prefix: []const u8, name: []const u8, out: usize, in: usize) !void { + if (out == 0 or in == 0 or in % group != 0) return error.UnsupportedHy4Quant; + try expect(weights, prefix, name, ".weight", .u8, &.{ out, in / 2 }); + try expect(weights, prefix, name, ".weight_scale", .f8_e4m3, &.{ out, in / group }); + try expect(weights, prefix, name, ".weight_scale_2", .f32, &.{}); + try expect(weights, prefix, name, ".input_scale", .f32, &.{}); +} + +/// A SwiGLU MLP of width `inner` over `h`, its three projections NVFP4. +fn mlp(weights: anytype, prefix: []const u8, h: usize, inner: usize) !void { + try linear(weights, prefix, "gate_proj", inner, h); + try linear(weights, prefix, "up_proj", inner, h); + try linear(weights, prefix, "down_proj", h, inner); +} + +fn bf16(weights: anytype, prefix: []const u8, name: []const u8, shape: []const usize) !void { + try expect(weights, prefix, name, ".weight", .bf16, shape); +} + +fn checkLayerNorms(weights: anytype, layer: []const u8, t: config.Text) !void { + for ([_][]const u8{ "input_layernorm", "post_attention_layernorm", "self_attn.post_proj_norm" }) |name| { + try bf16(weights, layer, name, &.{t.hidden_size}); + } + try bf16(weights, layer, "self_attn.q_a_layernorm", &.{t.q_lora_rank}); + try bf16(weights, layer, "self_attn.kv_a_layernorm", &.{t.kv_lora_rank}); +} + +fn checkAttention(weights: anytype, layer: []const u8, t: config.Text, index: u32) !void { + const h = t.hidden_size; + const heads = t.headShape(index); + const values = @as(usize, heads.heads) * heads.value; + try checkLayerNorms(weights, layer, t); + try bf16(weights, layer, "self_attn.q_a_proj", &.{ t.q_lora_rank, h }); + try bf16(weights, layer, "self_attn.q_b_proj", &.{ heads.queryRows(), t.q_lora_rank }); + try bf16(weights, layer, "self_attn.kv_a_proj_with_mqa", &.{ @as(usize, t.kv_lora_rank) + heads.rotary, h }); + try bf16(weights, layer, "self_attn.kv_b_proj", &.{ heads.kvRows(), t.kv_lora_rank }); + try bf16(weights, layer, "self_attn.linear_gate", &.{ values, h }); + try bf16(weights, layer, "self_attn.o_proj", &.{ h, values }); + try expect(weights, layer, "self_attn.learnable_sink_param", "", .f32, &.{heads.heads}); + if (t.layer_types[index] != .deepseek_sparse_attention) return; + const c = t.compressed_indexer_head_dim; + const n = t.compressed_indexer_num_attention_heads; + const ix = "self_attn.compressed_indexer."; + try bf16(weights, layer, ix ++ "token_key_projection", &.{ c, h }); + try bf16(weights, layer, ix ++ "query_projection", &.{ @as(usize, n) * c, t.q_lora_rank }); + try bf16(weights, layer, ix ++ "head_weight_projection", &.{ n, h }); + try expect(weights, layer, ix, "key_value_projection.weight", .f32, &.{ c, c }); + try expect(weights, layer, ix, "key_gate_projection.weight", .f32, &.{ c, c }); + try expect(weights, layer, ix, "intra_group_ape", .f32, &.{ t.compressed_indexer_compress_ratio, c }); + try bf16(weights, layer, ix ++ "key_norm", &.{c}); + try bf16(weights, layer, ix ++ "token_key_norm", &.{c}); +} + +fn checkStreams(weights: anytype, layer: []const u8, t: config.Text) !void { + const hcs: usize = t.hc_mult; + for ([_][]const u8{ "hc_attn_layer.hc_pre.", "hc_mlp_layer.hc_pre." }) |hc| { + try expect(weights, layer, hc, "hc_fn", .f32, &.{ hcs * 2, hcs * t.hidden_size }); + try expect(weights, layer, hc, "hc_base", .f32, &.{hcs * 2}); + try expect(weights, layer, hc, "hc_scale", .f32, &.{2}); + } +} + +fn checkFeed(weights: anytype, layer: []const u8, t: config.Text, index: u32) !void { + const h: usize = t.hidden_size; + var buffer: [96]u8 = undefined; + if (t.mlp_layer_types[index] == .dense) { + try mlp(weights, try std.fmt.bufPrint(&buffer, "{s}mlp.", .{layer}), h, t.intermediate_size); + try bf16(weights, layer, "mlp.post_fc2_norm", &.{h}); + return; + } + const inner: usize = t.moe_intermediate_size; + const latent: usize = t.routed_expert_hidden_size; + try bf16(weights, layer, "mlp.gate", &.{ t.n_routed_experts, h }); + try expect(weights, layer, "mlp.gate.e_score_correction_bias", "", .f32, &.{t.n_routed_experts}); + try bf16(weights, layer, "mlp.routed_expert_down_proj", &.{ latent, h }); + try bf16(weights, layer, "mlp.routed_expert_up_proj", &.{ h, latent }); + try bf16(weights, layer, "mlp.combine_output_norm", &.{h}); + try mlp(weights, try std.fmt.bufPrint(&buffer, "{s}mlp.shared_experts.", .{layer}), h, inner * t.n_shared_experts); + for (0..t.n_routed_experts) |e| { + try mlp(weights, try std.fmt.bufPrint(&buffer, "{s}mlp.experts.{d}.", .{ layer, e }), latent, inner); + } +} + +fn checkEngram(weights: anytype, layer: []const u8, t: config.Text, number: u32) !void { + const orders = t.engram_max_ngram_size - 1; + const rows = try t.engramRows(number); + const head_width = t.engram_n_embed_per_ngram / t.engram_n_head_per_ngram; + const input = @as(usize, orders) * t.engram_n_embed_per_ngram; + const h: usize = t.hidden_size; + const table = "engram_layer.multi_head_embedding.embedding."; + try expect(weights, layer, table, "weight", .f8_e4m3, &.{ rows, head_width }); + try expect(weights, layer, table, "weight_scale_inv", .bf16, &.{rows}); + try expect(weights, layer, "engram_layer.lookup_table", "", .i32, &.{t.engram_lookup_table_size}); + try bf16(weights, layer, "engram_layer.value_proj", &.{ h, input }); + try expect(weights, layer, "engram_layer.value_proj", ".bias", .bf16, &.{h}); + try expect(weights, layer, "engram_layer.unified_pre_gamma", "", .bf16, &.{h}); + var buffer: [68]u8 = undefined; + for (0..@as(usize, orders) * t.engram_n_head_per_ngram) |head| { + try bf16(weights, layer, try std.fmt.bufPrint(&buffer, "engram_layer.lookup_per_head_norms.{d}", .{head}), &.{head_width}); + } + for (0..t.hc_mult) |stream| { + const key = try std.fmt.bufPrint(&buffer, "engram_layer.key_projs.{d}", .{stream}); + try bf16(weights, layer, key, &.{ h, input }); + try expect(weights, layer, key, ".bias", .bf16, &.{h}); + try bf16(weights, layer, try std.fmt.bufPrint(&buffer, "engram_layer.norm_key.{d}", .{stream}), &.{h}); + try bf16(weights, layer, try std.fmt.bufPrint(&buffer, "engram_layer.norm_query.{d}", .{stream}), &.{h}); + try expect(weights, layer, try std.fmt.bufPrint(&buffer, "engram_layer.unified_per_hc_scales.{d}", .{stream}), "", .bf16, &.{h}); + } +} + +/// The DFly2 drafter, BF16 as released (its sink is BF16 too). +fn checkDraft(weights: anytype, model: config.Model) !void { + const t = model.text_config; + const h: usize = t.hidden_size; + const inner: usize = model.dfly_intermediate_size orelse try std.math.mul(u32, t.hidden_size, 3); + const root = "model.dfly_layers."; + try bf16(weights, root, "final_norm", &.{h}); + try bf16(weights, root, "confidence_head.proj", &.{ 1, h }); + try expect(weights, root, "confidence_head.proj.bias", "", .bf16, &.{1}); + for ([_][]const u8{ "enorm.weight", "hnorm.weight", "gate" }) |name| { + try expect(weights, root ++ "mtp_fusion.", name, "", .bf16, &.{h}); + } + try bf16(weights, root, "mtp_fusion.eh_proj", &.{ h, h * 2 }); + const correction = root ++ "hidden_correction."; + try bf16(weights, correction, "embed_norm", &.{h}); + try bf16(weights, correction, "hidden_norm", &.{h}); + try bf16(weights, correction, "gate_proj", &.{ h, h * 2 }); + try bf16(weights, correction, "up_proj", &.{ h, h * 2 }); + try bf16(weights, correction, "down_proj", &.{ h, h }); + for (model.dfly_target_kv_layers, 0..) |target_layer, draft_layer| { + var buffer: [60]u8 = undefined; + const layer = try std.fmt.bufPrint(&buffer, root ++ "{d}.", .{draft_layer}); + const heads = t.headShape(target_layer); + const channels = @as(usize, heads.heads) * heads.value; + try checkLayerNorms(weights, layer, t); + try bf16(weights, layer, "self_attn.q_a_proj", &.{ t.q_lora_rank, h }); + try bf16(weights, layer, "self_attn.q_b_proj", &.{ heads.queryRows(), t.q_lora_rank }); + try bf16(weights, layer, "self_attn.kv_a_proj_with_mqa", &.{ @as(usize, t.kv_lora_rank) + heads.rotary, h }); + try bf16(weights, layer, "self_attn.kv_b_proj", &.{ heads.kvRows(), t.kv_lora_rank }); + try bf16(weights, layer, "self_attn.linear_gate", &.{ channels, h }); + try bf16(weights, layer, "self_attn.o_proj", &.{ h, channels }); + try expect(weights, layer, "self_attn.learnable_sink_param", "", .bf16, &.{heads.heads}); + try bf16(weights, layer, "mlp.gate_proj", &.{ inner, h }); + try bf16(weights, layer, "mlp.up_proj", &.{ inner, h }); + try bf16(weights, layer, "mlp.down_proj", &.{ h, inner }); + } +} + +/// Every text and drafter tensor of an NVFP4 build, by name, stored type and shape. The vision tower is the +/// patch embedding only: the family refuses images until the tower runs in its own kernels. +pub fn check(weights: anytype, model: config.Model) !void { + try model.validate(); + const t = model.text_config; + const h: usize = t.hidden_size; + const hcs: usize = t.hc_mult; + try bf16(weights, "model.", "embed_tokens", &.{ t.vocab_size, h }); + try expect(weights, "", "lm_head.weight", "", .f32, &.{ t.vocab_size, h }); + try bf16(weights, "model.", "norm", &.{h}); + try expect(weights, "model.hc_head.", "hc_head_fn", "", .f32, &.{ hcs, hcs * h }); + try expect(weights, "model.hc_head.", "hc_head_base", "", .f32, &.{hcs}); + try expect(weights, "model.hc_head.", "hc_head_scale", "", .f32, &.{1}); + for (0..t.num_hidden_layers) |i| { + var buffer: [56]u8 = undefined; + const layer = try std.fmt.bufPrint(&buffer, "model.layers.{d}.", .{i}); + const index: u32 = @intCast(i); + try checkAttention(weights, layer, t, index); + try checkStreams(weights, layer, t); + try checkFeed(weights, layer, t, index); + // Engram's layer numbers are one-based: number 2 sits in model.layers.1. + if (std.mem.indexOfScalar(u32, t.engram_layer_ids, index + 1) != null) try checkEngram(weights, layer, t, index + 1); + } + const v = model.vision_config; + try bf16(weights, "vit.embeddings.", "patch_embedding", &.{ v.hidden_size, 3, v.patch_size, v.patch_size }); + try checkDraft(weights, model); +} diff --git a/zig/src/families/hy4_flash/nvfp4_weights_test.zig b/zig/src/families/hy4_flash/nvfp4_weights_test.zig new file mode 100644 index 00000000000..8d808d18fb5 --- /dev/null +++ b/zig/src/families/hy4_flash/nvfp4_weights_test.zig @@ -0,0 +1,97 @@ +//! The NVFP4 weight map against the published build's own safetensors headers (atakans/Hy4-flash-NVFP4): +//! nvfp4_header.txt keeps 344 of its 254,168 entries, every kind of tensor at the first, second, third and +//! last layers, two experts of two layers and the whole drafter. The full build holds 253,728 tensors outside +//! the vision tower's blocks, the same count check() asks for. +const std = @import("std"); +const config = @import("config.zig"); +const nvfp4 = @import("nvfp4_weights.zig"); + +const Entry = struct { dtype: nvfp4.DType, shape: [4]usize, rank: u8, seen: bool = false }; + +/// Answers check() from a sample of a header: a name in the sample must match it, any other name is only counted. +const Sample = struct { + entries: std.StringHashMapUnmanaged(Entry) = .empty, + asked: usize = 0, + + fn load(self: *Sample, a: std.mem.Allocator, text: []const u8) !void { + var lines = std.mem.tokenizeScalar(u8, text, '\n'); + while (lines.next()) |line| { + var fields = std.mem.tokenizeScalar(u8, line, ' '); + const name = fields.next().?; + const dtype_name = fields.next().?; + const dims = fields.next().?; + const dtype: nvfp4.DType = inline for (.{ .{ "BF16", .bf16 }, .{ "F32", .f32 }, .{ "I32", .i32 }, .{ "U8", .u8 }, .{ "F8_E4M3", .f8_e4m3 } }) |p| { + if (std.mem.eql(u8, dtype_name, p[0])) break p[1]; + } else return error.FixtureDType; + var entry: Entry = .{ .dtype = dtype, .shape = @splat(0), .rank = 0 }; + if (!std.mem.eql(u8, dims, "scalar")) { + var it = std.mem.tokenizeScalar(u8, dims, 'x'); + while (it.next()) |d| : (entry.rank += 1) entry.shape[entry.rank] = try std.fmt.parseInt(usize, d, 10); + } + try self.entries.put(a, name, entry); + } + } + + pub fn expect(self: *Sample, name: []const u8, dtype: nvfp4.DType, shape: []const usize) !void { + self.asked += 1; + const entry = self.entries.getPtr(name) orelse return; + if (entry.seen) return error.AskedTwice; + entry.seen = true; + if (entry.dtype != dtype or !std.mem.eql(usize, entry.shape[0..entry.rank], shape)) { + std.debug.print("{s}: the build stores {t} {any}, the map asks {t} {any}\n", .{ name, entry.dtype, entry.shape[0..entry.rank], dtype, shape }); + return error.UnexpectedTensor; + } + } +}; + +test "the NVFP4 map asks for every tensor of the published build, as it is stored" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const parsed = try config.parse(a, @embedFile("config_fixture.json")); + var sample: Sample = .{}; + try sample.load(a, @embedFile("nvfp4_header.txt")); + try std.testing.expectEqual(@as(usize, 344), sample.entries.count()); + try nvfp4.check(&sample, parsed.value); + var it = sample.entries.iterator(); + while (it.next()) |e| if (!e.value_ptr.seen) { + std.debug.print("{s} is in the build but not in the map\n", .{e.key_ptr.*}); + return error.MissedTensor; + }; + try std.testing.expectEqual(@as(usize, 253728), sample.asked); +} + +test "a changed tensor refuses by name" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const parsed = try config.parse(a, @embedFile("config_fixture.json")); + var sample: Sample = .{}; + try sample.load(a, @embedFile("nvfp4_header.txt")); + // An expert stored with BF16 block scales, as a build from another tool might store it. + sample.entries.getPtr("model.layers.41.mlp.experts.511.down_proj.weight_scale").?.dtype = .bf16; + try std.testing.expectError(error.UnexpectedTensor, nvfp4.check(&sample, parsed.value)); +} + +const modelopt = + \\{"producer": {"name": "modelopt", "version": "0.48.0"}, + \\ "quantization": {"quant_algo": "NVFP4", "kv_cache_quant_algo": null, "group_size": 16, + \\ "exclude_modules": ["lm_head", "model.layers.0.self_attn"]}} +; + +test "the quantization block: ModelOpt NVFP4 in groups of 16 only" { + const a = std.testing.allocator; + try nvfp4.checkQuant(a, modelopt); + const other = [_]struct { []const u8, []const u8 }{ + .{ "\"NVFP4\"", "\"FP8\"" }, + .{ "\"group_size\": 16", "\"group_size\": 32" }, + .{ "\"kv_cache_quant_algo\": null", "\"kv_cache_quant_algo\": \"FP8\"" }, + .{ "\"quantization\"", "\"quantisation\"" }, + }; + for (other) |o| { + const changed = try std.mem.replaceOwned(u8, a, modelopt, o[0], o[1]); + defer a.free(changed); + try std.testing.expectError(error.UnsupportedHy4Quant, nvfp4.checkQuant(a, changed)); + } + try std.testing.expectError(error.UnsupportedHy4Quant, nvfp4.checkQuant(a, "not json")); +} From 83acba016f539f512caa0dcc73314038a6af469d Mon Sep 17 00:00:00 2001 From: atakann <17346304+atakann@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:26:12 +0300 Subject: [PATCH 191/361] hy4_flash: one-line comments in the NVFP4 map and its test (lean check) --- zig/src/families/hy4_flash/nvfp4_weights.zig | 9 +++------ zig/src/families/hy4_flash/nvfp4_weights_test.zig | 5 +---- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/zig/src/families/hy4_flash/nvfp4_weights.zig b/zig/src/families/hy4_flash/nvfp4_weights.zig index b042676d197..c7bdd1b7fc1 100644 --- a/zig/src/families/hy4_flash/nvfp4_weights.zig +++ b/zig/src/families/hy4_flash/nvfp4_weights.zig @@ -1,7 +1,4 @@ //! ModelOpt NVFP4 builds of Hy4-flash: the quantization block they carry, and the tensor each name must be. -//! The routed experts, the shared experts and the dense MLP are NVFP4 (e2m1 codes two to a byte, an e4m3 scale -//! every 16 inputs, a per-tensor scale and an input scale). The Engram tables are e4m3 rows with one BF16 scale -//! a row. Everything else stays as Tencent released it: BF16, with the f32 tensors of the release. const std = @import("std"); const config = @import("config.zig"); @@ -30,7 +27,7 @@ fn expect(weights: anytype, prefix: []const u8, name: []const u8, suffix: []cons try weights.expect(full, dtype, shape); } -/// One NVFP4 linear of `out` rows by `in` inputs. +/// One NVFP4 linear of `out` rows by `in` inputs: e2m1 codes two to a byte, an e4m3 scale a 16 inputs, two f32 scalars. fn linear(weights: anytype, prefix: []const u8, name: []const u8, out: usize, in: usize) !void { if (out == 0 or in == 0 or in % group != 0) return error.UnsupportedHy4Quant; try expect(weights, prefix, name, ".weight", .u8, &.{ out, in / 2 }); @@ -114,6 +111,7 @@ fn checkFeed(weights: anytype, layer: []const u8, t: config.Text, index: u32) !v } } +/// An Engram layer: its table is e4m3 rows with one BF16 scale a row, everything else BF16 as released. fn checkEngram(weights: anytype, layer: []const u8, t: config.Text, number: u32) !void { const orders = t.engram_max_ngram_size - 1; const rows = try t.engramRows(number); @@ -179,8 +177,7 @@ fn checkDraft(weights: anytype, model: config.Model) !void { } } -/// Every text and drafter tensor of an NVFP4 build, by name, stored type and shape. The vision tower is the -/// patch embedding only: the family refuses images until the tower runs in its own kernels. +/// Every text and drafter tensor of an NVFP4 build by name, stored type and shape; the vision tower's patch embedding. pub fn check(weights: anytype, model: config.Model) !void { try model.validate(); const t = model.text_config; diff --git a/zig/src/families/hy4_flash/nvfp4_weights_test.zig b/zig/src/families/hy4_flash/nvfp4_weights_test.zig index 8d808d18fb5..5248f923d0c 100644 --- a/zig/src/families/hy4_flash/nvfp4_weights_test.zig +++ b/zig/src/families/hy4_flash/nvfp4_weights_test.zig @@ -1,7 +1,4 @@ -//! The NVFP4 weight map against the published build's own safetensors headers (atakans/Hy4-flash-NVFP4): -//! nvfp4_header.txt keeps 344 of its 254,168 entries, every kind of tensor at the first, second, third and -//! last layers, two experts of two layers and the whole drafter. The full build holds 253,728 tensors outside -//! the vision tower's blocks, the same count check() asks for. +//! The NVFP4 weight map against 344 of the 254,168 header entries of the published build (atakans/Hy4-flash-NVFP4). const std = @import("std"); const config = @import("config.zig"); const nvfp4 = @import("nvfp4_weights.zig"); From 9a38b1f7b33863507cdea47e88207d8b3bea3f22 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:56:14 +0000 Subject: [PATCH 192/361] changelog: #4110 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c1ed01eae6..d94754eb619 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 +- Hy4-flash: a host weight map for its ModelOpt NVFP4 build (groups of 16, no KV quantization), with the build's recipe and quality notes; serving it comes in later slices (#4110). Thanks @atakann. + - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. From 5093db5dd34bcc30af5a96de233f2f4585cd11ec Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:01:34 +0000 Subject: [PATCH 193/361] inkling2: the Mini Metal serving test lives with native, so the family imports no native families/inkling2/metal/serving_test.zig opened Mini through native/inkling2.zig, a family importing native: with native/inkling2.zig importing the family's Metal model, backend, state and dspark, that made a cycle between the two. The test moves unchanged to native/inkling2_serving_test.zig, beside native/inkling2.zig and its other tests, reaching the family files by path as native/inkling2.zig does. It is registered where it was reached before, under test-inkling2-metal-host's root (inkling2_metal_host_test.zig), on Darwin only, so both checkpoint tests keep their coverage. --- zig/src/families/inkling2/metal/host_test.zig | 2 -- zig/src/inkling2_metal_host_test.zig | 2 ++ .../inkling2_serving_test.zig} | 10 +++++----- 3 files changed, 7 insertions(+), 7 deletions(-) rename zig/src/{families/inkling2/metal/serving_test.zig => native/inkling2_serving_test.zig} (97%) diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index 8598da235d9..e9e1998f151 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -1,5 +1,4 @@ //! Host-only Inkling 2 Mini Metal launch plans and scalar arithmetic references. -const serving = if (@import("builtin").os.tag.isDarwin()) @import("serving_test.zig") else struct {}; test { _ = @import("attention_test.zig"); @@ -14,5 +13,4 @@ test { _ = @import("dspark_state.zig"); _ = @import("dspark.zig"); _ = @import("backend.zig"); - _ = serving; } diff --git a/zig/src/inkling2_metal_host_test.zig b/zig/src/inkling2_metal_host_test.zig index eb76bab6406..70389362ab0 100644 --- a/zig/src/inkling2_metal_host_test.zig +++ b/zig/src/inkling2_metal_host_test.zig @@ -1,6 +1,8 @@ //! Inkling 2 Mini Metal host tests rooted with the production engine sources. +const serving = if (@import("builtin").os.tag.isDarwin()) @import("native/inkling2_serving_test.zig") else struct {}; test { _ = @import("families/inkling2/metal/host_test.zig"); _ = @import("inkling2_native.zig"); + _ = serving; } diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/native/inkling2_serving_test.zig similarity index 97% rename from zig/src/families/inkling2/metal/serving_test.zig rename to zig/src/native/inkling2_serving_test.zig index eb761e0fecd..c7f6cb1d1aa 100644 --- a/zig/src/families/inkling2/metal/serving_test.zig +++ b/zig/src/native/inkling2_serving_test.zig @@ -3,11 +3,11 @@ const std = @import("std"); const mtl = @import("metal"); const lanes = @import("lanes"); const api = @import("engine_api"); -const native = @import("../../../native/inkling2.zig"); -const Model = @import("model.zig").Model; -const backend = @import("backend.zig"); -const st = @import("state.zig"); -const dspark = @import("dspark.zig"); +const native = @import("inkling2.zig"); +const Model = @import("../families/inkling2/metal/model.zig").Model; +const backend = @import("../families/inkling2/metal/backend.zig"); +const st = @import("../families/inkling2/metal/state.zig"); +const dspark = @import("../families/inkling2/metal/dspark.zig"); const gpa = std.testing.allocator; const io = std.testing.io; From d230489624cb3ce34bc26f656e574fa9c2f84e2a Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:21:53 -0500 Subject: [PATCH 194/361] inkling2 metal dspark: attention scale 1/sqrt(128), and the recurrent step reads kappa as the FP32 it is --- zig/kernels/metal/inkling2/dspark.metal | 4 ++-- zig/src/families/inkling2/metal/dspark_kernels_test.zig | 2 +- zig/tests/contract/metal_inkling2_dspark.zig | 5 +++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/zig/kernels/metal/inkling2/dspark.metal b/zig/kernels/metal/inkling2/dspark.metal index 01ee835290d..2e1eddeb750 100644 --- a/zig/kernels/metal/inkling2/dspark.metal +++ b/zig/kernels/metal/inkling2/dspark.metal @@ -9,7 +9,7 @@ constant uint DSP_HEAD = 128; constant uint DSP_RANK = 256; constant uint DSP_RNN = 768; constant float DSP_EPS = 1e-6f; -constant float DSP_SCALE = 0x1.6a09e6p-7f; +constant float DSP_SCALE = 0x1.6a09e6p-4f; struct DsparkPositionArgs { uint base; }; struct DsparkContextArgs { uint base, rows, ring; }; @@ -199,7 +199,7 @@ kernel void tf_ink2_dspark_kappa(const device bfloat* y [[buffer(0)]], const dev out[i] = sum; } -kernel void tf_ink2_dspark_recurrent(const device bfloat* state [[buffer(0)]], const device bfloat* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkTokenArgs& a [[buffer(7)]], uint i [[thread_position_in_grid]]) { +kernel void tf_ink2_dspark_recurrent(const device bfloat* state [[buffer(0)]], const device float* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkTokenArgs& a [[buffer(7)]], uint i [[thread_position_in_grid]]) { if (i >= DSP_RANK) return; float values[3]; for (uint part = 0; part < 3; ++part) { diff --git a/zig/src/families/inkling2/metal/dspark_kernels_test.zig b/zig/src/families/inkling2/metal/dspark_kernels_test.zig index b72660d3aa2..1dc97f19367 100644 --- a/zig/src/families/inkling2/metal/dspark_kernels_test.zig +++ b/zig/src/families/inkling2/metal/dspark_kernels_test.zig @@ -44,7 +44,7 @@ test "DSpark symbols, records, ABIs and disabled contraction are exact" { try t.expectEqual(@as(usize, 4), @sizeOf(k.CountArgs)); try t.expectEqual(@as(usize, 8), @sizeOf(k.BaseArgs)); try t.expect(std.mem.indexOf(u8, shader, "#pragma METAL fp contract(off)") != null); - try t.expect(std.mem.indexOf(u8, shader, "DSP_SCALE = 0x1.6a09e6p-7f") != null); + try t.expect(std.mem.indexOf(u8, shader, "DSP_SCALE = 0x1.6a09e6p-4f") != null); } test "raw base projection rounds the dot without applying target softcap" { diff --git a/zig/tests/contract/metal_inkling2_dspark.zig b/zig/tests/contract/metal_inkling2_dspark.zig index 6274197e9d0..9ab455fd7bd 100644 --- a/zig/tests/contract/metal_inkling2_dspark.zig +++ b/zig/tests/contract/metal_inkling2_dspark.zig @@ -263,7 +263,8 @@ pub const Probe = struct { self.f[1][2 * RANK] = c.fromBf16(c.toBf16(0.3)); for ([_]usize{ 0, RANK, 2 * RANK }) |channel| @memset(self.f[2][channel * 5120 ..][0..512], 0); if (nf) self.f[0][0] = std.math.nan(f32); - for (0..4) |j| self.refs[j] = try self.input(self.f[j], true); + // kappa arrives as the kappa kernel wrote it, in FP32; the other three are BF16. + for (0..4) |j| self.refs[j] = try self.input(self.f[j], j != 1); try self.output(0, RNN, .bf16); try self.output(1, RANK, .bf16); try self.output(2, RANK, .bf16); @@ -418,7 +419,7 @@ pub const Probe = struct { const k_at = if (j < retained) ((first_kept + j) % ring) * KV + kv * 128 else (j - retained) * KV + kv * 128; const keys = if (j < retained) self.f[3] else self.f[1]; for (0..128) |d| dot += self.f[0][q_at + d] * keys[k_at + d]; - scores[j] = dot * @as(f32, 0x1.6a09e6p-7); + scores[j] = dot * @as(f32, 0x1.6a09e6p-4); peak = @max(peak, scores[j]); } var den: f32 = 0; From 6ecc6c99f6afdba2a1e279e9dfeba836c49f7ce1 Mon Sep 17 00:00:00 2001 From: Seth For Privacy <40500387+sethforprivacy@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:21:54 -0500 Subject: [PATCH 195/361] inkling2 metal dspark: the recurrent step's z scratch holds the three ranks the kernel writes --- zig/src/families/inkling2/metal/dspark_state.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/metal/dspark_state.zig b/zig/src/families/inkling2/metal/dspark_state.zig index eb20bd1cd6d..fa01993a751 100644 --- a/zig/src/families/inkling2/metal/dspark_state.zig +++ b/zig/src/families/inkling2/metal/dspark_state.zig @@ -27,7 +27,7 @@ fn sizes() [fields.len]usize { r * query * b, r * kv * b, r * kv * b, r * query * b, r * kv * b, r * kv * b, r * query * b, r * intermediate * b, r * intermediate * b, r * intermediate * b, (r - 1) * 201024 * b, 4 * a * hidden * b, a * kv * b, a * kv * b, (r - 1) * 3 * rank * 4, - rank * b, rank * b, rank * b, rank * b, vocabulary * b, + rank * b, rank * b, 3 * rank * b, rank * b, vocabulary * b, }; } From 191b7e861b5debbff92badbcc442a7097d54e6a9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:08:13 +0000 Subject: [PATCH 196/361] changelog: #4447 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d94754eb619..cffcb7dffa3 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 +- Inkling 2 Mini on Metal: DSpark drafting uses the 1/sqrt(128) attention scale and reads the recurrent step's kappa as FP32, so one-stream draft acceptance on an M3 Ultra rises from 3% to 55% and drafted decode is about 56% faster; replies are unchanged (#4447). Thanks @sethforprivacy. + - Hy4-flash: a host weight map for its ModelOpt NVFP4 build (groups of 16, no KV quantization), with the build's recipe and quality notes; serving it comes in later slices (#4110). Thanks @atakann. - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. From 68653c270b70c37edce5e2d1eb255959a6a46ff2 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:08:13 +0000 Subject: [PATCH 197/361] changelog: #4447 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cffcb7dffa3..6c9549a0270 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on Metal: DSpark drafting uses the 1/sqrt(128) attention scale and reads the recurrent step's kappa as FP32, so one-stream draft acceptance on an M3 Ultra rises from 3% to 55% and drafted decode is about 56% faster; replies are unchanged (#4447). Thanks @sethforprivacy. + + - Hy4-flash: a host weight map for its ModelOpt NVFP4 build (groups of 16, no KV quantization), with the build's recipe and quality notes; serving it comes in later slices (#4110). Thanks @atakann. - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. From 9719d035cb23b58d7bf54828347c1750f2081f55 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:18:57 +0100 Subject: [PATCH 198/361] perf(lanes): the host GPU-rule sampler keeps the best 1,024 candidates in a bounded heap, not a full sort - gpu_rule.sample and gpu_full.plan sorted every scaled logit of the row to read at most 1,024 of them; on a 201,058-token vocabulary the sort is 15 ms of a draw that takes 0.11 ms without it. - rule.topCands keeps the first n entries of better's total (key, id) order in a heap with an early reject and sorts those n, so the prefix, the row maximum and every draw are the full sort's bit for bit; the row-order normalizer is summed only when top_k is off, and a top_k above 1,024 still sorts the row for its kth candidate. - gpu_top_test.zig compares the prefix, the maximum, the normalizer, the plan and the draws with a full-sort reference on 12 kinds of row (ties, signed zeros, NaN, infinities, extremes, ramps), 4 temperatures and 9 top_k, top_p and min_p rules. --- CHANGELOG.md | 2 + zig/src/core/lanes/gpu_full.zig | 26 ++-- zig/src/core/lanes/gpu_rule.zig | 68 +++++++--- zig/src/core/lanes/gpu_top_test.zig | 187 ++++++++++++++++++++++++++++ zig/src/core/lanes/lanes.zig | 1 + 5 files changed, 260 insertions(+), 24 deletions(-) create mode 100644 zig/src/core/lanes/gpu_top_test.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c9549a0270..c95ddc7069a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -210,6 +210,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen 3.5 and 3.8: one EOS rule for every family reader, and qwen27 now reads `generation_config.json`, so its stop tokens match the served set on the ten configs that declare `<|im_end|>` (#4678). Thanks @devopsfortunato. +- Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured. + - Nemotron on CUDA: `TF_NEMOTRON_WIDE_ROUNDS=1` (opt-in) runs decode rounds of up to 16 streams; +2% to +6% at 16 streams on a GB10, tokens unchanged; off changes nothing. - macOS: the native server links `memcpy` from libSystem again (Hy4-flash config parsing no longer pulls in compiler-rt), and two macOS-only tests match current behaviour. diff --git a/zig/src/core/lanes/gpu_full.zig b/zig/src/core/lanes/gpu_full.zig index ad743fcaa9b..2aef0561ef2 100644 --- a/zig/src/core/lanes/gpu_full.zig +++ b/zig/src/core/lanes/gpu_full.zig @@ -62,24 +62,30 @@ fn markOf(c: rule.Cand) Mark { pub fn plan(gpa: Allocator, logits: []const f32, s: Sampling) !Plan { const r = rule.rule(s); const inv_t = r.inv_t; - const order = try gpa.alloc(rule.Cand, logits.len); - defer gpa.free(order); - var m = -std.math.inf(f32); - for (order, logits, 0..) |*c, l, i| { - c.* = .{ .v = l * inv_t, .i = @intCast(i) }; - m = @max(m, c.v); - } - std.mem.sort(rule.Cand, order, {}, rule.better); + var head: [rule.candidates]rule.Cand = undefined; // the order's first 1,024: the nucleus and any top_k within them + const order = head[0..@min(logits.len, rule.candidates)]; + const m = rule.topCands(logits, inv_t, order); const min_log = r.min_log; var p = Plan{ .inv_t = inv_t, .m = m, .lo = @max(m + min_log, m - never) }; - if (s.top_k != 0 and s.top_k < logits.len) p.top = markOf(order[s.top_k - 1]); + if (s.top_k != 0 and s.top_k < logits.len) { + p.top = markOf(if (s.top_k <= order.len) order[s.top_k - 1] else try kth(gpa, logits, inv_t, s.top_k)); + } const top_p = r.top_p; if (top_p > 0.0 and top_p < 1.0) p.cut = nucleus(logits, p, order, top_p); return p; } +/// The order's `k`th candidate, 1-based, by a full sort: a top_k past the 1,024 kept candidates is rare. +fn kth(gpa: Allocator, logits: []const f32, inv_t: f32, k: u32) !rule.Cand { + const order = try gpa.alloc(rule.Cand, logits.len); + defer gpa.free(order); + for (order, logits, 0..) |*c, l, i| c.* = .{ .v = l * inv_t, .i = @intCast(i) }; + std.mem.sort(rule.Cand, order, {}, rule.better); + return order[k - 1]; +} + /// The nucleus's last token: tf_gpu_sample's sequential sum over its 1,024 candidates, extended when it falls short. -fn nucleus(logits: []const f32, p: Plan, order: []const rule.Cand, top_p: f32) Mark { +pub fn nucleus(logits: []const f32, p: Plan, order: []const rule.Cand, top_p: f32) Mark { const norm = mass(logits, p, 1.0, -std.math.inf(f32), start, p.top, end, false); const n = @min(order.len, rule.candidates); var cum: f32 = 0.0; diff --git a/zig/src/core/lanes/gpu_rule.zig b/zig/src/core/lanes/gpu_rule.zig index ac556643727..7f5e545dfd4 100644 --- a/zig/src/core/lanes/gpu_rule.zig +++ b/zig/src/core/lanes/gpu_rule.zig @@ -65,6 +65,47 @@ pub fn better(_: void, a: Cand, b: Cand) bool { return ka > kb or (ka == kb and a.i < b.i); } +/// Moves the node at `at` below any child it is better than, so a heap's root is its worst candidate. +fn sink(heap: []Cand, at: usize) void { + var i = at; + while (2 * i + 1 < heap.len) { + var w = 2 * i + 1; + if (w + 1 < heap.len and better({}, heap[w], heap[w + 1])) w += 1; + if (!better({}, heap[i], heap[w])) return; + std.mem.swap(Cand, &heap[i], &heap[w]); + i = w; + } +} + +/// Fills `out` (1 to `logits.len` long) with the sorted head of `better`'s order over `logits * inv_t`; returns max. +pub fn topCands(logits: []const f32, inv_t: f32, out: []Cand) f32 { + const n = out.len; + var m = -std.math.inf(f32); + for (out, logits[0..n], 0..) |*c, l, i| { + c.* = .{ .v = l * inv_t, .i = @intCast(i) }; + m = @max(m, c.v); + } + if (n < logits.len) { + var at = n / 2; + while (at > 0) { + at -= 1; + sink(out, at); + } + var floor = key(out[0].v); + for (logits[n..], n..) |l, i| { + const v = l * inv_t; + m = @max(m, v); + // an equal key has a later id than every kept one, so it ranks below the root + if (key(v) <= floor) continue; + out[0] = .{ .v = v, .i = @intCast(i) }; + sink(out, 0); + floor = key(out[0].v); + } + } + std.mem.sort(Cand, out, {}, better); + return m; +} + /// One row's draw under the kernel's rule; `ids` maps columns to token ids (a draft head's subset vocabulary). pub fn sample(gpa: Allocator, logits: []const f32, s: ?Sampling, position: u32, ids: ?[]const u32) !u32 { const st = s orelse { @@ -77,20 +118,16 @@ pub fn sample(gpa: Allocator, logits: []const f32, s: ?Sampling, position: u32, const min_log = r.min_log; const kc = r.top_k; const cap: usize = if (kc == 0 or kc > candidates) candidates else kc; - const all = try gpa.alloc(Cand, logits.len); + const n: usize = @min(@min(logits.len, candidates), cap); + const all = try gpa.alloc(Cand, n); defer gpa.free(all); - var m = -std.math.inf(f32); - for (all, logits, 0..) |*c, l, i| { - c.* = .{ .v = l * inv_t, .i = @intCast(i) }; - m = @max(m, c.v); - } - const z = threadSum(all, m); - std.mem.sort(Cand, all, {}, better); - const n: usize = @min(@min(all.len, candidates), cap); - var norm = z; - if (kc != 0) { + const m = topCands(logits, inv_t, all); + var norm: f32 = undefined; + if (kc == 0) { + norm = threadSum(logits, inv_t, m); // every token's mass, in row order: the sort never touches it + } else { norm = 0.0; - for (all[0..n]) |c| norm += @exp(c.v - m); + for (all) |c| norm += @exp(c.v - m); } var keep: usize = n; if (top_p > 0.0 and top_p < 1.0) { @@ -124,9 +161,12 @@ pub fn sample(gpa: Allocator, logits: []const f32, s: ?Sampling, position: u32, } /// The row's normalizer in the kernel's order: 1024 strided thread sums, a 32-lane butterfly, simdgroups in order. -fn threadSum(all: []const Cand, m: f32) f32 { +pub fn threadSum(logits: []const f32, inv_t: f32, m: f32) f32 { var lanes: [1024]f32 = @splat(0.0); - for (all, 0..) |c, i| lanes[i % 1024] += @exp(c.v - m); + for (logits, 0..) |l, i| { + const v = l * inv_t; + lanes[i % 1024] += @exp(v - m); + } return lanesSum(&lanes); } diff --git a/zig/src/core/lanes/gpu_top_test.zig b/zig/src/core/lanes/gpu_top_test.zig new file mode 100644 index 00000000000..f378e7cb2bb --- /dev/null +++ b/zig/src/core/lanes/gpu_top_test.zig @@ -0,0 +1,187 @@ +//! rule.topCands, rule.sample and full.plan against a reference that sorts the whole row, bit for bit. +const std = @import("std"); +const full = @import("gpu_full.zig"); +const rule = @import("gpu_rule.zig"); +const Sampling = @import("sampling.zig").Sampling; + +const a = std.testing.allocator; +const inf = std.math.inf(f32); +const nan = std.math.nan(f32); + +/// The whole row scaled and sorted: the reference every selection must equal. +fn sortedRow(logits: []const f32, inv_t: f32, max: *f32) ![]rule.Cand { + const order = try a.alloc(rule.Cand, logits.len); + var m = -inf; + for (order, logits, 0..) |*c, l, i| { + c.* = .{ .v = l * inv_t, .i = @intCast(i) }; + m = @max(m, c.v); + } + std.mem.sort(rule.Cand, order, {}, rule.better); + max.* = m; + return order; +} + +/// The row's normalizer as threadSum summed it: the scaled candidates in row order. +fn lanesNorm(logits: []const f32, inv_t: f32, m: f32) f32 { + var lanes: [1024]f32 = @splat(0.0); + for (logits, 0..) |l, i| { + const c: rule.Cand = .{ .v = l * inv_t, .i = @intCast(i) }; + lanes[i % 1024] += @exp(c.v - m); + } + return rule.lanesSum(&lanes); +} + +/// rule.sample over a full sort: the sum of every token's mass is taken in row order, the rest reads the sorted row. +fn fullSortSample(logits: []const f32, st: Sampling, position: u32) !u32 { + const r = rule.rule(st); + var m: f32 = undefined; + const all = try sortedRow(logits, r.inv_t, &m); + defer a.free(all); + const cap: usize = if (r.top_k == 0 or r.top_k > rule.candidates) rule.candidates else r.top_k; + const n: usize = @min(@min(all.len, rule.candidates), cap); + var norm = lanesNorm(logits, r.inv_t, m); + if (r.top_k != 0) { + norm = 0.0; + for (all[0..n]) |c| norm += @exp(c.v - m); + } + var keep: usize = n; + if (r.top_p > 0.0 and r.top_p < 1.0) { + var cum: f32 = 0.0; + for (all[0..n], 0..) |c, j| { + cum += @exp(c.v - m) / norm; + if (cum >= r.top_p) { + keep = j + 1; + break; + } + } + } + if (r.min_log > -inf) { + var j: usize = 0; + while (j < keep and all[j].v >= m + r.min_log) j += 1; + keep = j; + } + var best: usize = 0; + var best_score = -inf; + for (all[0..keep], 0..) |c, t| { + const score = c.v - @log(-@log(rule.uniform24(st.seed, position, c.i))); + if (t == 0 or score > best_score) { + best = t; + best_score = score; + } + } + return all[best].i; +} + +/// full.plan over a full sort. +fn fullSortPlan(logits: []const f32, s: Sampling) !full.Plan { + const r = rule.rule(s); + var m: f32 = undefined; + const order = try sortedRow(logits, r.inv_t, &m); + defer a.free(order); + var p = full.Plan{ .inv_t = r.inv_t, .m = m, .lo = @max(m + r.min_log, m - full.never) }; + if (s.top_k != 0 and s.top_k < logits.len) p.top = .{ .key = rule.key(order[s.top_k - 1].v), .id = order[s.top_k - 1].i }; + if (r.top_p > 0.0 and r.top_p < 1.0) p.cut = full.nucleus(logits, p, order, r.top_p); + return p; +} + +const kinds = 12; + +/// A row of 12 kinds: Gaussian, tied, equal, signed zeros, -inf, +inf, NaN, extremes, ramps, all -inf, plateaus. +fn fill(row: []f32, kind: usize, prng: *std.Random.DefaultPrng) void { + const rnd = prng.random(); + for (row, 0..) |*x, i| { + const g: f32 = @floatCast(rnd.floatNorm(f64) * 3.0); + const n: f32 = @floatFromInt(row.len); + const at: f32 = @floatFromInt(i); + x.* = switch (kind) { + 0 => g, + 1 => @round(g) * 0.5, + 2 => 1.25, + 3 => if (i % 2 == 0) 0.0 else -0.0, + 4 => if (rnd.uintLessThan(u8, 3) == 0) -inf else g, + 5 => if (rnd.uintLessThan(u8, 40) == 0) inf else g, + 6 => if (rnd.uintLessThan(u8, 30) == 0) (if (rnd.boolean()) nan else -nan) else g, + 7 => switch (rnd.uintLessThan(u8, 5)) { + 0 => 1e30, + 1 => -1e30, + 2 => 1e-30, + 3 => 1.0e-42, + else => g, + }, + 8 => at / n * 20.0, + 9 => (n - at) / n * 20.0, + 10 => -inf, + else => -@floor(at / 7.0) * 0.001, + }; + } +} + +const temperatures = [_]f64{ 0.7, 1.0, 1e-9, 1e3 }; +const settings = [_]struct { k: u32, p: f64, min: f64 }{ + .{ .k = 20, .p = 0.95, .min = 0 }, + .{ .k = 0, .p = 1.0, .min = 0 }, + .{ .k = 0, .p = 0.9, .min = 0 }, + .{ .k = 1, .p = 1.0, .min = 0 }, + .{ .k = 1024, .p = 0.9, .min = 0.05 }, + .{ .k = 1500, .p = 0.95, .min = 0 }, + .{ .k = 3000, .p = 0.5, .min = 0 }, + .{ .k = 50, .p = 1.0, .min = 0.02 }, + .{ .k = 7, .p = 0.0, .min = 0.9 }, +}; + +fn bitsEqual(x: anytype, y: @TypeOf(x)) bool { + return std.mem.eql(u8, std.mem.asBytes(&x), std.mem.asBytes(&y)); +} + +test "top leaves the full sort's prefix and maximum, bit for bit, on every kind of row" { + var prng = std.Random.DefaultPrng.init(4337); + var row: [3000]f32 = undefined; + for ([_]usize{ 1, 2, 5, 63, 1024, 1025, 3000 }) |len| for (0..kinds) |kind| for ([_]f32{ 1.0 / 0.7, 1e6, 0.001 }) |inv_t| { + fill(row[0..len], kind, &prng); + var m: f32 = undefined; + const want = try sortedRow(row[0..len], inv_t, &m); + defer a.free(want); + for ([_]usize{ 1, 2, 20, 1000, 1024, len }) |n| { + if (n > len) continue; + const got = try a.alloc(rule.Cand, n); + defer a.free(got); + const top_m = rule.topCands(row[0..len], inv_t, got); + try std.testing.expect(bitsEqual(m, top_m)); + try std.testing.expect(bitsEqual(lanesNorm(row[0..len], inv_t, m), rule.threadSum(row[0..len], inv_t, top_m))); + for (got, want[0..n]) |g, w| try std.testing.expect(bitsEqual(g, w)); + } + }; +} + +test "sample and plan draw as the full sort does, on adversarial rows and every sampling rule" { + var prng = std.Random.DefaultPrng.init(1234); + var row: [3000]f32 = undefined; + for ([_]usize{ 7, 1025, 3000 }) |len| for (0..kinds) |kind| { + fill(row[0..len], kind, &prng); + for (temperatures) |t| for (settings) |cfg| { + const s: Sampling = .{ .seed = 99 + kind, .temperature = t, .top_k = cfg.k, .top_p = cfg.p, .min_p = cfg.min }; + const want_plan = try fullSortPlan(row[0..len], s); + try std.testing.expect(bitsEqual(want_plan, try full.plan(a, row[0..len], s))); + for ([_]u32{ 0, 17, 66903620 }) |position| { + if (cfg.k <= rule.candidates) { + try std.testing.expectEqual(try fullSortSample(row[0..len], s, position), try rule.sample(a, row[0..len], s, position, null)); + } + try std.testing.expectEqual(full.race(row[0..len], want_plan, s.seed, position, null), try full.sample(a, row[0..len], s, position, null)); + } + }; + }; +} + +test "a vocabulary-sized row draws as its full sort does" { + var prng = std.Random.DefaultPrng.init(201058); + const row = try a.alloc(f32, 201058); + defer a.free(row); + for ([_]usize{ 0, 1, 8 }) |kind| { + fill(row, kind, &prng); + for (settings[0..5]) |cfg| { + const s: Sampling = .{ .seed = 7, .temperature = 0.7, .top_k = cfg.k, .top_p = cfg.p, .min_p = cfg.min }; + try std.testing.expect(bitsEqual(try fullSortPlan(row, s), try full.plan(a, row, s))); + if (cfg.k <= rule.candidates) try std.testing.expectEqual(try fullSortSample(row, s, 3), try rule.sample(a, row, s, 3, null)); + } + } +} diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index 2bed7691557..2828001c35f 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -83,6 +83,7 @@ test { _ = @import("recorder_test.zig"); _ = @import("gpu_full_test.zig"); _ = @import("gpu_launch_test.zig"); + _ = @import("gpu_top_test.zig"); _ = @import("drafted_test.zig"); _ = @import("drafter_depth_sweep_test.zig"); _ = @import("drafted_chances_test.zig"); From af3e22614566ff5c71eaf521dbf2bf0a9954acf4 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:07:52 +0100 Subject: [PATCH 199/361] changelog: name #4744 on the sampler bullet --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c95ddc7069a..8feffca83df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -210,7 +210,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen 3.5 and 3.8: one EOS rule for every family reader, and qwen27 now reads `generation_config.json`, so its stop tokens match the served set on the ten configs that declare `<|im_end|>` (#4678). Thanks @devopsfortunato. -- Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured. +- Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured (#4744). - Nemotron on CUDA: `TF_NEMOTRON_WIDE_ROUNDS=1` (opt-in) runs decode rounds of up to 16 streams; +2% to +6% at 16 streams on a GB10, tokens unchanged; off changes nothing. From b1bb795a8d127e4959e68d10afef693f8ccc2cad Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:08:14 +0000 Subject: [PATCH 200/361] changelog: #4744's line from lines/4744.txt in place of its own --- CHANGELOG.md | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8feffca83df..cca871bb5df 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 +- Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured (#4744). + - Inkling 2 Mini on Metal: DSpark drafting uses the 1/sqrt(128) attention scale and reads the recurrent step's kappa as FP32, so one-stream draft acceptance on an M3 Ultra rises from 3% to 55% and drafted decode is about 56% faster; replies are unchanged (#4447). Thanks @sethforprivacy. @@ -18,8 +20,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. - - - Flash Next on CUDA: the fused read-out is now the default, making prompt processing about 3-5% faster on GB10 with identical tokens; `TF_FLASHNEXT_READOUT_FUSED=0` keeps the old path (#4799). Thanks @BadAd84. - Ripple-65B-Preview on Metal: `--drafter` takes the publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) beside either release, with drafted replies equal to plain ones; with the drafter the server opens two streams unless `--parallel` is named, and refuses a named `--parallel` above 2 (#2260, fixes #2259). Thanks to @BobClawblaw. @@ -28,14 +28,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on CUDA: the loop gate runs as a down half and an up half, so one-stream decode is about 28% faster on GB10 with identical tokens (#4697). Thanks @jschmied. - - - 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). @@ -54,14 +50,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. - - - 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. @@ -210,8 +202,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen 3.5 and 3.8: one EOS rule for every family reader, and qwen27 now reads `generation_config.json`, so its stop tokens match the served set on the ten configs that declare `<|im_end|>` (#4678). Thanks @devopsfortunato. -- Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured (#4744). - - Nemotron on CUDA: `TF_NEMOTRON_WIDE_ROUNDS=1` (opt-in) runs decode rounds of up to 16 streams; +2% to +6% at 16 streams on a GB10, tokens unchanged; off changes nothing. - macOS: the native server links `memcpy` from libSystem again (Hy4-flash config parsing no longer pulls in compiler-rt), and two macOS-only tests match current behaviour. From 2731472dced6f92b83504ac95d163404f90156f6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:54:23 +0000 Subject: [PATCH 201/361] tools tests: the serialized-stream bench_prose case keeps a gap a busy CI host cannot close --- tools/tests/test_bench_prose.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/tests/test_bench_prose.py b/tools/tests/test_bench_prose.py index 29c10966c38..09738e59c17 100644 --- a/tools/tests/test_bench_prose.py +++ b/tools/tests/test_bench_prose.py @@ -353,6 +353,9 @@ def do_POST(self): ], done=True) self.wfile.write(c2) self.wfile.flush() + # Keep the lock past the last write, so the client's own scheduling delay on a busy host cannot + # stamp this stream's last token after the next stream's first one and read it as an overlap. + time.sleep(0.25) srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SerialHandler) th = threading.Thread(target=srv.serve_forever, daemon=True) From 220bf2d95965f725aae335ad37b518181ad222fb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:06:26 +0000 Subject: [PATCH 202/361] tools tests: the overlapping-stream bench_prose case holds both streams open past the barrier --- tools/tests/test_bench_prose.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/tests/test_bench_prose.py b/tools/tests/test_bench_prose.py index 09738e59c17..988028dcc2d 100644 --- a/tools/tests/test_bench_prose.py +++ b/tools/tests/test_bench_prose.py @@ -120,6 +120,9 @@ def do_POST(self): self.wfile.write(sse_bytes([{"choices": [{"index": 0, "delta": {"content": "part1 "}}]}], done=False)) self.wfile.flush() barrier.wait(timeout=5) + # Both streams are past their first token here; hold before the last one so the client's own + # scheduling delay on a busy host cannot stamp one stream's end before the other's start. + time.sleep(0.25) self.wfile.write(sse_bytes([ {"choices": [{"index": 0, "delta": {"content": "part2"}, "finish_reason": "stop"}]}, {"choices": [], "usage": {"prompt_tokens": 40, "completion_tokens": 4, "prompt_tokens_details": {"cached_tokens": 0}}, From 7ea9ec2ecdc0cdac4fc37c8dfebf672002c17503 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:31:30 +0000 Subject: [PATCH 203/361] changelog: #4930's line from lines/4930.txt in place of its own --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cca871bb5df..dca647c903d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,18 +4,16 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930). + - Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured (#4744). - Inkling 2 Mini on Metal: DSpark drafting uses the 1/sqrt(128) attention scale and reads the recurrent step's kappa as FP32, so one-stream draft acceptance on an M3 Ultra rises from 3% to 55% and drafted decode is about 56% faster; replies are unchanged (#4447). Thanks @sethforprivacy. - - - Hy4-flash: a host weight map for its ModelOpt NVFP4 build (groups of 16, no KV quantization), with the build's recipe and quality notes; serving it comes in later slices (#4110). Thanks @atakann. - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. - - - Inkling 2 Mini on CUDA: expert weights are staged a warp at a time in 128-byte rows with each expert's NVFP4 factor read once, so one-stream decode is about 70% faster on GB10, four streams about 60% faster and long prompts reach the first token about 25% sooner, with identical tokens (#4728). Thanks @jschmied. - MiniMax-H3-Image on CUDA: `tf-h3-image-prompt-cuda` runs the prompt path (Qwen3-VL to layer 50 and the token refiner) and `tf-h3-image-decoder-cuda` the image decoder, each writing the file its Metal sibling writes and carrying a self-test against the host's float64 reference (#3733). Thanks to @plotarmordev. From 0566962470c4ea3c7c23f7703af3a0157be1df8f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:42:39 +0000 Subject: [PATCH 204/361] qwen3_8 cuda: dependent launches by default on sm_12x GPUs TF_QWEN_PDL launches Qwen3.8's ModelOpt qmmf lanes and its glue kernels as programmatic dependent launches, and it was opt-in. Unset, it is now on for sm_12x GPUs (GB10, RTX 50 series) and off on every other GPU, Hopper included. 1 turns it on for any sm_90 or newer GPU, as before, and 0 turns it off everywhere. Only the launch attribute changes. Each glue kernel waits for the kernel before it in qwen_pdl::enter(), and the qmmf lanes wait after their weight loads, so every kernel reads the same inputs and tokens keep their bits. The switch is still read once. Since its default now depends on the GPU, the profile line reports an explicit 0 or 1 on any GPU. docs/environment.md gains the switch's row, and the "default off" comments go. A new step, test-qwen-pdl-policy-host, runs the policy tests, which no host step ran before. --- docs/environment.md | 1 + zig/build/cuda_family_host.zig | 1 + zig/dense_serving_test.zig | 4 +- zig/src/core/profile.zig | 2 +- zig/src/families/qwen3_5/cuda_engine.zig | 2 +- zig/src/families/qwen3_5/cuda_pdl.zig | 62 ++++++++++++++++++------ 6 files changed, 54 insertions(+), 18 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 3ecd467dbf6..cf54364e7b6 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -62,6 +62,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_HEAD_GEOMETRY` | Whole native-size nonnegative geometry count in the head benchmark | | `TF_ROCE_GID_INDEX` | Whole index 0 through 2147483647; unset searches for a RoCE v2 IPv4 GID | | `TF_QWEN35_ATTN_ALL_ROWS` | Qwen3.8 on CUDA: exactly `0` or `1`; unset, empty or `0` keeps the current BF16 decode attention launches. `1` uses the existing rows kernel at every context length and skips the separate partial launch for decode windows wider than one row. The kernel contract compares output bytes against the original dual-launch path | +| `TF_QWEN_PDL` | Qwen3.8 on CUDA: exactly `0` or `1`, read once. Unset, the ModelOpt qmmf lanes and the glue kernels launch as programmatic dependent launches on sm_12x GPUs (GB10, RTX 50 series) and plainly on every other GPU; `1` makes them dependent on any sm_90 or newer GPU, `0` makes them plain everywhere. A dependent launch lets a kernel begin (the qmmf lanes load their weights) while the one before it finishes, and it waits for that kernel's output before reading it, so tokens keep their bits | | `TF_QWEN35_CHUNK_SOLO` | Qwen 3.5/3.6/3.8 on CUDA: 4096 or 8192 rows a foreground prompt pass while no other stream decodes (a background warm pass keeps 4096); unset, empty or 4096 is off, with main's scratch. Checked when the model loads, with the family's own message | | `TF_GEMMA4_CHUNK_SOLO` | Gemma 4 on CUDA: a multiple of 512 from 512 through 4096; unset, empty or 512 is off. Checked when the model loads, with the family's own message | | `TF_GEMMA4_ARGMAX_GRAPH` | Gemma 4 on CUDA: exactly `0` or `1`; default off. `1` captures a greedy verify round's argmax (the same `tf_round_bf16_argmax` over the same logits) in the target forward's graph, skips the drawn-token download no greedy entry reads, and stages each forward's ids, positions and slots in pinned memory; target tokens keep their bits | diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 8cc3905a63d..4210cabcc7b 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -26,6 +26,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B step.dependOn(&wiring.step); b.step("test-qwen35-request-starts-host", "Request-start and shared-KV startup refusal without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"request starts:"} })).step); + b.step("test-qwen-pdl-policy-host", "Qwen3.8 PDL environment and compute-capability launch policy without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "Qwen PDL policy:", "a Qwen launch keeps", "TF_QWEN_PDL changes only" } })).step); b.step("test-memory-pressure-host", "Shared memory-pressure governor, admission and cache shedding without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.api, .filters = &.{"memory pressure:"} })).step); b.step("test-qwen35-shapes-host", "Captured window buckets for one and 2-8 rows, and the MT2 envelope, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "one-row and 2-8-row", "MT2 dispatch" } })).step); @import("minimax_cuda.zig").hostTests(b, host, cuda, mods.core, mods.lanes, step); diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index 980556f25f3..a847b354f82 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -18,7 +18,7 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group)); // #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel. try std.testing.expectEqualStrings("e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6", &hash(@embedFile("kernels/cuda/qmm_prefill.cu"))); - // KIA14 adds all_rows (false keeps selection/arithmetic); #4706 adds default-off TF_QWEN_PDL prologues + // KIA14 adds all_rows (false keeps selection/arithmetic); #4706 adds TF_QWEN_PDL prologues try std.testing.expectEqualStrings("79e97b0992f82e891ff8a80cdad68b534e07606b98feef3dffe25101477c99e1", &hash(@embedFile("kernels/cuda/qwen35.cu"))); // #1879's bytes: a comment names cuda_scratch.zig, where max_chunks moved; the code is unchanged try std.testing.expectEqualStrings("f9e4a040cf219aac8db211df25d264dba390fce4a7e8da45557652c6ff0f28ba", &hash(@embedFile("kernels/cuda/qwen35.cuh"))); @@ -51,6 +51,6 @@ test "dense serving: owned launches and projections retain their reviewed argume try out.append(std.testing.allocator, c); }; } - // main's moved delta scan and MTP's retained-row tap argument stay; #4706 adds TF_QWEN_PDL glue (default off) + // main's moved delta scan and MTP's retained-row tap argument stay; #4706 adds TF_QWEN_PDL glue try std.testing.expectEqualStrings("2822d47ae041b6d7051e39209bd389cb5e4f01520efee64838c1c0e0e5428b75", &hash(out.items)); } diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 12b4c9eb7fc..6906101c219 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -151,7 +151,7 @@ pub const entries = [_]Entry{ .{ .id = .TF_CUDA_POOL_AFTER_WARMUP, .families = &.{"qwen3_5"}, .class = .experimental, .syntax = .one, .report_values = &.{"1"}, .effect = "Size an idle device KV pool after Qwen DFlash2 warm-up", .evidence = "Default off; host sizing checks; device capacity and token checks required" }, .{ .id = .TF_CACHE_EVICT, .families = cuda_cache, .backend = "multiple", .scopes = &.{ .{ .backend = "cuda", .families = cuda_cache }, .{ .backend = "metal", .families = &.{ "nemotron_h", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "glm5_next", "glm_moe_dsa", "minimax_m3_vl", "gemma4", "gemma4_unified", "spark2_5", "llama", "lfm2_moe", "lfm3", "lfm3_vl", "step5_vl", "kimi_k3", "kimi_k31" } }, .{ .backend = "xpu", .families = &.{ "nemotron_h", "lfm3", "qwen3_5", "gemma4" } } }, .class = .experimental, .syntax = .present, .report_values = &.{"decayed_resume"}, .effect = "Opt into bounded resume credit for RAM snapshot eviction", .evidence = "#3241; synthetic host rows gate; default main unchanged" }, .{ .id = .TF_QWEN_REQUEST_STARTS, .families = qwen, .class = .arithmetic, .syntax = .one, .effect = "Opt into CUDA message-start prompt cuts", .evidence = "#1334; default-off; GB10 six-turn: resumed equals fresh, one reply differs from unset" }, - .{ .id = .TF_QWEN_PDL, .families = qwen, .backend = "cuda", .class = .identical, .syntax = .one, .effect = "Opt into programmatic dependent launches on Qwen3.8's qmmf lanes and glue", .evidence = "REV26; default-off; SASS gate and byte-identical contract cells" }, + .{ .id = .TF_QWEN_PDL, .families = qwen, .backend = "cuda", .class = .identical, .syntax = .one, .report_values = &.{ "0", "1" }, .effect = "Programmatic dependent launches on Qwen3.8's qmmf lanes and glue: unset, on for sm_12x alone; 0 off, 1 on from sm_90", .evidence = "REV26; SASS gate and byte-identical contract cells; #4706: GB10 tokens unchanged" }, .{ .id = .TF_GLM_REQUEST_STARTS, .families = &.{"glm5_next"}, .class = .arithmetic, .syntax = .one, .effect = "Opt into CUDA message-start prompt cuts", .evidence = "#2396; default-off; GB10 TP=2 receipts in #2404" }, .{ .id = .TF_QWEN_KV_PAGES, .families = qwen, .class = .identical, .effect = "KV pool page size; memory and workload tradeoffs", .evidence = "#1357" }, .{ .id = .TF_QWEN_KV_PAGES_ALL, .families = qwen, .class = .debug, .syntax = .one, .effect = "Put the engine's own stream on pages too", .evidence = "#1357" }, diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 30dbe7b7619..201eae4af22 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -393,7 +393,7 @@ pub const Engine = struct { try cuda.launch.launch(f, cfg, e.stream, &a); } - /// A glue kernel with a qwen_pdl::enter() prologue: dependent under TF_QWEN_PDL, plain by default. + /// A glue kernel with a qwen_pdl::enter() prologue: dependent as cuda_pdl.zig decides, plain otherwise. pub fn runPdl(e: *Engine, f: cuda.Function, grid: [3]usize, block: [3]usize, args: anytype) !void { if (@import("cuda_launch_trace.zig").active) |t| return t.note(.{ .launch = if (f.handle) |h| @intFromPtr(h) else 0 }); var a: cuda.Args = .{}; diff --git a/zig/src/families/qwen3_5/cuda_pdl.zig b/zig/src/families/qwen3_5/cuda_pdl.zig index ebedfcbace3..9d6678d657a 100644 --- a/zig/src/families/qwen3_5/cuda_pdl.zig +++ b/zig/src/families/qwen3_5/cuda_pdl.zig @@ -1,12 +1,14 @@ -//! Qwen3.8's launches as dependent launches (TF_QWEN_PDL, default off): the glue kernels open with qwen_pdl::enter(). +//! Qwen3.8's launches as dependent launches (TF_QWEN_PDL, unset: on for sm_12x): glue opens with qwen_pdl::enter(). const std = @import("std"); const cuda = @import("cuda"); -var state: std.atomic.Value(u8) = .init(0); // 0 unread, 1 off, 2 on +var state: std.atomic.Value(u8) = .init(0); // 0 unread, 1 off, 2 on, 3 unset (the bound GPU's default) var supported: std.atomic.Value(bool) = .init(true); +var by_default: std.atomic.Value(bool) = .init(false); // sm_12x (GB10, RTX 50): unset launches dependent fn bindMajor(major: c_int) void { supported.store(major >= 9, .release); + by_default.store(major == 12, .release); } /// Bind the process-wide launch policy to a context before loading any Qwen modules. @@ -14,13 +16,19 @@ pub fn bind(ctx: *const cuda.Context) !void { bindMajor(try ctx.attribute(.compute_capability_major)); } -/// TF_QWEN_PDL, read once: exact 0 launches Qwen's kernels plain (the environment refuses malformed values at startup). +/// TF_QWEN_PDL, read once: 0 launches Qwen's kernels plain, 1 dependent from sm_90, unset dependent on sm_12x alone. pub fn on() bool { - const v = state.load(.monotonic); - if (v != 0) return v == 2 and supported.load(.acquire); - const want = @import("sys").environment.value(bool, "TF_QWEN_PDL", @import("profile").lookup("TF_QWEN_PDL"), false) catch false; - state.store(if (want) 2 else 1, .monotonic); - return want and supported.load(.acquire); + var v = state.load(.monotonic); + if (v == 0) { + const set = @import("sys").environment.value(?bool, "TF_QWEN_PDL", @import("profile").lookup("TF_QWEN_PDL"), null) catch false; + v = if (set) |want| (if (want) 2 else 1) else 3; + state.store(v, .monotonic); + } + return switch (v) { + 2 => supported.load(.acquire), + 3 => by_default.load(.acquire), + else => false, + }; } /// `cfg` as a Qwen launch makes it: dependent when `pdl`. @@ -47,18 +55,44 @@ test "a Qwen launch keeps its config and sets only pdl" { try std.testing.expect(!config(c, false).pdl); } -test "Qwen PDL policy: default off, pre-sm90 devices disable it, sm90 retains an explicit on" { - state.store(2, .monotonic); - supported.store(true, .release); +test "Qwen PDL policy: unset is on for sm_12x alone, 1 from sm_90, 0 always off" { defer { state.store(0, .monotonic); supported.store(true, .release); + by_default.store(false, .release); + } + state.store(3, .monotonic); + for ([_]c_int{ 7, 8, 9, 10, 11, 13 }) |major| { + bindMajor(major); + try std.testing.expect(!on()); } + bindMajor(12); + try std.testing.expect(on()); + state.store(2, .monotonic); bindMajor(8); try std.testing.expect(!on()); - supported.store(true, .release); - bindMajor(9); - try std.testing.expect(on()); + for ([_]c_int{ 9, 10, 12 }) |major| { + bindMajor(major); + try std.testing.expect(on()); + } state.store(1, .monotonic); + for ([_]c_int{ 8, 9, 12 }) |major| { + bindMajor(major); + try std.testing.expect(!on()); + } +} + +test "Qwen PDL policy: the switch read once, unset taking the bound GPU's default" { + defer { + state.store(0, .monotonic); + supported.store(true, .release); + by_default.store(false, .release); + } + state.store(0, .monotonic); + if (@import("profile").lookup("TF_QWEN_PDL") != null) return error.SkipZigTest; // the test's own environment set it + bindMajor(12); + try std.testing.expect(on()); + try std.testing.expectEqual(@as(u8, 3), state.load(.monotonic)); + bindMajor(9); try std.testing.expect(!on()); } From c9abcf9859cdf109957fa7453d7e428d4e54bc12 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:03:30 +0000 Subject: [PATCH 205/361] changelog: qwen3_8 cuda: dependent launches by default on sm_12x GPUs --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index dca647c903d..a38d945270c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,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. - 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). +- Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). - 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. From 3942d6865ce9496c12d6cff0a26ddff2b80e0db5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:59:27 +0000 Subject: [PATCH 206/361] changelog: #4881's line from lines/4881.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a38d945270c..63dac063194 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). + - Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930). - Lanes: the shared host sampler behind Flint, Llama, Kimi K3 and MiniMax-M3's draws (`gpu_rule`, `gpu_full`) keeps a draw's best 1,024 candidates in one bounded heap pass instead of sorting every logit of the row, so a draw over a 201,058-token vocabulary takes 0.11 ms where the sort alone took 15 ms; the kept candidates, the row maximum and every drawn token are the full sort's bit for bit (a test compares them with a full-sort reference on tied, NaN, infinite and zero rows), and 160 seeded requests give the same token ids. On an M4 Pro a sampled stream of a model with that vocabulary decodes at 29.2 tokens a second where it did 21.2, and four streams at 56.1 where 33.5; greedy is unchanged, and the four families' own timings were not measured (#4744). @@ -53,7 +55,6 @@ 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. - 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). -- Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). - 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. From ac62f6cec44f3371715b340b0bbc2da9b15b333a Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:13:23 +0100 Subject: [PATCH 207/361] dsv41 metal: TF_DSV41_ROUND_PROF times each decode round and the drafter's passes, summed by launch shape --- docs/environment.md | 2 +- zig/src/families/deepseek_v41/metal/boot.zig | 6 +- .../families/deepseek_v41/metal/dspark.zig | 37 +- zig/src/families/deepseek_v41/metal/entry.zig | 1 + .../families/deepseek_v41/metal/forward.zig | 38 ++- zig/src/families/deepseek_v41/metal/metal.zig | 3 +- .../deepseek_v41/metal/round_clock_prof.zig | 66 ++++ .../deepseek_v41/metal/round_prof.zig | 320 +++++++++++++++--- zig/src/families/deepseek_v41/metal/serve.zig | 12 + .../families/deepseek_v41/metal/target.zig | 17 +- .../deepseek_v41/metal/target_launch.zig | 6 +- 11 files changed, 431 insertions(+), 77 deletions(-) create mode 100644 zig/src/families/deepseek_v41/metal/round_clock_prof.zig diff --git a/docs/environment.md b/docs/environment.md index cf54364e7b6..032d2be0c59 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -99,7 +99,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | | `TF_LFM3_METAL_WARM_TURNS` | Exactly `0` or `1`; default off. Uses one-row LFM3 Metal prefill even with caching disabled. A prompt cache enables background warm turns. | | `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs; `0` keeps Metal 3. DeepSeek-V4.1 defaults to `1` where the Mac has Metal 4 (its device test rigs to `0`); Macs without it stay on Metal 3 | -| `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows, every 1,024 rounds; default 0 | +| `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows every 1,024 rounds, plus host phases and drafter passes by launch shape; default 0 | | `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index a5015b24f1c..059f4b75f8a 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -8,7 +8,7 @@ const dspark = @import("dspark.zig"); const rope = @import("rope.zig"); const scratch = @import("scratch.zig"); const forward = @import("forward.zig"); -const round_prof = @import("round_prof.zig"); +const round_prof = @import("round_clock_prof.zig"); const serve = @import("serve.zig"); const target_ = @import("target.zig"); const vision = @import("vision.zig"); @@ -34,6 +34,8 @@ pub const Options = struct { cache_bytes: u64 = 4 << 30, /// a checkpoint of the release's format at other shapes (TF_DSV41_SMALL=1: the smoke test's tiny model) small: bool = false, + /// TF_DSV41_ROUND_PROF: time each decode round and log a summary + round_prof: bool = false, /// Engram row shards (null: TF_DSV41_ENGRAM_DIR, else the config's engram_table_dir beside the checkpoint) engram_dir: ?[]const u8 = null, /// prompts a chunk at a time between the other streams' rounds (serve.Options.steps) @@ -113,7 +115,7 @@ pub const Boot = struct { const r = b.w.report(); std.log.info("dsv41 metal: {d} layers, {d} shards ({d} MiB mapped, {d} MiB copied), {d} slots of {d} positions, DSpark {s}", .{ c.layers, r.shards, r.shard_bytes >> 20, r.arena_bytes >> 20, o.slots, limit, if (b.ds != null) "on" else "off" }); const env: target_.Env = .{ .device = b.device, .queue = b.queue, .c = c, .p = &b.p, .tables = &b.tables, .s = &b.s, .model = b.w.view(), .lookup = lookup, .vision = if (b.vw) |*w| .{ .kit = &b.kit.?, .w = w } else null }; - return serve.Metal.open(a, .{ .env = env, .top = &b.w.top, .dspark = if (b.ds) |*w| w else null, .owner = .{ .ctx = b, .close = close }, .resident = if (b.w.resident) |*wr| wr else null, .images = if (b.vw != null) .{ .io = io, .tokens = o.image_tokens, .count = o.max_images } else null }, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes, .steps = o.steps, .decode_share = o.decode_share, .gpu_chain = try environment.read(bool, "TF_DSV41_MARKOV_GPU", true), .narrow = blocks.narrow, .identity = try identity(a, io, dir, b.device, b.ds != null) }); + return serve.Metal.open(a, .{ .env = env, .top = &b.w.top, .dspark = if (b.ds) |*w| w else null, .owner = .{ .ctx = b, .close = close }, .resident = if (b.w.resident) |*wr| wr else null, .images = if (b.vw != null) .{ .io = io, .tokens = o.image_tokens, .count = o.max_images } else null }, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes, .steps = o.steps, .decode_share = o.decode_share, .gpu_chain = try environment.read(bool, "TF_DSV41_MARKOV_GPU", true), .narrow = blocks.narrow, .round_prof = o.round_prof, .identity = try identity(a, io, dir, b.device, b.ds != null) }); } /// The tower's kernels and weights, and each layer's image routing bias attached to the backbone's layers. diff --git a/zig/src/families/deepseek_v41/metal/dspark.zig b/zig/src/families/deepseek_v41/metal/dspark.zig index f0057edaf91..e914c88af87 100644 --- a/zig/src/families/deepseek_v41/metal/dspark.zig +++ b/zig/src/families/deepseek_v41/metal/dspark.zig @@ -16,6 +16,7 @@ const st = @import("dspark_stage.zig"); const undo_ = @import("dspark_undo.zig"); const mkv = @import("markov.zig"); const picks_ = @import("early_picks.zig"); +const round_prof = @import("round_prof.zig"); const Config = host.config.Config; const Params = host.dspark.Params; @@ -92,6 +93,8 @@ pub const Pass = struct { device: mtl.Device, queue: mtl.Queue, opt: Options, + /// TF_DSV41_ROUND_PROF: where the passes book their times (null: no clock reads) + prof: ?*round_prof.RoundProf = null, b: forward.Bufs, plan: plan_.Plan, /// act_quant of the taps rows [16][targets * hidden] @@ -109,6 +112,7 @@ pub const Pass = struct { resident: ?mtl.ResidencySet = null, /// command buffers committed and not yet waited for (`settle` waits), in commit order queued: [4]?mtl.CommandBuffer = @splat(null), + timing: [4]?Timing = @splat(null), /// a pass queued by `begin` that `collect` finishes begun: ?Begun = null, /// chains on the GPU (Options.gpu_chain, with a confidence head of a rank the kernels take) @@ -228,15 +232,13 @@ pub const Pass = struct { } /// The command buffer of one encoder of `kind`: `f` encodes, then it is committed and waited for. - fn run(x: *Pass, comptime F: type, f: F, kind: mtl.DispatchType) !void { - try x.queue1(F, f, kind); - try x.settle(); - } + const Timing = struct { start: u64, events: [2]round_prof.Event }; - /// `run` without the wait: the buffer is committed and kept for `settle` (the queue runs buffers in order). - fn queue1(x: *Pass, comptime F: type, f: F, kind: mtl.DispatchType) !void { + /// The buffer is committed and kept for `settle` (the queue runs buffers in order). + fn queue1(x: *Pass, comptime F: type, f: F, kind: mtl.DispatchType, events: [2]round_prof.Event) !void { const pool = mtl.objc.Pool.push(); defer pool.pop(); + const t0 = if (x.prof) |q| q.clock() else 0; const cb = x.queue.commandBuffer(); const e = cb.compute(kind); f.encode(e) catch |err| { @@ -244,14 +246,15 @@ pub const Pass = struct { return err; }; e.end(); - try x.hold(cb); + try x.hold(cb, if (x.prof != null) .{ .start = t0, .events = events } else null); } /// Commits `cb` and keeps it until `settle` (a full list is settled first). - pub fn hold(x: *Pass, cb: mtl.CommandBuffer) !void { + fn hold(x: *Pass, cb: mtl.CommandBuffer, timing: ?Timing) !void { if (x.queued[x.queued.len - 1] != null) try x.settle(); cb.commit(); - for (&x.queued) |*q| if (q.* == null) { + for (&x.queued, &x.timing) |*q, *tm| if (q.* == null) { + tm.* = timing; q.* = cb.retain(); return; }; @@ -266,7 +269,12 @@ pub const Pass = struct { }; if (last) |cb| cb.wait(); var failed = false; - for (&x.queued) |*q| if (q.*) |cb| { + for (&x.queued, &x.timing) |*q, *tm| if (q.*) |cb| { + if (tm.*) |t| { + const p = x.prof.?; + p.event(t.events[0], p.clock() -| t.start); + p.event(t.events[1], round_prof.secondsNs(cb.gpuSeconds())); + } if (cb.failure()) |msg| { std.debug.print("dspark command buffer failed: {s}\n", .{msg}); failed = true; @@ -325,7 +333,7 @@ pub const Pass = struct { try st.ingest(&cx, e, j.x.w, j.taps, .{ .buf = j.x.quant }, j.x.rings, j.refs.pos, j.refs.dest); } }; - try x.queue1(job, .{ .x = x, .n = n, .taps = .{ .buf = taps.buf, .off = taps.off + row0 * row_bytes }, .refs = refs }, .serial); + try x.queue1(job, .{ .x = x, .n = n, .taps = .{ .buf = taps.buf, .off = taps.off + row0 * row_bytes }, .refs = refs }, .serial, .{ .ingest_wall, .ingest_gpu }); } /// The ingest's encoders for `n` rows of `taps` (from its first row) with the plan's ingest rows, in `e` (serial). @@ -495,8 +503,11 @@ pub const Pass = struct { try j.x.encodeAll(e, j.l); } }; - try x.run(job, .{ .x = x, .l = &l }, .concurrent); + try x.queue1(job, .{ .x = x, .l = &l }, .concurrent, .{ .propose_wall, .propose_gpu }); + try x.settle(); + const t0 = if (x.prof) |q| q.clock() else 0; try x.finish(&l, out[at..][0..m]); + if (x.prof) |q| q.event(.finish, q.clock() -| t0); } } @@ -518,7 +529,7 @@ pub const Pass = struct { try j.x.encodeAll(e, j.l); } }; - x.queue1(job, .{ .x = x, .l = &b.l }, .concurrent) catch |e| { + x.queue1(job, .{ .x = x, .l = &b.l }, .concurrent, .{ .propose_wall, .propose_gpu }) catch |e| { x.begun = null; return e; }; diff --git a/zig/src/families/deepseek_v41/metal/entry.zig b/zig/src/families/deepseek_v41/metal/entry.zig index 036d2a10bd7..4ae1297a486 100644 --- a/zig/src/families/deepseek_v41/metal/entry.zig +++ b/zig/src/families/deepseek_v41/metal/entry.zig @@ -46,6 +46,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c .small = try env.read(bool, "TF_DSV41_SMALL", false), .steps = steps, .decode_share = o.decode_share, + .round_prof = try env.read(bool, "TF_DSV41_ROUND_PROF", false), }; const m = pkg.boot.Boot.open(gpa, io, o.dir, opts) catch |e| { problem.* = try std.fmt.allocPrint(a, "the DeepSeek-V4.1 Metal engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); diff --git a/zig/src/families/deepseek_v41/metal/forward.zig b/zig/src/families/deepseek_v41/metal/forward.zig index 95b65f2fa75..9be059b5f8f 100644 --- a/zig/src/families/deepseek_v41/metal/forward.zig +++ b/zig/src/families/deepseek_v41/metal/forward.zig @@ -14,6 +14,7 @@ const Ref = ctx_.Ref; const g = pipelines.glue; const cl = @import("calls.zig"); const round_prof = @import("round_prof.zig"); +const round_clock_prof = @import("round_clock_prof.zig"); const eng = pipelines.engram; const cv = ctx_.cv; const R = pipelines.max_rows; @@ -245,14 +246,19 @@ pub const Hooks = struct { /// `run` with `h`'s Engram rows and queued work. pub fn runWith(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs, h: Hooks) !void { + return runTimed(x, q, m, b, h, null); +} + +pub fn runTimed(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs, h: Hooks, rec: ?*round_prof.Round) !void { if (m.layers.len != x.c.layers) return error.LayerOrder; if (x.rows == 0 or x.rows > R or x.rows != x.total()) return error.BadRows; var cbs: [max_buffers]mtl.CommandBuffer = undefined; var n: usize = 0; defer for (cbs[0..n]) |cb| cb.release(); - const t0 = round_prof.begin(); + const t0 = round_clock_prof.begin(); var name: [24]u8 = undefined; q.roundBegin(std.fmt.bufPrint(&name, "decode {d} rows", .{x.rows}) catch "decode"); + var committed: [max_buffers]u64 = undefined; var lo: usize = 0; while (true) { const hi = chunkEnd(lo, m.layers.len); @@ -270,23 +276,49 @@ pub fn runWith(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs, h: Hooks) if (n > 0) cbs[n - 1].wait(); return err; }; + if (rec) |r| committed[n] = r.now(); cb.commit(); cbs[n] = cb.retain(); n += 1; if (hi == m.layers.len) break; lo = hi; } + if (rec) |r| r.lap(.encode); if (h.then) |f| f(h.ctx); cbs[n - 1].wait(); q.roundEnd(); - if (t0) |t| round_prof.end(t, x.rows, cbs[0], cbs[n - 1]); + if (t0) |t| round_clock_prof.end(t, x.rows, cbs[0], cbs[n - 1]); + if (rec) |r| { + r.lap(.wait); + bookBuffers(r, cbs[0..n], committed[0..n]); + r.skip(); + } for (cbs[0..n]) |cb| if (cb.failure()) |msg| { std.debug.print("dsv41 metal window failed: {s}\n", .{msg}); return error.CommandBufferFailed; }; } -const max_buffers = 16; +const max_buffers = round_prof.max_cbs; + +/// Each buffer's span on the GPU's clock, the idle time between them, and its wall time from commit to now. +fn bookBuffers(r: *round_prof.Round, cbs: []const mtl.CommandBuffer, committed: []const u64) void { + const done = r.now(); + var prev_end: f64 = 0; + for (cbs, committed, 0..) |cb, at, i| { + const t0 = cb.gpuStart(); + const t1 = cb.gpuEnd(); + r.buffer(done -| at, secondsNs(t1 - t0)); + r.book(.gpu, secondsNs(t1 - t0)); + if (i > 0) r.book(.gap, secondsNs(t0 - prev_end)); + prev_end = t1; + } + r.book(.commit_done, done -| committed[0]); +} + +fn secondsNs(s: f64) u64 { + return if (s > 0) @intFromFloat(s * 1e9) else 0; +} /// Layers lo .. hi of the forward, the embedding before layer 0 and the head after the last. fn encodeRange(x: *const Ctx, e: mtl.ComputeEncoder, m: Model, b: *const Bufs, lo: usize, hi: usize) !void { diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index 4a046635f86..e9f8f565cac 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -19,7 +19,7 @@ pub const indexer = @import("indexer.zig"); pub const segs = @import("segs.zig"); pub const moe = @import("moe.zig"); pub const forward = @import("forward.zig"); -pub const round_prof = @import("round_prof.zig"); +pub const round_prof = @import("round_clock_prof.zig"); pub const prompt = @import("prompt.zig"); pub const prompt_layer = @import("prompt_layer.zig"); pub const prompt_scratch = @import("prompt_scratch.zig"); @@ -59,4 +59,5 @@ test { _ = vision_prep; _ = vision_rows; _ = vision_prepare; + _ = @import("round_prof.zig"); } diff --git a/zig/src/families/deepseek_v41/metal/round_clock_prof.zig b/zig/src/families/deepseek_v41/metal/round_clock_prof.zig new file mode 100644 index 00000000000..6d215bd011c --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/round_clock_prof.zig @@ -0,0 +1,66 @@ +//! TF_DSV41_ROUND_PROF=1: decode rounds' host (encode to last wait) and GPU milliseconds by rows, logged now and then. +const std = @import("std"); +const mtl = @import("metal"); + +const Sum = struct { n: u64 = 0, host: f64 = 0, gpu: f64 = 0, timed: u64 = 0 }; +const every = 1024; + +var state: enum { unread, off, on } = .unread; +var sums: [17]Sum = @splat(.{}); +var rounds: u64 = 0; + +/// The host clock at a round's start, or null when off. +pub fn begin() ?f64 { + if (state == .unread) state = if (@import("sys").environment.read(bool, "TF_DSV41_ROUND_PROF", false) catch false) .on else .off; + return if (state == .on) mtl.clock.seconds() else null; +} + +/// Metal 4 reports a command buffer's GPU times after its wait returns: a round's are read at the next round's end. +var pending: ?struct { first: mtl.CommandBuffer, last: mtl.CommandBuffer, rows: u32 } = null; + +/// A round of `rows` rows from `t0`, its command buffers' first and last. +pub fn end(t0: f64, rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { + const s = &sums[@min(rows, sums.len - 1)]; + s.n += 1; + s.host += mtl.clock.seconds() - t0; + if (pending) |p| gpu(p.rows, p.first, p.last); + pending = null; + if (first.m4 != null) pending = .{ .first = first, .last = last, .rows = rows } else gpu(rows, first, last); + rounds += 1; + if (rounds % every == 0) log(); +} + +/// Reads and drops the pending round while its queue lives: an engine calls this before closing the queue. +pub fn forget() void { + if (pending) |p| gpu(p.rows, p.first, p.last); + pending = null; +} + +/// Whether a round's buffers wait to be read (tests). +pub fn holding() bool { + return pending != null; +} + +/// Turns the profiler on or off without the environment (tests). +pub fn force(on: bool) void { + state = if (on) .on else .off; +} + +fn gpu(rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { + const s = &sums[@min(rows, sums.len - 1)]; + const a = first.gpuTimes() orelse return; + const b = last.gpuTimes() orelse return; + s.gpu += b[1] - a[0]; + s.timed += 1; +} + +fn log() void { + var buf: [1024]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + for (sums, 0..) |s, rows| { + if (s.n == 0) continue; + const g = if (s.timed > 0) s.gpu / @as(f64, @floatFromInt(s.timed)) * 1e3 else 0; + w.print(" {d} rows: {d:.2} host, {d:.2} gpu ({d});", .{ rows, s.host / @as(f64, @floatFromInt(s.n)) * 1e3, g, s.n }) catch break; + } + std.log.info("dsv41 rounds, ms a round over {d}:{s}", .{ rounds, w.buffered() }); +} diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index 6d215bd011c..2575d7574a5 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -1,66 +1,284 @@ -//! TF_DSV41_ROUND_PROF=1: decode rounds' host (encode to last wait) and GPU milliseconds by rows, logged now and then. +//! TF_DSV41_ROUND_PROF: a decode round's host phases, GPU time and the drafter's passes, summed by launch shape. const std = @import("std"); -const mtl = @import("metal"); -const Sum = struct { n: u64 = 0, host: f64 = 0, gpu: f64 = 0, timed: u64 = 0 }; -const every = 1024; +/// The host phases of one round, in ns; `other` is what the named ones leave of the round's wall time. +pub const Phase = enum { prepare, encode, wait, choose, other, round, commit_done, gpu, gap, seam }; +const nphase = std.enums.values(Phase).len; +/// The drafter's passes: host wall time of each command buffer, its GPU span, and a launch's `finish`. +pub const Event = enum { ingest_wall, ingest_gpu, propose_wall, propose_gpu, finish }; +const nevent = std.enums.values(Event).len; -var state: enum { unread, off, on } = .unread; -var sums: [17]Sum = @splat(.{}); -var rounds: u64 = 0; +/// Command buffers a round can hold (forward.zig cuts a round into about five). +pub const max_cbs = 16; +/// Samples kept per series for the percentiles; later ones still count in the mean. +const max_samples = 1 << 15; +/// Rounds between summaries in the log. +pub const report_every = 4096; +const row_buckets = [_][]const u8{ "1", "2", "3-4", "5-8", "9-16" }; -/// The host clock at a round's start, or null when off. -pub fn begin() ?f64 { - if (state == .unread) state = if (@import("sys").environment.read(bool, "TF_DSV41_ROUND_PROF", false) catch false) .on else .off; - return if (state == .on) mtl.clock.seconds() else null; +fn realNow() u64 { + var t: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &t); + return @as(u64, @intCast(t.sec)) * std.time.ns_per_s + @as(u64, @intCast(t.nsec)); } -/// Metal 4 reports a command buffer's GPU times after its wait returns: a round's are read at the next round's end. -var pending: ?struct { first: mtl.CommandBuffer, last: mtl.CommandBuffer, rows: u32 } = null; - -/// A round of `rows` rows from `t0`, its command buffers' first and last. -pub fn end(t0: f64, rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { - const s = &sums[@min(rows, sums.len - 1)]; - s.n += 1; - s.host += mtl.clock.seconds() - t0; - if (pending) |p| gpu(p.rows, p.first, p.last); - pending = null; - if (first.m4 != null) pending = .{ .first = first, .last = last, .rows = rows } else gpu(rows, first, last); - rounds += 1; - if (rounds % every == 0) log(); -} +/// A run of durations: count, sum, and the first `max_samples` for the percentiles. +const Series = struct { + n: u64 = 0, + sum: u64 = 0, + at: std.ArrayList(u32) = .empty, -/// Reads and drops the pending round while its queue lives: an engine calls this before closing the queue. -pub fn forget() void { - if (pending) |p| gpu(p.rows, p.first, p.last); - pending = null; -} + fn add(s: *Series, a: std.mem.Allocator, ns: u64) void { + s.n += 1; + s.sum += ns; + if (s.at.items.len < max_samples) s.at.append(a, @intCast(@min(ns, std.math.maxInt(u32)))) catch {}; + } -/// Whether a round's buffers wait to be read (tests). -pub fn holding() bool { - return pending != null; -} + fn deinit(s: *Series, a: std.mem.Allocator) void { + s.at.deinit(a); + } + + fn mean(s: *const Series) f64 { + return if (s.n == 0) 0 else @as(f64, @floatFromInt(s.sum)) / @as(f64, @floatFromInt(s.n)); + } + + /// The nearest-rank percentile `q` (0 to 100) of the kept samples, in ns. + fn pct(s: *const Series, a: std.mem.Allocator, q: usize) f64 { + const n = s.at.items.len; + if (n == 0) return 0; + const tmp = a.dupe(u32, s.at.items) catch return 0; + defer a.free(tmp); + std.mem.sort(u32, tmp, {}, std.sort.asc(u32)); + return @floatFromInt(tmp[@min(n - 1, (q * n + 99) / 100 -| 1)]); + } +}; + +/// Rounds of one launch shape. +const Group = struct { n: u64 = 0, phase: [nphase]Series = @splat(.{}) }; + +/// One round being timed: the phases book their time as the round passes through them. +pub const Round = struct { + p: *RoundProf, + slots: u32, + rows: u32, + drafted: bool, + began: u64, + last: u64, + ns: [nphase]u64 = @splat(0), + cbs: u32 = 0, + cb_gpu: [max_cbs]u64 = @splat(0), + cb_wall: [max_cbs]u64 = @splat(0), + + pub fn now(r: *const Round) u64 { + return r.p.clock(); + } -/// Turns the profiler on or off without the environment (tests). -pub fn force(on: bool) void { - state = if (on) .on else .off; + /// The time since the last lap (or the start) booked to `ph`. + pub fn lap(r: *Round, ph: Phase) void { + const t = r.p.clock(); + r.ns[@backingInt(ph)] += t -| r.last; + r.last = t; + } + + /// The time since the last lap is left to `other`. + pub fn skip(r: *Round) void { + r.last = r.p.clock(); + } + + /// Time that passed outside the host's laps (the GPU's own clock) booked to `ph`, without moving the lap. + pub fn book(r: *Round, ph: Phase, ns: u64) void { + r.ns[@backingInt(ph)] += ns; + } + + /// One command buffer of the round done: its host wall time from commit and its GPU span, in ns. + pub fn buffer(r: *Round, wall: u64, gpu: u64) void { + if (r.cbs >= max_cbs) return; + r.cb_wall[r.cbs] = wall; + r.cb_gpu[r.cbs] = gpu; + r.cbs += 1; + } + + /// The round over: its wall time, the residue, and every phase into the shape's series. + pub fn end(r: *Round) void { + const t = r.p.clock(); + const named = r.ns[@backingInt(Phase.prepare)] + r.ns[@backingInt(Phase.encode)] + r.ns[@backingInt(Phase.wait)] + r.ns[@backingInt(Phase.choose)]; + r.ns[@backingInt(Phase.round)] = t -| r.began; + r.ns[@backingInt(Phase.other)] = r.ns[@backingInt(Phase.round)] -| named; + r.p.add(r); + r.p.last_end = t; + } +}; + +pub const RoundProf = struct { + a: std.mem.Allocator, + /// the clock in ns; a test replaces it + clock: *const fn () u64 = realNow, + last_end: u64 = 0, + rounds: u64 = 0, + groups: [17][row_buckets.len][2]?*Group = @splat(@splat(@splat(null))), + cb_gpu: [max_cbs]Series = @splat(.{}), + cb_wall: [max_cbs]Series = @splat(.{}), + ev: [nevent]Series = @splat(.{}), + + pub fn init(a: std.mem.Allocator) !*RoundProf { + const p = try a.create(RoundProf); + p.* = .{ .a = a }; + return p; + } + + pub fn deinit(p: *RoundProf) void { + for (&p.groups) |*bs| for (bs) |*ds| for (ds) |g| if (g) |gg| { + for (&gg.phase) |*s| s.deinit(p.a); + p.a.destroy(gg); + }; + for (&p.cb_gpu) |*s| s.deinit(p.a); + for (&p.cb_wall) |*s| s.deinit(p.a); + for (&p.ev) |*s| s.deinit(p.a); + p.a.destroy(p); + } + + /// A round of `slots` slots over `rows` rows starts; its `seam` is the time since the last one ended. + pub fn begin(p: *RoundProf, slots: u32, rows: u32) Round { + const t = p.clock(); + var r: Round = .{ .p = p, .slots = slots, .rows = rows, .drafted = rows > slots, .began = t, .last = t }; + if (p.last_end != 0) r.ns[@backingInt(Phase.seam)] = t -| p.last_end; + return r; + } + + /// A drafter event of `ns`. + pub fn event(p: *RoundProf, e: Event, ns: u64) void { + p.ev[@backingInt(e)].add(p.a, ns); + } + + pub fn rowBucket(rows: u32) usize { + return if (rows <= 2) rows -| 1 else if (rows <= 4) 2 else if (rows <= 8) 3 else 4; + } + + fn add(p: *RoundProf, r: *const Round) void { + const g = p.group(r); + g.n += 1; + p.rounds += 1; + for (&g.phase, r.ns, 0..) |*s, ns, i| { + const ph: Phase = @fromBackingInt(@intCast(i)); + if (ph == .seam and p.last_end == 0) continue; + s.add(p.a, ns); + } + for (0..r.cbs) |i| { + p.cb_gpu[i].add(p.a, r.cb_gpu[i]); + p.cb_wall[i].add(p.a, r.cb_wall[i]); + } + if (p.rounds % report_every == 0) p.log(); + } + + fn group(p: *RoundProf, r: *const Round) *Group { + const slot = &p.groups[@min(r.slots, 16)][rowBucket(r.rows)][@intFromBool(r.drafted)]; + if (slot.* == null) { + slot.* = p.a.create(Group) catch @panic("round profile: out of memory"); + slot.*.?.* = .{}; + } + return slot.*.?; + } + + /// The summary: one line a launch shape (slots, rows, drafted or plain), the command buffers, the drafter's passes. + pub fn write(p: *const RoundProf, w: *std.Io.Writer) !void { + try w.print("dsv41 round profile: {d} rounds; ms mean/p50/p95 (gpu, gap, commit_done: the round's command buffers)\n", .{p.rounds}); + for (p.groups, 0..) |bs, slots| for (bs, 0..) |ds, b| for (ds, 0..) |g, drafted| if (g) |gg| { + try w.print("slots {d} rows {s} {s} n {d}:", .{ slots, row_buckets[b], if (drafted == 1) "drafted" else "plain", gg.n }); + for (&gg.phase, 0..) |*s, i| if (s.n > 0) try p.cell(w, @tagName(@as(Phase, @fromBackingInt(@intCast(i)))), s); + try w.writeByte('\n'); + }; + for (&p.cb_gpu, &p.cb_wall, 0..) |*g, *wl, i| if (g.n > 0) { + try w.print("command buffer {d} n {d}:", .{ i, g.n }); + try p.cell(w, "gpu", g); + try p.cell(w, "wall", wl); + try w.writeByte('\n'); + }; + for (&p.ev, 0..) |*s, i| if (s.n > 0) { + try w.print("drafter n {d}:", .{s.n}); + try p.cell(w, @tagName(@as(Event, @fromBackingInt(@intCast(i)))), s); + try w.writeByte('\n'); + }; + } + + fn cell(p: *const RoundProf, w: *std.Io.Writer, name: []const u8, s: *const Series) !void { + try w.print(" {s} {d:.3}/{d:.3}/{d:.3}", .{ name, s.mean() / 1e6, s.pct(p.a, 50) / 1e6, s.pct(p.a, 95) / 1e6 }); + } + + /// The summary to the log, a line each. + pub fn log(p: *const RoundProf) void { + var out: std.Io.Writer.Allocating = .init(p.a); + defer out.deinit(); + p.write(&out.writer) catch return; + var it = std.mem.splitScalar(u8, out.written(), '\n'); + while (it.next()) |line| if (line.len > 0) std.log.scoped(.dsv41).info("{s}", .{line}); + } +}; + +var fake_now: u64 = 0; + +fn fakeClock() u64 { + return fake_now; } -fn gpu(rows: u32, first: mtl.CommandBuffer, last: mtl.CommandBuffer) void { - const s = &sums[@min(rows, sums.len - 1)]; - const a = first.gpuTimes() orelse return; - const b = last.gpuTimes() orelse return; - s.gpu += b[1] - a[0]; - s.timed += 1; +test "phase sums are the round's wall time with a fake clock" { + const a = std.testing.allocator; + const p = try RoundProf.init(a); + defer p.deinit(); + p.clock = fakeClock; + fake_now = 1000; + var r = p.begin(2, 5); + fake_now += 300; + r.lap(.prepare); + fake_now += 500; + r.lap(.encode); + fake_now += 1200; + r.lap(.wait); + r.buffer(1700, 1100); + fake_now += 40; + r.lap(.choose); + fake_now += 60; + r.end(); + const g = p.groups[2][3][1].?; + try std.testing.expectEqual(@as(u64, 1), g.n); + try std.testing.expectEqual(@as(u64, 2100), g.phase[@backingInt(Phase.round)].sum); + var sum: u64 = 0; + for ([_]Phase{ .prepare, .encode, .wait, .choose, .other }) |ph| sum += g.phase[@backingInt(ph)].sum; + try std.testing.expectEqual(@as(u64, 2100), sum); + try std.testing.expectEqual(@as(u64, 60), g.phase[@backingInt(Phase.other)].sum); + try std.testing.expectEqual(@as(u64, 0), g.phase[@backingInt(Phase.seam)].n); + // the next round's seam is the time since this one ended + fake_now += 250; + var r2 = p.begin(2, 5); + r2.end(); + try std.testing.expectEqual(@as(u64, 250), p.groups[2][3][1].?.phase[@backingInt(Phase.seam)].sum); } -fn log() void { - var buf: [1024]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - for (sums, 0..) |s, rows| { - if (s.n == 0) continue; - const g = if (s.timed > 0) s.gpu / @as(f64, @floatFromInt(s.timed)) * 1e3 else 0; - w.print(" {d} rows: {d:.2} host, {d:.2} gpu ({d});", .{ rows, s.host / @as(f64, @floatFromInt(s.n)) * 1e3, g, s.n }) catch break; +test "the summary names every launch shape and the drafter's passes, with percentiles" { + const a = std.testing.allocator; + const p = try RoundProf.init(a); + defer p.deinit(); + p.clock = fakeClock; + fake_now = 5; + for ([_]u64{ 1_000_000, 2_000_000, 9_000_000 }) |ns| { + var r = p.begin(1, 1); + fake_now += ns; + r.lap(.wait); + r.end(); } - std.log.info("dsv41 rounds, ms a round over {d}:{s}", .{ rounds, w.buffered() }); + p.event(.ingest_wall, 4_000_000); + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try p.write(&w); + const text = w.buffered(); + try std.testing.expect(std.mem.indexOf(u8, text, "slots 1 rows 1 plain n 3:") != null); + try std.testing.expect(std.mem.indexOf(u8, text, " wait 4.000/2.000/9.000") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "drafter n 1: ingest_wall 4.000/4.000/4.000") != null); +} + +test "row buckets" { + try std.testing.expectEqual(@as(usize, 0), RoundProf.rowBucket(1)); + try std.testing.expectEqual(@as(usize, 1), RoundProf.rowBucket(2)); + try std.testing.expectEqual(@as(usize, 2), RoundProf.rowBucket(4)); + try std.testing.expectEqual(@as(usize, 3), RoundProf.rowBucket(8)); + try std.testing.expectEqual(@as(usize, 4), RoundProf.rowBucket(16)); } diff --git a/zig/src/families/deepseek_v41/metal/serve.zig b/zig/src/families/deepseek_v41/metal/serve.zig index 31c60bcf690..d74128f346d 100644 --- a/zig/src/families/deepseek_v41/metal/serve.zig +++ b/zig/src/families/deepseek_v41/metal/serve.zig @@ -11,6 +11,7 @@ const early_ = @import("early.zig"); const pipelines = @import("pipelines.zig"); const vision_prepare = @import("vision_prepare.zig"); const calib = @import("calib.zig"); +const round_prof = @import("round_prof.zig"); const serve_lanes = host.serve_lanes; const iface = host.iface; @@ -54,6 +55,8 @@ pub const Options = struct { narrow: u32 = 0, /// the device and weights a stored cost table is specific to (0: none named) identity: u64 = 0, + /// time each decode round and the drafter's passes (TF_DSV41_ROUND_PROF) + round_prof: bool = false, }; /// A position's draft candidates the pass keeps (the shape the lanes size their buffers by). @@ -69,6 +72,7 @@ pub const Metal = struct { warm: ?mtl.keepalive.Target = null, ad: pass_.Pass = undefined, early: ?*early_.Early = null, + rp: ?*round_prof.RoundProf = null, prep: Prep = undefined, const Prep = struct { io: std.Io, cfg: @import("vision.zig").Config }; @@ -79,6 +83,11 @@ pub const Metal = struct { m.* = .{ .a = a, .parts = parts, .opt = opt, .t = undefined }; m.t = try target_.Target.init(a, parts.env, .{ .slots = opt.slots, .limit = opt.limit, .prompt = opt.prompt, .cache_bytes = opt.cache_bytes, .resident = parts.resident }); errdefer m.t.deinit(); + if (opt.round_prof) { + m.rp = try round_prof.RoundProf.init(a); + m.t.prof = m.rp; + } + errdefer if (m.rp) |p| p.deinit(); const e = parts.env; if (opt.drafts) if (parts.dspark) |w| { m.dp = try dspark.Pass.init(a, e.device, e.queue, e.c, e.p, e.s, e.tables, parts.top, w, .{ .slots = opt.slots, .candidates = @min(candidates, e.c.vocab), .gpu_chain = opt.gpu_chain, .narrow = opt.narrow }); @@ -87,6 +96,7 @@ pub const Metal = struct { if (opt.early) m.early = try early_.Early.init(a, m.dp.?); m.ad.early = m.early; m.t.behind = m.ad.behind(); + m.dp.?.prof = m.rp; }; try m.holdWarm(); return m; @@ -213,8 +223,10 @@ pub const Metal = struct { } m.t.behind = null; if (m.warm) |w| w.queue.deinit(); + if (m.rp) |p| p.log(); if (m.dp) |p| p.deinit(); m.t.deinit(); + if (m.rp) |p| p.deinit(); if (m.parts.owner) |o| o.close(o.ctx); m.a.destroy(m); } diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index a6e0695e398..b0802905edb 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -19,6 +19,8 @@ const vt = @import("vision_tower.zig"); const vrows = @import("vision_rows.zig"); const prep = @import("vision_prep.zig"); const pick = @import("pick.zig"); +const round_prof = @import("round_prof.zig"); + const iface = host.iface; const lanes = host.lanes; const Config = host.config.Config; @@ -69,6 +71,8 @@ pub const Target = struct { slots: []Slot, cache: snapshots.Store, stats: Stats = .{}, + /// TF_DSV41_ROUND_PROF: where the windows book their times (null: no clock reads) + prof: ?*round_prof.RoundProf = null, /// a command buffer failed: the device state is no longer trusted (the health hook) failed: bool = false, /// the target's own buffers joined the weights' residency owner (they leave it before they are freed) @@ -437,6 +441,7 @@ pub const Target = struct { for (g.tokens) |id| if (id >= c.vocab) return error.BadToken; total += @intCast(n); } + var rec: ?round_prof.Round = if (t.prof) |p| p.begin(@intCast(group.len), total) else null; for (group) |g| { const s = &t.slots[g.slot]; t.tree.close(g.slot); @@ -445,7 +450,7 @@ pub const Target = struct { try s.hist.appendSlice(t.a, g.tokens); s.high = @max(s.high, s.hist.items.len); } - t.launch(group) catch |e| return t.fail(e); + t.launch(group, if (rec) |*r| r else null) catch |e| return t.fail(e); const lg = t.b.logitsOf(c, total); var r0: usize = 0; for (group, choices) |g, out| { @@ -467,6 +472,10 @@ pub const Target = struct { r0 += n; } t.stats.launches += 1; + if (rec) |*r| { + r.lap(.choose); + r.end(); + } // each slot's next window starts with the pick after the drafts its picks accept: its Engram reads start now if (t.env.lookup) |l| for (group, choices) |g, out| t.prefetchNext(l, g, out); } @@ -483,20 +492,20 @@ pub const Target = struct { } /// One launch of the decode forward over the segments' rows, each slot's ids at its positions from `start`. - fn launch(t: *Target, group: []const iface.Segment) !void { + fn launch(t: *Target, group: []const iface.Segment, rec: ?*round_prof.Round) !void { const look = t.env.c.engram_max_ngram - 1; var runs: [R]Run = undefined; for (group, runs[0..group.len]) |g, *r| { const s = &t.slots[g.slot]; r.* = .{ .kv = &s.kv, .ids = g.tokens, .start = @intCast(g.start), .lookback = s.hist.items[@as(usize, @intCast(g.start)) -| look..@intCast(g.start)] }; } - return launch_.run(t, runs[0..group.len], group); + return launch_.run(t, runs[0..group.len], group, rec); } pub const Run = launch_.Run; pub fn launchRuns(t: *Target, runs: []const Run) !void { - return launch_.run(t, runs, &.{}); + return launch_.run(t, runs, &.{}, null); } /// Keep the window's first rows (a chain from row 0): later rows' ids go, the compressor's carry rewinds. diff --git a/zig/src/families/deepseek_v41/metal/target_launch.zig b/zig/src/families/deepseek_v41/metal/target_launch.zig index 736b39898e1..aa6f4148ed1 100644 --- a/zig/src/families/deepseek_v41/metal/target_launch.zig +++ b/zig/src/families/deepseek_v41/metal/target_launch.zig @@ -4,6 +4,7 @@ const host = @import("dsv41"); const kv = @import("kv.zig"); const forward = @import("forward.zig"); const scratch = @import("scratch.zig"); +const round_prof = @import("round_prof.zig"); const ctx_ = @import("ctx.zig"); const pipelines = @import("pipelines.zig"); const Target = @import("target.zig").Target; @@ -14,7 +15,7 @@ const R = pipelines.max_rows; pub const Run = struct { kv: *const kv.Slot, ids: []const u32, start: u32, lookback: []const u32 }; /// One launch of the decode forward over the runs' rows, in order (at most R rows). -pub fn run(t: *Target, runs: []const Run, group: []const iface.Segment) !void { +pub fn run(t: *Target, runs: []const Run, group: []const iface.Segment, rec: ?*round_prof.Round) !void { const e = t.env; const c = e.c; var pieces: [R]forward.Piece = undefined; @@ -32,11 +33,12 @@ pub fn run(t: *Target, runs: []const Run, group: []const iface.Segment) !void { const look_up = try forward.prepareIds(&t.b, c, pieces[0..runs.len], e.lookup); if (look_up) |l| forward.prefetchRows(pieces[0..runs.len], l); try e.s.writeSpans(c, spans[0..runs.len]); + if (rec) |r| r.lap(.prepare); const x: ctx_.Ctx = .{ .c = c, .p = e.p, .s = e.s, .slot = segs[0].slot, .tables = e.tables, .p0 = segs[0].p0, .rows = r0, .segs = segs[0..runs.len] }; const pool = mtl.objc.Pool.push(); defer pool.pop(); var hook: Hook = .{ .t = t, .group = group, .pieces = pieces[0..runs.len], .look_up = look_up }; - try forward.runWith(&x, e.queue, e.model, &t.b, .{ .ctx = &hook, .rows = if (look_up != null) Hook.rows else null, .then = if (t.behind != null and group.len > 0) Hook.then else null }); + try forward.runTimed(&x, e.queue, e.model, &t.b, .{ .ctx = &hook, .rows = if (look_up != null) Hook.rows else null, .then = if (t.behind != null and group.len > 0) Hook.then else null }, rec); } /// A launch's hooks: each Engram layer's rows before the command buffer that reads them, the drafter's chain after. From c11675de7922b63eb71f440fa41befe21562f418 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:13:23 +0100 Subject: [PATCH 208/361] dsv41 metal: the release-layer timing test covers 1 to 16 rows, 4 slots of one row, five layers and GB/s per shape --- zig/src/families/deepseek_v41/metal/metal.zig | 1 - zig/tests/dsv41_metal/fixture_serve.zig | 4 +- zig/tests/dsv41_metal/mv_sweep.zig | 5 +- zig/tests/dsv41_metal/serve_test.zig | 26 +++++ zig/tests/dsv41_metal/timing_real.zig | 101 +++++++++++++----- 5 files changed, 107 insertions(+), 30 deletions(-) diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index e9f8f565cac..907f4d36a35 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -19,7 +19,6 @@ pub const indexer = @import("indexer.zig"); pub const segs = @import("segs.zig"); pub const moe = @import("moe.zig"); pub const forward = @import("forward.zig"); -pub const round_prof = @import("round_clock_prof.zig"); pub const prompt = @import("prompt.zig"); pub const prompt_layer = @import("prompt_layer.zig"); pub const prompt_scratch = @import("prompt_scratch.zig"); diff --git a/zig/tests/dsv41_metal/fixture_serve.zig b/zig/tests/dsv41_metal/fixture_serve.zig index 4aebef24212..8decec4791c 100644 --- a/zig/tests/dsv41_metal/fixture_serve.zig +++ b/zig/tests/dsv41_metal/fixture_serve.zig @@ -44,7 +44,7 @@ const Held = struct { } }; -pub const Opts = struct { slots: u32 = 4, drafts: bool = true, cache_bytes: u64 = 0, chunk: u32 = 64, resident: bool = false, steps: bool = false, decode_share: ?f64 = null, early: bool = true, block: ?u32 = null, rank: ?u32 = null, gpu_chain: bool = false, narrow: u32 = 0 }; +pub const Opts = struct { slots: u32 = 4, drafts: bool = true, cache_bytes: u64 = 0, chunk: u32 = 64, resident: bool = false, steps: bool = false, decode_share: ?f64 = null, early: bool = true, block: ?u32 = null, rank: ?u32 = null, gpu_chain: bool = false, narrow: u32 = 0, round_prof: bool = false }; /// Set when a model opened with a residency owner closes: every buffer the target joined to it had left. pub var resident_left: ?bool = null; @@ -80,7 +80,7 @@ pub fn open(a: std.mem.Allocator, io: std.Io, seed: u64, o: Opts) !*pkg.serve.Me } const env: pkg.target.Env = .{ .device = r.device, .queue = r.queue, .c = &r.c, .p = &r.p, .tables = &r.tables, .s = &r.s, .model = h.f.model(), .lookup = h.f.lookup() }; const parts: pkg.serve.Parts = .{ .env = env, .top = &r.top.?, .dspark = &h.w, .owner = .{ .ctx = h, .close = Held.close }, .resident = if (h.res) |*x| x else null }; - return pkg.serve.Metal.open(a, parts, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes, .prompt = .{ .chunk = o.chunk }, .steps = o.steps, .decode_share = o.decode_share, .early = o.early, .gpu_chain = o.gpu_chain, .narrow = o.narrow }); + return pkg.serve.Metal.open(a, parts, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes, .prompt = .{ .chunk = o.chunk }, .steps = o.steps, .decode_share = o.decode_share, .early = o.early, .gpu_chain = o.gpu_chain, .narrow = o.narrow, .round_prof = o.round_prof }); } /// Closes a model `open` made (the served engine closes its own through serve_lanes). diff --git a/zig/tests/dsv41_metal/mv_sweep.zig b/zig/tests/dsv41_metal/mv_sweep.zig index f19eddaf835..e1715bcf8fa 100644 --- a/zig/tests/dsv41_metal/mv_sweep.zig +++ b/zig/tests/dsv41_metal/mv_sweep.zig @@ -58,7 +58,7 @@ pub fn run(device: mtl.Device, queue: mtl.Queue, junk: mtl.Buffer, n_runs: usize const pass = try counters.ComputePass.init(); defer pass.deinit(); var t: [16]f64 = undefined; - for (shapes) |sh| for ([_]u32{ 1, 2, 4, 5, 8, 16 }) |rows| { + for (shapes) |sh| for ([_]u32{ 1, 4, 6, 8, 16 }) |rows| { var best: [variants.len]f64 = undefined; for (&pipes, 0..) |p, vi| { const v = variants[vi]; @@ -102,7 +102,8 @@ pub fn run(device: mtl.Device, queue: mtl.Queue, junk: mtl.Buffer, n_runs: usize }; std.mem.sort(usize, &order, &best, C.lt); std.debug.print("mv {d}x{d} rows {d}:", .{ sh.k, sh.n, rows }); - for (order[0..6]) |i| std.debug.print(" {d}/{d}/{d} {d:.1}", .{ variants[i].rt, variants[i].nb, variants[i].u, best[i] * 1e6 }); + const bytes: f64 = @floatFromInt(@as(u64, sh.k) * sh.n * 2); + for (order[0..6]) |i| std.debug.print(" {d}/{d}/{d} {d:.1} us ({d:.0} GB/s)", .{ variants[i].rt, variants[i].nb, variants[i].u, best[i] * 1e6, bytes / best[i] / 1e9 }); std.debug.print("\n", .{}); }; } diff --git a/zig/tests/dsv41_metal/serve_test.zig b/zig/tests/dsv41_metal/serve_test.zig index 08f5e63d0db..85ed5918cd3 100644 --- a/zig/tests/dsv41_metal/serve_test.zig +++ b/zig/tests/dsv41_metal/serve_test.zig @@ -491,3 +491,29 @@ test "dsv41 metal serve: (j) with a residency owner the server gets an idle tick defer Served.close(s); try testing.expect(s.engine().keepaliveTarget() == null); } + +test "dsv41 metal serve: (k) the round profile on: the same replies, and every round and drafter pass is counted" { + const p0 = try ids(150, 1); + defer gpa.free(p0); + const p1 = try ids(620, 2); + defer gpa.free(p1); + const asks = [_]Ask{ .{ .prompt = p0 }, .{ .prompt = p1 } }; + var want: [2][]u32 = undefined; + try reference(&asks, &want); + defer freeAll(&want); + const m = try fs.open(gpa, io, seed, .{ .round_prof = true }); + const s = try Served.open(gpa, io, m.model(), ".", null); + defer Served.close(s); + var drafted: u64 = 0; + var got: [2][]u32 = undefined; + try serve(s.engine(), &asks, true, &got, &drafted); + defer freeAll(&got); + const bad = same(&want, &got); + const p = m.rp.?; + var sum: u64 = 0; + for (p.ev) |e| sum += e.n; + say(bad == 0 and p.rounds == m.t.stats.launches and sum > 0, "(k) profiled vs serial: {d} differ; {d} rounds profiled of {d} launches, {d} drafter events", .{ bad, p.rounds, m.t.stats.launches, sum }); + try testing.expectEqual(@as(usize, 0), bad); + try testing.expectEqual(m.t.stats.launches, p.rounds); + try testing.expect(sum > 0 and drafted > 0); +} diff --git a/zig/tests/dsv41_metal/timing_real.zig b/zig/tests/dsv41_metal/timing_real.zig index 58124a83c40..9fa279e0651 100644 --- a/zig/tests/dsv41_metal/timing_real.zig +++ b/zig/tests/dsv41_metal/timing_real.zig @@ -121,6 +121,21 @@ fn clockOf(before: counters.ClockSample, after: counters.ClockSample) Clock { pub const Run = struct { host: f64, gpu: f64, enc: f64, each: []f64 }; +/// A launch of `slots` slots, each `rows / slots` rows at p0: the rig's slot and `extra` (slots - 1 more). +const Multi = struct { + slots: u32 = 1, + extra: []const pkg.kv.Slot = &.{}, + + fn ctx(m: Multi, r: *const fixture.Rig, rows: u32, segs: *[16]pkg.ctx.Seg) pkg.ctx.Ctx { + var x = r.ctx(&r.slot, p0, rows); + if (m.slots == 1) return x; + const each = rows / m.slots; + for (0..m.slots) |i| segs[i] = .{ .slot = if (i == 0) &r.slot else &m.extra[i - 1], .p0 = p0, .r0 = @intCast(i * each), .n = each }; + x.segs = segs[0..m.slots]; + return x; + } +}; + /// The direct launch (host encode, GPU span), then its recording replayed whole and one dispatch an encoder. fn once(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, rec: *recorder.Recording, l: Launch, samples: counters.SampleBuffer, pass: counters.ComputePass, conc: counters.ComputePass) !Run { const w = l.w; @@ -181,15 +196,13 @@ fn once(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, rec: *recorder. /// One timed launch: a layer's weights, its context (one slot's rows, or segments) and the rows' spans. pub const Launch = struct { w: *const pkg.weights.Layer, ctx: pkg.ctx.Ctx, spans: []const pkg.scratch.Span }; -/// The launch of `rows` rows of the rig's first layer on its slot at `p0`. -fn single(r: *fixture.Rig, rows: u32, span: *[1]pkg.scratch.Span) Launch { - span[0] = .{ .p0 = p0, .n = rows }; - return .{ .w = &r.layers[0], .ctx = r.ctx(&r.slot, p0, rows), .spans = span }; -} - -fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const Names, rows: u32, n: usize) !void { - var span: [1]pkg.scratch.Span = undefined; - const t = try time(a, r, junk, names, single(r, rows, &span), n); +fn report(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *const Names, multi: Multi, rows: u32, n: usize) !void { + var segments: [16]pkg.ctx.Seg = undefined; + var spans: [16]pkg.scratch.Span = undefined; + for (spans[0..multi.slots]) |*span| span.* = .{ .p0 = p0, .n = rows / multi.slots }; + const launch: Launch = .{ .w = &r.layers[0], .ctx = multi.ctx(r, rows, &segments), .spans = spans[0..multi.slots] }; + const t = try time(a, r, junk, names, launch, n); + std.debug.print(" shape: {d} slot(s) x {d} row(s)\n", .{ multi.slots, rows / multi.slots }); t.print(r.layers[0].layer, rows, n, env("TF_DSV41_TIMING_EACH") != null); } @@ -285,7 +298,7 @@ pub fn time(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *con return .{ .gpu = gpu, .gpu_med = gpu_med, .host = hst, .enc = enc, .enc_med = enc_med, .sum = sum, .cls = cls.items, .tot = tot.items, .cnt = cnt.items, .each = each, .each_names = each_names }; } -/// Each dense FP8 projection of the layer alone at 1, 4 and 5 rows, by block kind, interleaved. +/// Each dense FP8 projection of the layer alone at 1 to 16 rows, by block kind, interleaved, with GB/s of its weights. fn fp8Shapes(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, n: usize) !void { const fp8 = pkg.pipelines.fp8; const w = &r.layers[0]; @@ -297,7 +310,7 @@ fn fp8Shapes(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, n: usize) defer pass.deinit(); const kinds = [_]fp8.Kind{ .b, .c }; const t = try a.alloc(f64, n * kinds.len); - for ([_]u32{ 1, 4, 5 }) |rows| for (shapes) |sh| { + for ([_]u32{ 1, 4, 6, 8, 16 }) |rows| for (shapes) |sh| { const call: fp8.Call = .{ .k = sh.w.k, .n = sh.w.n, .rows = rows, .split = fp8.splitOf(sh.w.k), .out = .bf16 }; for (0..n) |i| for (kinds, 0..) |kind, j| { flush(r, junk); @@ -315,7 +328,11 @@ fn fp8Shapes(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, n: usize) t[j * n + i] = clockOf(before, counters.sampleClocks(r.device)).span(res.values(), 0, 1); }; std.debug.print(" fp8 {s:<10} {d}x{d} at {d} row(s), launched as {s}:", .{ sh.name, sh.w.k, sh.w.n, rows, @tagName(fp8.kindOf(call)) }); - for (kinds, 0..) |kind, j| std.debug.print(" {s} {d:.1} us", .{ @tagName(kind), least(t[j * n ..][0..n]) * 1e6 }); + const bytes: f64 = @floatFromInt(@as(u64, sh.w.k) * sh.w.n + @as(u64, sh.w.k / 32) * (sh.w.n / 32)); + for (kinds, 0..) |kind, j| { + const us = least(t[j * n ..][0..n]); + std.debug.print(" {s} {d:.1} us ({d:.0} GB/s)", .{ @tagName(kind), us * 1e6, bytes / us / 1e9 }); + } std.debug.print("\n", .{}); }; } @@ -428,26 +445,41 @@ fn bits(r: *fixture.Rig, rows: u32, n: usize) !void { if (same != n) return error.ConcurrentBitsDiffer; } -test "dsv41 metal REAL layer decode timing at 1 and 4 rows" { - const dir = env("TF_DSV41_REAL") orelse return error.SkipZigTest; - const layer = if (env("TF_DSV41_REAL_LAYER")) |v| try std.fmt.parseInt(u32, v, 10) else 2; - const n = if (env("TF_DSV41_TIMING_N")) |v| try std.fmt.parseInt(usize, v, 10) else 21; - var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); - defer arena.deinit(); - const a = arena.allocator(); +/// A "SxN" token of TF_DSV41_TIMING_ROWS is S slots of N rows each; a bare number is one slot of that many rows. +fn parseShape(tok: []const u8) !struct { slots: u32, rows: u32 } { + const x = std.mem.indexOfScalar(u8, tok, 'x') orelse { + const rows = try std.fmt.parseInt(u32, tok, 10); + if (rows == 0 or rows > 16) return error.BadShape; + return .{ .slots = 1, .rows = rows }; + }; + const slots = try std.fmt.parseInt(u32, tok[0..x], 10); + const each = try std.fmt.parseInt(u32, tok[x + 1 ..], 10); + if (slots == 0 or each == 0 or slots > 16 / each) return error.BadShape; + return .{ .slots = slots, .rows = slots * each }; +} + +fn timeLayer(a: std.mem.Allocator, dir: []const u8, layer: u32, n: usize) !void { const r = try open(std.heap.page_allocator, std.testing.io, dir, layer); defer r.deinit(); const junk = try r.device.buffer(flush_bytes, mtl.ResourceOptions.private); defer junk.deinit(); var names: Names = .{}; try names.walk(a, pkg.pipelines.Pipelines, &r.p, "p"); - if (env("TF_DSV41_TIMING_MV") != null) return mv_sweep.run(r.device, r.queue, junk, n); for ([_]u32{ 1, 4 }) |rows| try bits(r, rows, 20); fixture.fillPast(&r.c, &r.slot, p0, 21); - // TF_DSV41_TIMING_ROWS: a comma list of row counts to time (default 1,4; at most 16) - var it = std.mem.tokenizeScalar(u8, env("TF_DSV41_TIMING_ROWS") orelse "1,4", ','); + // TF_DSV41_TIMING_ROWS: a comma list of launch shapes to time (default 1,4,6,8,16 rows and 4 slots x 1 row) + const extra = try a.alloc(pkg.kv.Slot, 15); + var made: usize = 0; + defer for (extra[0..made]) |*s| s.deinit(); + var it = std.mem.tokenizeScalar(u8, env("TF_DSV41_TIMING_ROWS") orelse "1,4,6,8,16,4x1", ','); while (it.next()) |t| { - const rows = try std.fmt.parseInt(u32, t, 10); + const sh = try parseShape(t); + const rows = sh.rows; + while (made + 1 < sh.slots) : (made += 1) { + extra[made] = try pkg.kv.Slot.init(r.a, r.device, &r.c, limit); + fixture.fillPast(&r.c, &extra[made], p0, 22 + made); + } + const multi: Multi = .{ .slots = sh.slots, .extra = extra[0..made] }; fixture.fillInput(r, rows, 31); // TF_DSV41_TIMING_SAME: every row's input is row 0's, so the rows mostly share their experts (a draft block) if (env("TF_DSV41_TIMING_SAME") != null) { @@ -456,7 +488,7 @@ test "dsv41 metal REAL layer decode timing at 1 and 4 rows" { const pre = r.io[2].slice(f32, rows * 4); for (1..rows) |i| @memcpy(pre[i * 4 ..][0..4], pre[0..4]); } - try report(a, r, junk, &names, rows, n); + try report(a, r, junk, &names, multi, rows, n); std.debug.print(" routed experts a round: {d} for {d} picks\n", .{ std.mem.bytesToValue(u32, r.s.bytes(r.s.plan[1], 4)), rows * r.c.topk }); } if (env("TF_DSV41_TIMING_FP8") != null) try fp8Shapes(a, r, junk, n); @@ -467,6 +499,25 @@ test "dsv41 metal REAL layer decode timing at 1 and 4 rows" { std.debug.print("as a window-only layer (compress ratio 0):\n", .{}); for ([_]u32{ 1, 4 }) |rows| { fixture.fillInput(r, rows, 31); - try report(a, r, junk, &names, rows, n); + try report(a, r, junk, &names, .{}, rows, n); + } +} + +test "dsv41 metal REAL layer decode timing at 1 to 16 rows and 4 slots" { + const dir = env("TF_DSV41_REAL") orelse return error.SkipZigTest; + const n = if (env("TF_DSV41_TIMING_N")) |v| try std.fmt.parseInt(usize, v, 10) else 21; + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + // TF_DSV41_REAL_LAYERS (or the one TF_DSV41_REAL_LAYER): comma list; default the five kinds of layer + const list = env("TF_DSV41_REAL_LAYERS") orelse env("TF_DSV41_REAL_LAYER") orelse "2,14,20,21,24"; + if (env("TF_DSV41_TIMING_MV") != null) { + const r = try open(std.heap.page_allocator, std.testing.io, dir, try std.fmt.parseInt(u32, std.mem.sliceTo(list, ','), 10)); + defer r.deinit(); + const junk = try r.device.buffer(flush_bytes, mtl.ResourceOptions.private); + defer junk.deinit(); + return mv_sweep.run(r.device, r.queue, junk, n); } + var layers = std.mem.tokenizeScalar(u8, list, ','); + while (layers.next()) |l| try timeLayer(a, dir, try std.fmt.parseInt(u32, l, 10), n); } From 97778c9e1fa1ca3ab234964f7769adf3ea3ed5db Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:16:00 +0100 Subject: [PATCH 209/361] dsv41 metal: the round profile skips a round it cannot allocate for, and each summary covers its own window --- docs/environment.md | 2 +- .../families/deepseek_v41/metal/forward.zig | 4 +- .../deepseek_v41/metal/round_prof.zig | 97 +++++++++++++++++-- zig/src/families/deepseek_v41/metal/serve.zig | 3 +- 4 files changed, 92 insertions(+), 14 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index 032d2be0c59..0521fcb8b99 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -99,7 +99,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_ANE_COLUMNS` | Whole u32 count; zero disables the experimental share; default zero | | `TF_LFM3_METAL_WARM_TURNS` | Exactly `0` or `1`; default off. Uses one-row LFM3 Metal prefill even with caching disabled. A prompt cache enables background warm turns. | | `TF_METAL4` | Metal: exactly `0` or `1`; `1` sends a family's GPU work through Metal 4 (macOS 26 and later) where the family supports it: the same kernels in the same order, with Metal 4's command queue, allocators, argument tables and barriers, and bit-identical outputs; `0` keeps Metal 3. DeepSeek-V4.1 defaults to `1` where the Mac has Metal 4 (its device test rigs to `0`); Macs without it stay on Metal 3 | -| `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` logs decode rounds' host milliseconds (first encode to last wait) and GPU milliseconds by rows every 1,024 rounds, plus host phases and drafter passes by launch shape; default 0 | +| `TF_DSV41_ROUND_PROF` | DeepSeek-V4.1 on Metal: exactly `0` or `1`, default 0. At 1 the row-count profiler logs every 1,024 rounds. The launch-shape profiler logs host phases, available GPU spans and drafter passes every 4,096 rounds and at close. Each launch-shape summary covers rounds since the previous summary. Malformed values fail at Metal startup. | | `TF_METAL4_TIMELINE` | Metal 4: a whole round count, default 0; `n` puts a GPU timestamp at every stage (between barriers) of `n` rounds of each kind a family names, after 8 warm ones, and logs their time by kernel and the longest stages. DeepSeek-V4.1 names its decode rounds by rows. Stamps cost GPU time, so stamped rounds read a little long | | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal: exactly `0` or `1`; default 1, where the 4-bit expert kernels (decode, grouped and prompt gathers) read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values from fewer weight bytes, and the routed experts' stored scales and biases are not kept in memory; `0` keeps and reads the stored arrays; ignored with `--ssd-experts` | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | diff --git a/zig/src/families/deepseek_v41/metal/forward.zig b/zig/src/families/deepseek_v41/metal/forward.zig index 9be059b5f8f..cb2802e3583 100644 --- a/zig/src/families/deepseek_v41/metal/forward.zig +++ b/zig/src/families/deepseek_v41/metal/forward.zig @@ -316,9 +316,7 @@ fn bookBuffers(r: *round_prof.Round, cbs: []const mtl.CommandBuffer, committed: r.book(.commit_done, done -| committed[0]); } -fn secondsNs(s: f64) u64 { - return if (s > 0) @intFromFloat(s * 1e9) else 0; -} +const secondsNs = round_prof.secondsNs; /// Layers lo .. hi of the forward, the embedding before layer 0 and the head after the last. fn encodeRange(x: *const Ctx, e: mtl.ComputeEncoder, m: Model, b: *const Bufs, lo: usize, hi: usize) !void { diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index 2575d7574a5..9350595af22 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -10,12 +10,17 @@ const nevent = std.enums.values(Event).len; /// Command buffers a round can hold (forward.zig cuts a round into about five). pub const max_cbs = 16; -/// Samples kept per series for the percentiles; later ones still count in the mean. +/// Samples kept per series within one summary window; later ones still count in the mean. const max_samples = 1 << 15; /// Rounds between summaries in the log. pub const report_every = 4096; const row_buckets = [_][]const u8{ "1", "2", "3-4", "5-8", "9-16" }; +/// A GPU span in seconds as ns; zero for a negative or non-finite span, and capped so the cast cannot trap. +pub fn secondsNs(s: f64) u64 { + return if (s > 0 and s < 1e9) @intFromFloat(s * 1e9) else 0; +} + fn realNow() u64 { var t: std.c.timespec = undefined; _ = std.c.clock_gettime(.MONOTONIC, &t); @@ -34,6 +39,12 @@ const Series = struct { if (s.at.items.len < max_samples) s.at.append(a, @intCast(@min(ns, std.math.maxInt(u32)))) catch {}; } + fn clear(s: *Series) void { + s.n = 0; + s.sum = 0; + s.at.clearRetainingCapacity(); + } + fn deinit(s: *Series, a: std.mem.Allocator) void { s.at.deinit(a); } @@ -115,6 +126,10 @@ pub const RoundProf = struct { clock: *const fn () u64 = realNow, last_end: u64 = 0, rounds: u64 = 0, + /// rounds before the current summary window + since: u64 = 0, + /// rounds between summaries; each one starts a new window + every: u64 = report_every, groups: [17][row_buckets.len][2]?*Group = @splat(@splat(@splat(null))), cb_gpu: [max_cbs]Series = @splat(.{}), cb_wall: [max_cbs]Series = @splat(.{}), @@ -155,7 +170,7 @@ pub const RoundProf = struct { } fn add(p: *RoundProf, r: *const Round) void { - const g = p.group(r); + const g = p.group(r) orelse return; g.n += 1; p.rounds += 1; for (&g.phase, r.ns, 0..) |*s, ns, i| { @@ -167,22 +182,39 @@ pub const RoundProf = struct { p.cb_gpu[i].add(p.a, r.cb_gpu[i]); p.cb_wall[i].add(p.a, r.cb_wall[i]); } - if (p.rounds % report_every == 0) p.log(); + if (p.rounds - p.since >= p.every) { + p.log(); + p.reset(); + } } - fn group(p: *RoundProf, r: *const Round) *Group { + /// The shape's group, made on first use; null when it cannot be allocated (the round is then not booked). + fn group(p: *RoundProf, r: *const Round) ?*Group { const slot = &p.groups[@min(r.slots, 16)][rowBucket(r.rows)][@intFromBool(r.drafted)]; if (slot.* == null) { - slot.* = p.a.create(Group) catch @panic("round profile: out of memory"); - slot.*.?.* = .{}; + const g = p.a.create(Group) catch return null; + g.* = .{}; + slot.* = g; } - return slot.*.?; + return slot.*; + } + + /// A new summary window: every series and count starts again, so a summary's mean and percentiles share rounds. + fn reset(p: *RoundProf) void { + p.since = p.rounds; + for (&p.groups) |*bs| for (bs) |*ds| for (ds) |g| if (g) |gg| { + gg.n = 0; + for (&gg.phase) |*s| s.clear(); + }; + for (&p.cb_gpu) |*s| s.clear(); + for (&p.cb_wall) |*s| s.clear(); + for (&p.ev) |*s| s.clear(); } /// The summary: one line a launch shape (slots, rows, drafted or plain), the command buffers, the drafter's passes. pub fn write(p: *const RoundProf, w: *std.Io.Writer) !void { - try w.print("dsv41 round profile: {d} rounds; ms mean/p50/p95 (gpu, gap, commit_done: the round's command buffers)\n", .{p.rounds}); - for (p.groups, 0..) |bs, slots| for (bs, 0..) |ds, b| for (ds, 0..) |g, drafted| if (g) |gg| { + try w.print("dsv41 round profile: rounds {d} to {d} ({d} rounds; mean and percentiles cover these rounds); ms mean/p50/p95\n", .{ p.since + 1, p.rounds, p.rounds - p.since }); + for (p.groups, 0..) |bs, slots| for (bs, 0..) |ds, b| for (ds, 0..) |g, drafted| if (g) |gg| if (gg.n > 0) { try w.print("slots {d} rows {s} {s} n {d}:", .{ slots, row_buckets[b], if (drafted == 1) "drafted" else "plain", gg.n }); for (&gg.phase, 0..) |*s, i| if (s.n > 0) try p.cell(w, @tagName(@as(Phase, @fromBackingInt(@intCast(i)))), s); try w.writeByte('\n'); @@ -282,3 +314,50 @@ test "row buckets" { try std.testing.expectEqual(@as(usize, 3), RoundProf.rowBucket(8)); try std.testing.expectEqual(@as(usize, 4), RoundProf.rowBucket(16)); } + +test "a failed allocation for a new shape leaves the round unbooked and the profiler usable" { + const a = std.testing.allocator; + const p = try RoundProf.init(a); + defer p.deinit(); + p.clock = fakeClock; + var failing = std.testing.FailingAllocator.init(a, .{ .fail_index = 0 }); + p.a = failing.allocator(); + fake_now = 10; + var r = p.begin(1, 1); + fake_now += 5; + r.end(); + try std.testing.expectEqual(@as(u64, 0), p.rounds); + try std.testing.expect(p.groups[1][0][0] == null); + p.a = a; + var r2 = p.begin(1, 1); + fake_now += 7; + r2.end(); + try std.testing.expectEqual(@as(u64, 1), p.rounds); + try std.testing.expectEqual(@as(u64, 1), p.groups[1][0][0].?.n); +} + +test "each periodic summary covers only the rounds since the last, and says so" { + const a = std.testing.allocator; + const p = try RoundProf.init(a); + defer p.deinit(); + p.clock = fakeClock; + p.every = 2; + fake_now = 1; + for ([_]u64{ 1_000_000, 1_000_000, 9_000_000 }) |ns| { + var r = p.begin(1, 1); + fake_now += ns; + r.lap(.wait); + r.end(); + } + // the first two rounds were summarised and dropped: the third stands alone + try std.testing.expectEqual(@as(u64, 3), p.rounds); + try std.testing.expectEqual(@as(u64, 2), p.since); + const g = p.groups[1][0][0].?; + try std.testing.expectEqual(@as(u64, 1), g.n); + try std.testing.expectEqual(@as(usize, 1), g.phase[@backingInt(Phase.wait)].at.items.len); + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try p.write(&w); + try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "rounds 3 to 3 (1 rounds; mean and percentiles cover these rounds)") != null); + try std.testing.expect(std.mem.indexOf(u8, w.buffered(), " wait 9.000/9.000/9.000") != null); +} diff --git a/zig/src/families/deepseek_v41/metal/serve.zig b/zig/src/families/deepseek_v41/metal/serve.zig index d74128f346d..7e1f8ae79c1 100644 --- a/zig/src/families/deepseek_v41/metal/serve.zig +++ b/zig/src/families/deepseek_v41/metal/serve.zig @@ -84,7 +84,8 @@ pub const Metal = struct { m.t = try target_.Target.init(a, parts.env, .{ .slots = opt.slots, .limit = opt.limit, .prompt = opt.prompt, .cache_bytes = opt.cache_bytes, .resident = parts.resident }); errdefer m.t.deinit(); if (opt.round_prof) { - m.rp = try round_prof.RoundProf.init(a); + // a diagnostic: without memory for it the server runs unprofiled + m.rp = round_prof.RoundProf.init(a) catch null; m.t.prof = m.rp; } errdefer if (m.rp) |p| p.deinit(); From 1405a36a7f7a03616fe9edab0380e3f9b7dc567e Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:46:46 +0100 Subject: [PATCH 210/361] dsv41 metal: the round profile writes no summary when no round was booked since the last one The summary at close followed a periodic one even when no round had been booked in between, and printed only a header such as "rounds 4097 to 4096 (0 rounds; ...)". write now returns at once when no round was booked since the last summary. A test writes a fresh profile (nothing) and one after a round (its header); it found 104 bytes before the change. --- .../deepseek_v41/metal/round_prof.zig | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index 9350595af22..ff7fce01ebf 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -213,6 +213,8 @@ pub const RoundProf = struct { /// The summary: one line a launch shape (slots, rows, drafted or plain), the command buffers, the drafter's passes. pub fn write(p: *const RoundProf, w: *std.Io.Writer) !void { + // no round since the last summary: nothing to say (the summary at close after a periodic one) + if (p.rounds == p.since) return; try w.print("dsv41 round profile: rounds {d} to {d} ({d} rounds; mean and percentiles cover these rounds); ms mean/p50/p95\n", .{ p.since + 1, p.rounds, p.rounds - p.since }); for (p.groups, 0..) |bs, slots| for (bs, 0..) |ds, b| for (ds, 0..) |g, drafted| if (g) |gg| if (gg.n > 0) { try w.print("slots {d} rows {s} {s} n {d}:", .{ slots, row_buckets[b], if (drafted == 1) "drafted" else "plain", gg.n }); @@ -361,3 +363,21 @@ test "each periodic summary covers only the rounds since the last, and says so" try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "rounds 3 to 3 (1 rounds; mean and percentiles cover these rounds)") != null); try std.testing.expect(std.mem.indexOf(u8, w.buffered(), " wait 9.000/9.000/9.000") != null); } + +test "a summary with no round since the last one writes nothing" { + const a = std.testing.allocator; + const p = try RoundProf.init(a); + defer p.deinit(); + p.clock = fakeClock; + fake_now = 1; + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try p.write(&w); + try std.testing.expectEqual(@as(usize, 0), w.buffered().len); + var r = p.begin(1, 1); + fake_now += 1_000_000; + r.lap(.wait); + r.end(); + try p.write(&w); + try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "rounds 1 to 1 (1 rounds;") != null); +} From 339d7af44b91645d40049022eb432560d6af7c08 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:27:10 +0000 Subject: [PATCH 211/361] Profile queued speculative chains at their existing wait --- zig/src/families/deepseek_v41/metal/dspark.zig | 7 ++++--- zig/src/families/deepseek_v41/metal/early.zig | 9 ++++++++- zig/src/families/deepseek_v41/metal/round_prof.zig | 2 +- zig/src/families/deepseek_v41/metal/serve.zig | 2 +- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/zig/src/families/deepseek_v41/metal/dspark.zig b/zig/src/families/deepseek_v41/metal/dspark.zig index e914c88af87..3ba17c9d485 100644 --- a/zig/src/families/deepseek_v41/metal/dspark.zig +++ b/zig/src/families/deepseek_v41/metal/dspark.zig @@ -231,7 +231,7 @@ pub const Pass = struct { x.undo.forget(slot); } - /// The command buffer of one encoder of `kind`: `f` encodes, then it is committed and waited for. + /// Timing attached to a queued command buffer until its existing wait. const Timing = struct { start: u64, events: [2]round_prof.Event }; /// The buffer is committed and kept for `settle` (the queue runs buffers in order). @@ -281,6 +281,7 @@ pub const Pass = struct { } cb.release(); q.* = null; + tm.* = null; }; if (failed) return error.CommandBufferFailed; } @@ -421,6 +422,8 @@ pub const Pass = struct { /// Candidates and the Markov chain over a launch's head outputs, each ask's results into `out` (its order). pub fn finish(x: *Pass, l: *const Launch, out: []Proposal) !void { + const start = if (x.prof) |p| p.clock() else 0; + defer if (x.prof) |p| p.event(.finish, p.clock() -| start); const n: usize = l.n; const B: usize = x.c.dspark_block; const k: usize = @min(x.opt.candidates, x.c.vocab); @@ -505,9 +508,7 @@ pub const Pass = struct { }; try x.queue1(job, .{ .x = x, .l = &l }, .concurrent, .{ .propose_wall, .propose_gpu }); try x.settle(); - const t0 = if (x.prof) |q| q.clock() else 0; try x.finish(&l, out[at..][0..m]); - if (x.prof) |q| q.event(.finish, q.clock() -| t0); } } diff --git a/zig/src/families/deepseek_v41/metal/early.zig b/zig/src/families/deepseek_v41/metal/early.zig index 326a15deb3f..4c3adaefd72 100644 --- a/zig/src/families/deepseek_v41/metal/early.zig +++ b/zig/src/families/deepseek_v41/metal/early.zig @@ -6,6 +6,7 @@ const dspark = @import("dspark.zig"); const plan_ = @import("dspark_plan.zig"); const pipelines = @import("pipelines.zig"); const picks_ = @import("early_picks.zig"); +const round_prof = @import("round_prof.zig"); const iface = host.iface; const lanes = host.lanes; @@ -38,6 +39,7 @@ const Chain = struct { block: u32, taps: mtl.Buffer, cb: mtl.CommandBuffer, + profile_start: u64, /// the window's first rows the lanes asked ingested: the chain's own ingest when its picks accepted as many deferred: ?u32 = null, /// the pass the lanes began over it @@ -125,13 +127,14 @@ pub const Early = struct { const skew = e.skew_every > 0 and n > 1 and (e.stats.queued + 1) % e.skew_every == 0; const pool = mtl.objc.Pool.push(); defer pool.pop(); + const started = if (x.prof) |p| p.clock() else 0; const cb = x.queue.commandBuffer(); // a buffer never committed never runs: the rings stay as they are e.encode(cb, logits, logits_off, taps, g.start, n, B, skew, if (keyed) g.sampling.? else null) catch return; cb.commit(); e.stats.skewed += @intFromBool(skew); e.stats.keyed += @intFromBool(keyed); - e.chain = .{ .slot = g.slot, .start = g.start, .rows = n, .block = B, .gpu = x.mk != null, .taps = taps, .cb = cb.retain() }; + e.chain = .{ .slot = g.slot, .start = g.start, .rows = n, .block = B, .gpu = x.mk != null, .taps = taps, .cb = cb.retain(), .profile_start = started }; e.stats.queued += 1; } @@ -244,6 +247,10 @@ pub const Early = struct { fn wait(e: *Early, ch: Chain) !Got { defer ch.cb.release(); ch.cb.wait(); + if (e.x.prof) |p| { + p.event(.chain_wall, p.clock() -| ch.profile_start); + p.event(.chain_gpu, round_prof.secondsNs(ch.cb.gpuSeconds())); + } if (ch.cb.failure()) |msg| { std.debug.print("dsv41 early drafts: command buffer failed: {s}\n", .{msg}); return error.CommandBufferFailed; diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index ff7fce01ebf..c51b83f38bf 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -5,7 +5,7 @@ const std = @import("std"); pub const Phase = enum { prepare, encode, wait, choose, other, round, commit_done, gpu, gap, seam }; const nphase = std.enums.values(Phase).len; /// The drafter's passes: host wall time of each command buffer, its GPU span, and a launch's `finish`. -pub const Event = enum { ingest_wall, ingest_gpu, propose_wall, propose_gpu, finish }; +pub const Event = enum { ingest_wall, ingest_gpu, propose_wall, propose_gpu, finish, chain_wall, chain_gpu }; const nevent = std.enums.values(Event).len; /// Command buffers a round can hold (forward.zig cuts a round into about five). diff --git a/zig/src/families/deepseek_v41/metal/serve.zig b/zig/src/families/deepseek_v41/metal/serve.zig index 7e1f8ae79c1..968c7d0d44d 100644 --- a/zig/src/families/deepseek_v41/metal/serve.zig +++ b/zig/src/families/deepseek_v41/metal/serve.zig @@ -224,8 +224,8 @@ pub const Metal = struct { } m.t.behind = null; if (m.warm) |w| w.queue.deinit(); - if (m.rp) |p| p.log(); if (m.dp) |p| p.deinit(); + if (m.rp) |p| p.log(); m.t.deinit(); if (m.rp) |p| p.deinit(); if (m.parts.owner) |o| o.close(o.ctx); From b82d2953db7f64b21cfa0edd3c63a4820258a236 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:13:23 +0100 Subject: [PATCH 212/361] dsv41 metal: TF_DSV41_ROUND_PROF times each decode round and the drafter's passes, summed by launch shape --- zig/src/families/deepseek_v41/metal/metal.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index 907f4d36a35..e9f8f565cac 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -19,6 +19,7 @@ pub const indexer = @import("indexer.zig"); pub const segs = @import("segs.zig"); pub const moe = @import("moe.zig"); pub const forward = @import("forward.zig"); +pub const round_prof = @import("round_clock_prof.zig"); pub const prompt = @import("prompt.zig"); pub const prompt_layer = @import("prompt_layer.zig"); pub const prompt_scratch = @import("prompt_scratch.zig"); From da871aa16d0c868ac4622721154717416bf3d25d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:26:31 +0000 Subject: [PATCH 213/361] dsv41 metal: include tree launches in the round profile --- .../families/deepseek_v41/metal/target.zig | 4 +- zig/src/families/deepseek_v41/metal/tree.zig | 49 ++++++++++++++++++- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index b0802905edb..41ea3205498 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -504,8 +504,8 @@ pub const Target = struct { pub const Run = launch_.Run; - pub fn launchRuns(t: *Target, runs: []const Run) !void { - return launch_.run(t, runs, &.{}, null); + pub fn launchRuns(t: *Target, runs: []const Run, rec: ?*round_prof.Round) !void { + return launch_.run(t, runs, &.{}, rec); } /// Keep the window's first rows (a chain from row 0): later rows' ids go, the compressor's carry rewinds. diff --git a/zig/src/families/deepseek_v41/metal/tree.zig b/zig/src/families/deepseek_v41/metal/tree.zig index a6c6e7cb3cb..af8923dd242 100644 --- a/zig/src/families/deepseek_v41/metal/tree.zig +++ b/zig/src/families/deepseek_v41/metal/tree.zig @@ -7,6 +7,7 @@ const snapshots = @import("snapshots.zig"); const pipelines = @import("pipelines.zig"); const picks = @import("pick.zig"); const target_ = @import("target.zig"); +const round_prof = @import("round_prof.zig"); const iface = host.iface; const Config = host.config.Config; @@ -142,6 +143,11 @@ pub const Tree = struct { }; } + /// One profiled round for chains packed into a tree launch. + fn beginLaunch(p: ?*round_prof.RoundProf, chains: usize, rows: usize) ?round_prof.Round { + return if (p) |prof| prof.begin(@intCast(chains), @intCast(rows)) else null; + } + /// The tree windows among `segs` into their `outs`: every chain of every tree in launches of R rows at most. pub fn window(tr: *Tree, t: *Target, segs: []const iface.Segment, outs: [][]u32) !void { var trees: [R]u32 = undefined; @@ -187,7 +193,8 @@ pub const Tree = struct { ci = 0; } } - t.launchRuns(runs[0..m]) catch |e| return t.fail(e); + var rec = beginLaunch(t.prof, m, rows); + t.launchRuns(runs[0..m], if (rec) |*r| r else null) catch |e| return t.fail(e); tr.stats.launches += 1; t.stats.launches += 1; const lg = t.b.logitsOf(c, @intCast(rows)); @@ -211,6 +218,10 @@ pub const Tree = struct { } r0 += ch.n; } + if (rec) |*r| { + r.lap(.choose); + r.end(); + } } for (trees[0..n]) |slot| tr.finish(t, slot); } @@ -402,3 +413,39 @@ test "chains of a tree: one from row 0, one a later sibling, each with the path const bad = [_]u64{ 5, 6, 8, 6, 7, 6, 8 }; try std.testing.expectError(error.TreeDraws, o.split(.{ .slot = 0, .start = 4, .tokens = &toks, .parents = &parents, .draws = &bad, .sampling = null })); } + +var profile_now: u64 = 0; + +fn profileClock() u64 { + return profile_now; +} + +test "a branched tree launch books its phases in the round summary" { + var o: Open = .{}; + const parents = [_]i32{ -1, 0, 1, 0, 3, 0, 2 }; + const draws = [_]u64{ 5, 6, 7, 6, 7, 6, 8 }; + const toks = [_]u32{ 10, 11, 12, 13, 14, 15, 16 }; + try o.split(.{ .slot = 0, .start = 4, .tokens = &toks, .parents = &parents, .draws = &draws, .sampling = null }); + var rows: usize = 0; + for (o.chains[0..o.n_chains]) |ch| rows += ch.n; + const p = try round_prof.RoundProf.init(std.testing.allocator); + defer p.deinit(); + p.clock = profileClock; + profile_now = 10; + var rec = beginLaunch(p, o.n_chains, rows).?; + profile_now += 4_000_000; + rec.lap(.prepare); + profile_now += 5_000_000; + rec.lap(.wait); + profile_now += 6_000_000; + rec.lap(.choose); + rec.end(); + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try p.write(&w); + const text = w.buffered(); + try std.testing.expect(std.mem.indexOf(u8, text, "slots 3 rows 9-16 drafted n 1:") != null); + try std.testing.expect(std.mem.indexOf(u8, text, " prepare 4.000/4.000/4.000") != null); + try std.testing.expect(std.mem.indexOf(u8, text, " wait 5.000/5.000/5.000") != null); + try std.testing.expect(std.mem.indexOf(u8, text, " choose 6.000/6.000/6.000") != null); +} From 0568fc3de8f917937717b144a4f50e5be5329586 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:27:36 +0000 Subject: [PATCH 214/361] dsv41 metal: keep drafter timings drained after a periodic summary --- zig/build/dsv41_metal.zig | 2 ++ .../deepseek_v41/metal/round_prof.zig | 32 +++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index 99a7948aa0f..af0f1aa3faa 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -43,6 +43,8 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module }); // the package's own checks run with the default test step; its device suites run from their named steps test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = p.pkg })).step); + const profile_run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{ "a branched tree launch books", "drafter timings drained after" } })); + b.step("test-dsv41-round-prof-host", "DeepSeek-V4.1 Metal: deterministic round profile host regressions").dependOn(&profile_run.step); const step = b.step("test-dsv41-metal", "DeepSeek-V4.1 Metal layer and forward: float64 stages, rows at once == one at a time"); // serve_lanes over the CPU twin, checked here so no CUDA step has to depend on the neutral served engine const lanes_test = b.createModule(.{ diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index c51b83f38bf..6bda10db41f 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -213,9 +213,11 @@ pub const RoundProf = struct { /// The summary: one line a launch shape (slots, rows, drafted or plain), the command buffers, the drafter's passes. pub fn write(p: *const RoundProf, w: *std.Io.Writer) !void { - // no round since the last summary: nothing to say (the summary at close after a periodic one) - if (p.rounds == p.since) return; - try w.print("dsv41 round profile: rounds {d} to {d} ({d} rounds; mean and percentiles cover these rounds); ms mean/p50/p95\n", .{ p.since + 1, p.rounds, p.rounds - p.since }); + if (p.rounds == p.since) { + var pending = false; + for (p.ev) |s| if (s.n > 0) { pending = true; break; }; + if (!pending) return; + } else try w.print("dsv41 round profile: rounds {d} to {d} ({d} rounds; mean and percentiles cover these rounds); ms mean/p50/p95\n", .{ p.since + 1, p.rounds, p.rounds - p.since }); for (p.groups, 0..) |bs, slots| for (bs, 0..) |ds, b| for (ds, 0..) |g, drafted| if (g) |gg| if (gg.n > 0) { try w.print("slots {d} rows {s} {s} n {d}:", .{ slots, row_buckets[b], if (drafted == 1) "drafted" else "plain", gg.n }); for (&gg.phase, 0..) |*s, i| if (s.n > 0) try p.cell(w, @tagName(@as(Phase, @fromBackingInt(@intCast(i)))), s); @@ -381,3 +383,27 @@ test "a summary with no round since the last one writes nothing" { try p.write(&w); try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "rounds 1 to 1 (1 rounds;") != null); } + +test "drafter timings drained after an exact periodic boundary reach the final summary" { + const a = std.testing.allocator; + const p = try RoundProf.init(a); + defer p.deinit(); + p.clock = fakeClock; + fake_now = 1; + for (0..report_every) |_| { + var r = p.begin(1, 1); + fake_now += 1000; + r.lap(.wait); + r.end(); + } + try std.testing.expectEqual(@as(u64, report_every), p.since); + p.event(.chain_gpu, 7_000_000); + p.event(.finish, 2_000_000); + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try p.write(&w); + const text = w.buffered(); + try std.testing.expect(std.mem.indexOf(u8, text, "drafter n 1: chain_gpu 7.000/7.000/7.000") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "drafter n 1: finish 2.000/2.000/2.000") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "0 rounds") == null); +} From 120c55f578a64336349d063f0cb04f92ab27a278 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:34:10 +0000 Subject: [PATCH 215/361] tests: make DSV41 profiler regressions host-runnable --- build.zig | 1 + zig/build/dsv41_metal.zig | 18 ++++++++++++++++-- .../families/deepseek_v41/metal/round_prof.zig | 5 ++++- zig/src/families/deepseek_v41/metal/tree.zig | 2 +- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/build.zig b/build.zig index 4d111ca78f7..128a3baab35 100644 --- a/build.zig +++ b/build.zig @@ -112,6 +112,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/checkpoint_security.zig").tests(b, test_step); @import("zig/build/quant_geometry_host.zig").steps(b, test_step); @import("zig/build/stage.zig").steps(b, test_step); + @import("zig/build/dsv41_metal.zig").hostSteps(b); if (b.graph.host.result.os.tag == .macos) { const step5_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); const empty = b.addWriteFiles().add("step5-compile-only.metallib", ""); diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index af0f1aa3faa..e2ecd24da51 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -31,6 +31,22 @@ pub fn engine(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Modul return m; } +/// The two deterministic profiler checks over host Metal stubs; no device step or Metal framework is run on Linux. +pub fn hostSteps(b: *std.Build) void { + const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = b.graph.host, .link_libc = true }); + if (b.graph.host.result.os.tag == .macos) { + metal.linkFramework("Metal", .{}); + metal.linkFramework("Foundation", .{}); + metal.linkFramework("IOSurface", .{}); + metal.linkSystemLibrary("objc", .{}); + } + const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); + sources.addAnonymousImport("nemotron_packed_metallib", .{ .root_source_file = b.addWriteFiles().add("dsv41-profile-empty.zig", "pub const bytes = \"\";\n") }); + const p = package(b, metal, sources, .Debug); + const run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{ "a branched tree launch books", "drafter timings drained after" } })); + b.step("test-dsv41-round-prof-host", "DeepSeek-V4.1 Metal: deterministic round profile host regressions").dependOn(&run.step); +} + /// `test-dsv41-metal`: package, layer and forward checks on this GPU; `test-dsv41-metal-real`: a TF_DSV41_REAL layer. pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module, test_step: *std.Build.Step) void { const p = package(b, metal, sources, .Debug); @@ -43,8 +59,6 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module }); // the package's own checks run with the default test step; its device suites run from their named steps test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = p.pkg })).step); - const profile_run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{ "a branched tree launch books", "drafter timings drained after" } })); - b.step("test-dsv41-round-prof-host", "DeepSeek-V4.1 Metal: deterministic round profile host regressions").dependOn(&profile_run.step); const step = b.step("test-dsv41-metal", "DeepSeek-V4.1 Metal layer and forward: float64 stages, rows at once == one at a time"); // serve_lanes over the CPU twin, checked here so no CUDA step has to depend on the neutral served engine const lanes_test = b.createModule(.{ diff --git a/zig/src/families/deepseek_v41/metal/round_prof.zig b/zig/src/families/deepseek_v41/metal/round_prof.zig index 6bda10db41f..7d28945f623 100644 --- a/zig/src/families/deepseek_v41/metal/round_prof.zig +++ b/zig/src/families/deepseek_v41/metal/round_prof.zig @@ -215,7 +215,10 @@ pub const RoundProf = struct { pub fn write(p: *const RoundProf, w: *std.Io.Writer) !void { if (p.rounds == p.since) { var pending = false; - for (p.ev) |s| if (s.n > 0) { pending = true; break; }; + for (p.ev) |s| if (s.n > 0) { + pending = true; + break; + }; if (!pending) return; } else try w.print("dsv41 round profile: rounds {d} to {d} ({d} rounds; mean and percentiles cover these rounds); ms mean/p50/p95\n", .{ p.since + 1, p.rounds, p.rounds - p.since }); for (p.groups, 0..) |bs, slots| for (bs, 0..) |ds, b| for (ds, 0..) |g, drafted| if (g) |gg| if (gg.n > 0) { diff --git a/zig/src/families/deepseek_v41/metal/tree.zig b/zig/src/families/deepseek_v41/metal/tree.zig index af8923dd242..674a0b97ab6 100644 --- a/zig/src/families/deepseek_v41/metal/tree.zig +++ b/zig/src/families/deepseek_v41/metal/tree.zig @@ -432,7 +432,7 @@ test "a branched tree launch books its phases in the round summary" { defer p.deinit(); p.clock = profileClock; profile_now = 10; - var rec = beginLaunch(p, o.n_chains, rows).?; + var rec = Tree.beginLaunch(p, o.n_chains, rows).?; profile_now += 4_000_000; rec.lap(.prepare); profile_now += 5_000_000; From 5c8eaa4f8e0e1858ede6026e0459fe50b3eee19c Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:13:57 +0100 Subject: [PATCH 216/361] dsv41 metal: guard optional indexer shape in FP8 timing and add host regression --- zig/build/dsv41_metal.zig | 2 +- .../families/deepseek_v41/metal/weights.zig | 40 +++++++++++++++++++ zig/tests/dsv41_metal/timing_real.zig | 4 +- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index e2ecd24da51..e77d1cc5f09 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -43,7 +43,7 @@ pub fn hostSteps(b: *std.Build) void { const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); sources.addAnonymousImport("nemotron_packed_metallib", .{ .root_source_file = b.addWriteFiles().add("dsv41-profile-empty.zig", "pub const bytes = \"\";\n") }); const p = package(b, metal, sources, .Debug); - const run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{ "a branched tree launch books", "drafter timings drained after" } })); + const run = b.addRunArtifact(b.addTest(.{ .root_module = p.pkg, .filters = &.{ "a branched tree launch books", "drafter timings drained after", "fp8 projection shapes" } })); b.step("test-dsv41-round-prof-host", "DeepSeek-V4.1 Metal: deterministic round profile host regressions").dependOn(&run.step); } diff --git a/zig/src/families/deepseek_v41/metal/weights.zig b/zig/src/families/deepseek_v41/metal/weights.zig index 4eff4ad368a..6e0336d0d5d 100644 --- a/zig/src/families/deepseek_v41/metal/weights.zig +++ b/zig/src/families/deepseek_v41/metal/weights.zig @@ -24,6 +24,9 @@ pub const max_backing = 8; /// A dense FP8 projection: E4M3 codes [n][k] and E8M0 scales [n/32][k/32]. pub const Fp8 = struct { w: Ref, s: Ref, k: u32, n: u32 }; +/// A named dense FP8 projection of one layer for timing runs. +pub const NamedFp8 = struct { name: []const u8, w: Fp8 }; + /// An Engram layer's GPU half: wkv [(hc + 1) * hidden][cols * 256] FP8, q_weight and k_weight [hc][hidden] bf16. pub const Engram = struct { wkv: Fp8, q: Ref, k: Ref }; @@ -107,6 +110,23 @@ pub const Layer = struct { } unreachable; } + + /// Dense FP8 projections timed per layer; appends `ix_wq_b` only when present. + pub fn fp8ProjectionShapes(l: *const Layer, out: *[7]NamedFp8) []const NamedFp8 { + out[0..6].* = .{ + .{ .name = "wq_a", .w = l.wq_a }, + .{ .name = "wkv", .w = l.wkv }, + .{ .name = "wq_b", .w = l.wq_b }, + .{ .name = "wo_b", .w = l.wo_b }, + .{ .name = "shared w1", .w = l.shared[0] }, + .{ .name = "shared w2", .w = l.shared[1] }, + }; + if (l.ix_wq_b) |ix| { + out[6] = .{ .name = "ix_wq_b", .w = ix }; + return out[0..7]; + } + return out[0..6]; + } }; /// Tensors queued by name, then read into one arena in a single pass (`fill`). @@ -359,3 +379,23 @@ pub fn loadTopFrom(a: std.mem.Allocator, io: std.Io, device: mtl.Device, pack: * try l.fill(io, arena.contents()[0..l.size]); return .{ .arena = arena, .embed = off[0].ref(arena), .head = off[1].ref(arena), .norm = off[2].ref(arena) }; } + +test "fp8 projection shapes omit indexer on non-index layers and include it when present" { + var l: Layer = undefined; + l.wq_a = .{ .w = .{ .buf = undefined }, .s = .{ .buf = undefined }, .k = 16, .n = 32 }; + l.wkv = .{ .w = .{ .buf = undefined }, .s = .{ .buf = undefined }, .k = 16, .n = 64 }; + l.wq_b = .{ .w = .{ .buf = undefined }, .s = .{ .buf = undefined }, .k = 32, .n = 96 }; + l.wo_b = .{ .w = .{ .buf = undefined }, .s = .{ .buf = undefined }, .k = 64, .n = 16 }; + l.shared = @splat(.{ .w = .{ .buf = undefined }, .s = .{ .buf = undefined }, .k = 16, .n = 128 }); + l.ix_wq_b = null; + var out: [7]NamedFp8 = undefined; + const non_index = l.fp8ProjectionShapes(&out); + try std.testing.expectEqual(@as(usize, 6), non_index.len); + for (non_index) |sh| try std.testing.expect(!std.mem.eql(u8, sh.name, "ix_wq_b")); + try std.testing.expectEqualStrings("shared w2", non_index[5].name); + l.ix_wq_b = .{ .w = .{ .buf = undefined }, .s = .{ .buf = undefined }, .k = 32, .n = 256 }; + const indexed = l.fp8ProjectionShapes(&out); + try std.testing.expectEqual(@as(usize, 7), indexed.len); + try std.testing.expectEqualStrings("ix_wq_b", indexed[6].name); + try std.testing.expectEqual(@as(u32, 256), indexed[6].w.n); +} diff --git a/zig/tests/dsv41_metal/timing_real.zig b/zig/tests/dsv41_metal/timing_real.zig index 9fa279e0651..9f6723c5498 100644 --- a/zig/tests/dsv41_metal/timing_real.zig +++ b/zig/tests/dsv41_metal/timing_real.zig @@ -302,8 +302,8 @@ pub fn time(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, names: *con fn fp8Shapes(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, n: usize) !void { const fp8 = pkg.pipelines.fp8; const w = &r.layers[0]; - const Shape = struct { name: []const u8, w: pkg.weights.Fp8 }; - const shapes = [_]Shape{ .{ .name = "wq_a", .w = w.wq_a }, .{ .name = "wkv", .w = w.wkv }, .{ .name = "wq_b", .w = w.wq_b }, .{ .name = "wo_b", .w = w.wo_b }, .{ .name = "shared w1", .w = w.shared[0] }, .{ .name = "shared w2", .w = w.shared[1] }, .{ .name = "ix_wq_b", .w = w.ix_wq_b.? } }; + var shape_buf: [7]pkg.weights.NamedFp8 = undefined; + const shapes = w.fp8ProjectionShapes(&shape_buf); const samples = try counters.SampleBuffer.init(r.device, 64); defer samples.deinit(); const pass = try counters.ComputePass.init(); From c576f59f9d08a4b405ad25eddece76d5d2a45d4d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:36:19 +0000 Subject: [PATCH 217/361] changelog: #2951 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63dac063194..b733f92194c 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 +- DeepSeek-V4.1 on Metal: `TF_DSV41_ROUND_PROF=1` times every decode round (host prepare, encode, wait and choose, each command buffer's GPU span and the gaps between them, and the drafter's ingest, propose and finish) and logs mean, p50 and p95 by slots, rows and drafted or plain every 4096 rounds and at close; it is off by default and changes no token (#2951, refs #2984). Thanks to @gilby. + - Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). - Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930). From d507f1ef8685f6c13b2712cf22c8be6def5fadce Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:36:19 +0000 Subject: [PATCH 218/361] changelog: #2951 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b733f92194c..f7c274554ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - DeepSeek-V4.1 on Metal: `TF_DSV41_ROUND_PROF=1` times every decode round (host prepare, encode, wait and choose, each command buffer's GPU span and the gaps between them, and the drafter's ingest, propose and finish) and logs mean, p50 and p95 by slots, rows and drafted or plain every 4096 rounds and at close; it is off by default and changes no token (#2951, refs #2984). Thanks to @gilby. + + - Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). - Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930). From 99c6f06b87237c39e70781600164a6aa2c21c149 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:58:11 +0100 Subject: [PATCH 219/361] glm metal: GLM_POOL_TOKENS sizes the shared latent pool apart from the per-stream window Unset keeps the pool equal to --context. A set pool is planned with its caches and window scratch, refused by name before cache allocation when the load limit cannot hold it, and refused with the two-Mac pair or GLM_POOL=0. Refs #3152. --- docs/environment.md | 1 + zig/build/glm_expiry.zig | 2 +- zig/src/families/glm/engine.zig | 12 +++-- zig/src/families/glm/glm.zig | 2 + zig/src/families/glm/pool.zig | 8 ++- zig/src/families/glm/pool_size.zig | 64 +++++++++++++++++++++++ zig/src/families/glm/pool_size_test.zig | 68 +++++++++++++++++++++++++ zig/src/glm_schedule_tests.zig | 4 ++ zig/src/native/glm_host.zig | 10 ++-- zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 7 +++ 11 files changed, 170 insertions(+), 9 deletions(-) create mode 100644 zig/src/families/glm/pool_size.zig create mode 100644 zig/src/families/glm/pool_size_test.zig diff --git a/docs/environment.md b/docs/environment.md index 0521fcb8b99..922bdc8e72a 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -114,6 +114,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_QWEN35_METAL_KV_PAGES` | Qwen 3.5 on Metal: exactly `0` or `1`; `1` puts the streams' keys and values in core-pool pages; unset or blank is `0` | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | | `GLM_ROUND_PROF` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `1` has the server log a summary of its verify windows when streams end (window GPU time, idle gap, drafts span and host phases by rows, streams and drafted or plain; partial accepts); default off | +| `GLM_POOL_TOKENS` | GLM-5.3-Flash on Metal, one Mac: a whole number of tokens from 1024 through 4294967231 for the shared latent pool; `--context` stays the most one stream may use, so `--parallel 3 --context 1048576 GLM_POOL_TOKENS=2000000` shares a 2M-token pool and a stream is cut to the pool when it is smaller; refused with the pair or `GLM_POOL=0`, and when the pool does not fit the load limit; unset or blank: the pool is the window, as before | | `TF_DSV41_SMALL` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` reads the checkpoint's config at its own small shapes (the served smoke test's tiny model); default 0 | | `TF_DSV41_ASSETS` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the Engram token map; unset or blank reads it beside the checkpoint | | `TF_DSV41_ENGRAM_DIR` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the packed Engram tables; unset or blank takes the checkpoint's `engram_table_dir` | diff --git a/zig/build/glm_expiry.zig b/zig/build/glm_expiry.zig index 9fbc177c59d..386de91f6f8 100644 --- a/zig/build/glm_expiry.zig +++ b/zig/build/glm_expiry.zig @@ -47,7 +47,7 @@ pub fn steps(b: *std.Build, test_step: *std.Build.Step, lanes: *std.Build.Module b.step("check-glm-gather-gpu-host", "Compile the GPU gather equality gate without compiling or running shaders").dependOn(&gpu_check.step); const core = sharedHostCore(b, metal); const sched_mod = hostMod(b, "zig/src/glm_schedule_tests.zig", metal, lanes, fabric, sources, core); - const schedule = b.addTest(.{ .filters = &.{ "glm prefill:", "fill aging:", "glm order:" }, .root_module = sched_mod }); + const schedule = b.addTest(.{ .filters = &.{ "glm prefill:", "fill aging:", "glm order:", "glm pool tokens:" }, .root_module = sched_mod }); if (b.graph.host.result.os.tag == .macos) schedule.root_module.linkSystemLibrary("objc", .{}); const schedule_run = b.addRunArtifact(schedule); b.step("test-glm-scheduling-host", "Actual GLM prefill chunks and lane-host decode fairness using a fake engine").dependOn(&schedule_run.step); diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 31b2e21c0f8..4ae8a28e915 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -16,6 +16,7 @@ const ep_mod = @import("ep.zig"); const CopyIndex = @import("../../core/copy_index.zig").CopyIndex; const checks = @import("checks.zig"); const load_plan = @import("load_plan.zig"); +const pool_size = @import("pool_size.zig"); const plain_rounds = @import("plain_rounds.zig"); const ranks = @import("ranks.zig"); const frags = @import("../../core/frags.zig"); @@ -105,11 +106,11 @@ pub const Engine = struct { /// Checkpoint `dir`, caches for `cap` tokens; GLM_LAYERS=N: the first N layers; GLM_EP=settings: half the experts. pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, cap: u32) !*Engine { - return loadWith(gpa, io, dir, cap, if (platform.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false, null, false); + return loadWith(gpa, io, dir, cap, if (platform.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false, null, false, null); } - /// `load` with expert parallel over `ep_path`'s link (one Mac when null) and `vision`'s image tower and rows. - pub fn loadWith(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool, vision: ?vision_mod.Limits, defer_residency: bool) !*Engine { + /// `load` with expert parallel over `ep_path`'s link, `vision`'s tower and GLM_POOL_TOKENS (`cap`: its pool). + pub fn loadWith(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool, vision: ?vision_mod.Limits, defer_residency: bool, pool_tokens: ?u32) !*Engine { const keep_resident = try residency.policy.flag(platform.getenv("GLM_RESIDENCY")); const e = try gpa.create(Engine); // undefined memory: every field is set below errdefer gpa.destroy(e); @@ -195,6 +196,11 @@ pub const Engine = struct { plan_bytes = lean_bytes; } } + var pool_why: [400]u8 = undefined; + if (pool_tokens) |t| if (try pool_size.check(&pool_why, gpa, &e.c, t, cap, chunked, plan_bytes + tower, limit, e.limit.source())) |why| { + std.log.err("glm: {s}", .{why}); // GLM_POOL_TOKENS, by name + return error.OverMemoryLimit; + }; if (platform.c.getenv("GLM_DRY") != null) return error.DryRun; e.arena = .{ .device = e.device, .gpa = gpa }; errdefer e.arena.deinit(); diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index 381635e8c22..502804bb1cf 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -13,6 +13,7 @@ pub const ep = @import("ep.zig"); pub const slots = @import("slots.zig"); pub const snapshot = @import("snapshot.zig"); pub const pool = @import("pool.zig"); +pub const pool_size = @import("pool_size.zig"); pub const backend = @import("backend.zig"); pub const mirror = @import("mirror.zig"); pub const timing = @import("timing.zig"); @@ -59,6 +60,7 @@ test { _ = @import("load_plan.zig"); _ = @import("page_cache.zig"); _ = pool; + _ = @import("pool_size_test.zig"); _ = @import("kept.zig"); _ = @import("round_prof.zig"); _ = @import("draw_test.zig"); diff --git a/zig/src/families/glm/pool.zig b/zig/src/families/glm/pool.zig index 5a6fb98cb3c..ca7c2ec08cd 100644 --- a/zig/src/families/glm/pool.zig +++ b/zig/src/families/glm/pool.zig @@ -19,7 +19,7 @@ pub const Pool = struct { pub const block: u32 = 256; // tokens; a multiple of the indexer's pooling width /// The tokens a region of `n` blocks holds: its last pooling block keeps the cache's extra pooled entry. - fn tokens(p: *const Pool, n: u32) u32 { + pub fn tokens(p: *const Pool, n: u32) u32 { return n * block - p.kpool; } @@ -42,7 +42,11 @@ pub const Pool = struct { /// Whether the slots share one pool: on one Mac (a pair's ranks mirror slot commands), unless GLM_POOL=0. pub fn on(e: *const Engine) bool { - if (e.ep != null or e.followsPeer()) return false; + return !(e.ep != null or e.followsPeer()) and wanted(); +} + +/// GLM_POOL is not 0: what a load decides on before its engine knows whether it serves one Mac. +pub fn wanted() bool { const v = platform.c.getenv("GLM_POOL") orelse return true; return !std.mem.eql(u8, std.mem.span(v), "0"); } diff --git a/zig/src/families/glm/pool_size.zig b/zig/src/families/glm/pool_size.zig new file mode 100644 index 00000000000..cf8112435a1 --- /dev/null +++ b/zig/src/families/glm/pool_size.zig @@ -0,0 +1,64 @@ +//! GLM_POOL_TOKENS: the shared latent pool sized apart from the per-stream window (unset: the pool is the window). +const std = @import("std"); +const platform = @import("sys"); +const st = @import("state.zig"); +const pool = @import("pool.zig"); +const cfg = @import("config.zig"); +const load_plan = @import("load_plan.zig"); + +/// Tokens of cache an engine is loaded with beyond the pool's last whole block's reach. +pub const slack: u32 = 64; + +pub const name = "GLM_POOL_TOKENS"; + +/// The setting, whole and checked by platform/environment.zig; null when unset or blank. +pub fn fromEnv() !?u32 { + return platform.environment.read(?u32, name, null); +} + +/// The caches an engine is loaded with: the window's (unset) or the pool's tokens, and the slack. +pub fn cacheTokens(window: u32, tokens: ?u32) u32 { + return (tokens orelse window) + slack; +} + +/// The setting needs the shared pool: one Mac and GLM_POOL not 0; without it a stream would own the whole pool. +pub fn needsPool(tokens: ?u32, pair: bool) error{PoolTokensNeedPool}!void { + if (tokens == null) return; + if (!pair and pool.wanted()) return; + std.log.err("glm: {s} sizes the shared pool of one Mac: it cannot be used with the two-Mac pair or GLM_POOL=0", .{name}); + return error.PoolTokensNeedPool; +} + +/// The tokens the pool holds for an engine loaded with `cap` tokens: whole blocks, less the pooled entry. +pub fn poolTokens(cap: u32, kpool: u32) u32 { + const p: pool.Pool = .{ .base = undefined, .blocks = cap / pool.Pool.block, .kpool = kpool }; + return p.tokens(p.blocks); +} + +/// The most tokens one stream serves: its window, within the pool less the rows a pass holds beside its last window. +pub fn streamWindow(window: u32, capacity: u32) u32 { + return @min(window, capacity -| (st.max_rows + 1)); +} + +/// The refusal text when the caches counted for the pool pass the load limit; null when they fit. +pub fn problem(buf: []u8, t: u32, need: usize, used: usize, limit: usize, source: []const u8) ?[]const u8 { + if (used + need <= limit) return null; + const gb = struct { + fn of(b: usize) f64 { + return @as(f64, @floatFromInt(b)) / 1e9; + } + }.of; + return std.fmt.bufPrint(buf, "{s}={d} needs {d:.1} GB of caches beside {d:.1} GB of weights and images, past this Mac's {d:.1} GB load limit ({s}); " ++ + "lower {s} or raise the limit", .{ name, t, gb(need), gb(used), gb(limit), source, name }) catch name; +} + +/// A load's early refusal text, before any cache is allocated: the pool's least caches, counted, against `limit`. +pub fn check(buf: []u8, gpa: std.mem.Allocator, c: *const cfg.Config, t: u32, cap: u32, chunked: bool, used: usize, limit: usize, source: []const u8) !?[]const u8 { + return problem(buf, t, try load_plan.leastArena(gpa, c, cap, chunked), used, limit, source); +} + +/// The startup line's context words: the window alone, or a stream's window and the pool it shares. +pub fn contextWords(buf: []u8, window: u32, tokens: ?u32, capacity: u32) []const u8 { + const t = tokens orelse return std.fmt.bufPrint(buf, "context {d} tokens", .{window}) catch "context"; + return std.fmt.bufPrint(buf, "context {d} tokens a stream in a shared pool of {d} tokens ({s}={d})", .{ window, capacity, name, t }) catch "context"; +} diff --git a/zig/src/families/glm/pool_size_test.zig b/zig/src/families/glm/pool_size_test.zig new file mode 100644 index 00000000000..d23c7a58d3b --- /dev/null +++ b/zig/src/families/glm/pool_size_test.zig @@ -0,0 +1,68 @@ +//! GLM_POOL_TOKENS: the planning functions with no device, and the setting's refusals. +const std = @import("std"); +const cfg = @import("config.zig"); +const load_plan = @import("load_plan.zig"); +const state = @import("state.zig"); +const pool_size = @import("pool_size.zig"); +const environment = @import("sys").environment; + +const window: u32 = 1_048_576; + +test "glm pool tokens: unset sizes the engine as the window did, a set value sizes it by the pool" { + try std.testing.expectEqual(window + 64, pool_size.cacheTokens(window, null)); + try std.testing.expectEqual(@as(u32, 2_000_064), pool_size.cacheTokens(window, 2_000_000)); + // the window's pool is the one a 1M --context always had; the set pool keeps whole blocks (the 2M pin's 1,999,868) + try std.testing.expectEqual(@as(u32, 1_048_572), pool_size.poolTokens(pool_size.cacheTokens(window, null), 4)); + try std.testing.expectEqual(@as(u32, 1_999_868), pool_size.poolTokens(pool_size.cacheTokens(window, 2_000_000), 4)); + try std.testing.expectEqual(window, pool_size.streamWindow(window, 1_999_868)); + try std.testing.expectEqual(@as(u32, 1_048_555), pool_size.streamWindow(window, 1_048_572)); + try std.testing.expectEqual(@as(u32, 3_000), pool_size.streamWindow(window, 3_017)); // a pool under the window cuts it + try std.testing.expectEqual(@as(u32, 0), pool_size.streamWindow(window, 8)); +} + +test "glm pool tokens: the memory plan counts the larger pool's caches and the scratch that grows with it" { + const c: cfg.Config = .{}; + const small = pool_size.cacheTokens(window, null); + const big = pool_size.cacheTokens(window, 2_000_000); + const gpa = std.testing.allocator; + const grew = try load_plan.leastArena(gpa, &c, big, true) - try load_plan.leastArena(gpa, &c, small, true); + const caches = state.stateBytes(&c, big, true) - state.stateBytes(&c, small, true); + const sscore = state.max_rows * @as(usize, (big - small) / c.kpool) * 4; // the window scratch's indexer scores + try std.testing.expect(grew >= caches + sscore); + try std.testing.expect(caches > 17_000_000_000); +} + +test "glm pool tokens: a pool past the load limit is refused by name, one inside it is not" { + var buf: [400]u8 = undefined; + const c: cfg.Config = .{}; + const need = try load_plan.leastArena(std.testing.allocator, &c, pool_size.cacheTokens(window, 2_000_000), true); + const weights: usize = 180_000_000_000; + try std.testing.expect(pool_size.problem(&buf, 2_000_000, need, weights, 300_000_000_000, "GLM_LOAD_LIMIT_GB") == null); + const why = pool_size.problem(&buf, 2_000_000, need, weights, 200_000_000_000, "GLM_LOAD_LIMIT_GB").?; + try std.testing.expect(std.mem.startsWith(u8, why, "GLM_POOL_TOKENS=2000000 needs ")); + try std.testing.expect(std.mem.indexOf(u8, why, "GLM_LOAD_LIMIT_GB") != null and std.mem.endsWith(u8, why, "lower GLM_POOL_TOKENS or raise the limit")); + const cap = pool_size.cacheTokens(window, 2_000_000); + const refused = (try pool_size.check(&buf, std.testing.allocator, &c, 2_000_000, cap, true, weights, 200_000_000_000, "70% of RAM")).?; + try std.testing.expect(std.mem.startsWith(u8, refused, "GLM_POOL_TOKENS=")); + try std.testing.expect(try pool_size.check(&buf, std.testing.allocator, &c, 2_000_000, cap, true, weights, 300_000_000_000, "70% of RAM") == null); +} + +test "glm pool tokens: malformed or out-of-range text is refused naming the setting, blank is unset" { + for ([_][]const u8{ "lots", "2k", "0", "1023", "-1", "+2000000", "1e6", "4294967232", "2 000" }) |raw| { + try std.testing.expectError(error.InvalidEnvironment, environment.value(?u32, pool_size.name, raw, null)); + const why = try environment.describe(std.testing.allocator, pool_size.name, raw); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.startsWith(u8, why, "GLM_POOL_TOKENS=\"")); + } + for ([_]?[]const u8{ null, "", " " }) |raw| try std.testing.expectEqual(@as(?u32, null), try environment.value(?u32, pool_size.name, raw, null)); + try std.testing.expectEqual(@as(?u32, 2_000_000), try environment.value(?u32, pool_size.name, " 2000000\t", null)); +} + +test "glm pool tokens: the startup line states the window and the pool, and is today's line when unset" { + var buf: [160]u8 = undefined; + try std.testing.expectEqualStrings("context 1048576 tokens", pool_size.contextWords(&buf, window, null, 1_048_572)); + try std.testing.expectEqualStrings( + "context 1048576 tokens a stream in a shared pool of 1999868 tokens (GLM_POOL_TOKENS=2000000)", + pool_size.contextWords(&buf, window, 2_000_000, 1_999_868), + ); +} diff --git a/zig/src/glm_schedule_tests.zig b/zig/src/glm_schedule_tests.zig index c7a4a1233b0..ed7b5ddd8a0 100644 --- a/zig/src/glm_schedule_tests.zig +++ b/zig/src/glm_schedule_tests.zig @@ -26,3 +26,7 @@ test { test { _ = @import("glm_order_tests.zig"); } + +test { + _ = @import("families/glm/pool_size_test.zig"); +} diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index 9088b6c5dfd..d798e82ad55 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -88,7 +88,9 @@ fn learnedStates(gpa: Allocator, io: std.Io, dir: []const u8, eng: *const ge.Eng pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, decode_share: ?f64, learn: ?Learn, vision: ?api.VisionOpen, drafter: ?[]const u8, drafter_name: ?[]const u8, drafter_bits: u8) !*Host { // a prompt's tower rows and images: the images' budget, and every video's frame groups beside it const limits: ?glm.vision.Limits = if (vision) |v| .{ .image_tokens = v.image_tokens + v.video_tokens, .max_images = v.max_images + v.max_videos * ((v.max_frames + 1) / 2) } else null; - const eng = try ge.Engine.loadWith(gpa, io, dir, window + 64, speed_up, learn != null, limits, true); + const pool_tokens = try glm.pool_size.fromEnv(); + try glm.pool_size.needsPool(pool_tokens, speed_up != null); + const eng = try ge.Engine.loadWith(gpa, io, dir, glm.pool_size.cacheTokens(window, pool_tokens), speed_up, learn != null, limits, true, pool_tokens); errdefer eng.deinit(); if (drafter) |d| try glm.metal_dflash_load.load(gpa, io, eng, d, drafter_bits); // freed with the engine var toks: [96]u32 = undefined; @@ -127,7 +129,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.wall = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.wall.clock()); errdefer h.core.deinit(); - const serves = @min(window, glm.pool.capacity(&h.slots) -| (glm.state.max_rows + 1)); // prompt + reply a stream's caches hold beside its last window (a pool keeps whole blocks) + const serves = glm.pool_size.streamWindow(window, glm.pool.capacity(&h.slots)); // a pool keeps whole blocks var offer: ?api.Vision = null; if (eng.vision) |v| { const o = vision.?; @@ -180,7 +182,9 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: errdefer h.host.stop(); if (eng.followsPeer()) h.follower = try std.Thread.spawn(.{ .stack_size = 16 << 20 }, follow, .{h}); const role = if (eng.ep == null) "" else if (eng.followsPeer()) ", speed-up rank 1" else ", speed-up rank 0"; - std.log.info("GLM-5.3-Flash loaded in {d:.1} s ({d:.1} GB of weights{s}), context {d} tokens, {d} streams", .{ eng.load_seconds, @as(f64, @floatFromInt(eng.w.bytes)) / 1e9, role, window, n }); + var ctx_words: [160]u8 = undefined; + const context = glm.pool_size.contextWords(&ctx_words, if (pool_tokens == null) window else serves, pool_tokens, glm.pool.capacity(&h.slots)); + std.log.info("GLM-5.3-Flash loaded in {d:.1} s ({d:.1} GB of weights{s}), {s}, {d} streams", .{ eng.load_seconds, @as(f64, @floatFromInt(eng.w.bytes)) / 1e9, role, context, n }); return h; } diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 711af5d540f..42186425cb9 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -118,6 +118,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, .{ .name = "TF_FN_GX_GATEUP_MB2", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's grouped gate/up decodes an expert's weights once for two rows; same output bits)" }, .{ .name = "TF_FN_GX_SHARED", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next shared rounds use eligible grouped experts with the per-row kernels' bits)" }, + .{ .name = "GLM_POOL_TOKENS", .scope = .metal, .kind = .u32, .trim = " \t", .first_digit = true, .min = 1024, .max = 4294967231, .forms = "a whole number of tokens from 1024 to 4294967231 (unset or blank: the --context window)" }, .{ .name = "TF_QWEN27_SLOT_RESUME", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 stops slot 0 resuming a later prompt; unset or blank keeps it on)" }, .{ .name = "TF_QWEN27_SHARED_PREFIX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 keeps the 27B's cached keys on the tail kernel before M5; unset or blank is 1)" }, .{ .name = "TF_QWEN27_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the 27B's keys and values in core-pool pages; unset or blank is 0)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 8b1fe873c5f..4be817491ea 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -176,6 +176,9 @@ const valid = [_]Case{ .{ .name = "GLM_EHPROJ_NAX", .raw = "1", .n = 1 }, .{ .name = "GLM_ROUND_PROF", .raw = "0", .n = 0 }, .{ .name = "GLM_ROUND_PROF", .raw = "1", .n = 1 }, + .{ .name = "GLM_POOL_TOKENS", .raw = "1024", .n = 1024 }, + .{ .name = "GLM_POOL_TOKENS", .raw = " 2000000 ", .n = 2000000 }, + .{ .name = "GLM_POOL_TOKENS", .raw = "4294967231", .n = 4294967231 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN27_SLOT_RESUME", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_SHARED_PREFIX", .raw = "0", .n = 0 }, @@ -318,6 +321,10 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "TF_MTP_TREES", "yes" }, .{ "TF_MTP_BATCH", "off" }, .{ "TF_QWEN_POOL_LOG", "true" }, .{ "TF_COST_KEY_TRACE", "on" }, .{ "TF_COST_KEY_TRACE", "on" }, .{ "TF_ROCE_HCA", "rocep1s0f0,roceP2p1s0f0,rocep1s0f1" }, + .{ "GLM_POOL_TOKENS", "0" }, .{ "GLM_POOL_TOKENS", "1023" }, + .{ "GLM_POOL_TOKENS", "4294967232" }, .{ "GLM_POOL_TOKENS", "2k" }, + .{ "GLM_POOL_TOKENS", "+2000000" }, .{ "GLM_POOL_TOKENS", "-1" }, + .{ "GLM_POOL_TOKENS", "1e6" }, .{ "GLM_POOL_TOKENS", "lots" }, }) |c| try t.expectError(error.InvalidEnvironment, e.parse(c[0], c[1])); try t.expectEqual(@as(?u64, null), try e.parse("TF_CUDA_DEVICE", " ")); try t.expectEqual(@as(?u64, 0), try e.parse("TF_Q27_COPY_ROWS", "+0")); From 0c935dc172e63b05528d8c79cd7d86017be65f60 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:43:18 +0100 Subject: [PATCH 220/361] glm: skip Metal Arena allocations at comptime off macOS for host tests --- zig/src/families/glm/state.zig | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/zig/src/families/glm/state.zig b/zig/src/families/glm/state.zig index ed168eaf5cf..e2c07ff459e 100644 --- a/zig/src/families/glm/state.zig +++ b/zig/src/families/glm/state.zig @@ -20,6 +20,11 @@ pub const Arena = struct { follow: ?mtl.ResidencySet.Follow = null, pub fn buffer(a: *Arena, len: usize) !Ref { + if (comptime @import("builtin").os.tag != .macos) { + std.debug.assert(a.dry); + a.bytes += @max(len, 16); + return .{ .buf = .{ .id = undefined } }; + } if (a.dry) { a.bytes += @max(len, 16); return .{ .buf = .{ .id = undefined } }; @@ -36,6 +41,10 @@ pub const Arena = struct { } pub fn deinit(a: *Arena) void { + if (comptime @import("builtin").os.tag != .macos) { + a.buffers.deinit(a.gpa); + return; + } for (a.buffers.items) |b| { if (a.follow) |f| f.leave(f.ctx, b); b.deinit(); From ea773ad6c6aa6e22b4b00175db718e1be85fb2cc Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:14:18 +0100 Subject: [PATCH 221/361] glm metal: keep explicit GLM_POOL_TOKENS refusal with MTP and point stream refusal to pool setting --- zig/src/families/glm/engine.zig | 28 +++++++------ zig/src/families/glm/pool_size.zig | 48 +++++++++++++++++++++ zig/src/families/glm/pool_size_test.zig | 55 +++++++++++++++++++++++++ zig/src/native/glm_host.zig | 7 ++-- 4 files changed, 122 insertions(+), 16 deletions(-) diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 4ae8a28e915..f3ad92375e9 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -186,21 +186,23 @@ pub const Engine = struct { // --vision: the image tower and its rows count against the limit beside the weights and caches const tower = if (vision) |lim| vision_mod.planBytes(lim, e.c.hidden) else 0; var plan_bytes = try load_plan.planBytes(gpa, e.device, dir, &e.c); - if (e.c.mtp > 0 and link == null and plan_bytes + tower + try load_plan.leastArena(gpa, &e.c, cap, chunked) > limit) { // one Mac: the MTP head stays on disk when only it passes the limit - var lean = e.c; - lean.mtp = 0; - const lean_bytes = try load_plan.planBytes(gpa, e.device, dir, &lean); - if (lean_bytes + tower + try load_plan.leastArena(gpa, &lean, cap, chunked) <= limit) { - std.log.info("glm: the MTP head would pass this Mac's {d:.1} GB load limit ({s}); loading without it (no MTP drafts, copy drafts stay)", .{ @as(f64, @floatFromInt(limit)) / 1e9, e.limit.source() }); - e.c = lean; - plan_bytes = lean_bytes; + const LeanPlan = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + dir: []const u8, + pub fn planBytes(self: @This(), lean: *const cfg.Config) !usize { + return load_plan.planBytes(self.gpa, self.device, self.dir, lean); } - } - var pool_why: [400]u8 = undefined; - if (pool_tokens) |t| if (try pool_size.check(&pool_why, gpa, &e.c, t, cap, chunked, plan_bytes + tower, limit, e.limit.source())) |why| { - std.log.err("glm: {s}", .{why}); // GLM_POOL_TOKENS, by name - return error.OverMemoryLimit; }; + var pool_why: [400]u8 = undefined; + switch (try pool_size.planFit(&pool_why, gpa, &e.c, pool_tokens, cap, chunked, link != null, tower, limit, e.limit.source(), &plan_bytes, LeanPlan{ .gpa = gpa, .device = e.device, .dir = dir })) { + .ok => {}, + .dropped_mtp => std.log.info("glm: the MTP head would pass this Mac's {d:.1} GB load limit ({s}); loading without it (no MTP drafts, copy drafts stay)", .{ @as(f64, @floatFromInt(limit)) / 1e9, e.limit.source() }), + .refused => |why| { + std.log.err("glm: {s}", .{why}); // GLM_POOL_TOKENS, by name + return error.OverMemoryLimit; + }, + } if (platform.c.getenv("GLM_DRY") != null) return error.DryRun; e.arena = .{ .device = e.device, .gpa = gpa }; errdefer e.arena.deinit(); diff --git a/zig/src/families/glm/pool_size.zig b/zig/src/families/glm/pool_size.zig index cf8112435a1..b18a85ea161 100644 --- a/zig/src/families/glm/pool_size.zig +++ b/zig/src/families/glm/pool_size.zig @@ -62,3 +62,51 @@ pub fn contextWords(buf: []u8, window: u32, tokens: ?u32, capacity: u32) []const const t = tokens orelse return std.fmt.bufPrint(buf, "context {d} tokens", .{window}) catch "context"; return std.fmt.bufPrint(buf, "context {d} tokens a stream in a shared pool of {d} tokens ({s}={d})", .{ window, capacity, name, t }) catch "context"; } + +/// Result of checking startup weight and pool fit against the load limit. +pub const StartupOutcome = union(enum) { + ok, + dropped_mtp, + refused: []const u8, +}; + +/// Drops MTP only when `tokens == null` and leaning out MTP fits, then checks explicit `GLM_POOL_TOKENS`. +pub fn planFit( + buf: []u8, + gpa: std.mem.Allocator, + c: *cfg.Config, + tokens: ?u32, + cap: u32, + chunked: bool, + paired: bool, + tower: usize, + limit: usize, + source: []const u8, + plan_bytes: *usize, + lean_ctx: anytype, +) !StartupOutcome { + var outcome: StartupOutcome = .ok; + if (tokens == null and c.mtp > 0 and !paired and plan_bytes.* + tower + try load_plan.leastArena(gpa, c, cap, chunked) > limit) { + var lean = c.*; + lean.mtp = 0; + const lean_bytes = try lean_ctx.planBytes(&lean); + if (lean_bytes + tower + try load_plan.leastArena(gpa, &lean, cap, chunked) <= limit) { + c.* = lean; + plan_bytes.* = lean_bytes; + outcome = .dropped_mtp; + } + } + if (tokens) |t| if (try check(buf, gpa, c, t, cap, chunked, plan_bytes.* + tower, limit, source)) |why| { + return .{ .refused = why }; + }; + return outcome; +} + +/// Refusal text when `want` fixed streams do not fit; blames `GLM_POOL_TOKENS` when set instead of `--context`. +pub fn fitProblem(buf: []u8, want: u32, cap: usize, limit: usize, source: []const u8, fit_count: u32, tokens: ?u32) []const u8 { + const lim_gb = @as(f64, @floatFromInt(limit)) / 1e9; + if (tokens) |t| { + return std.fmt.bufPrint(buf, "{d} streams beside {s}={d} pass this Mac's {d:.1} GB load limit ({s}); {d} fit (lower --parallel or {s})", .{ want, name, t, lim_gb, source, fit_count, name }) catch name; + } + return std.fmt.bufPrint(buf, "{d} streams of {d}-token caches pass this Mac's {d:.1} GB load limit ({s}); {d} fit (lower --parallel or --context)", .{ want, cap, lim_gb, source, fit_count }) catch "--parallel"; +} diff --git a/zig/src/families/glm/pool_size_test.zig b/zig/src/families/glm/pool_size_test.zig index d23c7a58d3b..daa391bcf5d 100644 --- a/zig/src/families/glm/pool_size_test.zig +++ b/zig/src/families/glm/pool_size_test.zig @@ -66,3 +66,58 @@ test "glm pool tokens: the startup line states the window and the pool, and is t pool_size.contextWords(&buf, window, 2_000_000, 1_999_868), ); } + +test "glm pool tokens: explicit pool preserves named refusal when MTP puts load over limit; unset drops MTP" { + const gpa = std.testing.allocator; + const cap = pool_size.cacheTokens(window, 65_536); + var lean_c: cfg.Config = .{ .mtp = 0 }; + var mtp_c: cfg.Config = .{ .mtp = 1 }; + const lean_arena = try load_plan.leastArena(gpa, &lean_c, cap, true); + const full_arena = try load_plan.leastArena(gpa, &mtp_c, cap, true); + const full_weights: usize = 180_000_000_000; + const lean_weights: usize = 175_000_000_000; + // Budget fits after dropping MTP (lean_weights + lean_arena <= limit), fails with MTP enabled. + const limit = full_weights + full_arena - 1; + try std.testing.expect(lean_weights + lean_arena <= limit); + + const LeanPlan = struct { + bytes: usize, + pub fn planBytes(self: @This(), _: *const cfg.Config) !usize { + return self.bytes; + } + }; + const lean_ctx: LeanPlan = .{ .bytes = lean_weights }; + var buf: [400]u8 = undefined; + + // Explicit GLM_POOL_TOKENS keeps MTP enabled and returns the named refusal instead of starting without MTP. + var explicit_bytes = full_weights; + var explicit_c = mtp_c; + const out_explicit = try pool_size.planFit(&buf, gpa, &explicit_c, 65_536, cap, true, false, 0, limit, "70% of RAM", &explicit_bytes, lean_ctx); + switch (out_explicit) { + .refused => |why| try std.testing.expect(std.mem.startsWith(u8, why, "GLM_POOL_TOKENS=65536 needs ")), + else => return error.TestUnexpectedResult, + } + try std.testing.expectEqual(@as(u32, 1), explicit_c.mtp); + try std.testing.expectEqual(full_weights, explicit_bytes); + + // Unset GLM_POOL_TOKENS keeps the existing MTP-drop fallback. + var unset_bytes = full_weights; + var unset_c = mtp_c; + const out_unset = try pool_size.planFit(&buf, gpa, &unset_c, null, cap, true, false, 0, limit, "70% of RAM", &unset_bytes, lean_ctx); + try std.testing.expectEqual(pool_size.StartupOutcome.dropped_mtp, out_unset); + try std.testing.expectEqual(@as(u32, 0), unset_c.mtp); + try std.testing.expectEqual(lean_weights, unset_bytes); +} + +test "glm pool tokens: fixed stream refusal blames GLM_POOL_TOKENS instead of --context when pool is set" { + var buf: [320]u8 = undefined; + const set_msg = pool_size.fitProblem(&buf, 4, 2_000_064, 200_000_000_000, "70% of RAM", 2, 2_000_000); + try std.testing.expect(std.mem.indexOf(u8, set_msg, "GLM_POOL_TOKENS") != null); + try std.testing.expect(std.mem.indexOf(u8, set_msg, "--parallel") != null); + try std.testing.expect(std.mem.indexOf(u8, set_msg, "--context") == null); + + var unset_buf: [320]u8 = undefined; + const unset_msg = pool_size.fitProblem(&unset_buf, 4, 1_048_640, 200_000_000_000, "70% of RAM", 2, null); + try std.testing.expect(std.mem.indexOf(u8, unset_msg, "--context") != null); + try std.testing.expect(std.mem.indexOf(u8, unset_msg, "--parallel") != null); +} diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index d798e82ad55..d58503335d2 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -47,14 +47,15 @@ fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 { } /// Streams fitting beside the weights under the load limit, at most `want` (`fixed`: all or none); pooled: KDA only. -fn fit(eng: *const ge.Engine, want: u32, fixed: bool) !u32 { +fn fit(eng: *const ge.Engine, want: u32, fixed: bool, pool_tokens: ?u32) !u32 { const per = glm.state.stateBytes(&eng.c, if (glm.pool.on(eng)) 0 else eng.s.cap, true) + 64 * 1024 + glm.metal_dflash_load.streamBytes(eng); const used = eng.w.bytes + eng.arena.bytes + glm.vision.heldBytes(eng.vision) + glm.metal_dflash_load.heldBytes(eng); const limit = eng.limit.bytes; const room: u64 = if (limit > used) (limit - used) / per else 0; const n: u32 = @intCast(@min(@as(u64, @max(want, 1)), 1 + room)); if (n < want and fixed) { - std.log.err("glm: {d} streams of {d}-token caches pass this Mac's {d:.1} GB load limit ({s}); {d} fit (lower --parallel or --context)", .{ want, eng.s.cap, @as(f64, @floatFromInt(limit)) / 1e9, eng.limit.source(), n }); + var buf: [320]u8 = undefined; + std.log.err("glm: {s}", .{glm.pool_size.fitProblem(&buf, want, eng.s.cap, limit, eng.limit.source(), n, pool_tokens)}); return error.OverMemoryLimit; } return n; @@ -103,7 +104,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.eng = eng; h.follower = null; h.learned = null; - h.slots = try glm.slots.Slots.init(gpa, eng, try fit(eng, streams, fixed)); + h.slots = try glm.slots.Slots.init(gpa, eng, try fit(eng, streams, fixed, pool_tokens)); errdefer h.slots.deinit(gpa); glm.residency.wire(eng, io); try glm.metal_dflash_load.joinResidency(gpa, eng); From d30325dcb5422d3981ab6de6633e2ae0af6ad17e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:36:22 +0000 Subject: [PATCH 222/361] changelog: #3906 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7c274554ec..aa885c41c69 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 +- GLM on Metal: `GLM_POOL_TOKENS` sizes the shared latent pool apart from each stream's `--context` window, so one Mac's streams can share a 2M-token pool with zero output-token differences (#3906). Thanks to @gilby. + - DeepSeek-V4.1 on Metal: `TF_DSV41_ROUND_PROF=1` times every decode round (host prepare, encode, wait and choose, each command buffer's GPU span and the gaps between them, and the drafter's ingest, propose and finish) and logs mean, p50 and p95 by slots, rows and drafted or plain every 4096 rounds and at close; it is off by default and changes no token (#2951, refs #2984). Thanks to @gilby. From 54c32bafe90721d51828c67dd72a4e84c246f982 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 223/361] 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 257d2488dd011befa45ab20e0c2eea3dd240f7e7 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 224/361] 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 c27941fb1120d112510f747526aea2aa2e57745e 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 225/361] 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 04a02ad354f94bcace64c593e23025264a1e97d3 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 226/361] 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 75977e9fb4f2d0b79dc78da58cd2f79f2b1eb9af 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 227/361] 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 5b2de1cafdcb68d77d419a793b019d148a1bbe55 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 228/361] 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 a0fe34833d42f61a92a5da0982302341098f8e0f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:35:32 +0000 Subject: [PATCH 229/361] changelog: #4802 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa885c41c69..debc40badff 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). + - GLM on Metal: `GLM_POOL_TOKENS` sizes the shared latent pool apart from each stream's `--context` window, so one Mac's streams can share a 2M-token pool with zero output-token differences (#3906). Thanks to @gilby. - DeepSeek-V4.1 on Metal: `TF_DSV41_ROUND_PROF=1` times every decode round (host prepare, encode, wait and choose, each command buffer's GPU span and the gaps between them, and the drafter's ingest, propose and finish) and logs mean, p50 and p95 by slots, rows and drafted or plain every 4096 rounds and at close; it is off by default and changes no token (#2951, refs #2984). Thanks to @gilby. From deb041e46ac65172adf26d3f0554af8797df1795 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:35:32 +0000 Subject: [PATCH 230/361] changelog: #4802 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index debc40badff..a263ecc7600 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - 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). + + - GLM on Metal: `GLM_POOL_TOKENS` sizes the shared latent pool apart from each stream's `--context` window, so one Mac's streams can share a 2M-token pool with zero output-token differences (#3906). Thanks to @gilby. - DeepSeek-V4.1 on Metal: `TF_DSV41_ROUND_PROF=1` times every decode round (host prepare, encode, wait and choose, each command buffer's GPU span and the gaps between them, and the drafter's ingest, propose and finish) and logs mean, p50 and p95 by slots, rows and drafted or plain every 4096 rounds and at close; it is off by default and changes no token (#2951, refs #2984). Thanks to @gilby. From ff73e7441c03e1f5e0c5b1c790a16881f8c0c013 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 231/361] 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 411220d791d..216320d9848 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 aa3422fe096980a483c0bd99e9752bf14e5de89f 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 232/361] 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 439c04b627b9ca01c85f4a3cae8c23a677e438b7 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 233/361] 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 a263ecc7600..15d0e07a266 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - 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). From 7aadce5e255e024af6e989c61d95c6650c016a29 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:35:35 +0000 Subject: [PATCH 234/361] changelog: #4894's line from lines/4894.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15d0e07a266..0d61065740f 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 +- 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). @@ -63,7 +65,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - 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). From 375b08ba0c81a0db83f18b042b3b1a88b02f59d6 Mon Sep 17 00:00:00 2001 From: BadAd84 Date: Fri, 20 Nov 2026 08:14:49 +0000 Subject: [PATCH 235/361] flashnext: a lone stream's copy window takes the width the boot check proves The net change of #4075 at be2dc1a573 over its merge base 3661a42814, as one commit: the branch's merge commits hold changes of their own. --- docs/environment.md | 1 + docs/optimization-ledger.md | 2 +- docs/receipts/flashnext-copy-window/README.md | 324 ++++++++++++++++++ docs/receipts/flashnext-copy-window/cells.csv | 115 +++++++ .../flashnext-copy-window/exactness.md | 21 ++ .../flashnext-copy-window/noise-rule.md | 40 +++ zig/build/cuda_fault_host.zig | 1 + .../families/flashnext/cuda_draft_draw.zig | 27 +- zig/src/families/flashnext/cuda_kv_lanes.zig | 16 +- zig/src/families/flashnext/cuda_lanes.zig | 10 +- .../flashnext/cuda_lanes_admission_test.zig | 2 +- .../families/flashnext/cuda_lanes_load.zig | 18 +- zig/src/families/flashnext/cuda_mtp.zig | 119 ++++++- zig/src/families/flashnext/cuda_mtp_check.zig | 85 ++++- zig/src/families/flashnext/cuda_mtp_draft.zig | 122 ++++--- zig/src/families/flashnext/cuda_mtp_draw.zig | 7 +- .../flashnext/cuda_mtp_nonfinite_fixture.zig | 17 +- zig/src/families/flashnext/cuda_mtp_ops.zig | 5 +- zig/src/native/cuda_cache_capacity_test.zig | 19 + zig/src/native/cuda_kv_pool.zig | 8 +- zig/src/native/cuda_memory.zig | 6 + zig/src/platform/environment.zig | 1 + zig/src/platform/environment_test.zig | 2 + zig/tests/cuda/contract_flashnext_late.zig | 5 +- zig/tests/fixtures/gradient-serving.tsv | 14 +- 25 files changed, 880 insertions(+), 107 deletions(-) create mode 100644 docs/receipts/flashnext-copy-window/README.md create mode 100644 docs/receipts/flashnext-copy-window/cells.csv create mode 100644 docs/receipts/flashnext-copy-window/exactness.md create mode 100644 docs/receipts/flashnext-copy-window/noise-rule.md diff --git a/docs/environment.md b/docs/environment.md index 922bdc8e72a..f3590fd284f 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -219,6 +219,7 @@ stops the start with the variable, the supplied text and the accepted forms. | `TF_FLASHNEXT_DRAFTS_GREEDY` | Whole draft count; default 8, then clamped to 1 through 15 | | `TF_FLASHNEXT_GREEDY_WIDE` | Whole round width; default 4 | | `TF_FLASHNEXT_WINDOW_ROWS` | Whole row count; default the shared round's rows, capped by them | +| `TF_FLASHNEXT_WINDOW_CHECK` | Exactly `0` or `1`; default off. `1` measures, before the model serves, the widest verify window whose every row scores byte-equal to its one-token step, and widens a lone stream's copy window up to it, past the 32 rows served without it and at most the 48 rows a window's pending-row log holds; a check that cannot run, fails, or proves nothing past 32 rows leaves 32 | | `TF_FLASHNEXT_READOUT_ROWS` | Whole row count; default 64; `0` never takes the tiles | | `TF_FLASHNEXT_CHUNK` | Whole prompt rows a pass, 1 through 16384; default 3072 | | `TF_FLASHNEXT_CHUNK_SOLO` | Whole prompt rows a pass with no stream decoding, from the chunk `TF_FLASHNEXT_CHUNK` resolves to through 16384; unset or blank is the larger of that chunk and 8192 on a server of one stream, and that chunk elsewhere | diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index f87341fe5c5..21a820266ba 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -66,7 +66,7 @@ last two hold the families with only a Metal, HIP or scoring backend. | 15. MTP | done [#1562]; dense C done [#3582] | done [#1925] | done [#1585]; wide C done [#2257] | done [#1385] | done [#997] | | 16. DFlash(2) | done [#1465] | yes | done C[#979], open M[#3152] | done C¹ M[#879] | yes | | 17. DSpark | yes | yes | yes | yes | yes | -| 18. Copy drafts | done [#1477] | done [#468] | done [#2146]; wide C done [#2257] | done [#2022] | done [#1974] | +| 18. Copy drafts | done [#1477] | done [#468]; wide C open | done [#2146]; wide C done [#2257] | done [#2022] | done [#1974] | | 19. Shared drafts | done [#1562] | no (null [#1762]) | done [#1779]; cap C done [#2257] | done [#1779] | done [#768] | | 20. Solo chunks | yes | done C[#1733] M[#2167] | done [#1823] | done C[#2391] | yes | | 21. Read-ahead | done [#1928] | no (row 22) | done [#1616] | done [#1928] | done [#2033] | diff --git a/docs/receipts/flashnext-copy-window/README.md b/docs/receipts/flashnext-copy-window/README.md new file mode 100644 index 00000000000..5280b688814 --- /dev/null +++ b/docs/receipts/flashnext-copy-window/README.md @@ -0,0 +1,324 @@ +# Flash Next copy window: main against the branch + +`TF_FLASHNEXT_WINDOW_CHECK=1`, off by default, runs a boot self-check that sweeps every verify width a window can +hold, compares each row's scores with the scores of a one-token step on the same machine, and serves a lone +stream's copy window at the largest width whose every row matched, past the 32 rows the engine ships and at most +the 48 rows a window's pending-row log holds. Unset or blank is main's 32 rows, and a check that cannot run, +fails, or proves nothing past 32 leaves the window at 32. + +## Source and environment + +- Main: `d8b947b1ff35ed1492b2a6aa675d30367b6ab777`. Branch: this pull request at `a13efbe9d95fe0dc96d8b4d8f8dddea557388d4f`; the receipt commit adds only this directory. +- Each image built from a verified `git archive` tree of its own commit, blob by blob against the commit's own + manifest: the recipe's Zig base image, nvcc 13.3, Zig 0.17.0, kernels embedded. +- One NVIDIA GB10 (sm_121), 121 GiB unified memory, one GPU. Host: 7.0.0-1019-nvidia-64k; Ubuntu 24.04.5 LTS; NVIDIA GB10, 580.178.04, [N/A]; RAM 123 GiB. +- Checkpoint `nvidia/Qwen3.8-Flash-Next-FP4-Local`, revision `b9ce18a6887e18c089fdea8509a33e63429a3300`, every + arm. +- `--context 32768 --parallel 8`, bf16 KV cache, drafts on (`TF_FLASHNEXT_DRAFTS=6`), a fresh server per arm, the + recipe's own defaults (`TF_FLASHNEXT_WARM_AHEAD=1`, `TENSORFOLD_MEMORY_RESERVE_GIB=9` and the rest of the + recipe's Flash Next settings), and nothing else. B1 adds `TF_FLASHNEXT_WINDOW_CHECK=1` and nothing else. +- Arms, in order: M1, B0a, B1a, B1b, B0b, M2 for the decode, copy and cold passes; M, B0, B1 for exactness, each + with a cache-on boot and a `--prompt-cache-gib 0` boot; MD and B1D for the drafts-off pass. + +Each arm ran, on its own fresh server: + +- `tools/bench_openai.py --tokens 256 --reps 3 --temperatures 0` (one stream, a code prompt and a chat prompt). +- `tools/bench_concurrent.py --tokens 256 --reps 3 --levels 1,2,4,6,8 --alone --serial --temperatures 0`, which is + both the decode cells and the concurrent-equals-solo contract, on the same code and chat prompts. +- `copy_bench.py`: one text of 1969 prompt tokens sent twice per rep, once with the instruction to repeat it + verbatim and once with the instruction to change one word, one stream, greedy, 3 reps, the reply's token ids + and their SHA-256 recorded. +- `/metrics` around every probe (`mtp_drafted_total`, `mtp_accepted_total`), and the server's own per-path request + counts before and after it, so an arm that saw a request it did not send would be rerun. + +The cold pass boots at `--context 131072 --parallel 4 --prompt-cache-gib 0`: `ttft.py` at 2k, 8k, 32k and 64k +(three reps each, thinking off, a fresh salt a prompt) and `tools/bench_cache.py --tokens 64 --repeats 2 +--streams 2 --require-cold`. + +## Before the first boot: the late-log contract, and the off path's pool line + +Two measurements were taken inside the window's lock, with production stopped, before the first timed boot. + +The branch serves the 48-row shape of the two late-log kernels `fn_gdn_front_log` and `fn_gdn_rows_late`, so the +kernel contract's gate 3 runs a 48-row window through both against the kernels they replace. One run, from the +branch image: + +``` +$ docker run --rm --gpus all --entrypoint /bin/sh tensorfold-qwen38:pcw-b-c14485f5 -c \ + 'ls -l /opt/tensorfold/bin/tf-cuda-test && /opt/tensorfold/bin/tf-cuda-test kernel-contract fn_gdn_front_log fn_gdn_rows_late' +kernel-contract rc 0 +``` + +`(filtered) SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 0 controls: 0 red as planted, 0 missed; 0 limit problems; gates 112 ms, limits 0 ms` + +So 2 kernels passed gates 1 to 4 with 0 failing, and all 0 planted controls were red as planted with 0 missed; exit status 0. + +The second measurement is the startup pool line, which is where the off path shows: with the switch unset the +branch must size every buffer a stream's window needs exactly as main does, and with it set the buffers hold the +log's 48 rows. Each boot's own line, from its container's log: + +| boot | context/streams | prompt cache | drafts | model GiB | per-stream GiB | GiB left | after reserve GiB | +|---|---|---|---|---|---|---|---| +| 1/M1 | 32768/8 | on | on | 72.71 | 1.29 | 27.8 | 9.0 | +| 1/B0a | 32768/8 | on | on | 72.71 | 1.29 | 27.8 | 9.0 | +| 1/B1a | 32768/8 | on | on | 72.71 | 1.32 | 27.8 | 9.0 | +| 1/B1b | 32768/8 | on | on | 72.71 | 1.32 | 27.8 | 9.0 | +| 1/B0b | 32768/8 | on | on | 72.71 | 1.29 | 27.9 | 9.0 | +| 1/M2 | 32768/8 | on | on | 72.71 | 1.29 | 27.9 | 9.0 | +| 2/M1 | 131072/4 | off | on | 72.73 | 4.11 | 27.8 | 9.0 | +| 2/B0a | 131072/4 | off | on | 72.73 | 4.11 | 27.8 | 9.0 | +| 2/B1a | 131072/4 | off | on | 72.73 | 4.13 | 27.8 | 9.0 | +| 2/B1b | 131072/4 | off | on | 72.73 | 4.13 | 27.8 | 9.0 | +| 2/B0b | 131072/4 | off | on | 72.73 | 4.11 | 27.8 | 9.0 | +| 2/M2 | 131072/4 | off | on | 72.73 | 4.11 | 27.8 | 9.0 | +| 3/M/on | 32768/8 | on | on | 72.71 | 1.29 | 27.9 | 9.0 | +| 3/M/off | 32768/8 | off | on | 72.71 | 1.29 | 27.8 | 9.0 | +| 3/B0/on | 32768/8 | on | on | 72.71 | 1.29 | 27.9 | 9.0 | +| 3/B0/off | 32768/8 | off | on | 72.71 | 1.29 | 27.8 | 9.0 | +| 3/B1/on | 32768/8 | on | on | 72.71 | 1.32 | 27.8 | 9.0 | +| 3/B1/off | 32768/8 | off | on | 72.71 | 1.32 | 27.8 | 9.0 | +| 4/MD | 32768/8 | on | off | 70.84 | 0.98 | 30.1 | 9.0 | +| 4/B1D | 32768/8 | on | off | 70.84 | 0.98 | 30.1 | 9.0 | + +- POOL B0 vs M 32768/8 cache off drafts on per-stream: M 1.29 B0 1.29 equal YES +- POOL B0 vs M 32768/8 cache off drafts on left: M 27.8 B0 27.8 equal YES +- POOL B1 vs M 32768/8 cache off drafts on per-stream: M 1.29 B1 1.32 equal NO +- POOL B1 vs M 32768/8 cache off drafts on left: M 27.8 B1 27.8 equal YES +- POOL M vs M 32768/8 cache off drafts on: per-stream 1.29 left 27.8 (1 boots) +- POOL B1 vs M 32768/8 cache on drafts off per-stream: M 0.98 B1 0.98 equal YES +- POOL B1 vs M 32768/8 cache on drafts off left: M 30.1 B1 30.1 equal YES +- POOL M vs M 32768/8 cache on drafts off: per-stream 0.98 left 30.1 (1 boots) +- POOL B0 vs M 32768/8 cache on drafts on per-stream: M 1.29 B0 1.29 equal YES +- POOL B0 vs M 32768/8 cache on drafts on left: M 27.8,27.9 B0 27.8,27.9 equal YES +- POOL B1 vs M 32768/8 cache on drafts on per-stream: M 1.29 B1 1.32 equal NO +- POOL B1 vs M 32768/8 cache on drafts on left: M 27.8,27.9 B1 27.8 equal WITHIN-MAIN-SPREAD +- POOL M vs M 32768/8 cache on drafts on: per-stream 1.29 left 27.8,27.9 (3 boots) +- POOL B0 vs M 131072/4 cache off drafts on per-stream: M 4.11 B0 4.11 equal YES +- POOL B0 vs M 131072/4 cache off drafts on left: M 27.8 B0 27.8 equal YES +- POOL B1 vs M 131072/4 cache off drafts on per-stream: M 4.11 B1 4.13 equal NO +- POOL B1 vs M 131072/4 cache off drafts on left: M 27.8 B1 27.8 equal YES +- POOL M vs M 131072/4 cache off drafts on: per-stream 4.11 left 27.8 (2 boots) + +B0's per-stream size equals main's on every group it booted in, so the branch with the switch off allocates +main's buffers and the switch is the only difference. With the switch on, a stream's pool entry carries the +wider size the 48-row window needs: B1 reads 1.32 GiB each against main's 1.29 at the pass A +window. + +## The check's line and the width it chose + +Every B1 boot printed the same line: `1176 of 1176 rows byte-equal to their one-token steps (widths 1-48)`, +followed by `serving 48-row copy windows after the self-check`. 1176 is the sum of widths +1 to 48, so every row the buffers hold was compared. + +M and B0 printed no self-check line at all; the startup-log shapes confirm that the check's line, or its +failure, is the only line the switch adds and that nothing else in the load changed: + +- Line shapes (digits normalised) common to M1 and B0a: 8 +- Shapes only B1a printed: 2 +- Shapes B1a did not print that both main runs did: 0 + - B1a only: info: flashnext: serving #-row copy windows after the self-check + - B1a only: info: flashnext: window self-check: # of # rows byte-equal to their one-token steps (widths #-#) + +The served width is 48, so a lone stream's copy window ramps to 47 copied tokens a +round on this machine, against 31 on main. The width is a measurement, not a target: another GB10 with +another driver may prove fewer rows, and the receipt would then say so. + +## Decode speed and tokens a round + +Aggregate tok/s, the mean of each arm's two runs; tokens a round is the tools' pooled tokens a streamed chunk. + +| invocation | prompt | case | streams | M1 | M2 | B0a | B0b | B1a | B1b | B0vsM | B1vsM | B1vsB0 | tokens a round, before / after: B0vsM, B1vsM, B1vsB0 | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| openai_t0 | fibonacci-raw | | 1 | 72.9 | 72.8 | 72.6 | 72.7 | 72.1 | 72.7 | -0.3% level | -0.6% level | -0.3% level | 5.22 / 5.22 / 5.22 / 5.22 / 5.22 / 5.22 | +| openai_t0 | gpu-chat-no-think | | 1 | 46.7 | 46.7 | 46.6 | 46.6 | 46.3 | 46.6 | -0.2% level | -0.5% level | -0.4% level | 2.81 / 2.81 / 2.81 / 2.81 / 2.81 / 2.81 | +| conc_t0 | chat | | 1 | 46.7 | 46.6 | 46.8 | 46.6 | 46.5 | 46.6 | +0.1% level | -0.2% level | -0.3% level | 2.81 / 2.81 / 2.81 / 2.81 / 2.81 / 2.81 | +| conc_t0 | chat | | 2 | 86.6 | 86.6 | 87.0 | 86.7 | 86.2 | 86.4 | +0.3% level | -0.3% level | -0.6% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | chat | | 4 | 156.0 | 156.0 | 156.8 | 156.3 | 156.0 | 156.0 | +0.4% level | +0.0% level | -0.4% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | chat | | 6 | 210.4 | 210.4 | 211.4 | 210.7 | 210.2 | 210.3 | +0.3% level | -0.1% level | -0.4% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | chat | | 8 | 257.2 | 257.2 | 258.9 | 257.5 | 256.8 | 257.4 | +0.4% level | -0.0% level | -0.4% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | code | | 1 | 72.9 | 72.7 | 72.6 | 72.4 | 72.3 | 72.6 | -0.4% level | -0.5% level | -0.1% level | 5.22 / 5.22 / 5.22 / 5.22 / 5.22 / 5.22 | +| conc_t0 | code | | 2 | 138.5 | 138.3 | 137.9 | 138.4 | 137.8 | 138.1 | -0.2% level | -0.3% level | -0.1% level | 4.83 / 4.83 / 4.83 / 4.83 / 4.83 / 4.83 | +| conc_t0 | code | | 4 | 242.7 | 242.4 | 242.1 | 242.8 | 242.0 | 242.8 | -0.0% level | -0.1% level | -0.0% level | 4.83 / 4.83 / 4.83 / 4.83 / 4.83 / 4.83 | +| conc_t0 | code | | 6 | 307.0 | 308.0 | 309.2 | 306.8 | 307.1 | 307.7 | +0.2% level | -0.0% level | -0.2% level | 4.49 / 4.49 / 4.49 / 4.49 / 4.49 / 4.49 | +| conc_t0 | code | | 8 | 371.5 | 373.0 | 373.5 | 371.7 | 372.1 | 371.6 | +0.1% level | -0.1% level | -0.2% level | 4.49 / 4.49 / 4.49 / 4.49 / 4.49 / 4.49 | +| copy | copy.txt | changed | 1 | 246.8 | 249.2 | 250.2 | 250.7 | 287.9 | 287.9 | +1.0% level | +16.1% faster | +15.0% faster | 23.27 / 23.27 / 23.27 / 28.44 / 23.27 / 28.44 | +| copy | copy.txt | verbatim | 1 | 255.5 | 256.8 | 256.0 | 257.7 | 295.8 | 296.2 | +0.3% level | +15.6% faster | +15.2% faster | 23.27 / 23.27 / 23.27 / 28.44 / 23.27 / 28.44 | + +Verdicts, B0 against M, B1 against M and B1 against B0: + +| comparison | streams | cells | mean change | faster | level | slower | +|---|---|---|---|---|---|---| +| B0vsM | 1 | 2 | -0.15% | 0 | 2 | 0 | +| B0vsM | 2 | 2 | +0.05% | 0 | 2 | 0 | +| B0vsM | 4 | 2 | +0.16% | 0 | 2 | 0 | +| B0vsM | 6 | 2 | +0.24% | 0 | 2 | 0 | +| B0vsM | 8 | 2 | +0.24% | 0 | 2 | 0 | +| B1vsM | 1 | 2 | -0.35% | 0 | 2 | 0 | +| B1vsM | 2 | 2 | -0.34% | 0 | 2 | 0 | +| B1vsM | 4 | 2 | -0.03% | 0 | 2 | 0 | +| B1vsM | 6 | 2 | -0.05% | 0 | 2 | 0 | +| B1vsM | 8 | 2 | -0.07% | 0 | 2 | 0 | +| B1vsB0 | 1 | 2 | -0.20% | 0 | 2 | 0 | +| B1vsB0 | 2 | 2 | -0.39% | 0 | 2 | 0 | +| B1vsB0 | 4 | 2 | -0.19% | 0 | 2 | 0 | +| B1vsB0 | 6 | 2 | -0.29% | 0 | 2 | 0 | +| B1vsB0 | 8 | 2 | -0.31% | 0 | 2 | 0 | + +- B0vsM: 0 faster, 14 level, 0 slower, 0 unmeasured. +- B1vsM: 2 faster, 12 level, 0 slower, 0 unmeasured. +- B1vsB0: 2 faster, 12 level, 0 slower, 0 unmeasured. + +The code prompt's cells at 1, 2, 4, 6 and 8 streams are the contract the copy window must not move: a shared +round's copies read `cfg.first_copy` only, because `copyProposal` reads `s.copy_width` under `e.alone`, so the +served width cannot reach a shared round. + +## The copy cells + +The same text repeated, one stream, greedy, three reps an arm; tokens a round is the server's own MTP figure for +the request, and the first difference is the first character at which the reply leaves the text. + +| case | arm | decode tok/s | tokens a round (median / max) | rounds (median) | copied reps | first diff (reps) | prompt tokens | +|---|---|---|---|---|---|---|---| +| changed | M1 | 246.8 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1968 | +| changed | M2 | 249.2 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1968 | +| changed | B0a | 250.2 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1968 | +| changed | B0b | 250.7 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1968 | +| changed | B1a | 287.9 | 28.444 / 28.444 | 9 | 3 | [None, None, None] | 1968 | +| changed | B1b | 287.9 | 28.444 / 28.444 | 9 | 3 | [None, None, None] | 1968 | +| verbatim | M1 | 255.5 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1969 | +| verbatim | M2 | 256.8 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1969 | +| verbatim | B0a | 256.0 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1969 | +| verbatim | B0b | 257.7 | 23.273 / 23.273 | 11 | 3 | [None, None, None] | 1969 | +| verbatim | B1a | 295.8 | 28.444 / 28.444 | 9 | 3 | [None, None, None] | 1969 | +| verbatim | B1b | 296.2 | 28.444 / 28.444 | 9 | 3 | [None, None, None] | 1969 | + +- `changed`: B0vsM +1.0% level; B1vsM +16.1% faster; B1vsB0 +15.0% faster; tokens a round before / after 23.27 / 23.27 / 23.27 / 28.44 / 23.27 / 28.44. +- `verbatim`: B0vsM +0.3% level; B1vsM +15.6% faster; B1vsB0 +15.2% faster; tokens a round before / after 23.27 / 23.27 / 23.27 / 28.44 / 23.27 / 28.44. + +Verdicts for the copy cells are in `noise-rule.md` with the rest; the two cells are the only ones where the +wider window is expected to show, because a copy proposal needs a context the reply can repeat. + +## Cold prompts + +Time to the first token, s, the median of three salted prompts, thinking off, prompt cache off. + +| prompt | M1 | M2 | B0a | B0b | B1a | B1b | B0vsM | B1vsM | B1vsB0 | +|---|---|---|---|---|---|---|---|---|---| +| cold2k-off | 1.061 | 1.055 | 1.055 | 1.074 | 1.061 | 1.072 | +0.6% level | +0.8% level | +0.2% level | +| cold8k-off | 4.007 | 4.009 | 4.010 | 4.039 | 3.999 | 3.982 | +0.4% level | -0.4% level | -0.8% level | +| cold32k-off | 16.022 | 16.054 | 16.008 | 16.086 | 16.076 | 16.055 | +0.1% level | +0.2% level | +0.1% level | +| cold64k-off | 32.968 | 33.065 | 32.977 | 33.168 | 33.068 | 33.070 | +0.2% level | +0.2% level | -0.0% level | +| first_ttft_s | 1.223 | 1.226 | 1.225 | 1.226 | 1.230 | 1.221 | +0.1% level | +0.1% level | +0.0% level | + +Every first request reported zero cached tokens. The change reaches decode windows only, and the check runs +before the first prompt, so a prompt cell can move only by boot noise. + +## The noise rule + +A cell is slower when both runs of the after arm are under both runs of the before arm and the mean gap is over +1% (for a latency: over), faster when both are over both and the gap is over 1%, level otherwise. A flagged cell +gets one rerun on fresh boots an arm, and a repeat of slower is a loss. + +- No cell was slower in the first pair, so no rerun was taken. +- Losses: 0 + +## Exactness + +`exactness.md` has every line. The three contracts, on each arm, with the prompt cache on and off: + +- B0 cache on concurrent: concurrent equals solo 156/0 (unverified 0); drafted equals `"draft": false` 56/0 +- B0 cache on golden: concurrent equals solo 13/0 (unverified 0); drafted equals `"draft": false` 24/0 +- B0 cache on drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B0 cache on turns: resumed from cached prompt tokens [13, 16, 16, 13, 24, 18, 3406] +- B0 cache off drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B0 cache off fresh: 7 of 7 resumed replies equal the fresh ones +- B1 cache on concurrent: concurrent equals solo 156/0 (unverified 0); drafted equals `"draft": false` 56/0 +- B1 cache on golden: concurrent equals solo 13/0 (unverified 0); drafted equals `"draft": false` 24/0 +- B1 cache on drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B1 cache on turns: resumed from cached prompt tokens [13, 16, 16, 13, 24, 18, 3406] +- B1 cache off drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B1 cache off fresh: 7 of 7 resumed replies equal the fresh ones +- M cache on concurrent: concurrent equals solo 156/0 (unverified 0); drafted equals `"draft": false` 56/0 +- M cache on golden: concurrent equals solo 13/0 (unverified 0); drafted equals `"draft": false` 24/0 +- M cache on drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- M cache on turns: resumed from cached prompt tokens [13, 16, 16, 13, 24, 18, 3406] +- M cache off drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- M cache off fresh: 7 of 7 resumed replies equal the fresh ones +- B0: replies equal over pass A's greedy cells (token_sha): 528 equal, 0 unequal +- B1: replies equal over pass A's greedy cells (token_sha): 528 equal, 0 unequal +- B1/M: replies equal over pass A's greedy cells (token_sha): 528 equal, 0 unequal + +Unequal or failed pairs across every contract: 0. + +## Boot time and the check's cost + +Wall time is the recipe's own launch to its own return, the smoke-test request included, so the difference +between a B1 boot and a B0 boot of the same image is what the check costs. + +The boot cells are a second window taken on the head above, after main's load-time page-cache change (#3467), +three boots an arm on a fresh server each, in the order M1 B0a B1a M2 B1b B0b M3 B0c B1c; every other cell in +this receipt is the first window's, whose source files are byte-identical on this head apart from main's own three +edited files. + +| arm | image | ctx/par | wall s | server answered s | began (UTC) | ended (UTC) | gpu at boot | check | +|---|---|---|---|---|---|---|---|---| +| B0a | pcw2-b-a13efbe9 | 32768/8 | 37.11 | 36 | 2026-11-19T16:27:10+00:00 | 2026-11-19T16:27:47+00:00 | 53,2470MHz,14.67W | - | +| B0b | pcw2-b-a13efbe9 | 32768/8 | 37.01 | 36 | 2026-11-19T16:32:52+00:00 | 2026-11-19T16:33:29+00:00 | 53,2437MHz,14.85W | - | +| B0c | pcw2-b-a13efbe9 | 32768/8 | 37.03 | 36 | 2026-11-19T16:34:26+00:00 | 2026-11-19T16:35:03+00:00 | 52,2411MHz,14.61W | - | +| B1a | pcw2-b-a13efbe9 | 32768/8 | 49.13 | 49 | 2026-11-19T16:27:58+00:00 | 2026-11-19T16:28:47+00:00 | 54,2405MHz,15.11W | 1176 of 1176, serving 48 | +| B1b | pcw2-b-a13efbe9 | 32768/8 | 49.14 | 49 | 2026-11-19T16:31:53+00:00 | 2026-11-19T16:32:42+00:00 | 56,2405MHz,15.15W | 1176 of 1176, serving 48 | +| B1c | pcw2-b-a13efbe9 | 32768/8 | 49.14 | 49 | 2026-11-19T16:35:14+00:00 | 2026-11-19T16:36:03+00:00 | 54,2411MHz,14.97W | 1176 of 1176, serving 48 | +| M1 | pcw2-m-d8b947b1 | 32768/8 | 37.04 | 36 | 2026-11-19T16:24:13+00:00 | 2026-11-19T16:24:50+00:00 | 45,2444MHz,13.94W | - | +| M2 | pcw2-m-d8b947b1 | 32768/8 | 37.01 | 36 | 2026-11-19T16:31:06+00:00 | 2026-11-19T16:31:43+00:00 | 54,2463MHz,14.90W | - | +| M3 | pcw2-m-d8b947b1 | 32768/8 | 37.03 | 37 | 2026-11-19T16:33:39+00:00 | 2026-11-19T16:34:16+00:00 | 52,2470MHz,14.72W | - | + +- Mean wall time: M 37.03 s, B0 37.05 s, B1 49.14 s; B1 minus B0 +12.09 s, B1 minus M +12.11 s, B0 minus M +0.02 s. +- Boot-to-boot spread within an arm: M 0.03 s, B0 0.1 s, B1 0.01 s, so the largest is 0.1 s; the B1 delta is larger than the spread, so it is a cost of the check. +- Mean `Server answered` time: M 36.3 s, B0 36.0 s, B1 49.0 s. +- The same window re-took the copy cells with one probe on every boot; tokens a round read B0 23.273, B1 28.444, M 23.273 (the first window's figures). +- The sweep's own duration is not logged separately; the boot-time difference above is what it costs. +- Boot time is reported, not treated as a regression: it is paid once a server, and the width it buys is the + lever. + +## Drafts off + +`MD` (main) and `B1D` (the branch, switch on) booted with `DRAFTS=0`. The copy window is a drafter's path, so +the switch must be inert here: the same tokens and the same speed. + +| arm | prompt | streams | aggregate tok/s | tokens a round | alone equal/unequal | +|---|---|---|---|---|---| +| B1D | code | 1 | 26.9 | 1.0 | 3/0 | +| B1D | code | 2 | 50.8 | 1.0 | 6/0 | +| B1D | code | 4 | 91.8 | 1.0 | 12/0 | +| B1D | chat | 1 | 26.9 | 1.0 | 3/0 | +| B1D | chat | 2 | 50.9 | 1.0 | 6/0 | +| B1D | chat | 4 | 91.8 | 1.0 | 12/0 | +| MD | code | 1 | 26.9 | 1.0 | 3/0 | +| MD | code | 2 | 51.0 | 1.0 | 6/0 | +| MD | code | 4 | 91.3 | 1.0 | 12/0 | +| MD | chat | 1 | 27.0 | 1.0 | 3/0 | +| MD | chat | 2 | 51.1 | 1.0 | 6/0 | +| MD | chat | 4 | 91.8 | 1.0 | 12/0 | + +- Token hashes B1D against MD: 42 equal, 0 unequal. + +## Memory + +Each arm's pool line, from its own startup log (the table above has the same lines with the per-stream and +memory-left figures parsed out): + +- MEMLINE 1/M1 model 72.71 GiB; 8 streams at once, 1.29 GiB each at a 32768-token window, of 27.8 GiB left after a 9.0 GiB reserve; prompts in passes of up to 1536 rows, a 16.0 GiB prompt cache; own glue kernels +- MEMLINE 1/B0a model 72.71 GiB; 8 streams at once, 1.29 GiB each at a 32768-token window, of 27.8 GiB left after a 9.0 GiB reserve; prompts in passes of up to 1536 rows, a 16.0 GiB prompt cache; own glue kernels +- MEMLINE 1/B1a model 72.71 GiB; 8 streams at once, 1.32 GiB each at a 32768-token window, of 27.8 GiB left after a 9.0 GiB reserve; prompts in passes of up to 1536 rows, a 16.0 GiB prompt cache; own glue kernels +- MEMLINE 1/B1b model 72.71 GiB; 8 streams at once, 1.32 GiB each at a 32768-token window, of 27.8 GiB left after a 9.0 GiB reserve; prompts in passes of up to 1536 rows, a 16.0 GiB prompt cache; own glue kernels +- MEMLINE 1/B0b model 72.71 GiB; 8 streams at once, 1.29 GiB each at a 32768-token window, of 27.9 GiB left after a 9.0 GiB reserve; prompts in passes of up to 1536 rows, a 16.0 GiB prompt cache; own glue kernels +- MEMLINE 1/M2 model 72.71 GiB; 8 streams at once, 1.29 GiB each at a 32768-token window, of 27.9 GiB left after a 9.0 GiB reserve; prompts in passes of up to 1536 rows, a 16.0 GiB prompt cache; own glue kernels + +## Not established + +- One GB10 and one checkpoint. The width is a property of this machine's kernels and driver, which is why it is + measured at boot; a machine that proves fewer rows serves fewer. +- TP=2, Metal and HIP were not run: the probe runs only with drafts on at TP=1, and every other backend keeps its + own width, so their behaviour is main's. +- The sampled decode cells are the temperature 1.0 cells of the exactness pass; no speed claim is made on them, + only that their replies equal the greedy and the solo ones. diff --git a/docs/receipts/flashnext-copy-window/cells.csv b/docs/receipts/flashnext-copy-window/cells.csv new file mode 100644 index 00000000000..60d95166e96 --- /dev/null +++ b/docs/receipts/flashnext-copy-window/cells.csv @@ -0,0 +1,115 @@ +arm,pass,invocation,prompt,case,temperature,streams,value,per_stream,tokens_per_round,accepted_per_round,server_accepted,server_drafted,server_acceptance,alone_equal,alone_unequal,serial_equal,serial_unequal,failed,unmeasured,copied,first_diff,prompt_tokens +M1,A,conc_t0,chat,,0.0,1,46.7,46.7,2.813,1.813,22760,33060,0.6884,3,0,1,0,0,0,,, +M1,A,conc_t0,chat,,0.0,2,86.6,43.5,2.51,1.51,22760,33060,0.6884,6,0,1,0,0,0,,, +M1,A,conc_t0,chat,,0.0,4,156.0,39.6,2.51,1.51,22760,33060,0.6884,12,0,1,0,0,0,,, +M1,A,conc_t0,chat,,0.0,6,210.4,35.9,2.51,1.51,22760,33060,0.6884,18,0,1,0,0,0,,, +M1,A,conc_t0,chat,,0.0,8,257.2,33.1,2.51,1.51,22760,33060,0.6884,24,0,1,0,0,0,,, +M1,A,conc_t0,code,,0.0,1,72.9,72.9,5.224,4.224,22760,33060,0.6884,3,0,1,0,0,0,,, +M1,A,conc_t0,code,,0.0,2,138.5,69.7,4.83,3.83,22760,33060,0.6884,6,0,1,0,0,0,,, +M1,A,conc_t0,code,,0.0,4,242.7,62.3,4.83,3.83,22760,33060,0.6884,12,0,1,0,0,0,,, +M1,A,conc_t0,code,,0.0,6,307.0,53.1,4.491,3.491,22760,33060,0.6884,18,0,1,0,0,0,,, +M1,A,conc_t0,code,,0.0,8,371.5,48.9,4.491,3.491,22760,33060,0.6884,24,0,1,0,0,0,,, +M1,A,copy,copy.txt,changed,0.0,1,246.8,246.8,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1968 +M1,A,copy,copy.txt,verbatim,0.0,1,255.5,255.5,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1969 +M1,A,openai_t0,fibonacci-raw,,0.0,1,72.93067062243887,72.93067062243887,5.224,4.224,1488,2384,0.6242,,,,,0,0,,, +M1,A,openai_t0,gpu-chat-no-think,,0.0,1,46.72303464481997,46.72303464481997,2.813,1.813,1488,2384,0.6242,,,,,0,0,,, +M2,A,conc_t0,chat,,0.0,1,46.6,46.6,2.813,1.813,22760,33060,0.6884,3,0,1,0,0,0,,, +M2,A,conc_t0,chat,,0.0,2,86.6,43.5,2.51,1.51,22760,33060,0.6884,6,0,1,0,0,0,,, +M2,A,conc_t0,chat,,0.0,4,156.0,39.5,2.51,1.51,22760,33060,0.6884,12,0,1,0,0,0,,, +M2,A,conc_t0,chat,,0.0,6,210.4,35.9,2.51,1.51,22760,33060,0.6884,18,0,1,0,0,0,,, +M2,A,conc_t0,chat,,0.0,8,257.2,33.1,2.51,1.51,22760,33060,0.6884,24,0,1,0,0,0,,, +M2,A,conc_t0,code,,0.0,1,72.7,72.7,5.224,4.224,22760,33060,0.6884,3,0,1,0,0,0,,, +M2,A,conc_t0,code,,0.0,2,138.3,69.8,4.83,3.83,22760,33060,0.6884,6,0,1,0,0,0,,, +M2,A,conc_t0,code,,0.0,4,242.4,62.4,4.83,3.83,22760,33060,0.6884,12,0,1,0,0,0,,, +M2,A,conc_t0,code,,0.0,6,308.0,53.4,4.491,3.491,22760,33060,0.6884,18,0,1,0,0,0,,, +M2,A,conc_t0,code,,0.0,8,373.0,49.0,4.491,3.491,22760,33060,0.6884,24,0,1,0,0,0,,, +M2,A,copy,copy.txt,changed,0.0,1,249.2,249.2,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1968 +M2,A,copy,copy.txt,verbatim,0.0,1,256.8,256.8,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1969 +M2,A,openai_t0,fibonacci-raw,,0.0,1,72.7805660556267,72.7805660556267,5.224,4.224,1488,2384,0.6242,,,,,0,0,,, +M2,A,openai_t0,gpu-chat-no-think,,0.0,1,46.70233922737316,46.70233922737316,2.813,1.813,1488,2384,0.6242,,,,,0,0,,, +B0a,A,conc_t0,chat,,0.0,1,46.8,46.8,2.813,1.813,22760,33060,0.6884,3,0,1,0,0,0,,, +B0a,A,conc_t0,chat,,0.0,2,87.0,43.8,2.51,1.51,22760,33060,0.6884,6,0,1,0,0,0,,, +B0a,A,conc_t0,chat,,0.0,4,156.8,39.9,2.51,1.51,22760,33060,0.6884,12,0,1,0,0,0,,, +B0a,A,conc_t0,chat,,0.0,6,211.4,36.0,2.51,1.51,22760,33060,0.6884,18,0,1,0,0,0,,, +B0a,A,conc_t0,chat,,0.0,8,258.9,33.3,2.51,1.51,22760,33060,0.6884,24,0,1,0,0,0,,, +B0a,A,conc_t0,code,,0.0,1,72.6,72.6,5.224,4.224,22760,33060,0.6884,3,0,1,0,0,0,,, +B0a,A,conc_t0,code,,0.0,2,137.9,69.7,4.83,3.83,22760,33060,0.6884,6,0,1,0,0,0,,, +B0a,A,conc_t0,code,,0.0,4,242.1,62.2,4.83,3.83,22760,33060,0.6884,12,0,1,0,0,0,,, +B0a,A,conc_t0,code,,0.0,6,309.2,53.5,4.491,3.491,22760,33060,0.6884,18,0,1,0,0,0,,, +B0a,A,conc_t0,code,,0.0,8,373.5,49.0,4.491,3.491,22760,33060,0.6884,24,0,1,0,0,0,,, +B0a,A,copy,copy.txt,changed,0.0,1,250.2,250.2,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1968 +B0a,A,copy,copy.txt,verbatim,0.0,1,256.0,256.0,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1969 +B0a,A,openai_t0,fibonacci-raw,,0.0,1,72.55750565222056,72.55750565222056,5.224,4.224,1488,2384,0.6242,,,,,0,0,,, +B0a,A,openai_t0,gpu-chat-no-think,,0.0,1,46.62761577108674,46.62761577108674,2.813,1.813,1488,2384,0.6242,,,,,0,0,,, +B0b,A,conc_t0,chat,,0.0,1,46.6,46.6,2.813,1.813,22760,33060,0.6884,3,0,1,0,0,0,,, +B0b,A,conc_t0,chat,,0.0,2,86.7,43.5,2.51,1.51,22760,33060,0.6884,6,0,1,0,0,0,,, +B0b,A,conc_t0,chat,,0.0,4,156.3,39.6,2.51,1.51,22760,33060,0.6884,12,0,1,0,0,0,,, +B0b,A,conc_t0,chat,,0.0,6,210.7,36.0,2.51,1.51,22760,33060,0.6884,18,0,1,0,0,0,,, +B0b,A,conc_t0,chat,,0.0,8,257.5,33.2,2.51,1.51,22760,33060,0.6884,24,0,1,0,0,0,,, +B0b,A,conc_t0,code,,0.0,1,72.4,72.4,5.224,4.224,22760,33060,0.6884,3,0,1,0,0,0,,, +B0b,A,conc_t0,code,,0.0,2,138.4,69.7,4.83,3.83,22760,33060,0.6884,6,0,1,0,0,0,,, +B0b,A,conc_t0,code,,0.0,4,242.8,62.3,4.83,3.83,22760,33060,0.6884,12,0,1,0,0,0,,, +B0b,A,conc_t0,code,,0.0,6,306.8,53.1,4.491,3.491,22760,33060,0.6884,18,0,1,0,0,0,,, +B0b,A,conc_t0,code,,0.0,8,371.7,48.8,4.491,3.491,22760,33060,0.6884,24,0,1,0,0,0,,, +B0b,A,copy,copy.txt,changed,0.0,1,250.7,250.7,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1968 +B0b,A,copy,copy.txt,verbatim,0.0,1,257.7,257.7,23.273,22.273,1488,1488,1.0,,,,,0,0,3,"[None, None, None]",1969 +B0b,A,openai_t0,fibonacci-raw,,0.0,1,72.67740774275987,72.67740774275987,5.224,4.224,1488,2384,0.6242,,,,,0,0,,, +B0b,A,openai_t0,gpu-chat-no-think,,0.0,1,46.634385985271585,46.634385985271585,2.813,1.813,1488,2384,0.6242,,,,,0,0,,, +B1a,A,conc_t0,chat,,0.0,1,46.5,46.5,2.813,1.813,22760,33060,0.6884,3,0,1,0,0,0,,, +B1a,A,conc_t0,chat,,0.0,2,86.2,43.4,2.51,1.51,22760,33060,0.6884,6,0,1,0,0,0,,, +B1a,A,conc_t0,chat,,0.0,4,156.0,39.6,2.51,1.51,22760,33060,0.6884,12,0,1,0,0,0,,, +B1a,A,conc_t0,chat,,0.0,6,210.2,35.8,2.51,1.51,22760,33060,0.6884,18,0,1,0,0,0,,, +B1a,A,conc_t0,chat,,0.0,8,256.8,33.0,2.51,1.51,22760,33060,0.6884,24,0,1,0,0,0,,, +B1a,A,conc_t0,code,,0.0,1,72.3,72.3,5.224,4.224,22760,33060,0.6884,3,0,1,0,0,0,,, +B1a,A,conc_t0,code,,0.0,2,137.8,69.6,4.83,3.83,22760,33060,0.6884,6,0,1,0,0,0,,, +B1a,A,conc_t0,code,,0.0,4,242.0,62.1,4.83,3.83,22760,33060,0.6884,12,0,1,0,0,0,,, +B1a,A,conc_t0,code,,0.0,6,307.1,53.1,4.491,3.491,22760,33060,0.6884,18,0,1,0,0,0,,, +B1a,A,conc_t0,code,,0.0,8,372.1,48.9,4.491,3.491,22760,33060,0.6884,24,0,1,0,0,0,,, +B1a,A,copy,copy.txt,changed,0.0,1,287.9,287.9,28.444,27.444,1500,1500,1.0,,,,,0,0,3,"[None, None, None]",1968 +B1a,A,copy,copy.txt,verbatim,0.0,1,295.8,295.8,28.444,27.444,1500,1500,1.0,,,,,0,0,3,"[None, None, None]",1969 +B1a,A,openai_t0,fibonacci-raw,,0.0,1,72.09172228212415,72.09172228212415,5.224,4.224,1488,2384,0.6242,,,,,0,0,,, +B1a,A,openai_t0,gpu-chat-no-think,,0.0,1,46.33038564436069,46.33038564436069,2.813,1.813,1488,2384,0.6242,,,,,0,0,,, +B1b,A,conc_t0,chat,,0.0,1,46.6,46.6,2.813,1.813,22760,33060,0.6884,3,0,1,0,0,0,,, +B1b,A,conc_t0,chat,,0.0,2,86.4,43.5,2.51,1.51,22760,33060,0.6884,6,0,1,0,0,0,,, +B1b,A,conc_t0,chat,,0.0,4,156.0,39.6,2.51,1.51,22760,33060,0.6884,12,0,1,0,0,0,,, +B1b,A,conc_t0,chat,,0.0,6,210.3,36.0,2.51,1.51,22760,33060,0.6884,18,0,1,0,0,0,,, +B1b,A,conc_t0,chat,,0.0,8,257.4,33.2,2.51,1.51,22760,33060,0.6884,24,0,1,0,0,0,,, +B1b,A,conc_t0,code,,0.0,1,72.6,72.6,5.224,4.224,22760,33060,0.6884,3,0,1,0,0,0,,, +B1b,A,conc_t0,code,,0.0,2,138.1,69.8,4.83,3.83,22760,33060,0.6884,6,0,1,0,0,0,,, +B1b,A,conc_t0,code,,0.0,4,242.8,62.3,4.83,3.83,22760,33060,0.6884,12,0,1,0,0,0,,, +B1b,A,conc_t0,code,,0.0,6,307.7,53.2,4.491,3.491,22760,33060,0.6884,18,0,1,0,0,0,,, +B1b,A,conc_t0,code,,0.0,8,371.6,48.9,4.491,3.491,22760,33060,0.6884,24,0,1,0,0,0,,, +B1b,A,copy,copy.txt,changed,0.0,1,287.9,287.9,28.444,27.444,1500,1500,1.0,,,,,0,0,3,"[None, None, None]",1968 +B1b,A,copy,copy.txt,verbatim,0.0,1,296.2,296.2,28.444,27.444,1500,1500,1.0,,,,,0,0,3,"[None, None, None]",1969 +B1b,A,openai_t0,fibonacci-raw,,0.0,1,72.69335241553834,72.69335241553834,5.224,4.224,1488,2384,0.6242,,,,,0,0,,, +B1b,A,openai_t0,gpu-chat-no-think,,0.0,1,46.59375740047666,46.59375740047666,2.813,1.813,1488,2384,0.6242,,,,,0,0,,, +M1,B,ttft,cold2k-off,cold2k-off,,,1.061,,,,,,,,,,,,,,, +M1,B,ttft,cold8k-off,cold8k-off,,,4.007,,,,,,,,,,,,,,, +M1,B,ttft,cold32k-off,cold32k-off,,,16.022,,,,,,,,,,,,,,, +M1,B,ttft,cold64k-off,cold64k-off,,,32.968,,,,,,,,,,,,,,, +M1,B,cache,bench_cache,first_ttft_s,,,1.223070956999436,,,,,,,,,,,,,,,2571 +M2,B,ttft,cold2k-off,cold2k-off,,,1.055,,,,,,,,,,,,,,, +M2,B,ttft,cold8k-off,cold8k-off,,,4.009,,,,,,,,,,,,,,, +M2,B,ttft,cold32k-off,cold32k-off,,,16.054,,,,,,,,,,,,,,, +M2,B,ttft,cold64k-off,cold64k-off,,,33.065,,,,,,,,,,,,,,, +M2,B,cache,bench_cache,first_ttft_s,,,1.2264332969207317,,,,,,,,,,,,,,,2571 +B0a,B,ttft,cold2k-off,cold2k-off,,,1.055,,,,,,,,,,,,,,, +B0a,B,ttft,cold8k-off,cold8k-off,,,4.01,,,,,,,,,,,,,,, +B0a,B,ttft,cold32k-off,cold32k-off,,,16.008,,,,,,,,,,,,,,, +B0a,B,ttft,cold64k-off,cold64k-off,,,32.977,,,,,,,,,,,,,,, +B0a,B,cache,bench_cache,first_ttft_s,,,1.2252961159683764,,,,,,,,,,,,,,,2571 +B0b,B,ttft,cold2k-off,cold2k-off,,,1.074,,,,,,,,,,,,,,, +B0b,B,ttft,cold8k-off,cold8k-off,,,4.039,,,,,,,,,,,,,,, +B0b,B,ttft,cold32k-off,cold32k-off,,,16.086,,,,,,,,,,,,,,, +B0b,B,ttft,cold64k-off,cold64k-off,,,33.168,,,,,,,,,,,,,,, +B0b,B,cache,bench_cache,first_ttft_s,,,1.2257813459727913,,,,,,,,,,,,,,,2571 +B1a,B,ttft,cold2k-off,cold2k-off,,,1.061,,,,,,,,,,,,,,, +B1a,B,ttft,cold8k-off,cold8k-off,,,3.999,,,,,,,,,,,,,,, +B1a,B,ttft,cold32k-off,cold32k-off,,,16.076,,,,,,,,,,,,,,, +B1a,B,ttft,cold64k-off,cold64k-off,,,33.068,,,,,,,,,,,,,,, +B1a,B,cache,bench_cache,first_ttft_s,,,1.2304603229276836,,,,,,,,,,,,,,,2571 +B1b,B,ttft,cold2k-off,cold2k-off,,,1.072,,,,,,,,,,,,,,, +B1b,B,ttft,cold8k-off,cold8k-off,,,3.982,,,,,,,,,,,,,,, +B1b,B,ttft,cold32k-off,cold32k-off,,,16.055,,,,,,,,,,,,,,, +B1b,B,ttft,cold64k-off,cold64k-off,,,33.07,,,,,,,,,,,,,,, +B1b,B,cache,bench_cache,first_ttft_s,,,1.221265524160117,,,,,,,,,,,,,,,2571 diff --git a/docs/receipts/flashnext-copy-window/exactness.md b/docs/receipts/flashnext-copy-window/exactness.md new file mode 100644 index 00000000000..ee8af267184 --- /dev/null +++ b/docs/receipts/flashnext-copy-window/exactness.md @@ -0,0 +1,21 @@ +- B0 cache on concurrent: concurrent equals solo 156/0 (unverified 0); drafted equals `"draft": false` 56/0 +- B0 cache on golden: concurrent equals solo 13/0 (unverified 0); drafted equals `"draft": false` 24/0 +- B0 cache on drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B0 cache on turns: resumed from cached prompt tokens [13, 16, 16, 13, 24, 18, 3406] +- B0 cache off drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B0 cache off fresh: 7 of 7 resumed replies equal the fresh ones +- B1 cache on concurrent: concurrent equals solo 156/0 (unverified 0); drafted equals `"draft": false` 56/0 +- B1 cache on golden: concurrent equals solo 13/0 (unverified 0); drafted equals `"draft": false` 24/0 +- B1 cache on drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B1 cache on turns: resumed from cached prompt tokens [13, 16, 16, 13, 24, 18, 3406] +- B1 cache off drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- B1 cache off fresh: 7 of 7 resumed replies equal the fresh ones +- M cache on concurrent: concurrent equals solo 156/0 (unverified 0); drafted equals `"draft": false` 56/0 +- M cache on golden: concurrent equals solo 13/0 (unverified 0); drafted equals `"draft": false` 24/0 +- M cache on drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- M cache on turns: resumed from cached prompt tokens [13, 16, 16, 13, 24, 18, 3406] +- M cache off drafts: 8 of 8 equal to `"draft": false` (basis token_ids) +- M cache off fresh: 7 of 7 resumed replies equal the fresh ones +- B0: replies equal over pass A's greedy cells (token_sha): 528 equal, 0 unequal +- B1: replies equal over pass A's greedy cells (token_sha): 528 equal, 0 unequal +- B1/M: replies equal over pass A's greedy cells (token_sha): 528 equal, 0 unequal diff --git a/docs/receipts/flashnext-copy-window/noise-rule.md b/docs/receipts/flashnext-copy-window/noise-rule.md new file mode 100644 index 00000000000..dd9c13bae42 --- /dev/null +++ b/docs/receipts/flashnext-copy-window/noise-rule.md @@ -0,0 +1,40 @@ +| invocation | prompt | case | streams | M1 | M2 | B0a | B0b | B1a | B1b | B0vsM | B1vsM | B1vsB0 | tokens a round, before / after: B0vsM, B1vsM, B1vsB0 | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| openai_t0 | fibonacci-raw | | 1 | 72.9 | 72.8 | 72.6 | 72.7 | 72.1 | 72.7 | -0.3% level | -0.6% level | -0.3% level | 5.22 / 5.22 / 5.22 / 5.22 / 5.22 / 5.22 | +| openai_t0 | gpu-chat-no-think | | 1 | 46.7 | 46.7 | 46.6 | 46.6 | 46.3 | 46.6 | -0.2% level | -0.5% level | -0.4% level | 2.81 / 2.81 / 2.81 / 2.81 / 2.81 / 2.81 | +| conc_t0 | chat | | 1 | 46.7 | 46.6 | 46.8 | 46.6 | 46.5 | 46.6 | +0.1% level | -0.2% level | -0.3% level | 2.81 / 2.81 / 2.81 / 2.81 / 2.81 / 2.81 | +| conc_t0 | chat | | 2 | 86.6 | 86.6 | 87.0 | 86.7 | 86.2 | 86.4 | +0.3% level | -0.3% level | -0.6% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | chat | | 4 | 156.0 | 156.0 | 156.8 | 156.3 | 156.0 | 156.0 | +0.4% level | +0.0% level | -0.4% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | chat | | 6 | 210.4 | 210.4 | 211.4 | 210.7 | 210.2 | 210.3 | +0.3% level | -0.1% level | -0.4% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | chat | | 8 | 257.2 | 257.2 | 258.9 | 257.5 | 256.8 | 257.4 | +0.4% level | -0.0% level | -0.4% level | 2.51 / 2.51 / 2.51 / 2.51 / 2.51 / 2.51 | +| conc_t0 | code | | 1 | 72.9 | 72.7 | 72.6 | 72.4 | 72.3 | 72.6 | -0.4% level | -0.5% level | -0.1% level | 5.22 / 5.22 / 5.22 / 5.22 / 5.22 / 5.22 | +| conc_t0 | code | | 2 | 138.5 | 138.3 | 137.9 | 138.4 | 137.8 | 138.1 | -0.2% level | -0.3% level | -0.1% level | 4.83 / 4.83 / 4.83 / 4.83 / 4.83 / 4.83 | +| conc_t0 | code | | 4 | 242.7 | 242.4 | 242.1 | 242.8 | 242.0 | 242.8 | -0.0% level | -0.1% level | -0.0% level | 4.83 / 4.83 / 4.83 / 4.83 / 4.83 / 4.83 | +| conc_t0 | code | | 6 | 307.0 | 308.0 | 309.2 | 306.8 | 307.1 | 307.7 | +0.2% level | -0.0% level | -0.2% level | 4.49 / 4.49 / 4.49 / 4.49 / 4.49 / 4.49 | +| conc_t0 | code | | 8 | 371.5 | 373.0 | 373.5 | 371.7 | 372.1 | 371.6 | +0.1% level | -0.1% level | -0.2% level | 4.49 / 4.49 / 4.49 / 4.49 / 4.49 / 4.49 | +| copy | copy.txt | changed | 1 | 246.8 | 249.2 | 250.2 | 250.7 | 287.9 | 287.9 | +1.0% level | +16.1% faster | +15.0% faster | 23.27 / 23.27 / 23.27 / 28.44 / 23.27 / 28.44 | +| copy | copy.txt | verbatim | 1 | 255.5 | 256.8 | 256.0 | 257.7 | 295.8 | 296.2 | +0.3% level | +15.6% faster | +15.2% faster | 23.27 / 23.27 / 23.27 / 28.44 / 23.27 / 28.44 | + +Verdicts: B0vsM: 0 faster, 14 level, 0 slower, 0 unmeasured; B1vsM: 2 faster, 12 level, 0 slower, 0 unmeasured; B1vsB0: 2 faster, 12 level, 0 slower, 0 unmeasured + +| comparison | streams | cells | mean change | faster | level | slower | +|---|---|---|---|---|---|---| +| B0vsM | 1 | 2 | -0.15% | 0 | 2 | 0 | +| B0vsM | 2 | 2 | +0.05% | 0 | 2 | 0 | +| B0vsM | 4 | 2 | +0.16% | 0 | 2 | 0 | +| B0vsM | 6 | 2 | +0.24% | 0 | 2 | 0 | +| B0vsM | 8 | 2 | +0.24% | 0 | 2 | 0 | +| B1vsM | 1 | 2 | -0.35% | 0 | 2 | 0 | +| B1vsM | 2 | 2 | -0.34% | 0 | 2 | 0 | +| B1vsM | 4 | 2 | -0.03% | 0 | 2 | 0 | +| B1vsM | 6 | 2 | -0.05% | 0 | 2 | 0 | +| B1vsM | 8 | 2 | -0.07% | 0 | 2 | 0 | +| B1vsB0 | 1 | 2 | -0.20% | 0 | 2 | 0 | +| B1vsB0 | 2 | 2 | -0.39% | 0 | 2 | 0 | +| B1vsB0 | 4 | 2 | -0.19% | 0 | 2 | 0 | +| B1vsB0 | 6 | 2 | -0.29% | 0 | 2 | 0 | +| B1vsB0 | 8 | 2 | -0.31% | 0 | 2 | 0 | + +Rerun (one per flagged cell; a repeat of slower is a loss): +No cell was slower in the first pair, so no rerun was taken. +Losses: 0 diff --git a/zig/build/cuda_fault_host.zig b/zig/build/cuda_fault_host.zig index 053ee87fd80..83178924406 100644 --- a/zig/build/cuda_fault_host.zig +++ b/zig/build/cuda_fault_host.zig @@ -6,6 +6,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, flashnext: *std.Build.Modul b.step("test-cuda-context-health-host", "Sticky CUDA context faults and real graph-instantiation refusal without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{ "CUDA context health:", "CUDA graph refusal:" } })).step); b.step("test-flashnext-loader-host", "The threaded NVFP4 expert loader: the loop's words, no pinned or device memory left after a failed load, geometry first").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{"Flash Next expert loader:"} })).step); b.step("test-flashnext-completion-host", "Actual CUDA sequence rollback drains asynchronous destinations before release").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"Flash Next completion:"} })).step); + b.step("test-flashnext-window-host", "The served copy window and its buffers: a width the boot check proved, the shipped rows unless it runs").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{ "the served copy window widens", "the boot check's sweep", "a draft at 65,536 tokens", "the saved pieces follow" } })).step); b.step("test-cuda-fault-admission-host", "Sticky context health reaches native status and queue admission").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA context health:"} })).step); b.step("test-cuda-readiness-host", "Real native readiness and synchronous startup preparation without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"family readiness reaches"} })).step); b.step("test-startup-log-host", "Ordered startup logs and early P2P facts without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"startup log:"} })).step); diff --git a/zig/src/families/flashnext/cuda_draft_draw.zig b/zig/src/families/flashnext/cuda_draft_draw.zig index 785fc08facd..4ef9e048b33 100644 --- a/zig/src/families/flashnext/cuda_draft_draw.zig +++ b/zig/src/families/flashnext/cuda_draft_draw.zig @@ -3,18 +3,17 @@ const std = @import("std"); const cuda = @import("cuda"); const mtp = @import("cuda_mtp.zig"); const draw = @import("cuda_mtp_draw.zig"); -const nrows = mtp.max_rows; -const vals_at = nrows * 16; -const cols_at = vals_at + nrows * draw.topk_max * 2; -const bytes = @import("cuda_mtp_draft.zig").best_bytes; +const mtp_draft = @import("cuda_mtp_draft.zig"); pub const lanes_max = 16; pub fn scoreBytes(v: usize) usize { return lanes_max * v * 2; } pub const Ready = struct { - words: [bytes / 8]u64 = undefined, + words: [mtp_draft.bestBytes(mtp.max_rows) / 8]u64 = undefined, k: usize, + /// The window rows of the draft whose best buffer it read: where that buffer holds candidates and columns. + rows: usize, fn best(r: *const Ready, row: usize) [4]f32 { return std.mem.bytesToValue([4]f32, std.mem.asBytes(&r.words)[row * 16 ..][0..16]); } @@ -22,16 +21,16 @@ pub const Ready = struct { const b = r.best(row); if (mtp.isSampled(sm) and (!draw.usable(sm.?) or sm.?.top_k != r.k)) return draw.pick(h, st, a, d, b, position, sm, batched); const data = std.mem.asBytes(&r.words); - const vals: []const u16 = @alignCast(std.mem.bytesAsSlice(u16, data[vals_at + row * r.k * 2 ..][0 .. r.k * 2])); - const cols: []const i32 = @alignCast(std.mem.bytesAsSlice(i32, data[cols_at + row * r.k * 4 ..][0 .. r.k * 4])); + const vals: []const u16 = @alignCast(std.mem.bytesAsSlice(u16, data[mtp_draft.valsAt(r.rows) + row * r.k * 2 ..][0 .. r.k * 2])); + const cols: []const i32 = @alignCast(std.mem.bytesAsSlice(i32, data[mtp_draft.colsAt(r.rows) + row * r.k * 4 ..][0 .. r.k * 4])); return draw.pickFrom(h, a, b, vals, cols, position, sm) catch |err| { if (err == error.ProposalNonfinite) draw.badRow(st, d, b, batched, d.dlogits.ptr, h.ids.len); return err; }; } fn load(r: *Ready, st: cuda.Stream, ptr: u64, rows: usize) !void { - const n = if (r.k == 0) rows * 16 else cols_at + rows * r.k * 4; - if (n > bytes) return error.ProposalScoreShape; + const n = if (r.k == 0) rows * 16 else mtp_draft.colsAt(r.rows) + rows * r.k * 4; + if (n > mtp_draft.bestBytes(r.rows)) return error.ProposalScoreShape; try st.synchronize(); try cuda.memory.download(st.d, ptr, std.mem.asBytes(&r.words)[0..n]); } @@ -45,22 +44,22 @@ pub fn single(h: *const mtp.Head, st: cuda.Stream, a: std.mem.Allocator, d: *mtp try cuda.memory.download(st.d, d.best.ptr, std.mem.sliceAsBytes(d.best_host[0..4])); return draw.pick(h, st, a, d, d.best_host[0..4].*, position, sm, false); } - var ready = Ready{ .k = if (mtp.isSampled(sm) and draw.usable(sm.?)) sm.?.top_k else 0 }; - if (ready.k != 0) try h.topk(st, d.dlogits.ptr, n, n, 1, ready.k, d.best.ptr + vals_at, d.best.ptr + cols_at); + var ready = Ready{ .k = if (mtp.isSampled(sm) and draw.usable(sm.?)) sm.?.top_k else 0, .rows = d.layout.rows }; + if (ready.k != 0) try h.topk(st, d.dlogits.ptr, n, n, 1, ready.k, d.best.ptr + mtp_draft.valsAt(ready.rows), d.best.ptr + mtp_draft.colsAt(ready.rows)); try ready.load(st, d.best.ptr, 1); return ready.pick(h, st, a, d, 0, position, sm, false); } pub fn gather(h: *const mtp.Head, st: cuda.Stream, ds: []const *mtp.Draft, active: []const usize, sms: []const ?mtp.Sampling) !Ready { const n = h.ids.len; - if (active.len > lanes_max or active.len > nrows) return error.ProposalScoreShape; - var ready = Ready{ .k = 0 }; + if (active.len > lanes_max or active.len > ds[0].layout.rows) return error.ProposalScoreShape; + var ready = Ready{ .k = 0, .rows = ds[0].layout.rows }; for (active, 0..) |i, row| { try st.d.check(st.d.api.cuMemcpyDtoDAsync_v2(h.draw_batch.scores.ptr + row * n * 2, ds[i].dlogits.ptr, n * 2, st.handle), "cuMemcpyDtoDAsync"); if (ready.k == 0 and mtp.isSampled(sms[i]) and draw.usable(sms[i].?)) ready.k = sms[i].?.top_k; } try h.best(st, h.draw_batch.scores.ptr, n, n, active.len, ds[0].best.ptr); - if (ready.k != 0) try h.topk(st, h.draw_batch.scores.ptr, n, n, active.len, ready.k, ds[0].best.ptr + vals_at, ds[0].best.ptr + cols_at); + if (ready.k != 0) try h.topk(st, h.draw_batch.scores.ptr, n, n, active.len, ready.k, ds[0].best.ptr + mtp_draft.valsAt(ready.rows), ds[0].best.ptr + mtp_draft.colsAt(ready.rows)); try ready.load(st, ds[0].best.ptr, active.len); return ready; } diff --git a/zig/src/families/flashnext/cuda_kv_lanes.zig b/zig/src/families/flashnext/cuda_kv_lanes.zig index d3d6a1a51d9..6bdb40cf91e 100644 --- a/zig/src/families/flashnext/cuda_kv_lanes.zig +++ b/zig/src/families/flashnext/cuda_kv_lanes.zig @@ -8,8 +8,10 @@ const mtp = @import("cuda_mtp.zig"); const snap = @import("cuda_snap.zig"); const wt = @import("cuda_prompt_wt.zig"); -/// Rows past a request's prompt and reply its pages hold: one drafted window's. -pub const window_rows: u32 = mtp.max_rows; +/// Rows past a request's prompt and reply its pages hold: one drafted window's, as many as the load's buffers hold. +pub fn windowRows() usize { + return mtp.bufferRows(); +} /// TF_FLASHNEXT_KV_PAGES=n: streams beside the first take n-position pages from one pool (unset, blank or 0: none). pub fn paging() !usize { @@ -30,7 +32,7 @@ pub fn pagedOnly() bool { /// Pages a stream maps at most: a full window and one more drafted window. fn mostPages(capacity: usize, tokens: usize) usize { - return (capacity + window_rows + tokens - 1) / tokens; + return (capacity + windowRows() + tokens - 1) / tokens; } fn al(n: usize) usize { @@ -96,7 +98,7 @@ pub const State = struct { pub fn fits(s: *const State, prompt_rows: u32, max_tokens: u32) bool { const p = s.pool orelse return true; if (!s.paged_only and !s.own_busy) return true; - return p.fits(@as(usize, prompt_rows) + max_tokens + window_rows); + return p.fits(@as(usize, prompt_rows) + max_tokens + windowRows()); } }; @@ -189,7 +191,7 @@ pub const Pool = struct { /// Whether a lane is free, the pool can promise a cache of `cap` rows and a run now, and a run is free. pub fn fits(p: *const Pool, cap: usize) bool { - if (cap > p.capacity + window_rows) return false; + if (cap > p.capacity + windowRows()) return false; const k = p.layout.runPages(); for (p.lanes) |x| if (!x.used) return p.pool.fits(p.layout.pages(cap) + k) and p.pool.findRun(k) != null; return false; @@ -222,7 +224,7 @@ pub const Pool = struct { /// A free lane's cleared cache (a copy) with `cap` rows' pages and its run; LaneMemory: not now. pub fn open(p: *Pool, cap: usize) !prompt.Seq { - if (cap > p.capacity + window_rows) return error.PromptTooLong; + if (cap > p.capacity + windowRows()) return error.PromptTooLong; const x = for (p.lanes) |*x| { if (!x.used) break x; } else return error.LaneMemory; @@ -415,7 +417,7 @@ test "a stream's pages: its rows and a drafted window, no more than a full windo try std.testing.expectEqual(pages.pageBytesOf(256, wt.attn_n + 1), h.pageBytes()); try std.testing.expect(h.run_bytes >= seqRunBytes() + mtp.Draft.runBytes(32768, 1536)); try std.testing.expectEqual(@as(usize, 161), mostPages(40960, 256)); - try std.testing.expect(l.pages(40960 + window_rows) <= mostPages(40960, 256)); + try std.testing.expect(l.pages(40960 + windowRows()) <= mostPages(40960, 256)); } test { diff --git a/zig/src/families/flashnext/cuda_lanes.zig b/zig/src/families/flashnext/cuda_lanes.zig index bc96b84e5bb..412e8b77b77 100644 --- a/zig/src/families/flashnext/cuda_lanes.zig +++ b/zig/src/families/flashnext/cuda_lanes.zig @@ -40,7 +40,7 @@ pub fn Namespace(comptime Tri: type) type { pub const snap_drop = snaps.drop; pub const kept_view = @import("cuda_disk.zig").View(@This()); // their disk image (native/cuda_kept.zig) /// TF_FLASHNEXT_KV_PAGES: the pool's lanes, the pages of a request's rows and a drafted window (kvl). - pub const window_rows = kvl.window_rows; + pub const windowRows = kvl.windowRows; pub fn attach(p: *anyopaque, streams: u32, count: usize) !void { const own = of(p); own.kv.pool = try kvl.Pool.initOn(own.gpa, own.engine, own.kv.layout.?, own.context, own.kv.head, streams, count, own.device, own.io); @@ -225,11 +225,11 @@ pub fn Namespace(comptime Tri: type) type { return .{ .ptr = self, .warm_images = false, .proposal_head = if (self.head) |h| &h.service else null, .first_before_draft = mtp.firstEarly(), .vtable = if (self.ranks == null) &scoring_table else &ranked_table }; } - /// With the head: chains of up to 16 rows cut by its confidence, copies of up to 32; else one-row rounds. + /// With the head: chains of up to 16 rows cut by its confidence, copies of up to the served window. pub fn facts(self: *const Cuda) lanes.Model { const drafting = self.head != null; return .{ - .exact_width = if (drafting) mtp.max_rows else 2, + .exact_width = if (drafting) @intCast(mtp.window()) else 2, .first_copy_rows = if (drafting) mtp.max_chain + 1 else 0, .gpu_tokens = false, .mtp = drafting, @@ -287,7 +287,7 @@ pub fn Namespace(comptime Tri: type) type { s.proposer = null; } // a window's rows past the reply's last token (its drafts) still need cache slots - const cap = @min(ids.len + s.max_new + (if (drafting) mtp.max_rows else 0), prompt.max_tokens); + const cap = @min(ids.len + s.max_new + (if (drafting) mtp.bufferRows() else 0), prompt.max_tokens); const from = self.kv.choose(); // a contiguous lane's fixed-size buffers from the parts kept from an earlier stream var part_seq: ?cuda.DeviceBuffer = null; @@ -465,7 +465,7 @@ pub fn Namespace(comptime Tri: type) type { const l = try self.lane(w.stream); const rows = w.rows(); if (l.draft != null) { - if (rows > mtp.max_rows) return error.WindowTooWide; + if (rows > mtp.window()) return error.WindowTooWide; for (w.positions, 0..) |p, r| if (p != l.seq.fed + 1 + r) return error.PositionMismatch; row_ids[wi][0] = w.pending; @memcpy(row_ids[wi][1..rows], w.tokens); diff --git a/zig/src/families/flashnext/cuda_lanes_admission_test.zig b/zig/src/families/flashnext/cuda_lanes_admission_test.zig index af7214eec91..3f3fff8483c 100644 --- a/zig/src/families/flashnext/cuda_lanes_admission_test.zig +++ b/zig/src/families/flashnext/cuda_lanes_admission_test.zig @@ -69,7 +69,7 @@ fn run(comptime Cuda: type, comptime open: anytype, comptime drop: anytype, coun const lane = try open(&rig.self, s); try std.testing.expect(s.drafts); try std.testing.expect(lane.draft != null); - try std.testing.expect(lane.seq.cap >= s.prompt().len + s.max_new + mtp.max_rows); + try std.testing.expect(lane.seq.cap >= s.prompt().len + s.max_new + mtp.bufferRows()); } try std.testing.expectEqual(count, rig.self.lanes.count()); for (streams[0..count]) |*s| { diff --git a/zig/src/families/flashnext/cuda_lanes_load.zig b/zig/src/families/flashnext/cuda_lanes_load.zig index 7acec9e38c3..a75916a8ab8 100644 --- a/zig/src/families/flashnext/cuda_lanes_load.zig +++ b/zig/src/families/flashnext/cuda_lanes_load.zig @@ -93,8 +93,22 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu own.confidence = try @import("sys").environment.read(f64, "TF_FLASHNEXT_CONFIDENCE", mtp.default_confidence); } errdefer if (own.head) |h| h.deinit(); + // TF_FLASHNEXT_WINDOW_CHECK=1: the boot self-check measures the copied rows against their one-token steps + const check = try @import("sys").environment.read(bool, "TF_FLASHNEXT_WINDOW_CHECK", false); + const runs = check and own.head != null and o.drafts and o.tp == 1; + mtp.sizeWindow(runs); // every window buffer from here on, the check's first: the shipped rows unless it runs + var proved: ?usize = null; + if (runs) { + const tri = own.tri(); + proved = @import("cuda_mtp_check.zig").probeServed(@TypeOf(tri), gpa, driver, &own.stream, tri, own.engine, own.head.?) catch |err| blk: { + std.log.warn("flashnext: the window self-check did not run ({s}); copy windows stay at {d} rows", .{ @errorName(err), mtp.base_rows }); + break :blk null; + }; + } + mtp.serveWindow(check, proved); + if (mtp.window() > mtp.base_rows) std.log.info("flashnext: serving {d}-row copy windows after the self-check", .{mtp.window()}); @import("cuda_prompt_wt.zig").dropPageCache(gpa, io, dir, e.ngram.files.items); - const window = @min(o.context + mtp.max_rows, prompt.max_tokens); + const window = @min(o.context + mtp.bufferRows(), prompt.max_tokens); // and an attention block's block scores at the window (64 MiB at 262,144 tokens) _ = try own.engine.reserveScores(window, @min(o.context, own.engine.chunk)); // a shared round's or a shared verify's scores: up to a drafting round's rows (facts' batch_rows) @@ -123,7 +137,7 @@ pub fn open(comptime F: type, gpa: std.mem.Allocator, io: std.Io, ctx: *const cu .vision = own.vision, .backend = own.backend(), .facts = own.facts(), - .rows = if (own.head != null) mtp.max_rows else 2, + .rows = if (own.head != null) @intCast(mtp.window()) else 2, .prompt_rows = @intCast(own.engine.chunk), .stream_bytes = stream_bytes, .ctx = own, diff --git a/zig/src/families/flashnext/cuda_mtp.zig b/zig/src/families/flashnext/cuda_mtp.zig index ffc7f15cea8..9b4cbd6efd9 100644 --- a/zig/src/families/flashnext/cuda_mtp.zig +++ b/zig/src/families/flashnext/cuda_mtp.zig @@ -80,8 +80,57 @@ test "the stop rule: per draft above zero, the running product below it, every d var all: Stop = .{ .c = 0 }; try std.testing.expect(all.take(5, 0.01).propose and all.take(6, 0.01).more); } -/// A verify window's rows at most: the pending token and a chain, or a copied continuation. -pub const max_rows: usize = 32; +/// A verify window's rows at most: a window's rows are the pending-row log's, and that log holds this many. +pub const max_rows: usize = batch.late_rows; +/// The verify window's rows a load serves before the boot check proves more: the width the engine ships. +pub const base_rows: usize = 32; +/// The rows a load's window buffers hold: `max_rows` for a load whose boot check runs, else `base_rows`. +pub var buffer_rows: usize = base_rows; +/// The window a load serves: the boot check's largest row-exact width past `base_rows`, else `base_rows`. +pub var served_rows: usize = base_rows; + +pub fn window() usize { + return served_rows; +} + +pub fn bufferRows() usize { + return buffer_rows; +} + +/// The rows a load's window buffers hold: the pending-row log's `max_rows` only when its boot check runs. +pub fn bufferWidth(check_runs: bool) usize { + return if (check_runs) max_rows else base_rows; +} + +/// Sizes every window buffer a load makes from here on, the check's own first: set before any is sized. +pub fn sizeWindow(check_runs: bool) void { + buffer_rows = bufferWidth(check_runs); +} + +/// Sets the window a load serves from the boot check's outcome (null: it did not run, or it failed). +pub fn serveWindow(check_on: bool, proved: ?usize) void { + served_rows = servedWidth(check_on, proved); +} + +/// The width a load serves: a run past `base_rows` only when the boot check ran and proved it, within the buffers. +pub fn servedWidth(check_on: bool, proved: ?usize) usize { + if (!check_on) return base_rows; + const run = proved orelse return base_rows; + return @min(@max(run, base_rows), buffer_rows); +} + +/// Whether a verify window of `n` rows is served: one row to the served window's, the engine's one bound. +pub fn rowsOk(n: usize) bool { + return n >= 1 and n <= served_rows; +} + +/// The boot check's widths and the window it measures them in: every width the buffers hold, served meanwhile. +pub fn probeWidths(rows: *[max_rows]usize) usize { + served_rows = buffer_rows; // the sweep measures every width its own draft holds, so it serves them all + for (rows[0..buffer_rows], 0..) |*w, i| w.* = i + 1; + return buffer_rows; +} + /// A drafting round's rows at most: a shared verify's (TF_FLASHNEXT_WINDOW_ROWS lowers it; 0: each alone). pub const round_rows: usize = 64; /// qmm.split_for(2560, 2560): fc_embedding and fc_hidden sum K in four slices, in order. @@ -461,12 +510,74 @@ test "a masked row draws only allowed tokens, greedy the best of them" { test "draft chains fit one verify window while the default stays six" { try std.testing.expectEqual(@as(usize, 16), max_chain + 1); - try std.testing.expectEqual(@as(usize, 32), max_rows); - try std.testing.expect(max_chain < max_rows and max_rows <= round_rows); + try std.testing.expectEqual(@as(usize, 48), max_rows); + try std.testing.expectEqual(@as(usize, 32), base_rows); + try std.testing.expect(max_chain + 1 <= base_rows and base_rows < max_rows and max_rows <= round_rows); try std.testing.expectEqual(@as(usize, 6), default_depth); try std.testing.expect(default_depth <= max_chain); } +test "the served copy window widens only to a width the boot check proved past the shipped rows" { + // the widest window is the pending-row log's own rows: a wider one overwrites the kept rows its rollback needs + try std.testing.expectEqual(@as(usize, 48), max_rows); + defer { + served_rows = base_rows; + buffer_rows = base_rows; + } + // a load whose check runs holds every width the check can prove; with the switch off, the shipped rows + try std.testing.expectEqual(max_rows, bufferWidth(true)); + try std.testing.expectEqual(base_rows, bufferWidth(false)); + sizeWindow(true); + const Case = struct { check: bool, proved: ?usize, want: usize }; + for ([_]Case{ + .{ .check = false, .proved = null, .want = base_rows }, + .{ .check = false, .proved = 48, .want = base_rows }, + .{ .check = true, .proved = null, .want = base_rows }, + .{ .check = true, .proved = base_rows, .want = base_rows }, + .{ .check = true, .proved = 40, .want = 40 }, + .{ .check = true, .proved = max_rows, .want = max_rows }, + .{ .check = true, .proved = 8, .want = base_rows }, + }) |c| try std.testing.expectEqual(c.want, servedWidth(c.check, c.proved)); + serveWindow(true, 40); + try std.testing.expectEqual(@as(usize, 40), window()); + serveWindow(false, 40); + try std.testing.expectEqual(base_rows, window()); + serveWindow(true, null); + try std.testing.expectEqual(base_rows, window()); + // no proved width is served past the rows the load's buffers hold + sizeWindow(false); + try std.testing.expectEqual(base_rows, servedWidth(true, max_rows)); +} + +test "the boot check's sweep is served every width a window holds, so its own verify accepts each" { + defer { + served_rows = base_rows; + buffer_rows = base_rows; + } + // a load whose check runs sizes its buffers for the sweep and serves the shipped width until the sweep ends + sizeWindow(true); + serveWindow(false, null); + try std.testing.expectEqual(base_rows, window()); + try std.testing.expect(rowsOk(1) and rowsOk(base_rows) and !rowsOk(0)); + // there the engine's verify refuses the 33rd row, the deadlock the sweep met + try std.testing.expect(!rowsOk(base_rows + 1)); + var widths: [max_rows]usize = undefined; + const n = probeWidths(&widths); + try std.testing.expectEqual(max_rows, n); + try std.testing.expectEqual(max_rows, window()); + for (widths[0..n], 0..) |w, i| try std.testing.expectEqual(i + 1, w); + for (widths[0..n]) |w| try std.testing.expect(rowsOk(w)); + // a sweep that fails afterwards leaves the load at the shipped width, and the guard narrows with it + serveWindow(true, null); + try std.testing.expectEqual(base_rows, window()); + try std.testing.expect(!rowsOk(max_rows)); + // buffers of the shipped rows: the sweep holds to them, so it never asks a width its draft cannot hold + sizeWindow(false); + try std.testing.expectEqual(base_rows, probeWidths(&widths)); + try std.testing.expectEqual(base_rows, window()); + try std.testing.expect(rowsOk(base_rows) and !rowsOk(base_rows + 1)); +} + test { _ = @import("cuda_mtp_nonfinite_test.zig"); _ = @import("cuda_mtp_load.zig"); diff --git a/zig/src/families/flashnext/cuda_mtp_check.zig b/zig/src/families/flashnext/cuda_mtp_check.zig index a5074333375..9152eedc6bb 100644 --- a/zig/src/families/flashnext/cuda_mtp_check.zig +++ b/zig/src/families/flashnext/cuda_mtp_check.zig @@ -114,7 +114,7 @@ pub fn check(comptime Tri: type, gpa: std.mem.Allocator, io: std.Io, driver: *cu const stop: []const u32 = &.{}; var same = true; for (prompts, 0..) |ids, pi| { - const cap = ids.len + count + max_rows; + const cap = ids.len + count + mtp.bufferRows(); var seq = try e.newSeq(cap); defer seq.deinit(gpa); var d = try Draft.init(gpa, driver, stream.*, cap, h.ids.len, e.chunk, e.heads); @@ -163,6 +163,89 @@ pub fn check(comptime Tri: type, gpa: std.mem.Allocator, io: std.Io, driver: *cu return same; } +/// One row's scores read back from the device. +fn downloadRow(stream: cuda.Stream, dst: []u16, src: u64) !void { + try stream.synchronize(); + try cuda.memory.download(stream.d, src, std.mem.sliceAsBytes(dst)); +} + +/// Each width's rows must score byte-equal to their one-token steps; `bad` takes each width's differing count. +pub fn windowCheck(comptime Tri: type, o: Ops(Tri), seq: *prompt.Seq, d: *Draft, prompt_ids: []const u32, widths: []const usize, bad: []usize) !usize { + if (widths.len == 0 or widths[widths.len - 1] > d.layout.rows) return error.WindowRowsTooWide; + const gpa = o.e.gpa; + const rows = widths[widths.len - 1]; + var cont: [max_rows]u32 = undefined; + var ref = try gpa.alloc(u16, rows * vocab); + defer gpa.free(ref); + const row = try gpa.alloc(u16, vocab); + defer gpa.free(row); + const got = try gpa.alloc(u16, vocab); + defer gpa.free(got); + // the greedy continuation, then every row's scores from a one-token step + try o.e.predict(Tri, o.tri, seq, prompt_ids); + for (row, 0..) |*v, i| v.* = std.mem.readInt(u16, seq.logits[2 * i ..][0..2], .little); + cont[0] = try drawRow(gpa, row, null, seq.fed, null); + for (0..rows) |r| { + var one = [_]u32{cont[r]}; + try o.e.predict(Tri, o.tri, seq, &one); + for (row, 0..) |*v, i| v.* = std.mem.readInt(u16, seq.logits[2 * i ..][0..2], .little); + @memcpy(ref[r * vocab ..][0..vocab], row); + if (r + 1 < rows) cont[r + 1] = try drawRow(gpa, row, null, seq.fed, null); + } + var total: usize = 0; + for (widths, bad) |w, *b| { + d.settle(seq); // the last window's spares back to the sequence before its reset + seq.fed = 0; + seq.history = .{ o.e.eos, o.e.eos }; + try resetSeq(seq, o.e.stream.*); + try o.e.predict(Tri, o.tri, seq, prompt_ids); + for (row, 0..) |*v, i| v.* = std.mem.readInt(u16, seq.logits[2 * i ..][0..2], .little); + if ((try drawRow(gpa, row, null, seq.fed, null)) != cont[0]) return error.FirstTokenDiffers; + try o.verify(seq, d, cont[0..w]); + var differ: usize = 0; + for (0..w) |r| { + try downloadRow(o.e.stream.*, got, d.logits.ptr + r * vocab * 2); + total += 1; + if (!std.mem.eql(u16, got, ref[r * vocab ..][0..vocab])) differ += 1; + } + b.* = differ; + } + return total; +} + +/// The boot self-check: sweeps every width the buffers hold on a synthetic prompt; returns the largest row-exact one. +pub fn probeServed(comptime Tri: type, gpa: std.mem.Allocator, driver: *cuda.Driver, stream: *cuda.Stream, tri: Tri, e: *prompt.Engine, h: *Head) !usize { + var ids: [96]u32 = undefined; + for (&ids, 0..) |*t, i| t.* = @intCast(1000 + (i * 7919) % 200_000); + const cap = ids.len + 2 * mtp.bufferRows(); + var seq = try e.newSeq(cap); + defer seq.deinit(gpa); + var d = try Draft.init(gpa, driver, stream.*, cap, h.ids.len, e.chunk, e.heads); + defer d.deinit(); + const o: Ops(Tri) = .{ .e = e, .tri = tri, .h = h }; + var widths: [max_rows]usize = undefined; + const n = mtp.probeWidths(&widths); + var bad: [max_rows]usize = @splat(0); + const compared = try windowCheck(Tri, o, &seq, &d, &ids, widths[0..n], bad[0..n]); + var differing: usize = 0; + var first_bad: usize = 0; + for (bad[0..n], 0..) |b, i| { + differing += b; + if (b > 0 and first_bad == 0) first_bad = i + 1; + } + std.log.info("flashnext: window self-check: {d} of {d} rows byte-equal to their one-token steps (widths 1-{d})", .{ compared - differing, compared, n }); + if (first_bad > 0) std.log.warn("flashnext: width {d} is the first with rows differing from their one-token steps", .{first_bad}); + if (differing == 0) return n; + // the largest width whose every row is byte-equal; past it some differ + var run: usize = 0; + for (bad[0..n], 0..) |b, i| { + if (b != 0) break; + run = i + 1; + } + std.log.info("flashnext: widths 1-{d} are row-equal at every row", .{run}); + return run; +} + /// A sequence's caches back to empty (the check reruns a prompt on one allocation). fn resetSeq(seq: *prompt.Seq, stream: cuda.Stream) !void { for (seq.conv) |*b| try b.fill8(0, stream.handle); diff --git a/zig/src/families/flashnext/cuda_mtp_draft.zig b/zig/src/families/flashnext/cuda_mtp_draft.zig index c5b032705b6..2a8d1f8ffb2 100644 --- a/zig/src/families/flashnext/cuda_mtp_draft.zig +++ b/zig/src/families/flashnext/cuda_mtp_draft.zig @@ -22,8 +22,19 @@ const Q4 = wt.Q4; const HcW = wt.HcW; const max_chain = mtp.max_chain; const max_rows = mtp.max_rows; -/// best: [max_rows, 4] fp32 best values, then [max_rows, topk_max] bf16 candidates and i32 columns (cuda_mtp_draw.zig). -pub const best_bytes: usize = max_rows * 16 + max_rows * @import("cuda_mtp_draw.zig").topk_max * 6; +const topk_max = @import("cuda_mtp_draw.zig").topk_max; +/// best at `rows` window rows: [rows, 4] fp32 best values, then the candidates (valsAt) and their columns (colsAt). +pub fn bestBytes(rows: usize) usize { + return colsAt(rows) + rows * topk_max * 4; +} +/// Where best holds a sampled draw's [rows, topk_max] bf16 candidates (cuda_mtp_draw.zig). +pub fn valsAt(rows: usize) usize { + return rows * 16; +} +/// Where best holds the candidates' [rows, topk_max] i32 columns. +pub fn colsAt(rows: usize) usize { + return valsAt(rows) + rows * topk_max * 2; +} const sizes = @import("cuda_seq_bytes.zig"); const Heads = @import("cuda_heads.zig").Heads; @@ -68,7 +79,7 @@ pub const Draft = struct { prompt_last: u64 = 0, /// The head's last output row (its streams after the MoE write-back): the next chained draft's input. out: cuda.DeviceBuffer, - /// A window's scores [max_rows, vocab], the draft head's [ids], best values [max_rows, 4]. + /// A window's scores [layout.rows, vocab], the draft head's [ids], best values (bestBytes at layout.rows). logits: cuda.DeviceBuffer, dlogits: cuda.DeviceBuffer, best: cuda.DeviceBuffer, @@ -97,6 +108,8 @@ pub const Draft = struct { /// `saved`'s pieces and the spares' size at the model's heads: conv windows, projection rows, tail, n-gram rows. pub const Layout = struct { heads: Heads, + /// The window rows it holds, the load's mtp.bufferRows(): saved's rows, a window's scores and best values. + rows: usize, conv: usize, proj: usize, hist_at: usize = 0, @@ -108,12 +121,13 @@ pub const Draft = struct { state: usize, pub fn of(h: Heads) Layout { + const rows = mtp.bufferRows(); const conv = sizes.convBytes(h); const proj = h.projWidth() * 2; const proj_at = linear_n * conv; - const tail_at = proj_at + linear_n * max_rows * proj; + const tail_at = proj_at + linear_n * rows * proj; const nrow_at = tail_at + ple_tail_n * wide * 2; - return .{ .heads = h, .conv = conv, .proj = proj, .proj_at = proj_at, .tail_at = tail_at, .nrow_at = nrow_at, .saved = nrow_at + max_rows * wide * 2, .state = sizes.stateBytes(h) }; + return .{ .heads = h, .rows = rows, .conv = conv, .proj = proj, .proj_at = proj_at, .tail_at = tail_at, .nrow_at = nrow_at, .saved = nrow_at + rows * wide * 2, .state = sizes.stateBytes(h) }; } }; @@ -125,7 +139,7 @@ pub const Draft = struct { const l = Layout.of(h); const head = 2 * sizes.kvBytes(cap, head_heads) + sizes.indexBytes(cap) + sizes.pooledBytes(cap); const log = if (late()) logBytes() else 0; - return head + @max(rows, max_rows) * wide * 2 + wide * 2 + max_rows * vocab * 2 + draft_n * 2 + best_bytes + l.saved + linear_n * l.state + log; + return head + @max(rows, l.rows) * wide * 2 + wide * 2 + l.rows * vocab * 2 + draft_n * 2 + bestBytes(l.rows) + l.saved + linear_n * l.state + log; } /// Drafting streams keep a partly kept window's DeltaNet rows pending (set at load; TF_FLASHNEXT_KEEP_LATE=0: off). @@ -159,7 +173,8 @@ pub const Draft = struct { /// A head cache of `cap` entries; `rows` the widest prompt chunk whose streams it keeps; `h` the model's heads. pub fn init(gpa: std.mem.Allocator, driver: *cuda.Driver, stream: cuda.Stream, cap: usize, draft_n: usize, rows: usize, h: Heads) !Draft { - var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .stream = stream, .gpa = gpa, .cap = cap, .rows_cap = @max(rows, max_rows), .kc = undefined, .vc = undefined, .ikc = undefined, .pooled = undefined, .streams = undefined, .out = undefined, .logits = undefined, .dlogits = undefined, .best = undefined, .saved = undefined, .host = undefined, .layout = .of(h) }; + const l: Layout = .of(h); + var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .stream = stream, .gpa = gpa, .cap = cap, .rows_cap = @max(rows, l.rows), .kc = undefined, .vc = undefined, .ikc = undefined, .pooled = undefined, .streams = undefined, .out = undefined, .logits = undefined, .dlogits = undefined, .best = undefined, .saved = undefined, .host = undefined, .layout = l }; d.kc = try cuda.DeviceBuffer.alloc(driver, sizes.kvBytes(cap, head_heads)); errdefer d.kc.free(); d.vc = try cuda.DeviceBuffer.alloc(driver, sizes.kvBytes(cap, head_heads)); @@ -172,11 +187,11 @@ pub const Draft = struct { errdefer d.streams.free(); d.out = try cuda.DeviceBuffer.alloc(driver, wide * 2); errdefer d.out.free(); - d.logits = try cuda.DeviceBuffer.alloc(driver, max_rows * vocab * 2); + d.logits = try cuda.DeviceBuffer.alloc(driver, l.rows * vocab * 2); errdefer d.logits.free(); d.dlogits = try cuda.DeviceBuffer.alloc(driver, draft_n * 2); errdefer d.dlogits.free(); - d.best = try cuda.DeviceBuffer.alloc(driver, best_bytes); + d.best = try cuda.DeviceBuffer.alloc(driver, bestBytes(l.rows)); errdefer d.best.free(); d.saved = try cuda.DeviceBuffer.alloc(driver, d.layout.saved); errdefer d.saved.free(); @@ -185,7 +200,7 @@ pub const Draft = struct { var made: usize = 0; errdefer for (d.spare[0..made]) |*b| b.free(); while (made < linear_n) : (made += 1) d.spare[made] = try cuda.DeviceBuffer.alloc(driver, d.layout.state); - d.host = try gpa.alloc(u16, @max(max_rows * vocab, draft_n)); + d.host = try gpa.alloc(u16, @max(l.rows * vocab, draft_n)); errdefer gpa.free(d.host); errdefer cuda.completion.drain(driver, stream, "Flash Next draft fills did not drain before rollback"); // zeroed on the compute stream, ahead of the passes that read them @@ -197,10 +212,10 @@ pub const Draft = struct { /// The fixed-size buffers of a draft in one block (initParts) at the model's heads `h`: all but the head's caches. pub fn partsBytes(draft_n: usize, rows: usize, h: Heads) usize { const a = std.mem.alignForward; - const rows_cap = @max(rows, max_rows); const l = Layout.of(h); + const rows_cap = @max(rows, l.rows); var n: usize = 0; - for ([_]usize{ rows_cap * wide * 2, wide * 2, max_rows * vocab * 2, draft_n * 2, best_bytes, l.saved, if (late()) logBytes() else 0 }) |x| n += a(usize, x, 256); + for ([_]usize{ rows_cap * wide * 2, wide * 2, l.rows * vocab * 2, draft_n * 2, bestBytes(l.rows), l.saved, if (late()) logBytes() else 0 }) |x| n += a(usize, x, 256); return n + linear_n * a(usize, l.state, 256); } @@ -208,7 +223,8 @@ pub const Draft = struct { pub fn initParts(gpa: std.mem.Allocator, driver: *cuda.Driver, stream: cuda.Stream, cap: usize, draft_n: usize, rows: usize, h: Heads, block: cuda.DeviceBuffer) !Draft { const bytes_in = partsBytes(draft_n, rows, h); if (block.len < bytes_in) return error.FlashNextRunTooShort; - var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .stream = stream, .gpa = gpa, .cap = cap, .rows_cap = @max(rows, max_rows), .kc = undefined, .vc = undefined, .ikc = undefined, .pooled = undefined, .streams = undefined, .out = undefined, .logits = undefined, .dlogits = undefined, .best = undefined, .saved = undefined, .spare = undefined, .host = undefined, .layout = .of(h) }; + const l: Layout = .of(h); + var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .stream = stream, .gpa = gpa, .cap = cap, .rows_cap = @max(rows, l.rows), .kc = undefined, .vc = undefined, .ikc = undefined, .pooled = undefined, .streams = undefined, .out = undefined, .logits = undefined, .dlogits = undefined, .best = undefined, .saved = undefined, .spare = undefined, .host = undefined, .layout = l }; d.kc = try cuda.DeviceBuffer.alloc(driver, sizes.kvBytes(cap, head_heads)); errdefer d.kc.free(); d.vc = try cuda.DeviceBuffer.alloc(driver, sizes.kvBytes(cap, head_heads)); @@ -227,14 +243,14 @@ pub const Draft = struct { var at = block.ptr; d.streams = Carve.take(driver, &at, d.rows_cap * wide * 2); d.out = Carve.take(driver, &at, wide * 2); - d.logits = Carve.take(driver, &at, max_rows * vocab * 2); + d.logits = Carve.take(driver, &at, l.rows * vocab * 2); d.dlogits = Carve.take(driver, &at, draft_n * 2); - d.best = Carve.take(driver, &at, best_bytes); + d.best = Carve.take(driver, &at, bestBytes(l.rows)); d.saved = Carve.take(driver, &at, d.layout.saved); if (late()) d.log = Carve.take(driver, &at, logBytes()); for (&d.spare) |*b| b.* = Carve.take(driver, &at, d.layout.state); std.debug.assert(at - block.ptr == bytes_in); - d.host = try gpa.alloc(u16, @max(max_rows * vocab, draft_n)); + d.host = try gpa.alloc(u16, @max(l.rows * vocab, draft_n)); errdefer gpa.free(d.host); errdefer cuda.completion.drain(driver, stream, "Flash Next draft fills did not drain before rollback"); for ([_]cuda.DeviceBuffer{ d.kc, d.vc, d.ikc, d.pooled }) |b| try b.fill8(0, stream.handle); @@ -249,7 +265,7 @@ pub const Draft = struct { for (&d.keep.layers, 0..) |*lk, layer| { if (!wt.linearLayer(layer)) continue; lk.hist = d.saved.ptr + d.layout.hist_at + li * d.layout.conv; - lk.proj = d.saved.ptr + d.layout.proj_at + li * max_rows * d.layout.proj; + lk.proj = d.saved.ptr + d.layout.proj_at + li * d.layout.rows * d.layout.proj; if (d.log) |b| { lk.log = b.ptr + log_ctl_bytes + li * layer_log_bytes; lk.log_ctl = b.ptr; @@ -282,17 +298,18 @@ pub const Draft = struct { } }; const head = wt.attn_n; - var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .gpa = gpa, .cap = cap, .rows_cap = @max(rows, max_rows), .kc = Carve.page(driver, paged.at(head, .key)), .vc = Carve.page(driver, paged.at(head, .value)), .ikc = Carve.page(driver, paged.at(head, .index)), .pooled = Carve.page(driver, paged.at(head, .pooled)), .pg = paged.pg(), .pooled_lane = true, .streams = undefined, .out = undefined, .logits = undefined, .dlogits = undefined, .best = undefined, .saved = undefined, .host = undefined, .layout = .of(pool_heads) }; + const l: Layout = .of(pool_heads); + var d: Draft = .{ .gen = @import("cuda_window_graph.zig").nextGen(), .gpa = gpa, .cap = cap, .rows_cap = @max(rows, l.rows), .kc = Carve.page(driver, paged.at(head, .key)), .vc = Carve.page(driver, paged.at(head, .value)), .ikc = Carve.page(driver, paged.at(head, .index)), .pooled = Carve.page(driver, paged.at(head, .pooled)), .pg = paged.pg(), .pooled_lane = true, .streams = undefined, .out = undefined, .logits = undefined, .dlogits = undefined, .best = undefined, .saved = undefined, .host = undefined, .layout = l }; d.streams = Carve.take(driver, &at, d.rows_cap * wide * 2); d.out = Carve.take(driver, &at, wide * 2); - d.logits = Carve.take(driver, &at, max_rows * vocab * 2); + d.logits = Carve.take(driver, &at, l.rows * vocab * 2); d.dlogits = Carve.take(driver, &at, draft_n * 2); - d.best = Carve.take(driver, &at, best_bytes); + d.best = Carve.take(driver, &at, bestBytes(l.rows)); d.saved = Carve.take(driver, &at, d.layout.saved); if (late()) d.log = Carve.take(driver, &at, logBytes()); for (&d.spare) |*b| b.* = Carve.take(driver, &at, d.layout.state); std.debug.assert(at - base <= len); - d.host = try gpa.alloc(u16, @max(max_rows * vocab, draft_n)); + d.host = try gpa.alloc(u16, @max(l.rows * vocab, draft_n)); d.point(); return d; } @@ -348,20 +365,30 @@ test "a draft at 65,536 tokens and 1,536-row chunks: the head's cache whole, sav const cap = 65536; const rows = 1536; const draft_n = 32768; - // the head's cache: two KV heads of 256, 128 indexer keys a position, a pooled row a block of 4 - const head: usize = cap * (2 * 2 * 256 * 2 + 128 * 2) + cap / 4 * 128 * 2; - // streams rows, the head's output row, a window's scores, the draft head's, best values - const buffers: usize = rows * 4 * 2560 * 2 + 4 * 2560 * 2 + 32 * 248320 * 2 + draft_n * 2 + best_bytes; - // saved: 36 conv windows, 36 layers' 32 projection rows, the n-gram tail and 32 n-gram rows; 36 spare states - const tail: usize = 9 * 4 * 2560 * 2 + 32 * 4 * 2560 * 2; - const full: usize = 36 * 3 * 10240 * 2 + 36 * 32 * 16480 * 2 + tail + 36 * 48 * 128 * 128 * 4; - const half: usize = 36 * 3 * 5120 * 2 + 36 * 32 * 8240 * 2 + tail + 36 * 24 * 128 * 128 * 4; - try std.testing.expectEqual(head + buffers + full, Draft.bytes(cap, draft_n, rows, .full)); - try std.testing.expectEqual(head + buffers + half, Draft.bytes(cap, draft_n, rows, .half)); - try std.testing.expectEqual(@as(usize, 356_905_472), Draft.bytes(cap, draft_n, rows, .full)); - try std.testing.expectEqual(@as(usize, 280_191_488), Draft.bytes(cap, draft_n, rows, .half)); - // with the stream's own caches at half the heads - try std.testing.expectEqual(@as(usize, 1_395_069_440), sizes.seqBytes(cap, .half) + Draft.bytes(cap, draft_n, rows, .half)); + defer mtp.buffer_rows = mtp.base_rows; + // the switch off sizes the shipped 32 rows; a load whose boot check runs, the pending-row log's 48 + const Size = struct { on: bool, w: usize, full: usize, half: usize, stream: usize }; + for ([_]Size{ + .{ .on = false, .w = 32, .full = 356_905_472, .half = 280_191_488, .stream = 1_395_069_440 }, + .{ .on = true, .w = 48, .full = 384_170_752, .half = 297_964_288, .stream = 1_412_842_240 }, + }) |s| { + mtp.sizeWindow(s.on); + try std.testing.expectEqual(s.w, Draft.Layout.of(.full).rows); + // the head's cache: two KV heads of 256, 128 indexer keys a position, a pooled row a block of 4 + const head: usize = cap * (2 * 2 * 256 * 2 + 128 * 2) + cap / 4 * 128 * 2; + // streams rows, the head's output row, a window's scores, the draft head's, best values and 64 candidates + const buffers: usize = rows * 4 * 2560 * 2 + 4 * 2560 * 2 + s.w * 248320 * 2 + draft_n * 2 + s.w * 16 + s.w * 64 * 6; + // saved: 36 conv windows, 36 layers' w projection rows, the n-gram tail and w n-gram rows; 36 spare states + const tail: usize = 9 * 4 * 2560 * 2 + s.w * 4 * 2560 * 2; + const full: usize = 36 * 3 * 10240 * 2 + 36 * s.w * 16480 * 2 + tail + 36 * 48 * 128 * 128 * 4; + const half: usize = 36 * 3 * 5120 * 2 + 36 * s.w * 8240 * 2 + tail + 36 * 24 * 128 * 128 * 4; + try std.testing.expectEqual(head + buffers + full, Draft.bytes(cap, draft_n, rows, .full)); + try std.testing.expectEqual(head + buffers + half, Draft.bytes(cap, draft_n, rows, .half)); + try std.testing.expectEqual(s.full, Draft.bytes(cap, draft_n, rows, .full)); + try std.testing.expectEqual(s.half, Draft.bytes(cap, draft_n, rows, .half)); + // with the stream's own caches at half the heads + try std.testing.expectEqual(s.stream, sizes.seqBytes(cap, .half) + Draft.bytes(cap, draft_n, rows, .half)); + } } test "blank TF_FLASHNEXT_KEEP_LATE: unset, empty or whitespace-only text asks for nothing, 1 and 0 keep their meaning" { @@ -389,15 +416,20 @@ test "blank TF_FLASHNEXT_KEEP_LATE: unset, empty or whitespace-only text asks fo } test "the saved pieces follow one another at the model's heads, and the spares hold its states" { - for ([_]Heads{ .full, .half }) |h| { - const l = Draft.Layout.of(h); - try std.testing.expectEqual(@as(usize, 36 * 3 * h.convDim() * 2), l.proj_at); - try std.testing.expectEqual(l.proj_at + 36 * 32 * h.projWidth() * 2, l.tail_at); - try std.testing.expectEqual(l.tail_at + 9 * 4 * 2560 * 2, l.nrow_at); - try std.testing.expectEqual(l.nrow_at + 32 * 4 * 2560 * 2, l.saved); - try std.testing.expectEqual(sizes.stateBytes(h), l.state); - try std.testing.expect(l.heads.eql(h)); + defer mtp.buffer_rows = mtp.base_rows; + // the shipped 32 rows' saved bytes with the switch off, the log's 48 rows' for a load whose boot check runs + for ([_]bool{ false, true }, [_][2]usize{ .{ 41_021_440, 20_930_560 }, .{ 60_334_080, 30_750_720 } }) |on, saved| { + mtp.sizeWindow(on); + for ([_]Heads{ .full, .half }) |h| { + const l = Draft.Layout.of(h); + try std.testing.expectEqual(@as(usize, 36 * 3 * h.convDim() * 2), l.proj_at); + try std.testing.expectEqual(l.proj_at + 36 * l.rows * h.projWidth() * 2, l.tail_at); + try std.testing.expectEqual(l.tail_at + 9 * 4 * 2560 * 2, l.nrow_at); + try std.testing.expectEqual(l.nrow_at + l.rows * 4 * 2560 * 2, l.saved); + try std.testing.expectEqual(sizes.stateBytes(h), l.state); + try std.testing.expect(l.heads.eql(h)); + } + try std.testing.expectEqual(saved[0], Draft.Layout.of(.full).saved); + try std.testing.expectEqual(saved[1], Draft.Layout.of(.half).saved); } - try std.testing.expectEqual(@as(usize, 41_021_440), Draft.Layout.of(.full).saved); - try std.testing.expectEqual(@as(usize, 20_930_560), Draft.Layout.of(.half).saved); } diff --git a/zig/src/families/flashnext/cuda_mtp_draw.zig b/zig/src/families/flashnext/cuda_mtp_draw.zig index 5e8e1b9342f..746b96fcb65 100644 --- a/zig/src/families/flashnext/cuda_mtp_draw.zig +++ b/zig/src/families/flashnext/cuda_mtp_draw.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const wt = @import("cuda_prompt_wt.zig"); const mtp = @import("cuda_mtp.zig"); +const mtp_draft = @import("cuda_mtp_draft.zig"); const lanes = @import("lanes"); const vocab = wt.vocab; @@ -73,11 +74,11 @@ fn finite(row: []const u16) bool { /// The candidates of `rows` rows of `v` scores `ld` apart, k a row, into d.best past its best values, then to d.host. fn candidates(h: *const mtp.Head, st: cuda.Stream, d: *mtp.Draft, scores: u64, v: usize, ld: usize, rows: usize, k: usize) !struct { vals: []u16, cols: []i32 } { - const tv = d.best.ptr + max_rows * 16; - const tc = tv + max_rows * topk_max * 2; + const tv = d.best.ptr + mtp_draft.valsAt(d.layout.rows); + const tc = d.best.ptr + mtp_draft.colsAt(d.layout.rows); try h.topk(st, scores, v, ld, rows, k, tv, tc); const vals = d.host[0 .. rows * k]; - const cols: []i32 = @alignCast(std.mem.bytesAsSlice(i32, std.mem.sliceAsBytes(d.host[max_rows * topk_max ..][0 .. 2 * rows * k]))); + const cols: []i32 = @alignCast(std.mem.bytesAsSlice(i32, std.mem.sliceAsBytes(d.host[d.layout.rows * topk_max ..][0 .. 2 * rows * k]))); try st.synchronize(); try copyReady(st, std.mem.sliceAsBytes(vals), tv); try copyReady(st, std.mem.sliceAsBytes(cols), tc); diff --git a/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig b/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig index ff4283e46de..57a90e0add7 100644 --- a/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig +++ b/zig/src/families/flashnext/cuda_mtp_nonfinite_fixture.zig @@ -3,7 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); const mtp = @import("cuda_mtp.zig"); -const draw = @import("cuda_mtp_draw.zig"); +const mtp_draft = @import("cuda_mtp_draft.zig"); const wt = @import("cuda_prompt_wt.zig"); pub const Device = struct { @@ -75,8 +75,9 @@ pub const Device = struct { reads += 1; std.debug.assert(!pending); const bytes = @as([*]u8, @ptrCast(dst.?))[0..n]; - const tv = 0x1000 + mtp.max_rows * 16; - const tc = tv + mtp.max_rows * draw.topk_max * 2; + const rows = mtp.bufferRows(); + const tv = 0x1000 + mtp_draft.valsAt(rows); + const tc = 0x1000 + mtp_draft.colsAt(rows); if (src == 0x9000) { event(.read_batch); const b = @import("cuda_draw_batch.zig"); @@ -85,13 +86,12 @@ pub const Device = struct { for (0..b.rows_max) |i| @memcpy(bytes[i * 16 ..][0..16], std.mem.asBytes(if (reductions.len > i) &reductions[i] else &best)); @memcpy(bytes[b.vals_at..][0 .. vals.len * 2], std.mem.sliceAsBytes(vals)); @memcpy(bytes[b.cols_at..][0 .. cols.len * 4], std.mem.sliceAsBytes(cols)); - } else if (src == 0x1000 and n > mtp.max_rows * 16) { + } else if (src == 0x1000 and n > rows * 16) { event(.read_batch); @memset(bytes, 0); - const rows = mtp.max_rows; for (0..rows) |i| @memcpy(bytes[i * 16 ..][0..16], std.mem.asBytes(if (reductions.len > i) &reductions[i] else &best)); - const va = rows * 16; - const ca = va + rows * draw.topk_max * 2; + const va = mtp_draft.valsAt(rows); + const ca = mtp_draft.colsAt(rows); @memcpy(bytes[va..][0..@min(vals.len * 2, ca - va)], std.mem.sliceAsBytes(vals)[0..@min(vals.len * 2, ca - va)]); @memcpy(bytes[ca..][0..@min(cols.len * 4, n - ca)], std.mem.sliceAsBytes(cols)[0..@min(cols.len * 4, n - ca)]); } else if (src == 0x1000) { @@ -169,7 +169,8 @@ pub fn draft(d: *cuda.Driver, host: []u16) mtp.Draft { x.host = host; x.rows = 1; x.fed0 = 2050; - x.best = .{ .d = d, .ptr = 0x1000, .len = @import("cuda_mtp_draft.zig").best_bytes }; + x.layout = .of(.full); + x.best = .{ .d = d, .ptr = 0x1000, .len = mtp_draft.bestBytes(x.layout.rows) }; x.out = .{ .d = d, .ptr = 0x2000, .len = wt.wide * 2 }; x.dlogits = .{ .d = d, .ptr = 0x3000, .len = 6 }; x.logits = .{ .d = d, .ptr = 0x4000, .len = wt.vocab * 2 }; diff --git a/zig/src/families/flashnext/cuda_mtp_ops.zig b/zig/src/families/flashnext/cuda_mtp_ops.zig index 7f10c6660dc..e8208e0d50d 100644 --- a/zig/src/families/flashnext/cuda_mtp_ops.zig +++ b/zig/src/families/flashnext/cuda_mtp_ops.zig @@ -38,7 +38,6 @@ const ple_tail_n = wt.ple_tail_n; const Q4 = wt.Q4; const HcW = wt.HcW; const max_chain = mtp.max_chain; -const max_rows = mtp.max_rows; const proj_bytes = mtp.proj_bytes; const fc_sk = mtp.fc_sk; const piece_rows = mtp.piece_rows; @@ -279,7 +278,7 @@ pub fn Ops(comptime Tri: type) type { if (o.main) |m| return m.verify(m.ptr, seq, d, ids); o.e.round_graph.clear(); const n = ids.len; - if (n == 0 or n > max_rows) return error.WindowTooWide; + if (!mtp.rowsOk(n)) return error.WindowTooWide; if (seq.fed + n > seq.cap) return error.PromptTooLong; if (!d.layout.heads.eql(seq.heads)) return error.DraftHeads; // its spares swap with the sequence's states d.settle(seq); @@ -299,7 +298,7 @@ pub fn Ops(comptime Tri: type) type { if (o.main != null) return error.UnsupportedRankOperation; // every window refused before any stream's state moves for (seqs, idss, ds) |seq, ids, d| { - if (ids.len == 0 or ids.len > max_rows) return error.WindowTooWide; + if (!mtp.rowsOk(ids.len)) return error.WindowTooWide; if (seq.fed + ids.len > seq.cap) return error.PromptTooLong; if (!d.layout.heads.eql(seq.heads)) return error.DraftHeads; } diff --git a/zig/src/native/cuda_cache_capacity_test.zig b/zig/src/native/cuda_cache_capacity_test.zig index d41873ba64a..30428972c9f 100644 --- a/zig/src/native/cuda_cache_capacity_test.zig +++ b/zig/src/native/cuda_cache_capacity_test.zig @@ -55,3 +55,22 @@ test "cache capacity: 256K context, four streams, 0.3 GiB cannot retain one plan try t.expectEqual(@as(?api.PromptCacheCapacity, null), pool.capacity(struct {}, loaded, kept, 262144)); try t.expectEqual(@as(?api.PromptCacheCapacity, null), pool.capacity(Fake, loaded, kept, 2048)); } + +test "KV pool plan: a family's load-set window rows before its build constant, and none without either" { + const l: @import("core").kv_pool.Layout = .{ .fixed_bytes = 0, .token_bytes = 1 << 20, .page_tokens = 1, .snap_bytes = 0 }; + const o: api.Open = .{ .dir = "model", .model_type = "n", .lanes = 8, .prompt_cache_gib = 0 }; + const Fixed = struct { + pub const window_rows: u32 = 8; + }; + const Loaded = struct { + var rows: usize = 32; + pub fn windowRows() usize { + return rows; + } + }; + try t.expectEqual(@as(u64, 8192 + 8), pool.budgetOf(Fixed, l, 88 << 30, o, 8192, false, false, 0, null).window); + try t.expectEqual(@as(u64, 8192 + 32), pool.budgetOf(Loaded, l, 88 << 30, o, 8192, false, false, 0, null).window); + Loaded.rows = 48; + try t.expectEqual(@as(u64, 8192 + 48), pool.budgetOf(Loaded, l, 88 << 30, o, 8192, false, false, 0, null).window); + try t.expectEqual(@as(u64, 8192), pool.budgetOf(struct {}, l, 88 << 30, o, 8192, false, false, 0, null).window); +} diff --git a/zig/src/native/cuda_kv_pool.zig b/zig/src/native/cuda_kv_pool.zig index c85ae511608..9d8fe6a37c5 100644 --- a/zig/src/native/cuda_kv_pool.zig +++ b/zig/src/native/cuda_kv_pool.zig @@ -155,7 +155,7 @@ fn cacheWanted(comptime F: type, o: api.Open) u64 { /// The asked cache (16 GiB unless --prompt-cache-gib says) whole beside the streams, by the startup plan's arithmetic. fn fits(comptime F: type, loaded: anytype, o: api.Open, room: u64, window: u64, stream_bytes: u64) bool { const want = cacheWanted(F, o); - const rows: u64 = if (comptime @hasDecl(F, "window_rows")) F.window_rows else 0; + const rows = budget.windowRows(F); if (layout(loaded)) |l| return kv_pool.holds(l, .{ .room = room, .engine = 0, .lanes = o.lanes, .fixed = o.lanes_fixed, .cache = want, .snaps = named(o), .window = window + rows, .engine_paged = enginePaged(loaded), .asked = o.prompt_cache_gib != null }); const n = budget.admit(room, stream_bytes, loaded.free_streams, o.lanes, o.lanes_fixed) catch return false; return room -| stream_bytes * (n -| loaded.free_streams) >= want; @@ -163,7 +163,7 @@ fn fits(comptime F: type, loaded: anytype, o: api.Open, room: u64, window: u64, /// Plan streams first, then half their remaining room with a 16 GiB floor, unless the cache was explicit. pub fn budgetOf(comptime F: type, l: kv_pool.Layout, room: u64, o: api.Open, window: u64, host_mode: bool, engine_paged: bool, kept_ppm: u32, slots: ?usize) kv_pool.Budget { - const rows: u64 = if (comptime @hasDecl(F, "window_rows")) F.window_rows else 0; + const rows = budget.windowRows(F); const want = if (host_mode) 0 else cacheWanted(F, o); var out: kv_pool.Budget = .{ .room = room, .engine = 0, .lanes = o.lanes, .fixed = o.lanes_fixed, .cache = want, .snaps = slots orelse named(o), .window = window + rows, .engine_paged = engine_paged, .kept_ppm = if (host_mode) 0 else kept_ppm, .slots_only = slots != null, .asked = o.prompt_cache_gib != null }; if (out.asked or host_mode or comptime keepsNoPrompts(F)) return out; @@ -180,7 +180,7 @@ pub fn budgetOf(comptime F: type, l: kv_pool.Layout, room: u64, o: api.Open, win /// The pool beside the engine's own sequence (in `model`: a window, or on pages its fixed part); null: see `problem`. pub fn plan(comptime F: type, a: Allocator, l: kv_pool.Layout, room: u64, o: api.Open, window: u64, problem: *[]const u8, host_mode: bool, engine_paged: bool, kept_ppm: u32, slots: ?usize) !?Plan { - const rows: u64 = if (comptime @hasDecl(F, "window_rows")) F.window_rows else 0; + const rows = budget.windowRows(F); return kv_pool.plan(l, budgetOf(F, l, room, o, window, host_mode, engine_paged, kept_ppm, slots)) catch |e| { problem.* = switch (e) { error.NoStream => if (engine_paged) try std.fmt.allocPrint(a, "the CUDA memory budget fits no stream beside the model: one at a {d}-token window takes {d:.2} GiB of KV pages, and the budget leaves {d:.2} GiB", .{ window, toGib(l.pages(window + rows) * l.pageBytes()), toGib(room) }) else "the CUDA memory budget fits no stream beside the model", @@ -253,7 +253,7 @@ pub fn report(a: Allocator, l: ?kv_pool.Layout, paged: ?Plan) !void { /// The startup line's streams and cache. pub fn text(comptime F: type, a: Allocator, stream_bytes: u64, l: ?kv_pool.Layout, paged: ?Plan, engine_paged: bool, all_on_pages: bool, window: u64, k: Kept, kv8: bool) ![2][]const u8 { - const rows: u64 = if (comptime @hasDecl(F, "window_rows")) F.window_rows else 0; // the plan's windows: window + rows + const rows = budget.windowRows(F); // the plan's windows: window + rows const shape = if (paged) |p| (if (all_on_pages) try std.fmt.allocPrint(a, "all {d} on {d} pages of {d} rows ({d:.2} GiB) as they need them, the engine's own window idle, {d:.0} MiB fixed each", .{ p.lanes, p.pages, l.?.page_tokens, toGib(p.pages * l.?.pageBytes()), @as(f64, @floatFromInt(l.?.fixed_bytes)) / (1 << 20) }) else if (engine_paged) try std.fmt.allocPrint(a, "the engine's own and {d} more taking {d} pages of {d} rows ({d:.2} GiB) as they need them (enough for {d} at a {d}-token window), {d:.0} MiB fixed each", .{ p.lanes - 1, p.pages, l.?.page_tokens, toGib(p.pages * l.?.pageBytes()), p.pages / l.?.pages(window + rows), window, @as(f64, @floatFromInt(l.?.fixed_bytes)) / (1 << 20) }) else try std.fmt.allocPrint(a, "the engine's own at a {d}-token window ({d:.2} GiB, in the model's), {d} more taking {d} pages of {d} rows ({d:.2} GiB) as they need them, {d:.0} MiB fixed each", .{ window, toGib(stream_bytes), p.lanes - 1, p.pages, l.?.page_tokens, toGib(p.pages * l.?.pageBytes()), @as(f64, @floatFromInt(l.?.fixed_bytes)) / (1 << 20) })) else try std.fmt.allocPrint(a, "{d:.2} GiB each at a {d}-token window{s}", .{ toGib(stream_bytes), window, if (kv8) " (fp8 caches)" else "" }); const placed = comptime @hasDecl(F, "snap_place"); // the startup line says where its prompt states went, and why if (k.copied > 0 and k.device) { diff --git a/zig/src/native/cuda_memory.zig b/zig/src/native/cuda_memory.zig index 0c3a01f4a5b..c4913f00633 100644 --- a/zig/src/native/cuda_memory.zig +++ b/zig/src/native/cuda_memory.zig @@ -214,6 +214,12 @@ pub fn cacheBytes(asked: ?f64, room: u64, streams: u64) u64 { return if (room == std.math.maxInt(u64)) @min(left, 16 << 30) else automaticCache(left, 16 << 30); } +/// Rows past a stream's window its pages hold: the width a family's load set (`windowRows()`), else `window_rows`. +pub fn windowRows(comptime F: type) u64 { + if (comptime @hasDecl(F, "windowRows")) return F.windowRows(); + return if (comptime @hasDecl(F, "window_rows")) F.window_rows else 0; +} + /// Integrated devices count procfs on Linux; Windows and WSL2 (`wsl_pool`: procfs is WSL's RAM) read CUDA's pool. pub fn hostCounts(unified: bool, windows: bool, wsl_pool: bool) bool { return unified and !windows and !wsl_pool; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 42186425cb9..23f6649c726 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -307,6 +307,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_DRAFTS_GREEDY", .scope = .flashnext, .kind = .size, .forms = "a whole draft count from 0 to the native size maximum (default 8; clamped to 1 through 15)" }, .{ .name = "TF_FLASHNEXT_GREEDY_WIDE", .scope = .flashnext, .kind = .size, .forms = "a whole round width from 0 to the native size maximum (default 4)" }, .{ .name = "TF_FLASHNEXT_WINDOW_ROWS", .scope = .flashnext, .kind = .size, .forms = "a whole row count from 0 to the native size maximum (default the shared round's rows; capped by them)" }, + .{ .name = "TF_FLASHNEXT_WINDOW_CHECK", .scope = .flashnext, .kind = .flag, .forms = "0 or 1 (1 runs the boot copy-window self-check; default 0)" }, .{ .name = "TF_FLASHNEXT_READOUT_ROWS", .scope = .flashnext, .kind = .size, .forms = "a whole row count from 0 to the native size maximum (default 64; 0 never takes the tiles)" }, .{ .name = "TF_FLASHNEXT_CHUNK", .scope = .flashnext, .kind = .size, .min = 1, .max = 16384, .forms = "whole prompt rows a pass, 1 to 16384 (default 3072)" }, .{ .name = "TF_FLASHNEXT_CHUNK_SOLO", .scope = .flashnext, .kind = .size, .max = 16384, .forms = "whole prompt rows a pass with no stream decoding, TF_FLASHNEXT_CHUNK to 16384 (unset: 8192 alone at --parallel 1, else off)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 4be817491ea..cb5aefc174d 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -147,6 +147,8 @@ const valid = [_]Case{ .{ .name = "TF_FN_GX_SHARED", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN35_CHUNK_SOLO", .raw = "8192", .n = 8192 }, .{ .name = "TF_QWEN35_CHUNK_SOLO", .raw = "6144", .n = 6144 }, + .{ .name = "TF_FLASHNEXT_WINDOW_CHECK", .raw = "0", .n = 0 }, + .{ .name = "TF_FLASHNEXT_WINDOW_CHECK", .raw = "1", .n = 1 }, .{ .name = "TF_GEMMA4_CHUNK_SOLO", .raw = "2048", .n = 2048 }, .{ .name = "TF_GEMMA4_ARGMAX_GRAPH", .raw = "0", .n = 0 }, .{ .name = "TF_GEMMA4_ARGMAX_GRAPH", .raw = "1", .n = 1 }, diff --git a/zig/tests/cuda/contract_flashnext_late.zig b/zig/tests/cuda/contract_flashnext_late.zig index 2e6c0531415..663c719267b 100644 --- a/zig/tests/cuda/contract_flashnext_late.zig +++ b/zig/tests/cuda/contract_flashnext_late.zig @@ -29,11 +29,12 @@ fn noSums(_: c.Shape) usize { return 0; } -/// A verify window's rows: one, a greedy window and the widest a window may be (mtp.max_rows). +/// A verify window's rows: one, a greedy window, the shipped 32 and the widest a window may be (the log's rows). const served = [_]c.Shape{ .{ .rows = 1, .n = nv * dv, .k = dk }, .{ .rows = 9, .n = nv * dv, .k = dk }, .{ .rows = 32, .n = nv * dv, .k = dk }, + .{ .rows = lr, .n = nv * dv, .k = dk }, }; pub fn spec(kind: Kind) c.Spec { @@ -110,7 +111,7 @@ pub const Late = struct { self.nout = 0; self.shape = shape; const m = shape.rows; - if (m == 0 or m > 32 or shape.n != nv * dv or shape.k != dk) return false; + if (m == 0 or m > lr or shape.n != nv * dv or shape.k != dk) return false; var prng = std.Random.DefaultPrng.init(seed ^ 0x6c617465); const r = prng.random(); const a = self.rig.gpu.gpa; diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 8a9ade3392a..9576448fadd 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -129,9 +129,9 @@ zig/src/families/flashnext/cuda_hc.zig 01f897ac65d6edd2cd6ac76d97cb4d96619c25ffa zig/src/families/flashnext/cuda_head.zig 734cc1ccea8e99ce9a061273a2dd3042f32e4848b622b5de616aa4b6f546bdd4 raw #3749: TF_FLASHNEXT_SHARD_HEAD read through platform/environment.zig, blank as unset zig/src/families/flashnext/cuda_images.zig 4696ef29dc81f30882f964d69a71c5378b247bfb772b51b354569639bf5a8812 raw #3164 (a resumed prompt sends only the images past its kept state); #3164 (a resumed prompt sends only the images past its kept state); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged zig/src/families/flashnext/cuda_images_test.zig 4278e5241f6c7e0e710e9a8ddf0482855db158eeee2463200a2c2de32c9dadd7 raw #3164 (resumed image rows tested) -zig/src/families/flashnext/cuda_lanes.zig 0aa9e028693cff3c88253952ff82526da59879b9018a01951ad6c5cf3dacae5e raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change), this change (the page pool opens with the load's device and io, for its arena mapped as pages are used; a new paged stream's first prompt step waits while the arena's thread maps its pieces; paging off: unchanged), #2917: one launch description and rank flags change this source; #3164 (resumed image rows passed to the tower), #3219, #2919 (the resolved rank and world reach visionBytes) -zig/src/families/flashnext/cuda_lanes_admission_test.zig a87b5320d8cda1f95d254c2148c849005c2158b70afb73da3e32b627e6d2f13d raw -zig/src/families/flashnext/cuda_lanes_load.zig 872cf185ad0e928b565b7ba9222563b8519167e66c9db91033eeac078c492be2 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged +zig/src/families/flashnext/cuda_lanes.zig 1268d74a1af2658e56ce0fcfdf22646a83e904f4977115725c4c367bbfd24700 raw main 4f6017ced (marks inside the pass), fbca90714 (shared solo-chunk rule, #2391), 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #1953: the ladder's values through snap_intermediate, #3308 (loader host test updates the named startup-refusal expectations; no runtime edit to this pinned file); #3135 (kept_disk renamed kept_view for the shared kept image; no served change), this change (the page pool opens with the load's device and io, for its arena mapped as pages are used; a new paged stream's first prompt step waits while the arena's thread maps its pieces; paging off: unchanged), #2917: one launch description and rank flags change this source; #3164 (resumed image rows passed to the tower), #3219, #2919 (the resolved rank and world reach visionBytes) +zig/src/families/flashnext/cuda_lanes_admission_test.zig eef300305c40846de8d362f32d1f5274fd3896fa3959a658cf72b86a394949cc raw this branch: the admission test's capacity expects the load's window buffers (mtp.bufferRows()) +zig/src/families/flashnext/cuda_lanes_load.zig c0d02de9960323d8101033a994923d0ea19a2eb60f6db0ae64096508aba850f9 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #3467: after load a shard drops its page cache except the n-gram ranges, and the sweep reaches nested shards; tensors and replies are unchanged, this change (the load's device and io handed to the page pool's arena; paging off: unchanged); #3456: a checkpoint's vision tower loads only with --vision, images without it are refused by the shared gate; text replies are unchanged zig/src/families/flashnext/cuda_lanes_restore_test.zig f9947521a6d9c7d7380ca1b784a93a43b364c6fa5861cad15efd3538d2b8ceff raw zig/src/families/flashnext/cuda_launch.zig f056079d88e9295455bf44bed7ed4053e55fdb8579cfdb392c31a4c3af18e73c raw exports cuda_moe_exchange.zig for its device test; no served change; #2837 (Flash Next TP=2 graph replay); #3413 exports cuda_tiles.zig and readout_fused.zig for their tests zig/src/families/flashnext/cuda_media.zig 394601e8a807f5516f501efcaefa6fb3308f392ee322db7296b11c90814f8eea raw @@ -141,11 +141,11 @@ zig/src/families/flashnext/cuda_mixed_experts.zig d0362f591e98c2d13581ae48fb75fb zig/src/families/flashnext/cuda_mlp.zig 8224a28003487487e69eb669be11eaafafdb1ce0bc4c5e57024cef0a6a29e66f raw zig/src/families/flashnext/cuda_modelopt_experts.zig de779975629770b33ad5c0ebf9aa6e334f7a98f173a452d2b7c33b50a08d968e raw zig/src/families/flashnext/cuda_moe.zig 87ba75343c1d228800ed9fcc6d933f1175df172c008e14a8c7a64ff7011bed44 raw -zig/src/families/flashnext/cuda_mtp.zig 25bd4a7ce6b740d2e4c1eec012bfdfb4a10a97a24cd3150b1335b89862dd970e raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run), the MTP rows' row best split over 32 blocks a row (fn_row_best_max, fn_row_best_sum), fn_row_best's bits, headBytes counts the split's scratch (split_bytes) -zig/src/families/flashnext/cuda_mtp_check.zig 35d9d0ad51171ca2d70a0458f90fe6a04dd5f759fd9f005593c9d1189fb7846d raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) -zig/src/families/flashnext/cuda_mtp_draft.zig 41628480a1071c4a58a229f5e8b42e26fcd030a046ca6796d2dcb2fedb8daf28 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader) +zig/src/families/flashnext/cuda_mtp.zig b5f0866c8282416436d441ead43a6c0d3f993ed2914be4687f9a0126673b3696 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), #2927, main 3a56d4eb92 (one added line, the test import of cuda_mtp_load.zig so its loader tests run), the MTP rows' row best split over 32 blocks a row (fn_row_best_max, fn_row_best_sum), fn_row_best's bits, headBytes counts the split's scratch (split_bytes) +zig/src/families/flashnext/cuda_mtp_check.zig 9b607870ecd55686cb04ea75c0a04d2512508a94878930e1b1aa3330d6d9b0d8 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning); probeServed and windowCheck sweep every width the buffers hold against their one-token steps +zig/src/families/flashnext/cuda_mtp_draft.zig 64ae69cbb65675e9bc0948c1034c77ccc40faf8ea1b4c62de351d017451dfc39 raw main 80e0fd72c (#2753: non-finite draft rows refused by name; finite rows unchanged), dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning), 52479d3036 (#2585: a test of the blank TF_FLASHNEXT_KEEP_LATE reader); a window's scores, best values and saved pieces size at the load's bufferRows() zig/src/families/flashnext/cuda_mtp_load.zig d205877fe6d9d6b7b24a0ae061e8fc59a947fdcb1911d38e9f788af2468816c2 raw main 3a56d4eb92 (the draft head's mode read through platform/environment.zig: unset or blank keeps affine4, bf16 keeps the stored rows; kernels and launch counts unchanged) -zig/src/families/flashnext/cuda_mtp_ops.zig c6e07580378538c0131fc687003d7559bca8b2318373c1f889ef1a07423ffa3c raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927 +zig/src/families/flashnext/cuda_mtp_ops.zig e36de264cd1730abe32570af7d5e4e5830235ad6f2f93f02dbd3ee67270fd444 raw main 4b2679bf9 (grouped draft head carries its page table), 4f6017ced, ec76abd45 (reserveRows), 80e0fd72c, c6a337753 (#2753: verify rows checked after one completion wait, non-finite rows refused; finite rows unchanged), #2927; a verify window's width is checked against the served window (mtp.rowsOk) zig/src/families/flashnext/cuda_norms.zig c6ca7f9c1a9049c0f9d512fe2a38c2672a2e96b5c060d6cec2bca0d39e34bad0 raw zig/src/families/flashnext/cuda_ple.zig 417abb05f6cf212c09042bbbd695f313666b13639a81229d9fc6b26e5026b6a2 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning); the shared pass gathers its lanes in one pool call (Split and part reachable from cuda_ple_gather_lanes.zig); every row is the per-stream call's zig/src/families/flashnext/cuda_ple_check.zig e8b7cac1e0d3718f106482f6cff7375c0063e1757c46814bd40da435c83ba8ed raw From 5e0d6e23ba5efeeeb0d3b65772a9de61ed7eafff Mon Sep 17 00:00:00 2001 From: BadAd84 Date: Mon, 23 Nov 2026 18:39:03 +0000 Subject: [PATCH 236/361] flashnext: the window's waits predicts with the rows its open takes State.waits added mtp.max_rows, the pending-row log's 48 rows, while open, the window buffers and windowRows take mtp.bufferRows(): 32 with TF_FLASHNEXT_WINDOW_CHECK unset. A request near a page boundary could then post and wait for a page its open never uses, so the off path was not main's. The prediction now adds windowRows; an off and paged host test pins the page it posts, none off and page 16 when the check runs. --- zig/build/cuda_fault_host.zig | 2 +- .../families/flashnext/cuda_kv_init_test.zig | 65 +++++++++++++++++++ zig/src/families/flashnext/cuda_kv_lanes.zig | 2 +- 3 files changed, 67 insertions(+), 2 deletions(-) diff --git a/zig/build/cuda_fault_host.zig b/zig/build/cuda_fault_host.zig index 83178924406..4b1c31db187 100644 --- a/zig/build/cuda_fault_host.zig +++ b/zig/build/cuda_fault_host.zig @@ -6,7 +6,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, flashnext: *std.Build.Modul b.step("test-cuda-context-health-host", "Sticky CUDA context faults and real graph-instantiation refusal without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{ "CUDA context health:", "CUDA graph refusal:" } })).step); b.step("test-flashnext-loader-host", "The threaded NVFP4 expert loader: the loop's words, no pinned or device memory left after a failed load, geometry first").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{"Flash Next expert loader:"} })).step); b.step("test-flashnext-completion-host", "Actual CUDA sequence rollback drains asynchronous destinations before release").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"Flash Next completion:"} })).step); - b.step("test-flashnext-window-host", "The served copy window and its buffers: a width the boot check proved, the shipped rows unless it runs").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{ "the served copy window widens", "the boot check's sweep", "a draft at 65,536 tokens", "the saved pieces follow" } })).step); + b.step("test-flashnext-window-host", "The served copy window and its buffers: a width the boot check proved, the shipped rows unless it runs").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = flashnext, .filters = &.{ "the served copy window widens", "the boot check's sweep", "a draft at 65,536 tokens", "the saved pieces follow", "the window's waits" } })).step); b.step("test-cuda-fault-admission-host", "Sticky context health reaches native status and queue admission").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA context health:"} })).step); b.step("test-cuda-readiness-host", "Real native readiness and synchronous startup preparation without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"family readiness reaches"} })).step); b.step("test-startup-log-host", "Ordered startup logs and early P2P facts without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = cuda, .filters = &.{"startup log:"} })).step); diff --git a/zig/src/families/flashnext/cuda_kv_init_test.zig b/zig/src/families/flashnext/cuda_kv_init_test.zig index 2470b0a02ca..baac3c44830 100644 --- a/zig/src/families/flashnext/cuda_kv_init_test.zig +++ b/zig/src/families/flashnext/cuda_kv_init_test.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const kv = @import("core").kv_pool; const pages = @import("cuda_kv_lanes.zig"); +const mtp = @import("cuda_mtp.zig"); const E = @import("cuda_prompt.zig").Engine; const gpa = std.testing.allocator; const layout: kv.Layout = .{ .fixed_bytes = 0, .token_bytes = 64, .page_tokens = 16, .snap_bytes = 0, .run_bytes = 64 }; @@ -307,3 +308,67 @@ test "kv safety: Flash Next open into unmapped pieces beside a running stream wa pool.deinit(); try Device.released(); } + +test "the window's waits: off, a request near a page boundary posts no page its open will not use" { + const arena = @import("cuda_kv_arena.zig"); + var d = Device.driver(); + d.api.cuCtxGetCurrent = Slow.getCurrent; + d.api.cuCtxSetCurrent = Slow.setCurrent; + d.api.cuStreamCreate = Slow.streamCreate; + d.api.cuStreamDestroy_v2 = Slow.streamDestroy; + var e = engine(&d); + e.round_graph = .{}; + defer finish(&d, e.stream.*); + // 96 pages of 16 MiB: six pieces; runs of 8 pages from the top; 224 rows plus 32 take 16 pages, plus 48 take 17 + const big: kv.Layout = .{ .fixed_bytes = 0, .token_bytes = 1 << 20, .page_tokens = 16, .snap_bytes = 0, .run_bytes = 128 << 20 }; + const pool = try pages.Pool.init(gpa, &e, big, 512, null, 2, 96); + var s: arena.Arena.Pieces = .{ .gpa = gpa, .vmm = undefined, .d = &d, .io = std.testing.io }; + var live = true; + defer if (live) { + if (s.ahead) |*x| x.deinit(); + pool.arena.pieces = null; + pool.deinit(); + }; + defer mtp.buffer_rows = mtp.base_rows; + s.vmm.va = pool.arena.buf.ptr; + s.vmm.va_len = 6 * arena.piece_bytes; + s.vmm.next = s.vmm.va; + s.vmm.granularity = 2 << 20; + s.vmm.device = 0; + s.vmm.prop = .{}; + s.vmm.failed = null; + s.vmm.api.create = Slow.create; + s.vmm.api.release = Slow.ok64; + s.vmm.api.map = Slow.map; + s.vmm.api.unmap = Slow.unmap; + s.vmm.api.setAccess = @ptrCast(&Slow.access); + var mapped: [6]bool = @splat(false); + s.lazy = .{ .base = pool.arena.buf.ptr, .len = pool.arena.buf.len, .piece = arena.piece_bytes, .mapped = &mapped }; + pool.arena.pieces = &s; + Slow.caller = std.Thread.getCurrentId(); + Slow.on_caller.store(0, .monotonic); + Slow.created.store(0, .monotonic); + // a paged lane, and the pieces an earlier open of the same 224 rows and the shipped 32 left mapped + const pb = big.pageBytes(); + try pool.arena.ensure(0, 16 * pb, Device.stream); + try pool.arena.ensure(88 * pb, 8 * pb, Device.stream); + var st: pages.State = .{ .pool = pool, .paged_only = true }; + mtp.sizeWindow(false); + try std.testing.expectEqual(mtp.base_rows, mtp.bufferRows()); + try std.testing.expect(!st.waits(224, 1)); // 256 rows: the 16 pages and the run its open takes, all mapped + try std.testing.expect(!mapped[1] and std.mem.indexOfScalar(bool, s.ahead.?.queued, true) == null); + // the check's own load: 48 buffer rows reach page 16 in piece 1, so the request waits for it, once + mtp.sizeWindow(true); + try std.testing.expectEqual(mtp.max_rows, mtp.bufferRows()); + try std.testing.expect(st.waits(224, 1)); + s.ahead.?.settle(); + try std.testing.expect(mapped[1] and !mapped[2]); + try std.testing.expect(!st.waits(224, 1)); + s.ahead.?.deinit(); + s.ahead = null; + s.lazy.?.unmapAll(.{ .be = s.vmm.backend(), .seek = undefined }); + pool.arena.pieces = null; + live = false; + pool.deinit(); + try Device.released(); +} diff --git a/zig/src/families/flashnext/cuda_kv_lanes.zig b/zig/src/families/flashnext/cuda_kv_lanes.zig index 6bdb40cf91e..ca408da95d9 100644 --- a/zig/src/families/flashnext/cuda_kv_lanes.zig +++ b/zig/src/families/flashnext/cuda_kv_lanes.zig @@ -91,7 +91,7 @@ pub const State = struct { /// Whether a new stream of `rows` rows waits for the arena's thread before its open (Pool.waits); own stream: no. pub fn waits(s: *const State, rows: usize, others: usize) bool { if (s.choose() != .pool) return false; - return s.pool.?.waits(@min(rows + mtp.max_rows, prompt.max_tokens), others > 0); + return s.pool.?.waits(@min(rows + windowRows(), prompt.max_tokens), others > 0); } /// The lane host's admission: the own stream is free, or a lane and the request's pages are. From 447cfb44094d61320f485b77de502836a349d20a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:14:33 +0000 Subject: [PATCH 237/361] flashnext env test: count TF_FLASHNEXT_WINDOW_CHECK (39 settings, 27 switches) The new switch is registered but the Flash Next settings test still expected 38 settings with 26 switches, so the host test failed. Test only. --- zig/src/platform/environment_flashnext_test.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/platform/environment_flashnext_test.zig b/zig/src/platform/environment_flashnext_test.zig index ae9a214ac3d..d2ec25edadb 100644 --- a/zig/src/platform/environment_flashnext_test.zig +++ b/zig/src/platform/environment_flashnext_test.zig @@ -33,13 +33,13 @@ fn check(name: []const u8, raw: []const u8, valid: bool) !void { try t.expect(std.mem.endsWith(u8, why.?, e.rule(name).forms)); } -test "Flash Next strict env: the table holds all 40 settings: 28 switches, 9 integers, 1 real, 2 structured" { +test "Flash Next strict env: the table holds all 41 settings: 29 switches, 9 integers, 1 real, 2 structured" { var counts: [4]usize = @splat(0); for (e.rules) |r| if (r.scope == .flashnext) { try t.expect(std.mem.startsWith(u8, r.name, "TF_FLASHNEXT_")); counts[@backingInt(group(r))] += 1; }; - try t.expectEqual([4]usize{ 28, 9, 1, 2 }, counts); + try t.expectEqual([4]usize{ 29, 9, 1, 2 }, counts); } test "Flash Next strict env: unset and blank settings both read as the caller's default" { From b2fe9c5d3b42e7f02ea0bc2c2064806f3c7fa226 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:54:42 +0000 Subject: [PATCH 238/361] docs: Flash Next checks 41 settings with TF_FLASHNEXT_WINDOW_CHECK --- docs/environment.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/environment.md b/docs/environment.md index f3590fd284f..b7dc68b1445 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -182,7 +182,7 @@ Windows uses the same proxy routes and timeout settings through native asynchron ## Flash Next -Flash Next checks these 40 settings when its engine loads, before any device or checkpoint work: a malformed value +Flash Next checks these 41 settings when its engine loads, before any device or checkpoint work: a malformed value stops the start with the variable, the supplied text and the accepted forms. | Variable | Accepted explicit value | From 1b3798b4f83e5184391f98ce1ca0b478e1d04806 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:36:41 +0000 Subject: [PATCH 239/361] changelog: #4075 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d61065740f..661fce9d0ed 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 +- Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_CHECK=1` (default off) runs a boot self-check that measures the widest verify window whose every row's scores equal its one-token step on that machine, and a lone stream's copy window then grows past the shipped 32 rows to at most the 48 the pending-row log holds; a check that cannot run, fails or proves nothing past 32 leaves the window at 32, and with the switch off every buffer the window sizes is main's (#4075). Thanks to @BadAd84. + - 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). From e119ed383988b3feb32b63ec5b1f5b2f5b7b92a0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:36:41 +0000 Subject: [PATCH 240/361] changelog: #4075 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 661fce9d0ed..da1b9717b23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_CHECK=1` (default off) runs a boot self-check that measures the widest verify window whose every row's scores equal its one-token step on that machine, and a lone stream's copy window then grows past the shipped 32 rows to at most the 48 the pending-row log holds; a check that cannot run, fails or proves nothing past 32 leaves the window at 32, and with the switch off every buffer the window sizes is main's (#4075). Thanks to @BadAd84. + + - 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). From 38a69cd749bf1862b77a94d3590f17de29736250 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:24:36 +0100 Subject: [PATCH 241/361] XPU qwen27: attn_decode takes a key's twelve exponentials as one vector exp, bit-equal --- zig/kernels/xpu/qwen27/decode.cl | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/zig/kernels/xpu/qwen27/decode.cl b/zig/kernels/xpu/qwen27/decode.cl index c2c242b48e8..3ac37cb6b7a 100644 --- a/zig/kernels/xpu/qwen27/decode.cl +++ b/zig/kernels/xpu/qwen27/decode.cl @@ -74,6 +74,9 @@ KERNEL(16) void gdn_step(global const ushort *Q, global const ushort *K, global // Decode attention by key slices: one subgroup per (row, K/V head, query part, slice). Grid y is AKV * QPARTS. #define SPLIT 32 +#if Q27_QPG > 8 +#error "attn_decode keeps head a's running max in lanes a and a + 8: at most 8 heads" +#endif KERNEL(16) void attn_decode(global const ushort *Q, global const ushort *KC, global const ushort *VC, global float *PM, global float *PL, global float *PO, int p0, int NS, float scale, global const int *TREE, global const ulong *MT, global const int *POS, int cap) { @@ -93,7 +96,7 @@ KERNEL(16) void attn_decode(global const ushort *Q, global const ushort *KC, glo base = TREE ? POS[wf] : 0x7fffffff; } const int last = MT ? POS[t] : p0 + DEPTH(t), j0 = sp * SPLIT, j1 = min(j0 + SPLIT, last + 1); - float q[Q27_QPG][16], o[Q27_QPG][16], m[Q27_QPG], l[Q27_QPG]; + float q[Q27_QPG][16], o[Q27_QPG][16], l[Q27_QPG], mv = -INFINITY; // mv: head a's running max in lanes a and a + 8 for (int a = 0; a < Q27_QPG; a++) { for (int i = 0; i < 16; i++) { #if Q27_QPARTS == 1 @@ -103,7 +106,6 @@ KERNEL(16) void attn_decode(global const ushort *Q, global const ushort *KC, glo #endif o[a][i] = 0.0f; } - m[a] = -INFINITY; l[a] = 0.0f; } for (int j = j0; j < j1; j++) { @@ -127,12 +129,16 @@ KERNEL(16) void attn_decode(global const ushort *Q, global const ushort *KC, glo for (int i = 0; i < 16; i++) kv[i] = (float)v8[i * 16 + lane] * vs; } else for (int i = 0; i < 16; i++) kv[i] = bf2f(VC[(kr * Q27_AKV + hk) * 256 + i * 16 + lane]); + // The running maxima sit in lanes a and a + 8 of mv, the scores in sv: all the exponentials are one vector exp. + float sv = -INFINITY; + for (int a = 0; a < Q27_QPG; a++) sv = select(sv, sc[a], (int)((lane & 7) == a)); + const float mn = fmax(mv, sv); + const float e = exp((lane < 8 ? mv : sv) - mn); // lanes below 8: exp(m - mn), the others: exp(sc - mn) + mv = mn; for (int a = 0; a < Q27_QPG; a++) { - const float mn = fmax(m[a], sc[a]); - const float al = exp(m[a] - mn), p = exp(sc[a] - mn); + const float al = sub_group_broadcast(e, a), p = sub_group_broadcast(e, a + 8); l[a] = l[a] * al + p; for (int i = 0; i < 16; i++) o[a][i] = o[a][i] * al + p * kv[i]; - m[a] = mn; } } for (int a = 0; a < Q27_QPG; a++) { @@ -142,7 +148,7 @@ KERNEL(16) void attn_decode(global const ushort *Q, global const ushort *KC, glo const long base = ((long)t * Q27_AQ + qh0 + a) * NS + sp; #endif if (lane == 0) { - PM[base] = m[a]; + PM[base] = sub_group_broadcast(mv, a); PL[base] = l[a]; } for (int i = 0; i < 16; i++) PO[base * 256 + i * 16 + lane] = o[a][i]; From 4ae11c8a54791690318d8f2b3d2f1c776c58f992 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:37:11 +0100 Subject: [PATCH 242/361] XPU contract: attn_decode's exponential vector gets a planted control --- docs/kernel-contract.md | 5 +++ zig/kernels/xpu/contract_gate_controls.cl | 45 +++++++++++++++++++++++ zig/src/core/contract/xpu_records.zig | 4 ++ zig/tests/xpu/contract_attn.zig | 12 ++++-- zig/tests/xpu/contract_live.zig | 1 + zig/tests/xpu/contract_run.zig | 3 ++ 6 files changed, 66 insertions(+), 4 deletions(-) diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index 55b60422ca8..566d9d54d70 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -130,6 +130,11 @@ edges, and 8,193 through 32,770 visible keys at selected root positions. The pos and normalization sums, without separately proving the query/key dot accumulator. The default NaN rule compares classes with the independent float64 formula. Int8 caches and multi-stream metadata are outside this registration. +`attn_decode` takes the exponentials of a key's six heads (`exp(m - mn)` and `exp(sc - mn)`) in one 16-lane vector +instead of twelve scalar ones; the arguments, the max and the update order are unchanged, and gate 3's bytes against the +upstream pair are the proof at every served shape. A planted control fills the scores into lanes 0 to 7 only, so every +`p` is `exp(-inf)`, and goes red at gate 3. + The `attn_merge` registration is a replacement: gate 3 requires the bytes of the merge it replaces, retained in `zig/kernels/xpu/contract_merge_upstream.cl`, on the same partials (random maxima, sums and values, with other values in the slices a row does not hold) at 1 to 16 tree rows and 33 to 131,073 visible keys, including 32-key slice edges. diff --git a/zig/kernels/xpu/contract_gate_controls.cl b/zig/kernels/xpu/contract_gate_controls.cl index 13612cb8bc5..2767f890999 100644 --- a/zig/kernels/xpu/contract_gate_controls.cl +++ b/zig/kernels/xpu/contract_gate_controls.cl @@ -210,3 +210,48 @@ KERNEL(16) void tf_ctl_attn_merge_unguarded(global const float *PM, global const } O[((long)t * 24 + hh) * 256 + g * 16 + lane] = intel_convert_bfloat16_as_ushort(o / l); } + +// Gate 3: attn_decode with its exponentials in one vector; planted: scores in lanes 0 to 7 only, so every p is 0. +KERNEL(16) void tf_ctl_attn_exp_lanes(global const ushort *Q, global const ushort *KC, global const ushort *VC, + global float *PM, global float *PL, global float *PO, int p0, int NS, float scale, + global const int *TREE, global const ulong *MT, global const int *POS, int cap) { + const int sp = get_group_id(2), hk = get_group_id(1), t = get_group_id(0), lane = get_sub_group_local_id(); + const int last = p0 + (TREE[t * 17] & 255), j0 = sp * 32, j1 = min(j0 + 32, last + 1); + float q[6][16], o[6][16], l[6], mv = -INFINITY; + for (int a = 0; a < 6; a++) { + for (int i = 0; i < 16; i++) { + q[a][i] = bf2f(Q[((long)t * 24 + hk * 6 + a) * 256 + i * 16 + lane]); + o[a][i] = 0.0f; + } + l[a] = 0.0f; + } + for (int j = j0; j < j1; j++) { + const long kr = j < p0 ? j : p0 + TREE[t * 17 + 1 + j - p0]; + float kv[16], sc[6]; + for (int i = 0; i < 16; i++) kv[i] = bf2f(KC[(kr * 4 + hk) * 256 + i * 16 + lane]); + for (int a = 0; a < 6; a++) { + float d = 0.0f; + for (int i = 0; i < 16; i++) d += q[a][i] * kv[i]; + sc[a] = sub_group_reduce_add(d) * scale; + } + for (int i = 0; i < 16; i++) kv[i] = bf2f(VC[(kr * 4 + hk) * 256 + i * 16 + lane]); + float sv = -INFINITY; + for (int a = 0; a < 6; a++) sv = select(sv, sc[a], (int)(lane == a)); + const float mn = fmax(mv, sv); + const float e = exp((lane < 8 ? mv : sv) - mn); + mv = mn; + for (int a = 0; a < 6; a++) { + const float al = sub_group_broadcast(e, a), p = sub_group_broadcast(e, a + 8); + l[a] = l[a] * al + p; + for (int i = 0; i < 16; i++) o[a][i] = o[a][i] * al + p * kv[i]; + } + } + for (int a = 0; a < 6; a++) { + const long base = ((long)t * 24 + hk * 6 + a) * NS + sp; + if (lane == 0) { + PM[base] = sub_group_broadcast(mv, a); + PL[base] = l[a]; + } + for (int i = 0; i < 16; i++) PO[base * 256 + i * 16 + lane] = o[a][i]; + } +} diff --git a/zig/src/core/contract/xpu_records.zig b/zig/src/core/contract/xpu_records.zig index 32fb95ecdf5..5d88402f645 100644 --- a/zig/src/core/contract/xpu_records.zig +++ b/zig/src/core/contract/xpu_records.zig @@ -100,6 +100,10 @@ pub const records = [_]Record{ .launch = .{ .name = "planted attn_merge dropping last slice", .symbol = "tf_ctl_attn_drop_slice", .image = "contract_gate_controls", .format = glue, .threads = .{ 16, 1, 1 }, .sub_group = 16, .grf = 256 }, .usage = .{.{ .threads = .{ 16, 1, 1 }, .sub_group = 16, .grf = 256 }}, }, + .{ + .launch = .{ .name = "planted attn_decode with its exponential vector half filled", .symbol = "tf_ctl_attn_exp_lanes", .image = "contract_gate_controls", .format = glue, .threads = .{ 16, 1, 1 }, .sub_group = 16, .grf = 256 }, + .usage = .{.{ .threads = .{ 16, 1, 1 }, .sub_group = 16, .grf = 256 }}, + }, .{ .launch = .{ .name = "upstream standalone attn_merge", .symbol = "attn_merge", .image = "contract_merge_upstream", .format = glue, .threads = .{ 16, 1, 1 }, .sub_group = 16, .grf = 256 }, .usage = .{.{ .threads = .{ 16, 1, 1 }, .sub_group = 16, .grf = 256 }}, diff --git a/zig/tests/xpu/contract_attn.zig b/zig/tests/xpu/contract_attn.zig index cf571b54e2c..873ec306960 100644 --- a/zig/tests/xpu/contract_attn.zig +++ b/zig/tests/xpu/contract_attn.zig @@ -1,4 +1,4 @@ -//! The decode attention pair as one replacement operator, and its controls: a merge losing a slice, the old grid. +//! The decode attention pair as one replacement operator, and its controls: a lost slice, the old grid, a half exp. const std = @import("std"); const xpu = @import("xpu"); const core = @import("core"); @@ -10,8 +10,8 @@ const ref = core.xpu_ref.attention; const Buffers = struct { pm: ?*anyopaque, pl: ?*anyopaque, po: ?*anyopaque, out: ?*anyopaque }; -/// The registration, or a planted control: the merge that loses the last slice, or attn_decode on the old grid. -pub const Plant = enum { none, drop_slice, old_grid }; +/// The registration, or a control: merge losing a slice, attn_decode on the old grid, or on a half-filled exp vector. +pub const Plant = enum { none, drop_slice, old_grid, exp_lanes }; /// Q rows, a bf16 K/V cache and a tree table to bf16 attention rows; no input is writable. pub const Attn = struct { @@ -31,7 +31,10 @@ pub const Attn = struct { baseline: Buffers = undefined, pub fn init(a: std.mem.Allocator, dev: *rig_.Dev, plant: Plant) !Attn { - var decode = try dev.kernelFor(.decode, "attn_decode", a); + var decode = if (plant == .exp_lanes) + try dev.kernel(.gate, "tf_ctl_attn_exp_lanes", .{ 16, 1, 1 }) + else + try dev.kernelFor(.decode, "attn_decode", a); errdefer decode.deinit(); var merge = if (plant == .drop_slice) try dev.kernel(.gate, "tf_ctl_attn_drop_slice", .{ 16, 1, 1 }) @@ -67,6 +70,7 @@ pub const Attn = struct { .none => {}, .drop_slice => s.name = "control: xpu attention merge losing its last slice", .old_grid => s.name = "control: xpu attn_decode launched on the old (slices, heads, rows) grid", + .exp_lanes => s.name = "control: xpu attn_decode whose exponential vector holds the scores in lanes 0 to 7 only", } return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (self.plant == .none) null else .shapes }; } diff --git a/zig/tests/xpu/contract_live.zig b/zig/tests/xpu/contract_live.zig index d7e093bfdd6..4bd13c995d8 100644 --- a/zig/tests/xpu/contract_live.zig +++ b/zig/tests/xpu/contract_live.zig @@ -42,6 +42,7 @@ fn argsOf(symbol: []const u8) u32 { .{ "tp4_allreduce_f32", 6 }, .{ "tp4_rs_f32", 7 }, .{ "attn_decode", 13 }, + .{ "tf_ctl_attn_exp_lanes", 13 }, .{ "attn_merge", 8 }, .{ "tf_ctl_attn_drop_slice", 8 }, .{ "tf_ctl_attn_merge_unguarded", 8 }, diff --git a/zig/tests/xpu/contract_run.zig b/zig/tests/xpu/contract_run.zig index b5037ef155e..b9abb1deaa6 100644 --- a/zig/tests/xpu/contract_run.zig +++ b/zig/tests/xpu/contract_run.zig @@ -72,6 +72,9 @@ pub fn main(init: std.process.Init) !u8 { var attn_grid = try attn_k.Attn.init(a, &dev, .old_grid); defer attn_grid.deinit(); try kernels.append(a, attn_grid.kernel()); + var attn_exp = try attn_k.Attn.init(a, &dev, .exp_lanes); + defer attn_exp.deinit(); + try kernels.append(a, attn_exp.kernel()); var merges: [std.enums.values(merge_k.Variant).len]merge_k.Merge = undefined; for (&merges, std.enums.values(merge_k.Variant)) |*x, v| x.* = try merge_k.Merge.init(a, &dev, v); defer for (&merges) |*x| x.deinit(); From 562b0bc65ec191521cfe8399e7b8b6949411e5d9 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:12:47 +0100 Subject: [PATCH 243/361] XPU qwen27: attn_decode vector exp receipts and changelog --- CHANGELOG.md | 2 + docs/receipts/xpu-qwen27-attn-exp/README.md | 160 ++++++++++++++++++ docs/receipts/xpu-qwen27-attn-exp/analyse.out | 57 +++++++ .../xpu-qwen27-attn-exp/binaries.sha256 | 2 + .../contract/contract-run-branch.out | Bin 0 -> 18676 bytes .../contract/contract-run-main.out | Bin 0 -> 18156 bytes .../contract/limits-branch.out | 70 ++++++++ .../xpu-qwen27-attn-exp/kernel/summarize.py | 16 ++ .../xpu-qwen27-attn-exp/kernel/summary.out | 8 + .../proofs/expprobe_all.out | 4 + .../xpu-qwen27-attn-exp/proofs/fmaxprobe.out | 2 + .../xpu-qwen27-attn-exp/runs/p1-main.jsonl | 24 +++ .../xpu-qwen27-attn-exp/runs/p2-branch.jsonl | 24 +++ .../xpu-qwen27-attn-exp/runs/p3-main.jsonl | 24 +++ .../xpu-qwen27-attn-exp/runs/p4-branch.jsonl | 24 +++ .../xpu-qwen27-attn-exp/scripts/analyse.py | 51 ++++++ .../xpu-qwen27-attn-exp/scripts/bench_tree.py | 89 ++++++++++ .../scripts/build_corp_code.sh | 13 ++ .../xpu-qwen27-attn-exp/scripts/driver.sh | 16 ++ .../scripts/expprobe_all.py | 68 ++++++++ .../xpu-qwen27-attn-exp/scripts/fmaxprobe.py | 72 ++++++++ .../xpu-qwen27-attn-exp/scripts/run_pass.sh | 30 ++++ 22 files changed, 756 insertions(+) create mode 100644 docs/receipts/xpu-qwen27-attn-exp/README.md create mode 100644 docs/receipts/xpu-qwen27-attn-exp/analyse.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/binaries.sha256 create mode 100644 docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-branch.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-main.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/contract/limits-branch.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/kernel/summarize.py create mode 100644 docs/receipts/xpu-qwen27-attn-exp/kernel/summary.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/proofs/expprobe_all.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/proofs/fmaxprobe.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs/p1-main.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs/p2-branch.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs/p3-main.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs/p4-branch.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/scripts/analyse.py create mode 100755 docs/receipts/xpu-qwen27-attn-exp/scripts/bench_tree.py create mode 100755 docs/receipts/xpu-qwen27-attn-exp/scripts/build_corp_code.sh create mode 100755 docs/receipts/xpu-qwen27-attn-exp/scripts/driver.sh create mode 100644 docs/receipts/xpu-qwen27-attn-exp/scripts/expprobe_all.py create mode 100644 docs/receipts/xpu-qwen27-attn-exp/scripts/fmaxprobe.py create mode 100755 docs/receipts/xpu-qwen27-attn-exp/scripts/run_pass.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index da1b9717b23..55c97d48746 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -345,6 +345,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - XPU: Qwen3.8-27B decode attention merges its slices with 16 subgroups a head instead of one, adding them in the same order, so every output byte is unchanged (token hashes equal to main, drafted and plain, bf16 and int8 KV). On an Arc Pro B70 plain decode gains 1.8 to 2.0 % at about 8,000 prompt tokens, 14.7 to 16.0 % at about 30,000 and 39.8 to 42.2 % at 121,022; drafted decode is level. The kernel contract registers it as a bit-equal replacement with two planted controls (#3960, lands #2799). Thanks to @Mirrdhyn. +- XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#NNNN, refs #2543). + - Flash Next on CUDA: `TF_FLASHNEXT_FUSED_SPLIT=1` (opt-in) runs decode projections that split K over a cluster, at 2,048 output columns or more, on the fused form, adding the K slices in the cluster's order so the bits are unchanged; unset, blank or `0` keeps the current kernels, and Metal and HIP refuse `1` at startup (#3475). Thanks to @BadAd84. - Host draw: greedy and masked rows scan 64-logit blocks and skip blocks whose mask word allows nothing, on both the row draw and the bounded top-k path; a `test-host-draw-timing` step times a row outside `test` and CI (#2846). diff --git a/docs/receipts/xpu-qwen27-attn-exp/README.md b/docs/receipts/xpu-qwen27-attn-exp/README.md new file mode 100644 index 00000000000..37e95d394a2 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/README.md @@ -0,0 +1,160 @@ +# XPU Qwen3.8-27B attn_decode: a key's twelve exponentials as one vector exp + +Receipts for a change to `attn_decode` in `zig/kernels/xpu/qwen27/decode.cl` (refs #2543). For each key the kernel +computed twelve scalar exponentials, `exp(m - mn)` and `exp(sc - mn)` for the six query heads of a K/V head. They are now +the 16 lanes of one vector `exp` (head a's two arguments in lanes a and a + 8), and each head reads its two results back +with `sub_group_broadcast`. The arguments, `fmax`, the update order and every operand are unchanged, and there is no new +branch, so the output bytes are equal. Measured on 2026-11-22 against `main` at `14951bc65`. + +## Builds and hardware + +- Branch `xpu-qwen27-attn-exp`: kernel change `2aa76b383`, planted control and its contract wiring `bc332f14e`, on + `main` at `14951bc65`. Neither binary carries a local patch: `zig/src/xpu/rt.zig` is main's. +- Zig 0.17.0. Binaries: `zig build -j4 -Dxpu xpu-native -Doptimize=ReleaseFast -Dxpu-dpas=true -Dngen-include=` + in each tree. Contract runner and limits audit: `zig build tf-xpu-contract-run xpu-kernel-contract-limits + -Dxpu-contract=true -Dxpu-dpas=true -Dngen-include= -Doptimize=ReleaseFast`. +- `tensorfold-native` SHA-256, main: `bd78137b649c987d4d2848f212790e46457e0fb18cdf0e08795432f6bf074d12` + (MD5 `9bf82d00509328c873abeeaa7c654ab6`); branch: + `90349ad00c0015c2ba7dd4dcdb80dc813a06b71c4f4bf0811f237c40023889fd` (MD5 `d211292a5c26a572209f94aabb3e169b`) + (`binaries.sha256`). +- Card: Intel Arc Pro B70 (BMG-G31, PCI id `0xe223`), the host's card 0 (PCIe 5.0 x16, `ZE_AFFINITY_MASK=0`) for every + served and kernel timing. The kernel contract ran on card 1 (`ZE_AFFINITY_MASK=1`). One host, one card at a time. +- Host: Intel Core Ultra 7 270K Plus, 30 GiB RAM, Ubuntu 26.04.1, Linux 7.0.0-43-generic. +- Driver (`dpkg -l`): `intel-igc-core-2` 2.41.5, `intel-igc-opencl-2` 2.41.5, `intel-ocloc` 26.35.39758.21, + `intel-opencl-icd` 26.35.39758.21, `libze-intel-gpu1` 26.35.39758.21, `libze1` 1.32.0, `libigdgmm12` 22.10.2. +- Checkpoints: `Qwen3.8-27B-GPTQ-Int4-sym-G128-MTP-BF16` and its `Qwen3.8-27B-DFlash2` drafter, local copies. Hugging Face + revisions from each copy's download metadata: target `9d189a60e4c0ad7f9f47cd94bfa393ca10b3924e`, drafter + `50307d4c4cde6860d4eee73e2547cd786fe8e8a4`. + +## Served: same tokens, and the speed + +Four server passes in this order, each a fresh `tensorfold-native serve` on card 0 (`--parallel 1 --context 132096 +--prompt-cache-gib 0`, bf16 KV, the DFlash2 drafter, no `XPU_TREE`): main, branch, main, branch (`scripts/driver.sh`, +`scripts/run_pass.sh`, with the page cache dropped after each). One pass runs `scripts/bench_tree.py`: code prompts of +7,588, 28,946 and 121,022 tokens (cells 8192, 32768 and 131072 of the script, the first lines of `corp_code`, see +Reproduce), greedy temperature 0, 256 new tokens, thinking off, each drafted (the default) and plain (`"draft": false`), +one warm-up request and three measured ones per cell. Every request records the server's `tensorfold.token_sha256`; +`runs/` holds all of them (`p-main.jsonl`, `p-branch.jsonl`, the pass's server and bench logs). + +### Tokens + +Each cell's 16 requests (four passes, main and branch, one warm-up and three measured each) carry one `token_sha256`, +and the drafted and the plain cell of a depth share it: `CELLS WITH MORE THAN ONE HASH: 0`. The drafter's counters agree too: +at each depth the `speculative` object (drafted, accepted, rounds) is identical on every drafted request of both sides +(1,065 drafted and 186 accepted in 71 rounds at 7,588 tokens; 1,050 and 188 in 70 at 28,946; 1,005 and 188 in 67 at +121,022). All 96 requests have a `token_sha256` (`analyse.out`, from `scripts/analyse.py runs`). + +| prompt tokens | token_sha256 (first 16 hex) | prompt_sha256 (first 16 hex) | +|---|---|---| +| 7,588 | `9764d2d6fb7cbdbf` | `829dddadac0f329f` | +| 28,946 | `1d59abb499c48841` | `0bd40816987651da` | +| 121,022 | `0ac2491477780561` | `60986a50b4990e56` | + +### Speed + +Decode tok/s, served, one stream: the median of a pass's three measured requests (the warm-up request is left out). +`main` is the mean of passes 1 and 3, `branch` the mean of passes 2 and 4; the ratio is branch over main on the +unrounded means; the last two columns are the paired ratios, pass 2 over 1 and pass 4 over 3. + +: the median of a pass's three measured requests (warm-up request excluded) + +| prompt tokens | mode | main p1 | branch p2 | main p3 | branch p4 | main mean | branch mean | branch / main | p2/p1 | p4/p3 | +|---|---|---|---|---|---|---|---|---|---|---| +| 7588 | drafted | 62.31 | 63.09 | 62.21 | 63.09 | 62.26 | 63.09 | 1.013 | 1.013 | 1.014 | +| 7588 | plain | 32.67 | 32.69 | 32.67 | 32.69 | 32.67 | 32.69 | 1.001 | 1.000 | 1.001 | +| 28946 | drafted | 36.33 | 37.42 | 36.31 | 37.41 | 36.32 | 37.41 | 1.030 | 1.030 | 1.030 | +| 28946 | plain | 28.94 | 28.98 | 28.94 | 28.96 | 28.94 | 28.97 | 1.001 | 1.002 | 1.001 | +| 121022 | drafted | 13.30 | 13.95 | 13.30 | 13.96 | 13.30 | 13.96 | 1.049 | 1.049 | 1.049 | +| 121022 | plain | 19.50 | 19.52 | 19.50 | 19.53 | 19.50 | 19.52 | 1.001 | 1.001 | 1.002 | + +Drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022 (the two paired ratios of a +cell differ by 0.001 or less). Plain decode is level (1.001 to 1.002 at the three depths): it runs one row a token +through `attn_decode`, where a drafted round runs 15 tree nodes, and the kernel's saving there is 2.4 % at 20,000 tokens +and 0.8 % at 58,543 (`kernel/`), a small part of a token. Every request is in `analyse.out`. + + +## attn_decode GPU time + +`attn_decode` GPU ms a drafted round (`XPU_PROFILE=1`, the dev runner, card 0, 20,000 and 58,543 prompt tokens; tree 3 is +4 rows a round, tree 15 is 16 rows; the serial column is ms a plain token). `kernel/` holds the eight logs and +`kernel/summarize.py` (`summary.out`) prints the table. The runner trees also carried an unlaunched second kernel +(`attn_decode_rows`, not part of this change); `attn_decode`'s source in them is the one on main and on the branch. + +| prompt tokens | 4 rows, main -> branch | 16 rows, main -> branch | plain token, main -> branch | +|---|---|---|---| +| 20,000 | 8.06 -> 7.60 ms (-5.7 %) | 33.51 -> 30.99 ms (-7.5 %) | 2.932 -> 2.861 ms (-2.4 %) | +| 58,543 | 23.12 -> 21.72 ms (-6.1 %) | 95.69 -> 90.43 ms (-5.5 %) | 8.796 -> 8.722 ms (-0.8 %) | + +`attn_merge` is unchanged (`summary.out`). Repeat runs of one cell agree to 0.1 %. With a 15-node tree at 58,543 tokens +the verify round goes from 169.9 to 160.7 ms on card 0 (`kernel/*-58543-tree15.log`: "verify ... ms a round"). + +Where the rest of the time goes (ablations of the new kernel, numerically wrong, timing only; 16 rows, 20,000 tokens, +31.5 ms a round): V loads replaced by a constant 23.8 ms, K loads replaced by a constant 24.9 ms, the dot cut to two +terms 26.1 ms, no `o * al` multiplications 30.5 ms. The kernel waits on K/V load latency and on the dot's dependent +chain, not on its instruction count; hand-scheduled variants of the loads (block reads, V requested before the dot, the +next key's K in registers) were slower, 31.4 to 65.5 ms, so this change is the one exact edit that paid. + +## Why the bits cannot differ + +For every (row, head, slice, key) the operations are main's: `mn = fmax(m, sc)`, `al = exp(m - mn)`, `p = exp(sc - mn)`, +`l = l*al + p`, `o = o*al + p*kv`, `m = mn`, in that order on those operands. Only the place where `exp` runs moves: head +a's `m - mn` is in lane a of a vector, its `sc - mn` in lane a + 8, and one `exp` serves all lanes. It needs two +facts, both measured on the card (`proofs/`, ctypes over the OpenCL runtime, the images' compiler options): + +1. The vector `exp` equals the scalar `exp` on every input: `exp` of all 4,294,967,296 float bit patterns, NaNs and + infinities included, as a SIMD16 vector against the same value through `sub_group_broadcast` (16 scalar + `math.exp` sequences, as `attn_decode` had): 0 mismatches (`proofs/expprobe_all.out`, 18.6 s). +2. The vector `fmax` equals the scalar one: 536,870,912 pairs (all pairs of 25 special values: signed zeros, NaN + payloads, infinities, denormals; nearby and random patterns), 0 mismatches (`proofs/fmaxprobe.out`). + +So no non-finite or signed-zero input can differ either, which is why the kernel needs no finite-score guard. Lanes 6, 7, +14 and 15 hold -inf and give NaN that nothing reads. Rerun with `ZE_AFFINITY_MASK=0 python3 -I +scripts/expprobe_all.py` and `scripts/fmaxprobe.py` (numpy and `libOpenCL.so.1`; about 20 s each). + +## Kernel contract + +`contract/contract-run-branch.out`, card 1, `tf-xpu-contract-run`: + +```text +SUMMARY bmg-g31 0xe223 21 kernels: 21 pass gates 1-4, 0 fail, 0 known findings; 12 controls: 12 red as planted, 0 missed; 0 limit problems +``` + +`contract/contract-run-main.out` is the same run on main: 21 kernels, 11 controls. The branch adds one control and no +kernel. `attn_decode` and `attn_merge` pass gates 1 to 4 against the bytes of the upstream `1a5644892` pair (`PASS shapes +xpu attn_decode + attn_merge (bf16 cache, tree): 20 shapes bit-equal`). The new planted control, +`tf_ctl_attn_exp_lanes` (the same kernel with the scores in lanes 0 to 7 only, so every `p` is `exp(-inf)`), goes red at +gate 3: `FAIL shapes control: xpu attn_decode whose exponential vector holds the scores in lanes 0 to 7 only`. Gate 5 +(`contract/limits-branch.out`, `xpu-kernel-contract-limits`: `PASS limits: 25 registered XPU launches against bmg-g31, 0 +problems`, `attn_decode`: 16 work-items, SLM 0, 256 GRF, 0 spill bytes, 0 private bytes, record current; the live gate +says the same of the loaded image). The first line of the run log, `Size of SLM (163840) larger than available (131072)`, +is the `160 KiB of SLM` limits control being refused as planted. + +Host checks, no GPU: `zig build test-kernel-contract test-qwen27-config-xpu-host test-qwen27-prompt-tail-xpu-host` +(48 of 48 steps, 288 of 288 tests; the rerun on the final commit, which only changed two +comments, ran the 252 tests that were not cached and passed them all). + +## Limits + +- Code prompts only, at the three depths named. One host, one card for the served numbers, one driver stack. +- Tokens were also compared at the kernel level, serial and drafted (trees of 15 and 3), for code and text at 8,192 and + 30,000 prompt tokens, with `XPU_KV_INT8=1` and on the multi-stream path; those dev-runner runs are not in this receipt. + The served cells above are the receipt. +- The kernel saves 5.5 to 7.5 % of `attn_decode`'s GPU time in a drafted round; what a served request gains is that + kernel's share of its decode time, which grows with the prompt (the served table). + +## Reproduce + +Set `WORK` to a directory holding `bin-main/`, `bin-branch/` (each `xpu/bin/tensorfold-native`), `inputs/` and `scripts/` +(from here), and `MODELS` to the checkpoints' parent: + +```sh +scripts/build_corp_code.sh inputs/corp_code.txt +BINMAIN=... BINPR=... MODEL=... DRAFTER=... OUT=runs scripts/driver.sh +python3 -I scripts/analyse.py runs +``` + +`corp_code` is rebuilt, not stored: the top-level `*.py` files of the `python3.14` standard library at +`/usr/lib/python3.14` (Ubuntu 26.04 `python3.14` 3.14.4-1ubuntu0.2; 157 files), sorted by file name with case and +punctuation ignored, concatenated and cut to 1,500,000 bytes; its SHA-256 must be +`31b2f903b4a2ea01728927e53436d924994c93cf3114c7b7f35e58d906961e30` (`build_corp_code.sh` prints it). `prompt_sha256` in +every line identifies the exact prompt. diff --git a/docs/receipts/xpu-qwen27-attn-exp/analyse.out b/docs/receipts/xpu-qwen27-attn-exp/analyse.out new file mode 100644 index 00000000000..218db2b2777 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/analyse.out @@ -0,0 +1,57 @@ +requests 96, not ok 0, with no token_sha256 0 + +## Tokens: distinct token_sha256 per cell (all four passes, drafted and plain, main and branch) + +| prompt tokens | mode | requests | distinct hashes | token_sha256 (first 16 hex) | prompt_sha256 (first 16) | +|---|---|---|---|---|---| +| 7588 | draft | 16 | 1 | 9764d2d6fb7cbdbf | 829dddadac0f329f | +| 7588 | plain | 16 | 1 | 9764d2d6fb7cbdbf | 829dddadac0f329f | +| 28946 | draft | 16 | 1 | 1d59abb499c48841 | 0bd40816987651da | +| 28946 | plain | 16 | 1 | 1d59abb499c48841 | 0bd40816987651da | +| 121022 | draft | 16 | 1 | 0ac2491477780561 | 60986a50b4990e56 | +| 121022 | plain | 16 | 1 | 0ac2491477780561 | 60986a50b4990e56 | + +CELLS WITH MORE THAN ONE HASH (main against branch, per mode): 0 +prompt tokens 7588: drafted and plain together, main and branch: 1 hash(es) +prompt tokens 28946: drafted and plain together, main and branch: 1 hash(es) +prompt tokens 121022: drafted and plain together, main and branch: 1 hash(es) + +## Decode tok/s: the median of a pass's three measured requests (warm-up request excluded) + +| prompt tokens | mode | main p1 | branch p2 | main p3 | branch p4 | main mean | branch mean | branch / main | p2/p1 | p4/p3 | +|---|---|---|---|---|---|---|---|---|---|---| +| 7588 | drafted | 62.31 | 63.09 | 62.21 | 63.09 | 62.26 | 63.09 | 1.013 | 1.013 | 1.014 | +| 7588 | plain | 32.67 | 32.69 | 32.67 | 32.69 | 32.67 | 32.69 | 1.001 | 1.000 | 1.001 | +| 28946 | drafted | 36.33 | 37.42 | 36.31 | 37.41 | 36.32 | 37.41 | 1.030 | 1.030 | 1.030 | +| 28946 | plain | 28.94 | 28.98 | 28.94 | 28.96 | 28.94 | 28.97 | 1.001 | 1.002 | 1.001 | +| 121022 | drafted | 13.30 | 13.95 | 13.30 | 13.96 | 13.30 | 13.96 | 1.049 | 1.049 | 1.049 | +| 121022 | plain | 19.50 | 19.52 | 19.50 | 19.53 | 19.50 | 19.52 | 1.001 | 1.001 | 1.002 | + +## Every measured request (tok/s) + +| prompt tokens | mode | pass | side | reps 1-3 tok/s | +|---|---|---|---|---| +| 7588 | draft | 1 | main | 62.34, 62.31, 62.30 | +| 7588 | draft | 2 | branch | 63.11, 63.09, 63.08 | +| 7588 | draft | 3 | main | 62.23, 62.21, 62.21 | +| 7588 | draft | 4 | branch | 63.13, 63.09, 63.08 | +| 7588 | plain | 1 | main | 32.67, 32.67, 32.67 | +| 7588 | plain | 2 | branch | 32.69, 32.68, 32.69 | +| 7588 | plain | 3 | main | 32.68, 32.67, 32.67 | +| 7588 | plain | 4 | branch | 32.69, 32.69, 32.69 | +| 28946 | draft | 1 | main | 36.33, 36.33, 36.31 | +| 28946 | draft | 2 | branch | 37.42, 37.40, 37.42 | +| 28946 | draft | 3 | main | 36.30, 36.32, 36.31 | +| 28946 | draft | 4 | branch | 37.41, 37.40, 37.41 | +| 28946 | plain | 1 | main | 28.94, 28.94, 28.94 | +| 28946 | plain | 2 | branch | 28.98, 28.98, 28.98 | +| 28946 | plain | 3 | main | 28.94, 28.94, 28.94 | +| 28946 | plain | 4 | branch | 28.95, 28.96, 28.96 | +| 121022 | draft | 1 | main | 13.30, 13.30, 13.31 | +| 121022 | draft | 2 | branch | 13.95, 13.96, 13.95 | +| 121022 | draft | 3 | main | 13.30, 13.30, 13.30 | +| 121022 | draft | 4 | branch | 13.96, 13.96, 13.96 | +| 121022 | plain | 1 | main | 19.50, 19.50, 19.50 | +| 121022 | plain | 2 | branch | 19.52, 19.52, 19.51 | +| 121022 | plain | 3 | main | 19.50, 19.49, 19.50 | +| 121022 | plain | 4 | branch | 19.53, 19.52, 19.53 | diff --git a/docs/receipts/xpu-qwen27-attn-exp/binaries.sha256 b/docs/receipts/xpu-qwen27-attn-exp/binaries.sha256 new file mode 100644 index 00000000000..7735934bd7e --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/binaries.sha256 @@ -0,0 +1,2 @@ +bd78137b649c987d4d2848f212790e46457e0fb18cdf0e08795432f6bf074d12 .../bin-main/xpu/bin/tensorfold-native +90349ad00c0015c2ba7dd4dcdb80dc813a06b71c4f4bf0811f237c40023889fd .../bin-branch/xpu/bin/tensorfold-native diff --git a/docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-branch.out b/docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-branch.out new file mode 100644 index 0000000000000000000000000000000000000000..0a5babb190e882d1f75ec805640ca24fde0a973a GIT binary patch literal 18676 zcmds9$#UCB5}mWYqHZI_h-z#EA^GH9JmF~D?XboXJ(p1wi6Vs%2(STAq`+E_^(Kv{LOo`=eE~M{2B-1pClc~7O z9u+=Lrpgydyto$Qndx5LiN0xB^ja@}Pe#753}@hp{6Rd=X7el+Q<;q(F~1VyFqWC? zh*2ohRHb_6M9q}U_MUbeJS&mRqf`uEGSv%w6=lIlhFFndIR-yXudYQ9@#G}cWG)jw z74s;I=c7mEUqfsWKdU5^Gc7~yHjL+(@^TR;X(o)DTgN1g z(CYaUNM;D-PcU1e#`6@LI(*@epHvd5FqdaO-CvqqhyYuyC&z9+k$Q|btSgbyXp49r z`eGWSslX@8YcU*~E(CO!;!+CJ?G1xWXqAa^9ER~CWwG!wEg<~^n+Tz0D$?{nJ@W_a zPDnilzVY`|C<3Gi@C`9mi(;gCI7_t@_zG<~Ag~CciI!J(TR34gU0X3H_4p;;(LilA#-fUdoP+kXFca75fTPu&b(oE`53@NE{Q z1Bwm9=!W7?KfD!M$6L)wvrxW*alprPFkOk6`=RuZhf*|4@Zj z{QF9DW!lENld_Het?}(nYWJMYI!37Hc?XA9yCvwL)?3T%=8{&8)oxj~n<>|HoPEM7 z^RHs2(nT-{=i0-{Q5HPQEQq5r3vkv^>J1Fr{dSb@n64S3w&Nk5rJUf9=zqubUGQn! z-SD|;c6JD|pP8u-g4B(}sbi1IEASy`EDKFe^9e221M3 z+vY_JImG%z?|n4B)}O`;g%1PBy%aGx5RnD>))>pdSpP!`sv?-Oe2h|tYB0)@30&AO zNQtdMwu}GMJo&QgM8@Wtn~%WZ2LKGu`W6q0uwN}`K;QuesVghzZ24I(1`QuPd zh+n|q1p3w4c(^x00cPcw2~(p`NgCScr@z+Z698uZa0PUL0|OCI0|(;6{So^Ewju{x z8cZU9{ZEy|U`jxx`h$jp8Uv;t-~U zVKi0XIK?ng@`>Pq1FqG-NMiiDkS{PUppKT79inOpf4I^+;ZF&hlpr8Z7#tJW3|M$WO>xqw4i-v)e9;G zUs)3e;N?e5wyNn6Z?F-76Co)}j+u!%I#i90Li-~&1?1@}Ly&(^Jt-ZbX1MjjnOTHM zj7B)pF;kh)bu1zresUNv7zlHr6NJC&W)#BZYH`ynCW0!+G&5B@!@HK#e3p-sMDLpa zwm3c~b_%=X*mAhnz>&?Y2N{OI!+fM35Ww7tjZ6bk%{NsVwv64Zn8Qr$mZ>_#qn%xI zmEvxhczXnD?TS9V8;(8~v92ZLWfiUp(8=+GM2)f#C5-$FG!0@@eIPSMWut)N!$_h) zz|?;jr<;*tHgis>@Qtxgr|^xb&ZY2;iS;38dKM=BNjMY;kt3i2o+jsOMInk1qw$i% z9xe^x0a>NxI{!}4O41XY$zssc>829=TuP~CeEr9-*#9FMTBk(H>6BW{aW17+GoJ8> zRo;(IbyWv0kKL>)`0+y+ z@3knA*6}?~CoghcQ_#RVZ^ZqZd8701@q#@Hv+)y7;Mbk*nHYQ%zRrko! zbO(chWo|oK+Pfb4OjU!PR6!I%bv#ArJR%;Mn2xRuV&pT58BeGZ?(N93h|1rwuf#v# z#qgWv+%DN8jwD!RuqTO9pm0qS^dX3zmCnFh*Z9VKz4QDnDn3dbo0q@uW>`i+x}d?X z$J{UF%A{}I@dqLaTpl;5r3cXR)q(B2U+dVht-*l1^13C9Lf^mI7yTDoojT9ml)1G#Qlgc@9_u78gO!rXES?6V9&VDbyr7{eNrt=*MLW3hQOe6Mnzmevi@O~_ z7N@o7RVr4{QH4<33Vg9tWhIGyw+wn=w^W=V|uSkv_4%P&6*p~t9N38(^tt2@b4 z4_C8ri%05T*x{qduLDYIZFxZ}L*na$-!v4oUXDa}pr}1%IuEm82C@=5hLh;&rZ6I$ zI}L8ShWIu3kw(Ggv#u}W;#N&G3Vz}2#6Q2h>o`!g03hH9qj=5p*E9~Lq2Vl7>7Dre z(|hV3F_y}*;N?B>%U9Cd@2W@fD?P{_sdobpBYbu(?%#j>8PWc=fYAB3(hKgg%F)2% z^C3Yi*F%0<05r0heuBvp;l~JwNuzudkUt5g5v`pSE@r5GDZ~M-_yCkU!=q|KdJfweg5Nxt&AjwwP!d1Mj#nc#VERYhdx+ z#N4Q~rWVeZgwz8)Ow4uV29;iLg6CL)+ z-6<5um9I%EZuU7;AmezOwAndymyt(5f|coKYsUS~gp%g5IWJ zs6L1Ugd_ZN|(nJ=hJ5E&gDJub=uKS;@OP2nR>10HHw=Tp{Ua+ zrz$oJ8lW}6YlTS2&I#7`161Mxz4MVTL;B+jukcW9fkr#S`h74`r*f*~ovy1?i88na zfQA0n1r-Iu7hEVCh4E-TlSgrQj4BxZ%nbNa^~^=mk}s=`Muo+af~Y;$*H`qL`p@S4 zx8NH7cX9vq$2ji%}Z1xVo0F`0$czTsZHg-=j$F^ zJOC2rVb%IY7D!C@Oy6JkNF_;}+=^-J&qF01=0WJ+io4)XCE~HT`|wd*ny&3R#+3+V zGEs@h9%UrtvkXG{fHy8p+cXB&)y3Z~KEJ)Y6Hy$EgDA+9SkC4``u=?~O`|xOip%U# z;p1ege38V9YcZag?$xd6o0dhd_44;*^OK3@3W57w=a zdJTNz@2OCvkRrf0#8@qgmFD3r)m-2!bmUNhMG#FiPZN@*aV-{)L9QXZ0elst0)Gyv zCUl&5Ar%m(z|M&ItG#r#TmurCg>s}wb!`i(Yj5anzdsxtQE!_`H>)pf$2)=gHnY+} ziw(o*rp2Frcq_Dwx4M&NrhEnGfR9N+idWbn>wCQMoqSX)>1IJ6-A}dh(cj-!b(S(m z4)!i)gg$E@^3CdebicI^JEzp@M&Gp$WBd89iOiILU!_<4 z`$~3Y+Qxd2vW@=G`1T;Rn`X0&k?MKg!Ku}54myZ+Xt~`&(yFuC&C7N-<(iJOPg-UE zRoqm%2qxiNM_4(^f@hfpaa2|T&bpR*1H*Q|T}yY6YgSR)@sQ6_O>ju|zk_@i{j}|F z`nl?Mb}+J^o2f5?(v8!pX33d$|44${pw%q4zT+HKXd9%vh-`R}OKCmr?cT&3IEL5Y zPHHup0cXPXGc;V6XjDxtqOv-oy30aUR@R!&GMuB{q3Rd)7+$LvX;g>d@dUNijC2$g zc~!Sjts19FP~~_WTVfd78ugj9jROTC)1*0d_ zU-S}ILkvVE4=~~}4*its$xrf=7{${WR{&!frq~0sKn$i&!EC1dH~c!SL=R~xMmSJy z^QMJ-!2U$6 z_yQIurC+7S%e@f_YF2)kbZQhTNlW|u^w%1H0*aYGTv0lx11lm_4H$@z@JHwm(288y z(qIxn+5c2Y45S25N{;i?RHo@Xn)Rk{9iEakQ8k@2=}!{_Ta@VC+xH&|u10Z`C2 z!fG^Cz&OQ2qT~~)2Mk<`f04xabs=BiTmT&{EyuHgA6dpN+pl33&MtgRN@%fH&9)Aczo`CC1D^9T`<)pwRJ%T>(Y9$`RxrR8Pu4s1a_xaYh#5 z5~C4JI%X&nvW`Ur!+fOfk-*%FjY)Vffp3sHm%uj&Ya?fP7B2otIFtxcAfN`G2Ip%{A<7V=@siUX zZVll9d8Oq#{!Xfuq$jY+V$svdregeDLa8Xee)B8N|A>y(DK+JELak_=OQ;pa6Pj2R z{m2?m7XI|&r;|=SjB8rwlF}ySZYD_Hu@=eM|FwnlcH3U}YIkqtiaYR|w6_?j;78T<7A&B={ zmPq^f9@fd5T$hy9Ia_f7h?rYsRo9AR%W7lo6Uu6XRtH)2yAE*FONkA_>$2*eS(@%( zFtE&Rrlq6nk!`A4^rQl!6sn^YVe*J@WI{T+4v10AC@7v#Bs|-ZWf8T%V_%7XAd2BP zjk#TNL>x(=%0N#Nr2yfYCg4K=Ju8!eL)ZAmdc8CK77-t%kImcP_b@D@09`O(*JJFL zYGsnQp7;Zh1T2pS)Y1cB`O08BpVzwX*w$dcQ+eHrMGBN#G1{CV8q`GpMe7Yf077c1 zDS=^7V4z_zQaMUXJ@zHqr##U}4PBrN<1vu+aS~6(e3nAbde*w6s2M5eOhV zeuZMBFg9_`4vg)9YV&!}5~p34K`7@Djh<2iibRh-hPdQCqjm5IBo{vbkEB=V$_1F@ zMV<)fc$$N-hpyLn7NwPU<+%BP)}X!eXmSU_Si}Q2BMFtJ!+;Ozrx; zHpLD&3YqREpWEo<+-f?zS*7zNOn#9BSrJzmrZ}AAEpfAj+77vPOtBkW3R%%B4%1;U1$VdTeM7}3 zL5cg7swkB3Gqrt>fhW&qqEV?>Fb9&94e zwA13IYlvTiA88d_pz8WEE+5rcqXZ7oPWePc+up%5DF5n>9yg=Vo$*aJ z9v;&nl9gBYtLkKHx7pwlFf~)D5H#eEIa-*w6ILBOQcoU9(DfMzO=IXgF1=l2=FJ*d ze7`RD?x^l&K^PX!o@{|eWO0^MxZni`GeeX46va<|->rc&s;>D`-9g;hu6I1{su^iG z1SsakY)RNR?7BWvxdRU1q=BTpC?Z1z+I zL`%uY8F^}TRjXYe-Jv@pZynU@?7Z#NueGk<>pV7YL7b7b9j8_`DbC1Ks|C~md?bX2 zBsQHKtJxZ^D~RfxJb7*2tAyHL<$ys)qCx^zP+H|)PFVQzeSn;zl*!CA3whR^6%osyxbRP zLg>nua3GTqXw1OV?HpnD(CNpm0#xGk^C_bHL_lTv4|Kdi-?spL@Fsqty;XM_=nc9@ dMmM+&4HA{WkuK^%z_5n4AYdx5lJQD<@qcfn3Eltz literal 0 HcmV?d00001 diff --git a/docs/receipts/xpu-qwen27-attn-exp/contract/limits-branch.out b/docs/receipts/xpu-qwen27-attn-exp/contract/limits-branch.out new file mode 100644 index 00000000000..6841b6dc5f4 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/contract/limits-branch.out @@ -0,0 +1,70 @@ +PASS limits bmg-g31 add_rmsnorm: 128 work-items, 10272 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD add_rmsnorm: .usage = .{ .{ .threads = .{ 128, 1, 1 }, .slm = 10272, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 add_rmsnorm_dec: 512 work-items, 10368 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD add_rmsnorm_dec: .usage = .{ .{ .threads = .{ 512, 1, 1 }, .slm = 10368, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 gated_norm: 256 work-items, 12288 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD gated_norm: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 12288, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 swiglu: 256 work-items, 2048 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD swiglu: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 2048, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 argmax: 256 work-items, 2048 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD argmax: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 2048, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 topk_part: 256 work-items, 192 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD topk_part: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 192, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 topk_merge: 256 work-items, 192 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD topk_merge: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 192, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 embed: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD embed: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp2_allreduce_f16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp2_allreduce_f16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp4_allreduce_f16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp4_allreduce_f16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp2_rs_f16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp2_rs_f16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp4_rs_f16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp4_rs_f16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp2_allreduce_bf16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp2_allreduce_bf16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp4_allreduce_bf16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp4_allreduce_bf16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp2_allreduce_f32: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp2_allreduce_f32: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp4_allreduce_f32: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp4_allreduce_f32: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 tp4_rs_f32: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD tp4_rs_f32: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 attn_decode: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD attn_decode: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 attn_merge: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD attn_merge: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 upstream attn_decode: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD upstream attn_decode: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 upstream attn_merge: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD upstream attn_merge: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 planted attn_merge dropping last slice: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD planted attn_merge dropping last slice: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 planted attn_decode with its exponential vector half filled: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD planted attn_decode with its exponential vector half filled: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 upstream standalone attn_merge: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD upstream standalone attn_merge: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +PASS limits bmg-g31 planted attn_merge weighing past its last slice: 16 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current) +RECORD planted attn_merge weighing past its last slice: .usage = .{ .{ .threads = .{ 16, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +RED limits bmg-g31 control: 2048 work-items a work-group: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current): control: 2048 work-items a work-group on bmg-g31: 2048 work-items a work-group, the most is 1024 +control: 2048 work-items a work-group on bmg-g31: a work-group dimension of 2048, the most is 1024 +control: 2048 work-items a work-group on bmg-g31: 2048 work-items at 256 GRF and sub-group 16, a Xe-core holds 512 +RECORD control: 2048 work-items a work-group: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +RED limits bmg-g31 control: 200 work-items, not a multiple of sub-group 16: 256 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current): control: 200 work-items, not a multiple of sub-group 16 on bmg-g31: 200 work-items are not a multiple of sub-group 16 +RECORD control: 200 work-items, not a multiple of sub-group 16: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +RED limits bmg-g31 control: 160 KiB of SLM: 256 work-items, 163840 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current): control: 160 KiB of SLM on bmg-g31: 163840 SLM bytes a work-group, the most is 131072 +RECORD control: 160 KiB of SLM: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 163840, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +RED limits bmg-g31 control: 1024 work-items at 256 GRF: 1024 work-items, 0 SLM bytes, sub-group 16, 256 GRF, 0 spill bytes, 0 private bytes (record current): control: 1024 work-items at 256 GRF on bmg-g31: 1024 work-items at 256 GRF and sub-group 16, a Xe-core holds 512 +RECORD control: 1024 work-items at 256 GRF: .usage = .{ .{ .threads = .{ 1024, 1, 1 }, .slm = 0, .sub_group = 16, .grf = 256, .spill = 0, .private = 0 }, } +RED limits bmg-g31 control: sub-group 32 at 256 GRF: 256 work-items, 0 SLM bytes, sub-group 32, 256 GRF, 0 spill bytes, 0 private bytes (record current): control: sub-group 32 at 256 GRF on bmg-g31: sub-group 32 at 256 GRF (the most is 16) +RECORD control: sub-group 32 at 256 GRF: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 32, .grf = 256, .spill = 0, .private = 0 }, } +RED limits bmg-g31 control: sub-group 8: declared only, ocloc does not build it for this device: control: sub-group 8 on bmg-g31: sub-group 8, the device runs { 16, 32 } +RECORD control: sub-group 8: .usage = .{ .{ .threads = .{ 256, 1, 1 }, .slm = 0, .sub_group = 8, .grf = 256, .spill = 0, .private = 0 }, } +PASS xpu-kernel-contract-limits: every registered launch fits bmg-g31, every record current, every control red + +real 0m15,613s +user 0m25,099s +sys 0m1,462s +rc=0 diff --git a/docs/receipts/xpu-qwen27-attn-exp/kernel/summarize.py b/docs/receipts/xpu-qwen27-attn-exp/kernel/summarize.py new file mode 100644 index 00000000000..cb063f78ad7 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/kernel/summarize.py @@ -0,0 +1,16 @@ +import re,sys,glob,os +# usage: ysum.py logs... : serial attn_decode ms/token and drafted attn_decode ms/round, merge, eq_serial +for f in sys.argv[1:]: + s=open(f,errors="ignore").read() + m=re.search(r"drafted: \d+ tokens in (\d+) rounds.*equal to serial: (\w+)",s) + d=re.search(r"^decode: (\d+) tokens",s,re.M) + if not m or not d: print(os.path.basename(f),"no result"); continue + rounds=int(m.group(1)); nd=int(d.group(1)) + def sec(label): + i=s.index("GPU time, "+label) + j=s.find("GPU time,",i+5) + return s[i:j if j>0 else len(s)] + def ms(t,k): + r=re.search(k+r"\s+([\d.]+) ms",t); return float(r.group(1)) if r else float("nan") + sd=sec("decode"); dr=sec("drafted rounds") + print("%-34s serial attn_decode %7.3f ms/tok | drafted %7.2f ms/round merge %6.2f | rounds %3d eq %s" % (os.path.basename(f), ms(sd,"attn_decode")/nd, ms(dr,"attn_decode")/rounds, ms(dr,"attn_merge")/rounds, rounds, m.group(2))) diff --git a/docs/receipts/xpu-qwen27-attn-exp/kernel/summary.out b/docs/receipts/xpu-qwen27-attn-exp/kernel/summary.out new file mode 100644 index 00000000000..1922f0b1bee --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/kernel/summary.out @@ -0,0 +1,8 @@ +main-20000-tree3.log serial attn_decode 2.931 ms/tok | drafted 8.06 ms/round merge 2.42 | rounds 14 eq true +branch-20000-tree3.log serial attn_decode 2.859 ms/tok | drafted 7.60 ms/round merge 2.42 | rounds 14 eq true +main-20000-tree15.log serial attn_decode 2.932 ms/tok | drafted 33.51 ms/round merge 7.93 | rounds 10 eq true +branch-20000-tree15.log serial attn_decode 2.861 ms/tok | drafted 30.99 ms/round merge 7.88 | rounds 10 eq true +main-58543-tree3.log serial attn_decode 8.791 ms/tok | drafted 23.12 ms/round merge 6.21 | rounds 21 eq true +branch-58543-tree3.log serial attn_decode 8.723 ms/tok | drafted 21.72 ms/round merge 6.19 | rounds 21 eq true +main-58543-tree15.log serial attn_decode 8.796 ms/tok | drafted 95.69 ms/round merge 21.74 | rounds 19 eq true +branch-58543-tree15.log serial attn_decode 8.722 ms/tok | drafted 90.43 ms/round merge 21.74 | rounds 19 eq true diff --git a/docs/receipts/xpu-qwen27-attn-exp/proofs/expprobe_all.out b/docs/receipts/xpu-qwen27-attn-exp/proofs/expprobe_all.out new file mode 100644 index 00000000000..157985f056a --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/proofs/expprobe_all.out @@ -0,0 +1,4 @@ +exp(+0) vector 3f800000 scalar 3f800000 (1.0 = 3f800000) +exp(-0) vector 3f800000 scalar 3f800000 +checked 4294967296 values, mismatches 0 in 18.6 s +rc 0 diff --git a/docs/receipts/xpu-qwen27-attn-exp/proofs/fmaxprobe.out b/docs/receipts/xpu-qwen27-attn-exp/proofs/fmaxprobe.out new file mode 100644 index 00000000000..96e7b651113 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/proofs/fmaxprobe.out @@ -0,0 +1,2 @@ +fmax: checked 536870912 pairs (all special-value pairs, nearby and random patterns), mismatches 0 +rc 0 diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs/p1-main.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs/p1-main.jsonl new file mode 100644 index 00000000000..667863cc2a0 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs/p1-main.jsonl @@ -0,0 +1,24 @@ +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.003129482269287, "decode_tok_s": 59.136692413621965, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.992744207382202, "decode_tok_s": 62.3415567490174, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9982972145080566, "decode_tok_s": 62.30853618147494, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.000979900360107, "decode_tok_s": 62.29691540000444, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.997554063796997, "decode_tok_s": 32.6756742017996, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.001293182373047, "decode_tok_s": 32.6747957457748, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.000255584716797, "decode_tok_s": 32.668028227098894, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.999317169189453, "decode_tok_s": 32.669214660559035, "label": "p1-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.029279470443726, "decode_tok_s": 35.655104347302554, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.0330491065979, "decode_tok_s": 36.33374769064196, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.05267357826233, "decode_tok_s": 36.32607320776154, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.062016248703003, "decode_tok_s": 36.306202993066485, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.050702333450317, "decode_tok_s": 28.93898015664235, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.04752254486084, "decode_tok_s": 28.936545988639523, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.04220962524414, "decode_tok_s": 28.93590560977757, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.039936780929565, "decode_tok_s": 28.941208769843836, "label": "p1-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.54420876502991, "decode_tok_s": 13.23290497537224, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.39319157600403, "decode_tok_s": 13.30492835567759, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.48191833496094, "decode_tok_s": 13.303087639434604, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.49677872657776, "decode_tok_s": 13.306556017440007, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.48573517799377, "decode_tok_s": 19.500743347342127, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.55101656913757, "decode_tok_s": 19.495572158956936, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5536196231842, "decode_tok_s": 19.497108513131252, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.49289560317993, "decode_tok_s": 19.497141211710897, "label": "p1-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs/p2-branch.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs/p2-branch.jsonl new file mode 100644 index 00000000000..0ce8b6846be --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs/p2-branch.jsonl @@ -0,0 +1,24 @@ +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.012376546859741, "decode_tok_s": 59.80481180605806, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.01097559928894, "decode_tok_s": 63.110004258482135, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.009952783584595, "decode_tok_s": 63.092488239481014, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.011241912841797, "decode_tok_s": 63.08324831677838, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.019011497497559, "decode_tok_s": 32.68308705681663, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.009963750839233, "decode_tok_s": 32.68780471733594, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.01649022102356, "decode_tok_s": 32.68275748078747, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.008352518081665, "decode_tok_s": 32.68547218690749, "label": "p2-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.06614375114441, "decode_tok_s": 36.73565943246185, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.061936140060425, "decode_tok_s": 37.41608150445216, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.079582929611206, "decode_tok_s": 37.40041624341732, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.076348304748535, "decode_tok_s": 37.415629928949144, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.064850330352783, "decode_tok_s": 28.981172125366843, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.065658569335938, "decode_tok_s": 28.980181119303868, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.048384428024292, "decode_tok_s": 28.983031818865808, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.05044412612915, "decode_tok_s": 28.98131033761984, "label": "p2-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.57329988479614, "decode_tok_s": 13.864582196772211, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.48653602600098, "decode_tok_s": 13.954004218136106, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.48857975006104, "decode_tok_s": 13.956645941718175, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.55881643295288, "decode_tok_s": 13.953952151199378, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5343074798584, "decode_tok_s": 19.524034853645613, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.49271202087402, "decode_tok_s": 19.521350096819404, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5300645828247, "decode_tok_s": 19.524923402081072, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.50815439224243, "decode_tok_s": 19.514392908483643, "label": "p2-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs/p3-main.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs/p3-main.jsonl new file mode 100644 index 00000000000..55103176a66 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs/p3-main.jsonl @@ -0,0 +1,24 @@ +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.01093316078186, "decode_tok_s": 59.04545055556568, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.0089733600616455, "decode_tok_s": 62.22617742172708, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.010528087615967, "decode_tok_s": 62.21463438412546, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.0215373039245605, "decode_tok_s": 62.20940541152994, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.013369798660278, "decode_tok_s": 32.674864623006556, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.011291027069092, "decode_tok_s": 32.67728349603474, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.01171350479126, "decode_tok_s": 32.672855323967894, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.010499715805054, "decode_tok_s": 32.6679414182779, "label": "p3-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.05134344100952, "decode_tok_s": 35.655222021153556, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.069698095321655, "decode_tok_s": 36.29714321086247, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.069788694381714, "decode_tok_s": 36.316176074866064, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.07242178916931, "decode_tok_s": 36.311734972982315, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.068844079971313, "decode_tok_s": 28.94008502351795, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.042952299118042, "decode_tok_s": 28.9397577047633, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.04263925552368, "decode_tok_s": 28.940547041059983, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.04600477218628, "decode_tok_s": 28.942865965467703, "label": "p3-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.48043751716614, "decode_tok_s": 13.231275475027148, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.54954123497009, "decode_tok_s": 13.30357230259853, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.4977490901947, "decode_tok_s": 13.304267836909238, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.53417873382568, "decode_tok_s": 13.304506979828863, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.54346752166748, "decode_tok_s": 19.501320424148275, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.53732228279114, "decode_tok_s": 19.497561327132285, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5494282245636, "decode_tok_s": 19.49491760277302, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.51863813400269, "decode_tok_s": 19.498995969383834, "label": "p3-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs/p4-branch.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs/p4-branch.jsonl new file mode 100644 index 00000000000..df8542cd524 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs/p4-branch.jsonl @@ -0,0 +1,24 @@ +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.011505126953125, "decode_tok_s": 59.78864103186752, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.0083231925964355, "decode_tok_s": 63.132489640563364, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.009398937225342, "decode_tok_s": 63.09435664784991, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.0181496143341064, "decode_tok_s": 63.07760075616628, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.010854721069336, "decode_tok_s": 32.685856756800035, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.0075318813323975, "decode_tok_s": 32.689415206690924, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.009256601333618, "decode_tok_s": 32.69013458323199, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.010522365570068, "decode_tok_s": 32.68857697313558, "label": "p4-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.0620436668396, "decode_tok_s": 36.751358605919854, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.067583560943604, "decode_tok_s": 37.41133069076612, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.067113161087036, "decode_tok_s": 37.398763213686266, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.06892728805542, "decode_tok_s": 37.406968334021165, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.07318663597107, "decode_tok_s": 28.957873161865937, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.050286531448364, "decode_tok_s": 28.952158703728546, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.040491342544556, "decode_tok_s": 28.956930787265385, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.04018497467041, "decode_tok_s": 28.95623776555169, "label": "p4-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.57827401161194, "decode_tok_s": 13.870805702379196, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.54896998405457, "decode_tok_s": 13.95921378570801, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.4707043170929, "decode_tok_s": 13.961953897444312, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.58082890510559, "decode_tok_s": 13.963448957303745, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5491886138916, "decode_tok_s": 19.52813076163812, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5001449584961, "decode_tok_s": 19.526939954999662, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.51724314689636, "decode_tok_s": 19.524968669248583, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.5212471485138, "decode_tok_s": 19.532244796764473, "label": "p4-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/analyse.py b/docs/receipts/xpu-qwen27-attn-exp/scripts/analyse.py new file mode 100644 index 00000000000..1692e17344c --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/analyse.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Served table from the pass files. usage: analyse.py RUNS_DIR (files p-main.jsonl and p-branch.jsonl)""" +import collections, glob, json, os, statistics as st, sys + +R = [] +for f in sorted(glob.glob(os.path.join(sys.argv[1], "p*.jsonl"))): + p, side = os.path.basename(f)[:-6].split("-", 1) + for l in open(f): + r = json.loads(l) + r["pass"], r["side"] = int(p[1:]), side + R.append(r) +DEPTHS = sorted({r["depth"] for r in R}) +ptok = {d: sorted({r["prompt_tokens"] for r in R if r["depth"] == d}) for d in DEPTHS} +failed = sum(not r["ok"] for r in R) +print(f"requests {len(R)}, not ok {failed}, with no token_sha256 {sum(not r['token_sha256'] for r in R)}\n") + +print("## Tokens: distinct token_sha256 per cell (all four passes, drafted and plain, main and branch)\n") +print("| prompt tokens | mode | requests | distinct hashes | token_sha256 (first 16 hex) | prompt_sha256 (first 16) |\n|---|---|---|---|---|---|") +bad = 0 +for d in DEPTHS: + for mode in ("draft", "plain"): + rs = [r for r in R if r["depth"] == d and r["mode"] == mode] + sh = {r["token_sha256"] for r in rs} + ps = {r["prompt_sha256"] for r in rs} + bad += len(sh) != 1 + print(f"| {ptok[d][0]} | {mode} | {len(rs)} | {len(sh)} | {', '.join(sorted(x[:16] for x in sh))} | {', '.join(sorted(x[:16] for x in ps))} |") +print(f"\nCELLS WITH MORE THAN ONE HASH (main against branch, per mode): {bad}") +for d in DEPTHS: + sh = {r["token_sha256"] for r in R if r["depth"] == d} + print(f"prompt tokens {ptok[d][0]}: drafted and plain together, main and branch: {len(sh)} hash(es)") + +print("\n## Decode tok/s: the median of a pass's three measured requests (warm-up request excluded)\n") +per = collections.defaultdict(list) +for r in R: + if not r["warmup"]: + per[(r["depth"], r["mode"], r["pass"], r["side"])].append(r["decode_tok_s"]) +print("| prompt tokens | mode | main p1 | branch p2 | main p3 | branch p4 | main mean | branch mean | branch / main | p2/p1 | p4/p3 |\n|---|---|---|---|---|---|---|---|---|---|---|") +for d in DEPTHS: + for mode in ("draft", "plain"): + m = {p: st.median(per[(d, mode, p, "main" if p % 2 else "branch")]) for p in (1, 2, 3, 4)} + mm, bm = (m[1] + m[3]) / 2, (m[2] + m[4]) / 2 + print(f"| {ptok[d][0]} | {'drafted' if mode == 'draft' else 'plain'} | {m[1]:.2f} | {m[2]:.2f} | {m[3]:.2f} | {m[4]:.2f} | " + f"{mm:.2f} | {bm:.2f} | {bm / mm:.3f} | {m[2] / m[1]:.3f} | {m[4] / m[3]:.3f} |") + +print("\n## Every measured request (tok/s)\n") +print("| prompt tokens | mode | pass | side | reps 1-3 tok/s |\n|---|---|---|---|---|") +for d in DEPTHS: + for mode in ("draft", "plain"): + for p in (1, 2, 3, 4): + s = "main" if p % 2 else "branch" + print(f"| {ptok[d][0]} | {mode} | {p} | {s} | {', '.join('%.2f' % x for x in per[(d, mode, p, s)])} |") diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/bench_tree.py b/docs/receipts/xpu-qwen27-attn-exp/scripts/bench_tree.py new file mode 100755 index 00000000000..73d532c41b6 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/bench_tree.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Served decode by prompt depth, one JSON line per request. usage: bench_tree.py URL LABEL OUTDIR [reps] + +Per (depth, mode) cell: 1 warm-up request and `reps` measured ones. Modes: draft (greedy, the default), plain +("draft": false) and sampled (temperature 1.0, top_k 20, top_p 0.95, fixed seed). A request without a +tensorfold.token_sha256 is a failure. The prompts are the first lines of inputs/corp_code.txt (build_corp_code.sh). +Env: CELLS="0:code;32768:code;65536:code;131072:code" (depth:kind), MODES="draft,plain", CORP=inputs/corp_code.txt. +""" +import hashlib, json, os, sys, time, urllib.request + +URL, LABEL, OUT = sys.argv[1], sys.argv[2], sys.argv[3] +REPS = int(sys.argv[4]) if len(sys.argv) > 4 else 3 +CELLS = [(int(c.split(":")[0]), c.split(":")[1]) for c in + os.environ.get("CELLS", "0:code;32768:code;65536:code;131072:code").split(";")] +H = os.path.dirname(os.path.abspath(__file__)) +os.makedirs(OUT, exist_ok=True) +CORP = open(os.environ.get("CORP", f"{H}/../inputs/corp_code.txt"), errors="ignore").read() +ASK = "Review the code above in detail, then write one new, complete Python function in the same style." +SHORT = ("Write a complete Python function that parses a CSV file and prints the average of each numeric column, " + "with comments.") +SEED = 7 + + +def post(content, mode): + body = {"model": "m", "messages": [{"role": "user", "content": content}], "max_tokens": 256, "temperature": 0, + "stream": True, "stream_options": {"include_usage": True}, "chat_template_kwargs": {"enable_thinking": False}} + if mode == "plain": + body["draft"] = False + if mode == "sampled": + body.update(temperature=1.0, top_k=20, top_p=0.95, seed=SEED) + req = urllib.request.Request(URL + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + t0, first, text, usage, tsha, spec = time.time(), None, [], None, None, None + with urllib.request.urlopen(req, timeout=3600) as r: + for line in r: + line = line.decode().strip() + if not line.startswith("data: {"): + continue + d = json.loads(line[6:]) + if d.get("usage"): + usage = d["usage"] + tf = d.get("tensorfold") or (d.get("usage") or {}).get("tensorfold") or {} + if d.get("speculative") is not None: + spec = d["speculative"] + elif (d.get("usage") or {}).get("speculative") is not None: + spec = d["usage"]["speculative"] + if tf.get("token_sha256"): + tsha = tf["token_sha256"] + c = (d.get("choices") or [{}])[0].get("delta", {}).get("content") + if c: + first = first or time.time() + text.append(c) + t1, s = time.time(), "".join(text) + n = (usage or {}).get("completion_tokens", 0) + ok = bool(text and usage and tsha) and (mode == "plain" or spec is not None) + return {"ok": ok, "speculative": spec, "token_sha256": tsha, "text_sha256": hashlib.sha256(s.encode()).hexdigest(), + "prompt_tokens": (usage or {}).get("prompt_tokens"), "completion_tokens": n, + "ttft_s": (first or t1) - t0, + "decode_tok_s": (n - 1) / (t1 - first) if first and t1 > first and n > 1 else None} + + +tokens_per_char = [] + + +def prompt(depth): + if depth == 0: + return SHORT + if not tokens_per_char: + r = post(CORP[:20000], "plain") + tokens_per_char.append(20000 / (r["prompt_tokens"] - 15)) + return "Here is the material:\n\n" + CORP[:int((depth - 300) * tokens_per_char[0])] + "\n\n" + ASK + + +failed = 0 +with open(f"{OUT}/{LABEL}.jsonl", "a") as out: + for depth, kind in CELLS: + content = prompt(depth) + psha = hashlib.sha256(content.encode()).hexdigest() + for mode in os.environ.get("MODES", "draft,plain").split(","): + for rep in range(REPS + 1): + r = post(content, mode) + r.update(label=LABEL, depth=depth, kind=kind, mode=mode, rep=rep, warmup=rep == 0, prompt_sha256=psha) + out.write(json.dumps(r) + "\n") + out.flush() + failed += not r["ok"] + print(f"{LABEL} d={depth} {kind} {mode} rep{rep}: pt={r['prompt_tokens']} n={r['completion_tokens']} " + f"{r['decode_tok_s'] or 0:.2f} tok/s tsha={(r['token_sha256'] or 'NONE')[:16]}", flush=True) +print("FINI failed=%d" % failed, flush=True) +sys.exit(1 if failed else 0) diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/build_corp_code.sh b/docs/receipts/xpu-qwen27-attn-exp/scripts/build_corp_code.sh new file mode 100755 index 00000000000..290360a87d4 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/build_corp_code.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# Rebuilds inputs/corp_code.txt: the top-level *.py of the Ubuntu 26.04 python3.14 standard library (3.14.4-1ubuntu0.2), +# concatenated without separator in the order of a punctuation- and case-blind sort of the file names, cut to 1,500,000 +# bytes. usage: build_corp_code.sh OUTFILE expects sha256 31b2f903b4a2ea01728927e53436d924994c93cf3114c7b7f35e58d906961e30 +set -e +python3 -I - "$1" <<"PY" +import hashlib, os, re, sys +root = "/usr/lib/python3.14" +names = sorted((f for f in os.listdir(root) if f.endswith(".py")), key=lambda f: (re.sub("[^a-z0-9]", "", f.lower()), f)) +data = b"".join(open(os.path.join(root, f), "rb").read() for f in names)[:1500000] +open(sys.argv[1], "wb").write(data) +print(hashlib.sha256(data).hexdigest(), len(data), "bytes from", len(names), "files") +PY diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/driver.sh b/docs/receipts/xpu-qwen27-attn-exp/scripts/driver.sh new file mode 100755 index 00000000000..32390a07fb4 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/driver.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# The table's order of passes: main, branch, main, branch, each a fresh server on card 0. +# usage: BINMAIN=... BINPR=... MODEL=... DRAFTER=... OUT=... driver.sh +HERE=$(cd "$(dirname "$0")" && pwd) +export ZE_AFFINITY_MASK=0 PLAIN=1 CELLS_GREEDY="8192:code;32768:code;131072:code" +export MODEL DRAFTER OUT +run() { # label bin + BIN=$2 bash "$HERE/run_pass.sh" "$1" "" || { echo "pass $1 failed"; exit 1; } + sync; echo 3 | sudo -n tee /proc/sys/vm/drop_caches >/dev/null + echo "$(date -Is) pass $1 done" +} +run p1-main "$BINMAIN" +run p2-branch "$BINPR" +run p3-main "$BINMAIN" +run p4-branch "$BINPR" +echo "all passes done" diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/expprobe_all.py b/docs/receipts/xpu-qwen27-attn-exp/scripts/expprobe_all.py new file mode 100644 index 00000000000..642024dcae6 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/expprobe_all.py @@ -0,0 +1,68 @@ +# Exhaustive check that exp() of a 16-lane vector argument and exp() of the same value as a uniform scalar agree bit +# for bit, over all 2^32 float bit patterns (NaNs and infinities included). Uses ctypes against libOpenCL (no headers). +import ctypes as C, numpy as np, sys, time +cl = C.CDLL("libOpenCL.so.1") +SRC = b""" +#pragma OPENCL FP_CONTRACT OFF +__attribute__((intel_reqd_sub_group_size(16))) __attribute__((reqd_work_group_size(16, 1, 1))) +kernel void probe(global const float *X, global float *V, global float *S) { + const int lane = get_sub_group_local_id(), g = get_group_id(0); + const float x = X[g * 16 + lane]; + V[g * 16 + lane] = exp(x); + float s[16]; + for (int k = 0; k < 16; k++) s[k] = exp(sub_group_broadcast(x, k)); + S[g * 16 + lane] = s[lane]; +} +""" +u32, u64, i32 = C.c_uint32, C.c_uint64, C.c_int32 +cl.clGetPlatformIDs.argtypes = [u32, C.POINTER(C.c_void_p), C.POINTER(u32)] +n = u32(0); cl.clGetPlatformIDs(0, None, C.byref(n)) +plats = (C.c_void_p * n.value)(); cl.clGetPlatformIDs(n.value, plats, None) +dev = C.c_void_p() +cl.clGetDeviceIDs.argtypes = [C.c_void_p, u64, u32, C.POINTER(C.c_void_p), C.POINTER(u32)] +cl.clGetDeviceIDs(plats[0], 1 << 2, 1, C.byref(dev), None) # CL_DEVICE_TYPE_GPU, first device (after ZE_AFFINITY_MASK) +err = i32(0) +cl.clCreateContext.restype = C.c_void_p +ctx = cl.clCreateContext(None, 1, C.byref(dev), None, None, C.byref(err)); assert err.value == 0 +cl.clCreateCommandQueueWithProperties.restype = C.c_void_p +q = cl.clCreateCommandQueueWithProperties(C.c_void_p(ctx), dev, None, C.byref(err)); assert err.value == 0 +cl.clCreateProgramWithSource.restype = C.c_void_p +ln = C.c_size_t(len(SRC)); sp = C.c_char_p(SRC) +prog = cl.clCreateProgramWithSource(C.c_void_p(ctx), 1, C.byref(sp), C.byref(ln), C.byref(err)); assert err.value == 0 +r = cl.clBuildProgram(C.c_void_p(prog), 1, C.byref(dev), b"-cl-std=CL3.0 -cl-intel-256-GRF-per-thread", None, None) +if r != 0: sys.exit("build failed %d" % r) +cl.clCreateKernel.restype = C.c_void_p +k = cl.clCreateKernel(C.c_void_p(prog), b"probe", C.byref(err)); assert err.value == 0 +if len(sys.argv) > 1 and sys.argv[1] == "bin": # dump the device binary for disassembly + sz = C.c_size_t(0); cl.clGetProgramInfo(C.c_void_p(prog), 0x1165, C.sizeof(C.c_size_t), C.byref(sz), None) + buf = C.create_string_buffer(sz.value); ptr = C.c_char_p(C.addressof(buf)) + cl.clGetProgramInfo(C.c_void_p(prog), 0x1166, C.sizeof(C.c_void_p), C.byref(ptr), None) + open("expprobe.bin", "wb").write(buf.raw); sys.exit(0) +cl.clCreateBuffer.restype = C.c_void_p +CHUNK = 1 << 26 +def buf(sz): + b = cl.clCreateBuffer(C.c_void_p(ctx), 1, C.c_size_t(sz), None, C.byref(err)); assert err.value == 0; return b +bx, bv, bs = buf(CHUNK * 4), buf(CHUNK * 4), buf(CHUNK * 4) +for i, b in enumerate((bx, bv, bs)): + cl.clSetKernelArg(C.c_void_p(k), i, C.c_size_t(8), C.byref(C.c_void_p(b))) +bad = 0; total = 0 +# every float bit pattern, NaNs and infinities included +starts = list(range(0, 1 << 32, CHUNK)) +t0 = time.time() +for st in starts: + cnt = CHUNK + x = (np.arange(cnt, dtype=np.uint64) + st).astype(np.uint32) + cnt = (len(x) + 15) // 16 * 16 + xp = np.zeros(cnt, np.uint32); xp[:len(x)] = x + cl.clEnqueueWriteBuffer(C.c_void_p(q), C.c_void_p(bx), 1, 0, C.c_size_t(cnt * 4), xp.ctypes.data_as(C.c_void_p), 0, None, None) + gs = C.c_size_t(cnt); ls = C.c_size_t(16) + cl.clEnqueueNDRangeKernel(C.c_void_p(q), C.c_void_p(k), 1, None, C.byref(gs), C.byref(ls), 0, None, None) + v = np.empty(cnt, np.uint32); s = np.empty(cnt, np.uint32) + cl.clEnqueueReadBuffer(C.c_void_p(q), C.c_void_p(bv), 1, 0, C.c_size_t(cnt * 4), v.ctypes.data_as(C.c_void_p), 0, None, None) + cl.clEnqueueReadBuffer(C.c_void_p(q), C.c_void_p(bs), 1, 0, C.c_size_t(cnt * 4), s.ctypes.data_as(C.c_void_p), 0, None, None) + n_ = len(x); d = np.nonzero(v[:n_] != s[:n_])[0] + bad += len(d); total += n_ + if len(d): print("DIFF at", [(hex(int(x[i])), hex(int(v[i])), hex(int(s[i]))) for i in d[:5]]) + if st == 0: print("exp(+0) vector %08x scalar %08x (1.0 = 3f800000)" % (v[0], s[0])) + if st == 0x80000000: print("exp(-0) vector %08x scalar %08x" % (v[0], s[0])) +print("checked", total, "values, mismatches", bad, "in %.1f s" % (time.time() - t0)) diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/fmaxprobe.py b/docs/receipts/xpu-qwen27-attn-exp/scripts/fmaxprobe.py new file mode 100644 index 00000000000..207a4e33b5b --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/fmaxprobe.py @@ -0,0 +1,72 @@ +# fmax() of 16-lane vector arguments against fmax() of the same values as uniform scalars, bit for bit. Uses ctypes against libOpenCL (no headers). +import ctypes as C, numpy as np, sys, time +cl = C.CDLL("libOpenCL.so.1") +SRC = b""" +#pragma OPENCL FP_CONTRACT OFF +__attribute__((intel_reqd_sub_group_size(16))) __attribute__((reqd_work_group_size(16, 1, 1))) +kernel void probe(global const float *X, global float *V, global float *S, global const float *Y) { + const int lane = get_sub_group_local_id(), g = get_group_id(0); + const float x = X[g * 16 + lane], y = Y[g * 16 + lane]; + V[g * 16 + lane] = fmax(x, y); + float s[16]; + for (int k = 0; k < 16; k++) s[k] = fmax(sub_group_broadcast(x, k), sub_group_broadcast(y, k)); + S[g * 16 + lane] = s[lane]; +} +""" +u32, u64, i32 = C.c_uint32, C.c_uint64, C.c_int32 +cl.clGetPlatformIDs.argtypes = [u32, C.POINTER(C.c_void_p), C.POINTER(u32)] +n = u32(0); cl.clGetPlatformIDs(0, None, C.byref(n)) +plats = (C.c_void_p * n.value)(); cl.clGetPlatformIDs(n.value, plats, None) +dev = C.c_void_p() +cl.clGetDeviceIDs.argtypes = [C.c_void_p, u64, u32, C.POINTER(C.c_void_p), C.POINTER(u32)] +cl.clGetDeviceIDs(plats[0], 1 << 2, 1, C.byref(dev), None) # CL_DEVICE_TYPE_GPU, first device (after ZE_AFFINITY_MASK) +err = i32(0) +cl.clCreateContext.restype = C.c_void_p +ctx = cl.clCreateContext(None, 1, C.byref(dev), None, None, C.byref(err)); assert err.value == 0 +cl.clCreateCommandQueueWithProperties.restype = C.c_void_p +q = cl.clCreateCommandQueueWithProperties(C.c_void_p(ctx), dev, None, C.byref(err)); assert err.value == 0 +cl.clCreateProgramWithSource.restype = C.c_void_p +ln = C.c_size_t(len(SRC)); sp = C.c_char_p(SRC) +prog = cl.clCreateProgramWithSource(C.c_void_p(ctx), 1, C.byref(sp), C.byref(ln), C.byref(err)); assert err.value == 0 +r = cl.clBuildProgram(C.c_void_p(prog), 1, C.byref(dev), b"-cl-std=CL3.0 -cl-intel-256-GRF-per-thread", None, None) +if r != 0: sys.exit("build failed %d" % r) +cl.clCreateKernel.restype = C.c_void_p +k = cl.clCreateKernel(C.c_void_p(prog), b"probe", C.byref(err)); assert err.value == 0 +if len(sys.argv) > 1 and sys.argv[1] == "bin": # dump the device binary for disassembly + sz = C.c_size_t(0); cl.clGetProgramInfo(C.c_void_p(prog), 0x1165, C.sizeof(C.c_size_t), C.byref(sz), None) + buf = C.create_string_buffer(sz.value); ptr = C.c_char_p(C.addressof(buf)) + cl.clGetProgramInfo(C.c_void_p(prog), 0x1166, C.sizeof(C.c_void_p), C.byref(ptr), None) + open("expprobe.bin", "wb").write(buf.raw); sys.exit(0) +cl.clCreateBuffer.restype = C.c_void_p +CHUNK = 1 << 26 +def buf(sz): + b = cl.clCreateBuffer(C.c_void_p(ctx), 1, C.c_size_t(sz), None, C.byref(err)); assert err.value == 0; return b +bx, bv, bs, by = buf(CHUNK * 4), buf(CHUNK * 4), buf(CHUNK * 4), buf(CHUNK * 4) +for i, b in enumerate((bx, bv, bs, by)): + cl.clSetKernelArg(C.c_void_p(k), i, C.c_size_t(8), C.byref(C.c_void_p(b))) +spec = np.array([0x00000000, 0x80000000, 0x00000001, 0x80000001, 0x007fffff, 0x807fffff, 0x00800000, 0x80800000, 0x3f800000, + 0xbf800000, 0x7f7fffff, 0xff7fffff, 0x7f800000, 0xff800000, 0x7fc00000, 0xffc00000, 0x7f800001, 0xff800001, + 0x7fc00001, 0x7fffffff, 0xffffffff, 0x40490fdb, 0xc0490fdb, 0x3f000000, 0xbf000000], np.uint32) +px, py = np.meshgrid(spec, spec) +rng = np.random.default_rng(7) +rx = rng.integers(0, 1 << 32, CHUNK - px.size, dtype=np.uint64).astype(np.uint32) +ry = rng.integers(0, 1 << 32, CHUNK - px.size, dtype=np.uint64).astype(np.uint32) +# also random pairs of nearby values (max of close numbers) +ry[: len(ry) // 2] = rx[: len(rx) // 2] ^ rng.integers(0, 4, len(rx) // 2, dtype=np.uint64).astype(np.uint32) +X = np.concatenate([px.ravel(), rx]).astype(np.uint32); Y = np.concatenate([py.ravel(), ry]).astype(np.uint32) +bad = 0; total = 0 +for rep in range(8): + if rep: + X = rng.integers(0, 1 << 32, CHUNK, dtype=np.uint64).astype(np.uint32) + Y = np.where(rng.random(CHUNK) < 0.5, X ^ rng.integers(0, 4, CHUNK, dtype=np.uint64).astype(np.uint32), rng.integers(0, 1 << 32, CHUNK, dtype=np.uint64).astype(np.uint32)).astype(np.uint32) + cnt = CHUNK + cl.clEnqueueWriteBuffer(C.c_void_p(q), C.c_void_p(bx), 1, 0, C.c_size_t(cnt * 4), X.ctypes.data_as(C.c_void_p), 0, None, None) + cl.clEnqueueWriteBuffer(C.c_void_p(q), C.c_void_p(by), 1, 0, C.c_size_t(cnt * 4), Y.ctypes.data_as(C.c_void_p), 0, None, None) + gs = C.c_size_t(cnt); ls = C.c_size_t(16) + cl.clEnqueueNDRangeKernel(C.c_void_p(q), C.c_void_p(k), 1, None, C.byref(gs), C.byref(ls), 0, None, None) + v = np.empty(cnt, np.uint32); s = np.empty(cnt, np.uint32) + cl.clEnqueueReadBuffer(C.c_void_p(q), C.c_void_p(bv), 1, 0, C.c_size_t(cnt * 4), v.ctypes.data_as(C.c_void_p), 0, None, None) + cl.clEnqueueReadBuffer(C.c_void_p(q), C.c_void_p(bs), 1, 0, C.c_size_t(cnt * 4), s.ctypes.data_as(C.c_void_p), 0, None, None) + d = np.nonzero(v != s)[0]; bad += len(d); total += cnt + if len(d): print("DIFF", [(hex(int(X[i])), hex(int(Y[i])), hex(int(v[i])), hex(int(s[i]))) for i in d[:5]]) +print("fmax: checked", total, "pairs (all special-value pairs, nearby and random patterns), mismatches", bad) diff --git a/docs/receipts/xpu-qwen27-attn-exp/scripts/run_pass.sh b/docs/receipts/xpu-qwen27-attn-exp/scripts/run_pass.sh new file mode 100755 index 00000000000..974d90e9d13 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/scripts/run_pass.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# One server pass. usage: BIN=... MODEL=... DRAFTER=... OUT=... run_pass.sh LABEL [TREE] +# TREE unset or empty: no XPU_TREE (the default). PLAIN=1 adds the plain ("draft": false) mode, SAMPLED=1 the seeded +# sampled cells (34 and 121,022 tokens). PORT defaults to 8091. The load-time window costs go to OUT/LABEL.window.log. +L=$1; T=$2; PORT=${PORT:-8091}; HERE=$(cd "$(dirname "$0")" && pwd) +export LC_ALL=C +[ -n "$T" ] && export XPU_TREE=$T || unset XPU_TREE +unset XPU_KV_INT8 +mkdir -p "$OUT" +ss -ltn | grep -q ":$PORT " && { echo "port $PORT busy"; exit 3; } +"$BIN" serve "$MODEL" --drafter "$DRAFTER" --context 132096 --parallel 1 --host 127.0.0.1 --port "$PORT" --name m \ + --no-update-check --prompt-cache-gib 0 > "$OUT/$L.server.log" 2>&1 & +SP=$! +sleep 2; kill -0 $SP 2>/dev/null || { echo "server died at launch"; exit 1; } +for i in $(seq 300); do kill -0 $SP 2>/dev/null || break; curl -sf localhost:$PORT/health >/dev/null && break; sleep 2; done +curl -sf localhost:$PORT/health >/dev/null || { echo "server not ready"; kill $SP 2>/dev/null; exit 1; } +RC=0 +CORP=${CORP:-$HERE/../inputs/corp_code.txt} +export CORP +MODES=draft; [ "$PLAIN" = 1 ] && MODES=draft,plain +CELLS="${CELLS_GREEDY:-0:code;32768:code;65536:code;131072:code}" MODES=$MODES python3 -I "$HERE/bench_tree.py" http://127.0.0.1:$PORT "$L" "$OUT" 3 \ + > "$OUT/$L.bench.log" 2>&1 || RC=1 +if [ "$SAMPLED" = 1 ]; then + CELLS="${CELLS_SAMPLED:-0:code;131072:code}" MODES=sampled python3 -I "$HERE/bench_tree.py" http://127.0.0.1:$PORT "$L-sampled" "$OUT" 3 \ + > "$OUT/$L-sampled.bench.log" 2>&1 || RC=1 +fi +kill -INT $SP; for i in $(seq 90); do kill -0 $SP 2>/dev/null || break; sleep 1; done; kill -9 $SP 2>/dev/null +wait $SP 2>/dev/null; ss -ltn | grep -q ":$PORT " && { echo "port $PORT still busy after the pass"; exit 4; } +grep -E "window ms by rows" "$OUT/$L.server.log" > "$OUT/$L.window.log" +exit $RC From b7e7b79fe5b3fd83edd8047c4391d1ecdd69d924 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:42:39 +0100 Subject: [PATCH 244/361] changelog: the attn_decode vector exp line names #4651 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 55c97d48746..d24d6c01d5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -345,7 +345,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - XPU: Qwen3.8-27B decode attention merges its slices with 16 subgroups a head instead of one, adding them in the same order, so every output byte is unchanged (token hashes equal to main, drafted and plain, bf16 and int8 KV). On an Arc Pro B70 plain decode gains 1.8 to 2.0 % at about 8,000 prompt tokens, 14.7 to 16.0 % at about 30,000 and 39.8 to 42.2 % at 121,022; drafted decode is level. The kernel contract registers it as a bit-equal replacement with two planted controls (#3960, lands #2799). Thanks to @Mirrdhyn. -- XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#NNNN, refs #2543). +- XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#4651, refs #2543). - Flash Next on CUDA: `TF_FLASHNEXT_FUSED_SPLIT=1` (opt-in) runs decode projections that split K over a cluster, at 2,048 output columns or more, on the fused form, adding the K slices in the cluster's order so the bits are unchanged; unset, blank or `0` keeps the current kernels, and Metal and HIP refuse `1` at startup (#3475). Thanks to @BadAd84. From 19651c15816bfea7068e061bd1a7b71b62149c98 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:11:16 +0100 Subject: [PATCH 245/361] receipt: the exp and fmax proofs name the IGC and compute-runtime versions they ran on --- .../xpu-qwen27-attn-exp/proofs/README.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 docs/receipts/xpu-qwen27-attn-exp/proofs/README.md diff --git a/docs/receipts/xpu-qwen27-attn-exp/proofs/README.md b/docs/receipts/xpu-qwen27-attn-exp/proofs/README.md new file mode 100644 index 00000000000..b565a6c9f22 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/proofs/README.md @@ -0,0 +1,20 @@ +# Proofs: vector exp and fmax equal scalar on the card + +Whether a vector `exp` or `fmax` gives the scalar one's bits depends on the compiler, so these are the versions the two +runs used, on 2026-11-22, one Arc Pro B70 (bmg-g31), Ubuntu 26.04.1, Linux 7.0.0-43-generic: + +- Compiler: IGC 2.41.5 (`intel-igc-core-2` and `intel-igc-opencl-2` 2.41.5, `/usr/local/lib/libigc.so.2` and + `libigdfcl.so.2`). +- Compute-runtime: 26.35.39758.21 (`intel-opencl-icd`, `libze-intel-gpu1`, `intel-ocloc`). +- The probes build their kernel through the OpenCL runtime (`clBuildProgram`, `-cl-std=CL3.0 + -cl-intel-256-GRF-per-thread`). The host also has Ubuntu's IGC 2.41.16 + (`libigc2`, `libigdfcl2`), which neither the runtime nor `ocloc` loads here: `LD_DEBUG=files` shows both resolve + `libigc.so.2` and `libigdfcl.so.2` to `/usr/local/lib`, the 2.41.5 build. + +| File | Script | What it checks | +|---|---|---| +| `expprobe_all.out` | `../scripts/expprobe_all.py` | all 2^32 float bit patterns, 16-lane vector `exp` against scalar `exp`: 0 mismatches | +| `fmaxprobe.out` | `../scripts/fmaxprobe.py` | 536,870,912 pairs (all special-value pairs, nearby and random patterns), vector `fmax` against scalar: 0 mismatches | + +A different IGC can give a different answer: rerun both scripts after a driver or compiler change before relying on +the kernel's bits. From 4219086554e27f54e62c2e912d7e479e1b3a5cd7 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:35:35 +0100 Subject: [PATCH 246/361] xpu: qwen27 decode broadcasts the head max on every lane before lane 0 stores it --- zig/kernels/xpu/contract_gate_controls.cl | 3 ++- zig/kernels/xpu/qwen27/decode.cl | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/zig/kernels/xpu/contract_gate_controls.cl b/zig/kernels/xpu/contract_gate_controls.cl index 2767f890999..02eb854c25f 100644 --- a/zig/kernels/xpu/contract_gate_controls.cl +++ b/zig/kernels/xpu/contract_gate_controls.cl @@ -248,8 +248,9 @@ KERNEL(16) void tf_ctl_attn_exp_lanes(global const ushort *Q, global const ushor } for (int a = 0; a < 6; a++) { const long base = ((long)t * 24 + hk * 6 + a) * NS + sp; + const float ma = sub_group_broadcast(mv, a); if (lane == 0) { - PM[base] = sub_group_broadcast(mv, a); + PM[base] = ma; PL[base] = l[a]; } for (int i = 0; i < 16; i++) PO[base * 256 + i * 16 + lane] = o[a][i]; diff --git a/zig/kernels/xpu/qwen27/decode.cl b/zig/kernels/xpu/qwen27/decode.cl index 3ac37cb6b7a..3778bb7cf88 100644 --- a/zig/kernels/xpu/qwen27/decode.cl +++ b/zig/kernels/xpu/qwen27/decode.cl @@ -147,8 +147,9 @@ KERNEL(16) void attn_decode(global const ushort *Q, global const ushort *KC, glo #else const long base = ((long)t * Q27_AQ + qh0 + a) * NS + sp; #endif + const float ma = sub_group_broadcast(mv, a); if (lane == 0) { - PM[base] = sub_group_broadcast(mv, a); + PM[base] = ma; PL[base] = l[a]; } for (int i = 0; i < 16; i++) PO[base * 256 + i * 16 + lane] = o[a][i]; From faf95639502e731246da2683c0de94a91725d2c3 Mon Sep 17 00:00:00 2001 From: Mirrdhyn <21200274+Mirrdhyn@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:22:52 +0100 Subject: [PATCH 247/361] receipt: the review fix rerun, contract and served token hashes unchanged --- docs/receipts/xpu-qwen27-attn-exp/README.md | 30 ++++++++++++++++++ .../contract/contract-run-branch-fix.out | Bin 0 -> 18668 bytes .../runs-fix/q1-branch.jsonl | 16 ++++++++++ .../runs-fix/q2-main.jsonl | 16 ++++++++++ .../runs-fix/q3-branch.jsonl | 8 +++++ .../runs-fix/q4-main.jsonl | 8 +++++ .../xpu-qwen27-attn-exp/runs-fix/summarize.py | 15 +++++++++ 7 files changed, 93 insertions(+) create mode 100644 docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-branch-fix.out create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs-fix/q1-branch.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs-fix/q2-main.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs-fix/q3-branch.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs-fix/q4-main.jsonl create mode 100644 docs/receipts/xpu-qwen27-attn-exp/runs-fix/summarize.py diff --git a/docs/receipts/xpu-qwen27-attn-exp/README.md b/docs/receipts/xpu-qwen27-attn-exp/README.md index 37e95d394a2..0829aaef7a6 100644 --- a/docs/receipts/xpu-qwen27-attn-exp/README.md +++ b/docs/receipts/xpu-qwen27-attn-exp/README.md @@ -133,6 +133,36 @@ Host checks, no GPU: `zig build test-kernel-contract test-qwen27-config-xpu-host (48 of 48 steps, 288 of 288 tests; the rerun on the final commit, which only changed two comments, ran the 252 tests that were not cached and passed them all). +## Rerun after the review fix + +Review: in `attn_decode`, `sub_group_broadcast(mv, a)` sat inside `if (lane == 0)`, so only lane 0 reached the +collective. Commit `8b99d80e3` computes `const float ma = sub_group_broadcast(mv, a);` before the branch on every lane +and lane 0 stores `ma`; the same hoist is in the planted control `tf_ctl_attn_exp_lanes`, whose score-lane mutation is +unchanged. Nothing else moved. The branch binary is new, `tensorfold-native` SHA-256 +`b286eee7271352a1c8044692374a61a47cf801b863786e1445a3b0cd60378dc3` (MD5 `707d02a181dda93c756e692d01452ab3`), built +as above on 2026-11-24; the main binary is the one of the table above (same SHA-256). Same host, driver stack and +checkpoints, every run on card 0 (`ZE_AFFINITY_MASK=0`). + +- Kernel contract, `contract/contract-run-branch-fix.out`: `SUMMARY bmg-g31 0xe223 21 kernels: 21 pass gates 1-4, 0 fail, + 0 known findings; 12 controls: 12 red as planted, 0 missed; 0 limit problems`. Apart from timings the file is the same as + `contract/contract-run-branch.out`, which ran on card 1. `xpu-kernel-contract-limits`: every launch fits, `attn_decode` + 16 work-items, SLM 0, 256 GRF, 0 spill bytes. +- Served, `runs-fix/` (same script, `scripts/run_pass.sh`; one fresh server a pass, one pass a side and depth group: + branch then main at 7,588 and 28,946 tokens, then branch then main at 121,022; `summarize.py` prints the table): + every request of every cell carries the `token_sha256` of the first table, in full, and the drafter's counters are + unchanged (71 rounds, 1,065 drafted, 186 accepted at 7,588; 70, 1,050, 188 at 28,946; 67, 1,005, 188 at 121,022). + +| prompt tokens | mode | token_sha256 (first 16 hex) | main | branch | branch / main | +|---|---|---|---|---|---| +| 7588 | drafted | `9764d2d6fb7cbdbf` | 62.26 | 63.28 | 1.016 | +| 7588 | plain | `9764d2d6fb7cbdbf` | 32.67 | 32.69 | 1.001 | +| 28946 | drafted | `1d59abb499c48841` | 36.34 | 37.47 | 1.031 | +| 28946 | plain | `1d59abb499c48841` | 28.94 | 28.98 | 1.001 | +| 121022 | drafted | `0ac2491477780561` | 13.30 | 13.97 | 1.050 | +| 121022 | plain | `0ac2491477780561` | 19.50 | 19.54 | 1.002 | + +Decode tok/s, the median of three measured requests (one pass a side, so no paired ratio); the speed matches the table above. + ## Limits - Code prompts only, at the three depths named. One host, one card for the served numbers, one driver stack. diff --git a/docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-branch-fix.out b/docs/receipts/xpu-qwen27-attn-exp/contract/contract-run-branch-fix.out new file mode 100644 index 0000000000000000000000000000000000000000..4cee405f8385364b35a608b199a5150230cf8049 GIT binary patch literal 18668 zcmds9$#UCB5}mWYqHZI_h-z#EA^GH9JmF~D?XboXJ(p1wi6Vs%2(STAq`+E_^(Kv{LOo`=eE~M{2B-1pClc~7O z9u+=Lrpgydyto$Qndx5LiN0xB^ja@}Pe#753}@hp{6Rd=X7el+Q<;q(F~1VyFqWC? zh*2ohRHb_6M9q}U_MUbeJS&mRqf`uEGSv%w6=lIlhFFndIR-yXudYQ9@#G}cWG)jw z74s;I=c7mEUqfsWKdU5^Gc7~yHjL+(@^TR;X(o)DTgN1g z(CYaUNM;D-PcU1e#`6@LI(*@epHvd5FqdaO-CvqqhyYuyC&z9+k$Q|btSgbyXp49r z`eGWSslX@8YcU*~E(CO!;!+CJ?G1xWXqAa^9ER~CWwG!wEg<~^n+Tz0D$?{nJ@W_a zPDnilzVY`|C<3Gi@C`9mi(;gCI7_t@_zG<~Ag~CciI!J(TR34gU0X3H_4p;;(LilA#-fUdoP+kXFca75fTPu&b(oE`53@NE{Q z1Bwm9=!W7?KfD!M$6L)wvrxW*alprPFkOk6`=RuZhf*|4@Zj z{QF9DW!lENld_Het?}(nYWJMYI!37Hc?XA9yCvwL)?3T%=8{&8)oxj~n<>|HoPEM7 z^RHs2(nT-{=i0-{Q5HPQEQq5r3vkv^>J1Fr{dSb@n64S3w&Nk5rJUf9=zqubUGQn! z-SD|;c6JD|pP8u-g4B(}sbi1IEASy`EDKFe^9e221M3 z+vY_JImG%z?|n4B)}O`;g%1PBy%aGx5RnD>))>pdSpP!`sv?-Oe2h|tYB0)@30&AO zNQtdMwu}GMJo&QgM8@Wtn~%WZ2LKGu`W6q0uwN}`K;QuesVghzZ24I(1`QuPd zh+n|q1p3w4c(^x00cPcw2~(p`NgCScr@z+Z698uZa0PUL0|OCI0|(;6{So^Ewju{x z8cZU9{ZEy|U`jxx`h$jp8Uv;t-~U zVKi0XIK?ng@`>Pq1FqG-NMiiDkS{PUppKT79inOpf4I^+;ZF&hlpr8Z7#tJW3|M$WO>xqw4i-v)e9;G zUs)3e;N?e5wyNn6Z?F-76Co)}j+u!%I#i90Li-~&1?1@}Ly&(^Jt-ZbX1MjjnOTHM zj7B)pF;kh)bu1zresUNv7zlHr6NJC&W)#BZYH`ynCW0!+G&5B@!@HK#e3p-sMDLpa zwm3c~b_%=X*mAhnz>&?Y2N{OI!+fM35Ww7tjZ6bk%{NsVwv64Zn8Qr$mZ>_#qn%xI zmEvxhczXnD?TS9V8;(8~v92ZLWfiUp(8=+GM2)f#C5-$FG!0@@eIPSMWut)N!$_h) zz|?;jr<;*tHgis>@Qtxgr|^xb&ZY2;iS;38dKM=BNjMY;kt3i2o+jsOMInk1qw$i% z9xe^x0a>NxI{!}4O41XY$zssc>829=TuP~CeEr9-*#9FMTBk(H>6BW{aW17+GoJ8> zRo;(IbyWv0kKL>)`0+y+ z@3knA*6}?~CoghcQ_#RVZ^ZqZd8701@q#@Hv+)y7;Mbk*nHYQ%zRrko! zbO(chWo|oK+Pfb4OjU!PR6!I%bv#ArJR%;Mn2xRuV&pT58BeGZ?(N93h|1rwuf#v# z#qgWv+%DN8jwD!RuqTO9pm0qS^dX3zmCnFh*Z9VKz4QDnDn3dbo0q@uW>`i+x}d?X z$J{UF%A{}I@dqLaTpl;5r3cXR)q(B2U+dVht-*l1^13C9Lf^mI7yTDoojT9ml)1G#Qlgc@9_u78gO!rXES?6V9&VDbyr7{eNrt=*MLW3hQOe6Mnzmevi@O~_ z7N@o7RVr4{QH4<33Vg9tWhIGyw+wn=w^W=V|uSkv_4%P&6*p~t9N38(^tt2@b4 z4_C8ri%05T*x{qduLDYIZFxZ}L*na$-!v4oUXDa}pr}1%IuEm82C@=5hLh;&rZ6I$ zI}L8ShWIu3kw(Ggv#u}W;#N&G3Vz}2#6Q2h>o`!g03hH9qj=5p*E9~Lq2Vl7>7Dre z(|hV3F_y}*;N?B>%U9Cd@2W@fD?P{_sdobpBYbu(?%#j>8PWc=fYAB3(hKgg%F)2% z^C3Yi*F%0<05r0heuBvp;l~JwNuzudkUt5g5v`pSE@r5GDZ~M-_yCkU!=q|KdJfweg5Nxt&AjwwP!d1Mj#nc#VERYhdx+ z#N4Q~rWVeZgwz8)Ow4uV29;iLg6CL)+ z-6<5um9I%EZuU7;AmezOwAndymyt(5f|coKYsUS~gp%g5IWJ zs6L1Ugd_ZN|(nJ=hJ5E&gDJub=uKS;@OP2nR>10HHw=Tp{Ua+ zrz$oJ8lW}6YlTS2&I#7`161Mxz4MVTL;B+jukcW9fkr#S`h74`r*f*~ovy1?i88na zfQA0n1r-Iu7hEVCh4E-TlSgrQj4BxZ%nbNa^~^=mk}s=`Muo+af~Y;$*H`qL`p@S4 zx8NH7cX9vq6`fF;{QoNykr0X literal 0 HcmV?d00001 diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q1-branch.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q1-branch.jsonl new file mode 100644 index 00000000000..185a4538e8a --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q1-branch.jsonl @@ -0,0 +1,16 @@ +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9737508296966553, "decode_tok_s": 59.95386196145522, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9637303352355957, "decode_tok_s": 63.302072948683744, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9854934215545654, "decode_tok_s": 63.27853440764605, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9936442375183105, "decode_tok_s": 63.25152318808996, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9754438400268555, "decode_tok_s": 32.693264239645316, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.986355781555176, "decode_tok_s": 32.69352806948633, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.9881577491760254, "decode_tok_s": 32.69015556552297, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 3.989605188369751, "decode_tok_s": 32.691193722982824, "label": "q1-branch", "depth": 8192, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.96733283996582, "decode_tok_s": 36.920351892795935, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.9724543094635, "decode_tok_s": 37.472347897230755, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.98386573791504, "decode_tok_s": 37.49758643020011, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.991858959197998, "decode_tok_s": 37.46541328855105, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.99635100364685, "decode_tok_s": 28.986951464610755, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.997910737991333, "decode_tok_s": 28.9848540473511, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.998458862304688, "decode_tok_s": 28.988178633726285, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 16.989659547805786, "decode_tok_s": 28.98386200403214, "label": "q1-branch", "depth": 32768, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q2-main.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q2-main.jsonl new file mode 100644 index 00000000000..adb78c7f3fc --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q2-main.jsonl @@ -0,0 +1,16 @@ +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.005206823348999, "decode_tok_s": 59.110238930710956, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.0023534297943115, "decode_tok_s": 62.28943060264021, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.006161689758301, "decode_tok_s": 62.26204280399482, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 71, "drafted": 1065, "accepted": 186, "acceptance_rate": 0.17464788732394365, "tokens_per_round": 3.6056338028169015}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.007861614227295, "decode_tok_s": 62.263035929502166, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.003872871398926, "decode_tok_s": 32.673491126096906, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.000025033950806, "decode_tok_s": 32.67591578548724, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.000680446624756, "decode_tok_s": 32.67059378571517, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "9764d2d6fb7cbdbf23bc8f718d2423cf3265d074e21ab5b9ecde120a106e10e6", "text_sha256": "e5b9e5902f52299fc7deb601236e54ebf0ffe68c2ef72532230a59bd30856db8", "prompt_tokens": 7588, "completion_tokens": 256, "ttft_s": 4.003466606140137, "decode_tok_s": 32.66962479342993, "label": "q2-main", "depth": 8192, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "829dddadac0f329f368008ab5291dee91863a9d6eae58966f093c194eed2b57f"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.024474382400513, "decode_tok_s": 35.689913777733494, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.024023056030273, "decode_tok_s": 36.33314166003929, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.03570032119751, "decode_tok_s": 36.36622641290028, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 70, "drafted": 1050, "accepted": 188, "acceptance_rate": 0.17904761904761904, "tokens_per_round": 3.657142857142857}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.034622192382812, "decode_tok_s": 36.344441098812695, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.032517671585083, "decode_tok_s": 28.93875543500877, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.022751092910767, "decode_tok_s": 28.939448403174868, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.01985216140747, "decode_tok_s": 28.93656869207786, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "1d59abb499c488410dbce2b32cb15ab00a5ef2ac89cc7f94e964fa217cb00a1b", "text_sha256": "f6a1e744753be1934e78f75642b5f54d4ae24632262dcd41bf0ae78f91050069", "prompt_tokens": 28946, "completion_tokens": 256, "ttft_s": 17.01674723625183, "decode_tok_s": 28.94449906835058, "label": "q2-main", "depth": 32768, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "0bd40816987651daf0956745e407acfa5fd65d9e8d3fabbfe57d7b4cca7bdb44"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q3-branch.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q3-branch.jsonl new file mode 100644 index 00000000000..abaff9ea74b --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q3-branch.jsonl @@ -0,0 +1,8 @@ +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.29008746147156, "decode_tok_s": 13.74740096334215, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.3503737449646, "decode_tok_s": 13.973852692818154, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.38139367103577, "decode_tok_s": 13.97134151236847, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.39988207817078, "decode_tok_s": 13.966604179499832, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.4212634563446, "decode_tok_s": 19.542541757239903, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.46932935714722, "decode_tok_s": 19.54513269513833, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.35794973373413, "decode_tok_s": 19.53826705116219, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.43273901939392, "decode_tok_s": 19.537448665784893, "label": "q3-branch", "depth": 131072, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q4-main.jsonl b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q4-main.jsonl new file mode 100644 index 00000000000..893da70dd1e --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/q4-main.jsonl @@ -0,0 +1,8 @@ +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.40995359420776, "decode_tok_s": 13.122292888195204, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.35932612419128, "decode_tok_s": 13.30539775941583, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.40938115119934, "decode_tok_s": 13.302770286103197, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 67, "drafted": 1005, "accepted": 188, "acceptance_rate": 0.18706467661691542, "tokens_per_round": 3.8208955223880596}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.42309188842773, "decode_tok_s": 13.303129998480314, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "draft", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.46938061714172, "decode_tok_s": 19.503807258500345, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 0, "warmup": true, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.45482969284058, "decode_tok_s": 19.502552204480946, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 1, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.45661854743958, "decode_tok_s": 19.50110210518491, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 2, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} +{"ok": true, "speculative": {"rounds": 255, "drafted": 0, "accepted": 0, "acceptance_rate": 0.0, "tokens_per_round": 1.003921568627451}, "token_sha256": "0ac2491477780561c3575840554b597015e900c4afb2507675acbbf279e634b8", "text_sha256": "a52d08fa575ee9a434fc9b5ee958fbd0f355aa8057012c78e6a464727cb7161c", "prompt_tokens": 121022, "completion_tokens": 256, "ttft_s": 101.43135643005371, "decode_tok_s": 19.503931030015643, "label": "q4-main", "depth": 131072, "kind": "code", "mode": "plain", "rep": 3, "warmup": false, "prompt_sha256": "60986a50b4990e56899a109dfbc956788c4f1380b8eb3b74c9bd0dccbe8ff1a7"} diff --git a/docs/receipts/xpu-qwen27-attn-exp/runs-fix/summarize.py b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/summarize.py new file mode 100644 index 00000000000..e9e2cf998f6 --- /dev/null +++ b/docs/receipts/xpu-qwen27-attn-exp/runs-fix/summarize.py @@ -0,0 +1,15 @@ +# usage: cd runs-fix && python3 -I summarize.py (per cell: token_sha256 set and median decode tok/s of the measured requests) +import json,glob,statistics as st,sys +R=[] +for f in sorted(glob.glob("q*.jsonl")): + for l in open(f): + r=json.loads(l); r["f"]=f[:-6]; R.append(r) +cells={} +for r in R: + cells.setdefault((r["depth"],r["mode"]),[]).append(r) +for (d,m),rs in sorted(cells.items()): + hs={r["token_sha256"] for r in rs} + sides={} + for r in rs: + if not r["warmup"]: sides.setdefault(r["f"],[]).append(r["decode_tok_s"]) + print(d,rs[0]["prompt_tokens"],m,"n",len(rs),"ok",all(r["ok"] for r in rs),"hashes",[h[:16] for h in hs],{k:round(st.median(v),2) for k,v in sides.items()}) From 2f34edf033ae495fb7a8b3cf45b1a2fe3c3880aa Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:36:46 +0000 Subject: [PATCH 248/361] changelog: #4651's line from lines/4651.txt in place of its own --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d24d6c01d5f..453161804fe 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 +- XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#4651, refs #2543). + - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_CHECK=1` (default off) runs a boot self-check that measures the widest verify window whose every row's scores equal its one-token step on that machine, and a lone stream's copy window then grows past the shipped 32 rows to at most the 48 the pending-row log holds; a check that cannot run, fails or proves nothing past 32 leaves the window at 32, and with the switch off every buffer the window sizes is main's (#4075). Thanks to @BadAd84. @@ -345,8 +347,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - XPU: Qwen3.8-27B decode attention merges its slices with 16 subgroups a head instead of one, adding them in the same order, so every output byte is unchanged (token hashes equal to main, drafted and plain, bf16 and int8 KV). On an Arc Pro B70 plain decode gains 1.8 to 2.0 % at about 8,000 prompt tokens, 14.7 to 16.0 % at about 30,000 and 39.8 to 42.2 % at 121,022; drafted decode is level. The kernel contract registers it as a bit-equal replacement with two planted controls (#3960, lands #2799). Thanks to @Mirrdhyn. -- XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#4651, refs #2543). - - Flash Next on CUDA: `TF_FLASHNEXT_FUSED_SPLIT=1` (opt-in) runs decode projections that split K over a cluster, at 2,048 output columns or more, on the fused form, adding the K slices in the cluster's order so the bits are unchanged; unset, blank or `0` keeps the current kernels, and Metal and HIP refuse `1` at startup (#3475). Thanks to @BadAd84. - Host draw: greedy and masked rows scan 64-logit blocks and skip blocks whose mask word allows nothing, on both the row draw and the bounded top-k path; a `test-host-draw-timing` step times a row outside `test` and CI (#2846). From 0d0189863fb6514439df8e4270fc9f6d0750ad8e Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:14:06 +0000 Subject: [PATCH 249/361] refactor(server): move the UUID v4 helper to ids.zig PaddleX's replies carry a logId that is a UUID v4 when the client sends none, and the benchmark receipt already builds one for its run id. The builder moves to ids.zig as uuid4 beside the other id helpers, and runId calls it, so both callers share one source. --- zig/src/server/benchmark_receipt.zig | 9 +-------- zig/src/server/ids.zig | 12 ++++++++++++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/zig/src/server/benchmark_receipt.zig b/zig/src/server/benchmark_receipt.zig index fdc8bf3cd7c..e242c2f521b 100644 --- a/zig/src/server/benchmark_receipt.zig +++ b/zig/src/server/benchmark_receipt.zig @@ -316,14 +316,7 @@ fn indented(w: *std.Io.Writer, v: Value, depth: usize) std.Io.Writer.Error!void /// A random lowercase UUID v4, as ``str(uuid.uuid4())``. pub fn runId(io: std.Io) [36]u8 { - var b: [16]u8 = undefined; - io.random(&b); - b[6] = (b[6] & 0x0f) | 0x40; - b[8] = (b[8] & 0x3f) | 0x80; - const hex = std.fmt.bytesToHex(b, .lower); - var out: [36]u8 = undefined; - _ = std.fmt.bufPrint(&out, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable; - return out; + return @import("ids.zig").uuid4(io); } /// UTC wall time as ``datetime.isoformat()`` with Z: microseconds only when not zero. diff --git a/zig/src/server/ids.zig b/zig/src/server/ids.zig index 384888a4548..0acb042b909 100644 --- a/zig/src/server/ids.zig +++ b/zig/src/server/ids.zig @@ -17,6 +17,18 @@ pub fn make(a: Allocator, prefix: []const u8, n: usize) Allocator.Error![]const return out; } +/// A random lowercase UUID v4, as ``str(uuid.uuid4())``. +pub fn uuid4(io: std.Io) [36]u8 { + var b: [16]u8 = undefined; + io.random(&b); + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + const hex = std.fmt.bytesToHex(b, .lower); + var out: [36]u8 = undefined; + _ = std.fmt.bufPrint(&out, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable; + return out; +} + /// ``prefix`` then the first ``n`` (at most 64) lowercase hex digits of ``digest``. fn hexed(a: Allocator, prefix: []const u8, n: usize, digest: [32]u8) Allocator.Error![]const u8 { const hex = std.fmt.bytesToHex(digest, .lower); From 46381711627fc48af25713d0fc38e2ee527ba0f5 Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:14:35 +0000 Subject: [PATCH 250/361] feat(ocr): POST /ocr in PaddleX's OCR serving contract PaddleX's serving clients post JSON with a base64 file and read prunedResult and a visualisation, so POST /ocr now answers JSON bodies in PaddleX's envelope: fields converted as its pydantic models convert them, rec_* lines filtered by textRecScoreThresh, integer polygons rounded half to even, word boxes on request, and inputImage and ocrImage with each polygon outlined under the shared image budget. A PDF is read to the page budget as PaddleX reads its first max_num_input_imgs pages, with dataInfo.numPages still the document's page count so a client sees the cut; detector knobs it cannot apply are refused, and file URLs share the Mistral route's fetch. --- zig/src/server/ocr/budget.zig | 2 +- zig/src/server/ocr/draw.zig | 81 ++++++ zig/src/server/ocr/draw_test.zig | 34 +++ zig/src/server/ocr/fetch.zig | 2 +- zig/src/server/ocr/geometry.zig | 43 +++ zig/src/server/ocr/geometry_test.zig | 22 +- zig/src/server/ocr/paddlex.zig | 295 +++++++++++++++++++ zig/src/server/ocr/paddlex_reply.zig | 228 +++++++++++++++ zig/src/server/ocr/paddlex_test.zig | 420 +++++++++++++++++++++++++++ zig/src/server/ocr/route.zig | 16 +- zig/src/server/ocr/route_test.zig | 10 +- zig/src/server/ocr/run.zig | 6 +- zig/src/server/ocr/run_pdf_test.zig | 15 +- zig/src/server/ocr/types.zig | 1 + zig/src/server/root.zig | 2 + 15 files changed, 1162 insertions(+), 15 deletions(-) create mode 100644 zig/src/server/ocr/draw.zig create mode 100644 zig/src/server/ocr/draw_test.zig create mode 100644 zig/src/server/ocr/paddlex.zig create mode 100644 zig/src/server/ocr/paddlex_reply.zig create mode 100644 zig/src/server/ocr/paddlex_test.zig diff --git a/zig/src/server/ocr/budget.zig b/zig/src/server/ocr/budget.zig index d2dcbc4c654..a94b5aeb5b1 100644 --- a/zig/src/server/ocr/budget.zig +++ b/zig/src/server/ocr/budget.zig @@ -30,7 +30,7 @@ pub const Pages = struct { } }; -/// The crops a request has encoded, against its limits. +/// The crops and visualisations a request has encoded, against its limits. pub const Encodes = struct { count: u32 = 0, pixels: u64 = 0, diff --git a/zig/src/server/ocr/draw.zig b/zig/src/server/ocr/draw.zig new file mode 100644 index 00000000000..1bd4affa092 --- /dev/null +++ b/zig/src/server/ocr/draw.zig @@ -0,0 +1,81 @@ +//! Region outlines on a page's RGB pixels for the visualisation images (PaddleX ``ocrImage``). +const std = @import("std"); + +/// The one outline colour the visualisations use. +pub const red: [3]u8 = .{ 255, 0, 0 }; + +/// Draws the closed polygon ``poly`` on ``w`` x ``h`` RGB rows, lines ``width_px`` thick, every pixel clipped. +pub fn outline(rgb: []u8, w: u32, h: u32, poly: [4][2]i32, rgb_color: [3]u8, width_px: u32) void { + std.debug.assert(rgb.len >= @as(usize, w) * h * 3); + if (w == 0 or h == 0 or width_px == 0) return; + for (0..4) |i| segment(rgb, w, h, poly[i], poly[(i + 1) % 4], rgb_color, width_px); +} + +/// One Bresenham line, first clipped to the image grown by the line width so a far-off corner costs no steps. +fn segment(rgb: []u8, w: u32, h: u32, from: [2]i32, to: [2]i32, color: [3]u8, n: u32) void { + const pad: f64 = @floatFromInt(n); + var p0: [2]f64 = .{ @floatFromInt(from[0]), @floatFromInt(from[1]) }; + var p1: [2]f64 = .{ @floatFromInt(to[0]), @floatFromInt(to[1]) }; + if (!clip(&p0, &p1, .{ -pad, -pad, @as(f64, @floatFromInt(w)) + pad, @as(f64, @floatFromInt(h)) + pad })) return; + var x: i64 = @intFromFloat(@round(p0[0])); + var y: i64 = @intFromFloat(@round(p0[1])); + const x1: i64 = @intFromFloat(@round(p1[0])); + const y1: i64 = @intFromFloat(@round(p1[1])); + const dx: i64 = @intCast(@abs(x1 - x)); + const dy: i64 = -@as(i64, @intCast(@abs(y1 - y))); + const sx: i64 = if (x < x1) 1 else -1; + const sy: i64 = if (y < y1) 1 else -1; + var err = dx + dy; + while (true) { + dot(rgb, w, h, x, y, color, n); + if (x == x1 and y == y1) break; + const e2 = 2 * err; + if (e2 >= dy) { + err += dy; + x += sx; + } + if (e2 <= dx) { + err += dx; + y += sy; + } + } +} + +/// An ``n`` x ``n`` square centred on (x, y) (2 px: x-1..x), so an edge on the image border stays visible. +fn dot(rgb: []u8, w: u32, h: u32, x: i64, y: i64, color: [3]u8, n: u32) void { + const back: i64 = @intCast(n / 2); + for (0..n) |j| for (0..n) |i| { + const px = x - back + @as(i64, @intCast(i)); + const py = y - back + @as(i64, @intCast(j)); + if (px < 0 or py < 0 or px >= w or py >= h) continue; + const at: usize = (@as(usize, @intCast(py)) * w + @as(usize, @intCast(px))) * 3; + rgb[at..][0..3].* = color; + }; +} + +/// Liang-Barsky: trims the segment to the box ``[xmin, ymin, xmax, ymax]``; false when nothing is left. +fn clip(p0: *[2]f64, p1: *[2]f64, b: [4]f64) bool { + const d: [2]f64 = .{ p1[0] - p0[0], p1[1] - p0[1] }; + const ps = [4]f64{ -d[0], d[0], -d[1], d[1] }; + const qs = [4]f64{ p0[0] - b[0], b[2] - p0[0], p0[1] - b[1], b[3] - p0[1] }; + var t0: f64 = 0; + var t1: f64 = 1; + for (ps, qs) |p, q| { + if (p == 0) { + if (q < 0) return false; + continue; + } + const r = q / p; + if (p < 0) { + if (r > t1) return false; + t0 = @max(t0, r); + } else { + if (r < t0) return false; + t1 = @min(t1, r); + } + } + const start = p0.*; + p0.* = .{ start[0] + t0 * d[0], start[1] + t0 * d[1] }; + p1.* = .{ start[0] + t1 * d[0], start[1] + t1 * d[1] }; + return true; +} diff --git a/zig/src/server/ocr/draw_test.zig b/zig/src/server/ocr/draw_test.zig new file mode 100644 index 00000000000..51eb035023e --- /dev/null +++ b/zig/src/server/ocr/draw_test.zig @@ -0,0 +1,34 @@ +//! The region outline PaddleX's ocrImage draws: its thickness along the edges and its clipping to the image. +const std = @import("std"); +const draw = @import("draw.zig"); +const t = std.testing; + +fn isRed(rgb: []const u8, w: u32, x: u32, y: u32) bool { + const at = (y * w + x) * 3; + return std.mem.eql(u8, rgb[at..][0..3], &draw.red); +} + +test "ocr draw: an outline is 2 px thick along the polygon's edges" { + const w = 12; + const h = 10; + var rgb: [w * h * 3]u8 = @splat(0); + draw.outline(&rgb, w, h, .{ .{ 2, 2 }, .{ 8, 2 }, .{ 8, 7 }, .{ 2, 7 } }, draw.red, 2); + for ([_][2]u32{ .{ 2, 2 }, .{ 5, 2 }, .{ 5, 1 }, .{ 8, 4 }, .{ 7, 4 }, .{ 2, 7 }, .{ 1, 5 }, .{ 8, 7 } }) |p| try t.expect(isRed(&rgb, w, p[0], p[1])); + for ([_][2]u32{ .{ 5, 5 }, .{ 0, 0 }, .{ 11, 9 }, .{ 5, 3 }, .{ 3, 5 }, .{ 9, 4 }, .{ 5, 8 } }) |p| try t.expect(!isRed(&rgb, w, p[0], p[1])); +} + +test "ocr draw: an outline is clipped to the image" { + const w = 8; + const h = 6; + var rgb: [w * h * 3]u8 = @splat(0); + draw.outline(&rgb, w, h, .{ .{ -5, -5 }, .{ 20, -5 }, .{ 20, 3 }, .{ -5, 3 } }, draw.red, 2); + for (0..w) |x| try t.expect(isRed(&rgb, w, @intCast(x), 3)); + try t.expect(!isRed(&rgb, w, 3, 0)); + // corners far outside cost no work and write nothing out of bounds + var far: [w * h * 3]u8 = @splat(0); + const big = std.math.maxInt(i32); + draw.outline(&far, w, h, .{ .{ -big, -big }, .{ big, -big }, .{ big, -big + 1 }, .{ -big, -big + 1 } }, draw.red, 2); + for (far) |b| try t.expectEqual(@as(u8, 0), b); + draw.outline(&far, w, h, .{ .{ 0, 0 }, .{ w, 0 }, .{ w, h }, .{ 0, h } }, draw.red, 2); + try t.expect(isRed(&far, w, 0, 0) and isRed(&far, w, w - 1, h - 1) and !isRed(&far, w, 3, 3)); +} diff --git a/zig/src/server/ocr/fetch.zig b/zig/src/server/ocr/fetch.zig index dc99305de3e..90ffaffef86 100644 --- a/zig/src/server/ocr/fetch.zig +++ b/zig/src/server/ocr/fetch.zig @@ -1,4 +1,4 @@ -//! A document's bytes from a public HTTPS URL, for POST /v1/ocr's document URLs. +//! A document's bytes from a public HTTPS URL, for the OCR dialects that take URLs (Mistral, PaddleX). const std = @import("std"); const Allocator = std.mem.Allocator; const images = @import("../images.zig"); diff --git a/zig/src/server/ocr/geometry.zig b/zig/src/server/ocr/geometry.zig index 6ea4344febb..5636343fffe 100644 --- a/zig/src/server/ocr/geometry.zig +++ b/zig/src/server/ocr/geometry.zig @@ -53,6 +53,30 @@ pub fn mistralBox(q: Quad) [4]i32 { return .{ toInt(@floor(b[0])), toInt(@floor(b[1])), toInt(@ceil(b[2])), toInt(@ceil(b[3])) }; } +/// PaddleX's polygon: corners rounded; a degenerate result becomes its integer box, a zero side widened by 1 px. +pub fn paddlePoly(q: Quad, w: u32, h: u32) [4][2]i32 { + var p: [4][2]i32 = undefined; + for (q, &p) |c, *o| o.* = .{ toInt(roundEven(c[0])), toInt(roundEven(c[1])) }; + if (isSimpleConvex(toQuad(p))) return p; + var b: [4]i32 = .{ p[0][0], p[0][1], p[0][0], p[0][1] }; + for (p[1..]) |c| { + b[0] = @min(b[0], c[0]); + b[1] = @min(b[1], c[1]); + b[2] = @max(b[2], c[0]); + b[3] = @max(b[3], c[1]); + } + const x = widenInt(b[0], b[2], limitInt(w)); + const y = widenInt(b[1], b[3], limitInt(h)); + return .{ .{ x[0], y[0] }, .{ x[1], y[0] }, .{ x[1], y[1] }, .{ x[0], y[1] } }; +} + +/// The integer polygon as a float quad (exact for page coordinates). +pub fn toQuad(p: [4][2]i32) Quad { + var q: Quad = undefined; + for (p, &q) |c, *o| o.* = .{ @floatFromInt(c[0]), @floatFromInt(c[1]) }; + return q; +} + fn box(x0: f32, y0: f32, x1: f32, y1: f32) Quad { return .{ .{ x0, y0 }, .{ x1, y0 }, .{ x1, y1 }, .{ x0, y1 } }; } @@ -64,6 +88,25 @@ fn widen(lo: f32, hi: f32, limit: f32) [2]f32 { return .{ @max(0, limit - 1), limit }; } +fn widenInt(lo: i32, hi: i32, limit: i32) [2]i32 { + if (hi > lo) return .{ lo, hi }; + if (lo +| 1 <= limit) return .{ lo, lo + 1 }; + return .{ @max(0, limit - 1), limit }; +} + +fn limitInt(n: u32) i32 { + return @intCast(@min(n, std.math.maxInt(i32))); +} + +/// Python's ``round(x)``: to nearest, a tie to the even neighbour. +pub fn roundEven(x: f32) f32 { + const f = @floor(x); + const d = x - f; + if (d < 0.5) return f; + if (d > 0.5) return f + 1; + return if (@mod(f, 2) == 0) f else f + 1; +} + fn toInt(x: f32) i32 { return std.math.lossyCast(i32, x); } diff --git a/zig/src/server/ocr/geometry_test.zig b/zig/src/server/ocr/geometry_test.zig index c2f2cd72f0e..34510be24ef 100644 --- a/zig/src/server/ocr/geometry_test.zig +++ b/zig/src/server/ocr/geometry_test.zig @@ -1,4 +1,4 @@ -//! Quad validation and the Mistral integer form. +//! Quad validation and the Mistral and PaddleX integer forms. const std = @import("std"); const api = @import("engine_api"); const g = @import("geometry.zig"); @@ -77,3 +77,23 @@ test "ocr geometry: Mistral floors the minimum and ceils the maximum" { try t.expectEqual([4]i32{ 3, 4, 7, 8 }, g.mistralBox(rect(3, 4, 7, 8))); try t.expectEqual([4]i32{ 2, 1, 9, 9 }, g.mistralBox(.{ .{ 2.5, 1.5 }, .{ 8.5, 3 }, .{ 8, 8.5 }, .{ 3, 7 } })); } + +test "ocr geometry: PaddleX rounds corners and keeps a polygon that stays convex" { + const q: Quad = .{ .{ 1.4, 1.6 }, .{ 50.6, 2.2 }, .{ 50.2, 20.7 }, .{ 0.6, 19.4 } }; + try t.expectEqual([4][2]i32{ .{ 1, 2 }, .{ 51, 2 }, .{ 50, 21 }, .{ 1, 19 } }, g.paddlePoly(q, 100, 100)); + const turned: Quad = .{ .{ 30, 0 }, .{ 30, 60 }, .{ 0, 60 }, .{ 0, 0 } }; + try t.expectEqual([4][2]i32{ .{ 30, 0 }, .{ 30, 60 }, .{ 0, 60 }, .{ 0, 0 } }, g.paddlePoly(turned, 100, 100)); +} + +test "ocr geometry: PaddleX falls back to the integer box when rounding collapses the polygon" { + // a thin diagonal parallelogram (8 px²) whose rounded corners land on its diagonal + const thin: Quad = .{ .{ 0, 1 }, .{ 10, 11 }, .{ 10.4, 10.6 }, .{ 0.4, 0.6 } }; + try t.expect(g.isSimpleConvex(thin)); + try t.expectEqual([4][2]i32{ .{ 0, 1 }, .{ 10, 1 }, .{ 10, 11 }, .{ 0, 11 } }, g.paddlePoly(thin, 100, 100)); + // narrower than 1 px across x: rounds to one column, widened by 1 px + const narrow: Quad = .{ .{ 4.6, 0 }, .{ 5.4, 0 }, .{ 5.4, 10 }, .{ 4.6, 10 } }; + try t.expectEqual([4][2]i32{ .{ 5, 0 }, .{ 6, 0 }, .{ 6, 10 }, .{ 5, 10 } }, g.paddlePoly(narrow, 100, 100)); + // the same column on the page's right edge widens leftward, staying inside + try t.expectEqual([4][2]i32{ .{ 4, 0 }, .{ 5, 0 }, .{ 5, 10 }, .{ 4, 10 } }, g.paddlePoly(narrow, 5, 100)); + for ([_]Quad{ thin, narrow }) |v| try t.expect(g.isSimpleConvex(g.toQuad(g.paddlePoly(v, 100, 100)))); +} diff --git a/zig/src/server/ocr/paddlex.zig b/zig/src/server/ocr/paddlex.zig new file mode 100644 index 00000000000..79200a01837 --- /dev/null +++ b/zig/src/server/ocr/paddlex.zig @@ -0,0 +1,295 @@ +//! POST /ocr in the PaddleX OCR serving contract: the JSON request, its file and knobs, then the page loop. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const json = @import("json"); +const errors = @import("../errors.zig"); +const images = @import("../images.zig"); +const http_body = @import("../http_body.zig"); +const ids = @import("../ids.zig"); +const pdf = @import("../pdf.zig"); +const Conn = @import("../http_conn.zig").Conn; +const Server = @import("../server.zig").Server; +const types = @import("types.zig"); +const run = @import("run.zig"); +const fetch = @import("fetch.zig"); +const query = @import("../query.zig"); +const lines = @import("lines.zig"); +const reply = @import("paddlex_reply.zig"); +const Value = json.Value; +const Fault = types.Fault; +const Step = run.Step; + +pub const Options = reply.Options; + +/// What decoding needs from the server: the PDF switch and the URL fetcher. +pub const Facts = struct { + pdf: bool, + fetch: ?images.Fetch, + + pub fn of(srv: *const Server) Facts { + return .{ .pdf = srv.config.vision_pdf, .fetch = if (srv.config.vision_urls) images.Fetch.network(srv.io) else null }; + } +}; + +/// A decoded request: the reply's options and its one file. +pub const Request = struct { options: Options, source: types.Source }; + +/// Answers one PaddleX POST /ocr whose body has been read; a client that leaves gets nothing. +pub fn post(srv: *Server, conn: *Conn, a: Allocator, body: []const u8, gone: anytype) void { + var fault: Fault = .{ .class = .internal, .message = "" }; + var log_id: []const u8 = ""; + const out = handle(srv, a, body, gone, &fault, &log_id) catch |e| { + if (log_id.len == 0) log_id = fresh(srv, a); + switch (e) { + error.Faulted => return reply.sendFault(conn, a, log_id, fault), + error.OutOfMemory => return reply.sendFault(conn, a, log_id, .{ .class = .internal, .message = "out of memory" }), + error.Cancelled => { + conn.close = true; + return; + }, + } + }; + conn.sendJson(200, out); +} + +/// A new UUID v4 for a request whose logId is absent or empty. +fn fresh(srv: *const Server, a: Allocator) []const u8 { + const id = ids.uuid4(srv.io); + return a.dupe(u8, &id) catch ""; +} + +fn handle(srv: *Server, a: Allocator, body: []const u8, gone: anytype, fault: *Fault, log_id: *[]const u8) Step![]const u8 { + const raw = switch (try json.parse(a, body)) { + .ok => |v| v, + .err => |m| return schema(a, fault, &.{.{ .type = "json_invalid", .loc = "body", .msg = try std.fmt.allocPrint(a, "the body is not valid JSON: {s}", .{m}) }}), + }; + // the request's own logId is echoed by every reply once the body parsed + if (raw.field("logId")) |v| if (v == .string and v.string.len > 0) { + log_id.* = v.string; + }; + try run.gate(srv, a, fault); + const req = try decode(a, raw, Facts.of(srv), fault); + var enc: reply.Encoder = .{ .o = req.options, .geometry = srv.info.ocr.?.geometry, .gpa = srv.gpa }; + try run.run(srv, a, &.{req.source}, enc.sink(), fault, gone); + if (log_id.*.len == 0) log_id.* = fresh(srv, a); + return enc.reply(a, log_id.*, req.source.kind == .pdf); +} + +/// One validation error as PaddleX's 422 lists it; ``loc`` is dot-joined. +pub const Issue = struct { type: []const u8, loc: []const u8, msg: []const u8 }; + +/// Faults as bad input with ``errorMsg`` the JSON list of ``issues``, as ``json.dumps`` writes it. +fn schema(a: Allocator, fault: *Fault, issues: []const Issue) Step { + const list = try a.alloc(Value, issues.len); + for (issues, list) |i, *v| { + const o = try json.newObject(a); + try o.put(a, "type", .{ .string = i.type }); + try o.put(a, "loc", .{ .string = i.loc }); + try o.put(a, "msg", .{ .string = i.msg }); + v.* = .{ .object = o }; + } + fault.* = .{ .class = .bad_input, .message = try json.stringify(a, .{ .array = list }, .{}) }; + return error.Faulted; +} + +fn bad(a: Allocator, fault: *Fault, comptime fmt: []const u8, args: anytype) Step { + return fault.fail(a, .bad_input, fmt, args); +} + +/// The fields as PaddleX's schema types them, each read as pydantic's lax mode reads it. +pub const Kind = enum { boolean, integer, string, number }; +const typed = [_]struct { []const u8, Kind }{ + .{ "logId", .string }, .{ "useDocOrientationClassify", .boolean }, .{ "useDocUnwarping", .boolean }, + .{ "useTextlineOrientation", .boolean }, .{ "textDetLimitSideLen", .integer }, .{ "textDetLimitType", .string }, + .{ "textDetThresh", .number }, .{ "textDetBoxThresh", .number }, .{ "textDetUnclipRatio", .number }, + .{ "textRecScoreThresh", .number }, .{ "returnWordBox", .boolean }, .{ "visualize", .boolean }, +}; + +/// Knobs that change which text a detector returns: refused unless null (or false, for the switches). +const switches = [_][]const u8{ "useDocOrientationClassify", "useDocUnwarping", "useTextlineOrientation" }; +const detector = [_][]const u8{ "textDetLimitSideLen", "textDetLimitType", "textDetThresh", "textDetBoxThresh", "textDetUnclipRatio" }; + +/// The typed fields after conversion: absent or null fields stay null. +const Fields = struct { + values: [typed.len]?Value = @splat(null), + + fn get(f: *const Fields, comptime name: []const u8) ?Value { + inline for (typed, 0..) |x, i| if (comptime std.mem.eql(u8, x[0], name)) return f.values[i]; + @compileError("no field " ++ name); + } +}; + +/// The request's fields checked as docs/api.md OCR: PaddleX states, and the file's bytes; ``null``: absent. +pub fn decode(a: Allocator, body: Value, facts: Facts, fault: *Fault) Step!Request { + if (body != .object) return schema(a, fault, &.{.{ .type = "model_attributes_type", .loc = "body", .msg = "the body must be a JSON object" }}); + var issues: std.ArrayList(Issue) = .empty; + const file = body.get("file"); + if (file == null) try issues.append(a, .{ .type = "missing", .loc = "body.file", .msg = "Field required" }); + if (file != null and file.? != .string) try issues.append(a, .{ .type = "string_type", .loc = "body.file", .msg = "Input should be a valid string" }); + // Literal[0, 1] in lax mode: a bool or a number equal to 0 or 1 is that literal; a string is not + var file_type: ?bool = null; // true: 1 (an image), false: 0 (a PDF) + if (body.field("fileType")) |v| { + file_type = switch (v) { + .bool => |b| b, + .int => |n| if (std.mem.eql(u8, n, "0")) false else if (std.mem.eql(u8, n, "1")) true else null, + .float => |f| if (f == 0) false else if (f == 1) true else null, + else => null, + }; + if (file_type == null) try issues.append(a, .{ .type = "literal_error", .loc = "body.fileType", .msg = "fileType must be 0 (a PDF) or 1 (an image)" }); + } + var fields: Fields = .{}; + for (typed, &fields.values) |f, *slot| if (body.field(f[0])) |v| switch (lax(v, f[1])) { + .ok => |c| slot.* = c, + .bad => |b| try issues.append(a, .{ .type = b[0], .loc = try loc(a, f[0]), .msg = b[1] }), + }; + if (issues.items.len > 0) return schema(a, fault, issues.items); + inline for (switches) |name| if (fields.get(name)) |v| if (v.bool) + try issues.append(a, .{ .type = "unsupported", .loc = "body." ++ name, .msg = "TensorFold reads the page as sent, with no preprocessing; send null or false" }); + inline for (detector) |name| if (fields.get(name) != null) + try issues.append(a, .{ .type = "unsupported", .loc = "body." ++ name, .msg = "TensorFold has no text detector to apply this to; send null" }); + if (issues.items.len > 0) return schema(a, fault, issues.items); + const o: Options = .{ + .thresh = if (fields.get("textRecScoreThresh")) |v| v.float else 0, + .word_box = if (fields.get("returnWordBox")) |v| v.bool else false, + .visualize = if (fields.get("visualize")) |v| v.bool else true, + }; + const bytes = try fileBytes(a, fault, file.?.string, facts); + // the image signature first: a PNG may hold "%PDF-" in an early text chunk + const is_image = switch (images.sniff(bytes)) { + .png, .jpeg, .webp => true, + else => false, + }; + const is_pdf = !is_image and std.mem.indexOf(u8, bytes[0..@min(bytes.len, 1024)], "%PDF-") != null; + const want_pdf: ?bool = if (file_type) |image| !image else null; + // a file that is neither kind is refused below, whatever fileType says + if (want_pdf) |w| if (w != is_pdf and (is_pdf or is_image)) + return bad(a, fault, "fileType {d} names {s}, but the file is {s}; send fileType {d}, or leave fileType out", .{ @intFromBool(!w), if (w) "a PDF" else "an image", if (is_pdf) "a PDF" else "an image", @intFromBool(w) }); + if (is_pdf) { + if (!facts.pdf) return bad(a, fault, "{s}", .{pdf.off_message}); + // read to the page budget, as PaddleX's OCR docs read max_num_input_imgs pages; numPages keeps the count + return .{ .options = o, .source = .{ .name = "file", .bytes = bytes, .kind = .pdf, .sel = .{ .first = std.math.maxInt(u32) } } }; + } + if (!is_image) return bad(a, fault, "the file is neither a PDF nor a PNG, JPEG or WebP image (TIFF is not read)", .{}); + return .{ .options = o, .source = .{ .name = "file", .bytes = bytes, .kind = .image, .sel = .{ .all_within = 1 } } }; +} + +/// A converted value (.bool, .int, .string, or a finite .float), or a pydantic error type and message. +pub const Lax = union(enum) { ok: Value, bad: [2][]const u8 }; + +/// ``v`` read as pydantic's lax mode reads ``k``; a number must also be finite. +pub fn lax(v: Value, k: Kind) Lax { + const finite: Lax = .{ .bad = .{ "finite_number", "a finite number is expected; infinity, NaN and numbers past the float range are not" } }; + switch (k) { + .string => return if (v == .string) .{ .ok = v } else .{ .bad = .{ "string_type", "Input should be a valid string" } }, + .boolean => { + const no: Lax = .{ .bad = .{ "bool_parsing", "Input should be a valid boolean, unable to interpret input" } }; + return switch (v) { + .bool => .{ .ok = v }, + .int => |n| if (std.mem.eql(u8, n, "0") or std.mem.eql(u8, n, "1")) .{ .ok = .{ .bool = n[0] == '1' } } else no, + .float => |f| if (f == 0 or f == 1) .{ .ok = .{ .bool = f == 1 } } else if (std.math.isFinite(f) and f == @trunc(f)) no else .{ .bad = .{ "bool_type", "a boolean is expected: true, false, 0, 1, or a word such as yes or off" } }, + .string => |s| if (query.boolean(s)) |b| .{ .ok = .{ .bool = b } } else no, + else => .{ .bad = .{ "bool_type", "a boolean is expected: true, false, 0, 1, or a word such as yes or off" } }, + }; + }, + .integer => return switch (v) { + .int => .{ .ok = v }, + .bool => |b| .{ .ok = .{ .int = if (b) "1" else "0" } }, + .float => |f| if (!std.math.isFinite(f)) finite else if (f == @trunc(f)) .{ .ok = v } else .{ .bad = .{ "int_from_float", "an integer is expected; this number has a fractional part" } }, + // past i64 an integer string stays text: it is never the default, so the knob check refuses it + .string => |s| if (intText(lines.trimSpace(s))) .{ .ok = v } else .{ .bad = .{ "int_parsing", "Input should be a valid integer, unable to parse string as an integer" } }, + else => .{ .bad = .{ "int_type", "Input should be a valid integer" } }, + }, + .number => { + const f: f64 = switch (v) { + .int => |n| std.fmt.parseFloat(f64, n) catch return finite, + .float => |f| f, + .bool => |b| if (b) 1 else 0, + .string => |s| floatText(lines.trimSpace(s)) orelse return .{ .bad = .{ "float_parsing", "Input should be a valid number, unable to parse string as a number" } }, + else => return .{ .bad = .{ "float_type", "a number is expected: an integer, a float or a numeric string" } }, + }; + return if (std.math.isFinite(f)) .{ .ok = .{ .float = f } } else finite; + }, + } +} + +/// An integer as pydantic reads a string: a sign, digits, then optionally "." and zeros only; any length. +fn intText(s: []const u8) bool { + var i: usize = if (s.len > 0 and (s[0] == '+' or s[0] == '-')) 1 else 0; + const digits = i; + while (i < s.len and std.ascii.isDigit(s[i])) i += 1; + if (i == digits) return false; + if (i < s.len and s[i] == '.') { + i += 1; + while (i < s.len and s[i] == '0') i += 1; + } + return i == s.len; +} + +/// A float in decimal syntax only (sign, digits, ".", digits, exponent; or inf, infinity, nan); null otherwise. +fn floatText(s: []const u8) ?f64 { + var i: usize = if (s.len > 0 and (s[0] == '+' or s[0] == '-')) 1 else 0; + for ([_][]const u8{ "inf", "infinity", "nan" }) |word| if (std.ascii.eqlIgnoreCase(s[i..], word)) return std.math.inf(f64); + var digits: usize = 0; + while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) digits += 1; + if (i < s.len and s[i] == '.') { + i += 1; + while (i < s.len and std.ascii.isDigit(s[i])) : (i += 1) digits += 1; + } + if (digits == 0) return null; + if (i < s.len and (s[i] == 'e' or s[i] == 'E')) { + i += 1; + if (i < s.len and (s[i] == '+' or s[i] == '-')) i += 1; + const exp = i; + while (i < s.len and std.ascii.isDigit(s[i])) i += 1; + if (i == exp) return null; + } + if (i != s.len) return null; + return std.fmt.parseFloat(f64, s) catch null; +} + +fn loc(a: Allocator, field: []const u8) Allocator.Error![]const u8 { + return std.mem.concat(a, u8, &.{ "body.", field }); +} + +/// The file's bytes: base64 (decoded leniently), a data URL, or an https URL fetched when --vision-urls is on. +fn fileBytes(a: Allocator, fault: *Fault, raw: []const u8, facts: Facts) Step![]const u8 { + const text = std.mem.trim(u8, raw, " \t\r\n"); + if (std.ascii.startsWithIgnoreCase(text, "data:")) { + var cx: errors.Cx = .{ .a = a }; + return images.dataBytesOf(&cx, text, http_body.limit, "file") catch |e| switch (e) { + error.OutOfMemory => error.OutOfMemory, + error.Refused => bad(a, fault, "{s}", .{cx.message}), + }; + } + if (std.ascii.startsWithIgnoreCase(text, "http://") or std.ascii.startsWithIgnoreCase(text, "https://")) { + return switch (try fetch.https(a, facts.fetch, text, facts.pdf)) { + .bytes => |b| b, + .refused => |m| bad(a, fault, "{s}", .{m}), + }; + } + return try base64(a, text) orelse bad(a, fault, "file is not base64 data, a data: URL or an https:// URL", .{}); +} + +/// Base64 as Python's ``b64decode`` reads it: bytes outside the alphabet skipped, the padding repaired; null if none. +pub fn base64(a: Allocator, text: []const u8) Allocator.Error!?[]const u8 { + const clean = try a.alloc(u8, text.len + 3); + var n: usize = 0; + for (text) |c| if (std.ascii.isAlphanumeric(c) or c == '+' or c == '/') { + clean[n] = c; + n += 1; + }; + if (n == 0 or n % 4 == 1) return null; + // the last character's bits past the data are ignored, as Python ignores them: 4 before "==", 2 before "=" + const tail = n % 4; + if (tail != 0) { + const alphabet = std.base64.standard_alphabet_chars; + const at = std.mem.indexOfScalar(u8, &alphabet, clean[n - 1]).?; + clean[n - 1] = alphabet[at & @as(usize, if (tail == 2) 0b110000 else 0b111100)]; + } + while (n % 4 != 0) : (n += 1) clean[n] = '='; + const d = std.base64.standard.Decoder; + const size = d.calcSizeForSlice(clean[0..n]) catch return null; + const out = try a.alloc(u8, size); + d.decode(out, clean[0..n]) catch return null; + return if (out.len > 0) out else null; +} diff --git a/zig/src/server/ocr/paddlex_reply.zig b/zig/src/server/ocr/paddlex_reply.zig new file mode 100644 index 00000000000..a6d9fee0edc --- /dev/null +++ b/zig/src/server/ocr/paddlex_reply.zig @@ -0,0 +1,228 @@ +//! PaddleX OCR replies: each page's prunedResult and images, the result around them, and the error envelope. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const api = @import("engine_api"); +const json = @import("json"); +const picture = @import("core").picture; +const jpeg_out = @import("../jpeg_out.zig"); +const Conn = @import("../http_conn.zig").Conn; +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const geometry = @import("geometry.zig"); +const lines = @import("lines.zig"); +const draw = @import("draw.zig"); +const run = @import("run.zig"); +const Value = json.Value; +const Fault = types.Fault; +const Step = run.Step; + +/// The request fields that shape the reply (docs/api.md OCR: PaddleX). +pub const Options = struct { + thresh: f64 = 0, // textRecScoreThresh: rec_* keep lines with score >= thresh + word_box: bool = false, // returnWordBox + visualize: bool = true, // anything but false: ocrImage and inputImage +}; + +/// JPEG quality of ocrImage and inputImage. +pub const jpeg_quality = 85; + +/// The page sink: each page's ocrResults entry and size, in the request arena. +pub const Encoder = struct { + o: Options, + geometry: api.ocr.Geometry, + /// Scratch for JPEG bytes, freed after each encode. + gpa: Allocator, + results: std.ArrayList(Value) = .empty, + sizes: std.ArrayList([2]u32) = .empty, + /// The PDF's own page count, past ``sizes.len`` when the page budget cut it (docs/api.md OCR: PaddleX). + doc_pages: u32 = 0, + + pub fn sink(e: *Encoder) run.PageSink { + return .{ .ctx = e, .page = onPage }; + } + + fn onPage(ctx: *anyopaque, a: Allocator, _: u32, page: *const types.OcrPage, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step!void { + const e: *Encoder = @ptrCast(@alignCast(ctx)); + e.doc_pages = page.doc_pages; + const w = page.width; + const h = page.height; + const ls = lines.fromBlocks(a, page, e.geometry) catch |err| return unreadable(a, fault, page.index, err); + const polys = try a.alloc([4][2]i32, ls.len); + for (ls, polys) |l, *p| p.* = if (l.quad) |q| geometry.paddlePoly(q, w, h) else whole(w, h); + var rec: std.ArrayList(usize) = .empty; + for (ls, 0..) |l, i| if (@as(f64, l.score) >= e.o.thresh) try rec.append(a, i); + const settings = try json.newObject(a); + try settings.put(a, "use_doc_preprocessor", .{ .bool = false }); + try settings.put(a, "use_textline_orientation", .{ .bool = false }); + const pruned = try json.newObject(a); + try pruned.put(a, "model_settings", .{ .object = settings }); + try pruned.put(a, "dt_polys", try polyList(a, polys, null)); + try pruned.put(a, "text_type", .{ .string = "general" }); + if (ls.len > 0) { + const angles = try a.alloc(Value, ls.len); + for (angles) |*v| v.* = .{ .int = "-1" }; + try pruned.put(a, "textline_orientation_angles", .{ .array = angles }); + } + try pruned.put(a, "text_rec_score_thresh", .{ .float = e.o.thresh }); + try pruned.put(a, "return_word_box", .{ .bool = e.o.word_box }); + const texts = try a.alloc(Value, rec.items.len); + const scores = try a.alloc(Value, rec.items.len); + const boxes = try a.alloc(Value, rec.items.len); + for (rec.items, texts, scores, boxes) |i, *t, *s, *b| { + t.* = .{ .string = ls[i].text }; + s.* = .{ .float = ls[i].score }; + b.* = try box(a, polys[i]); + } + try pruned.put(a, "rec_texts", .{ .array = texts }); + try pruned.put(a, "rec_scores", .{ .array = scores }); + try pruned.put(a, "rec_polys", try polyList(a, polys, rec.items)); + try pruned.put(a, "rec_boxes", .{ .array = boxes }); + if (e.o.word_box) try e.words(a, pruned, page, ls, rec.items, fault); + const result = try json.newObject(a); + try result.put(a, "prunedResult", .{ .object = pruned }); + if (e.o.visualize) { + const input = try e.jpeg64(a, rgb, enc, fault); // before the outlines are drawn on the same pixels + for (rec.items) |i| draw.outline(rgb.pixels, w, h, polys[i], draw.red, 2); + try result.put(a, "ocrImage", .{ .string = try e.jpeg64(a, rgb, enc, fault) }); + try result.put(a, "inputImage", .{ .string = input }); + } + try e.results.append(a, .{ .object = result }); + try e.sizes.append(a, .{ w, h }); + } + + /// ``text_word`` and ``text_word_boxes``: per kept line, its estimated words and their integer xyxy boxes. + fn words(_: *Encoder, a: Allocator, pruned: *json.Object, page: *const types.OcrPage, ls: []const types.OcrLine, rec: []const usize, fault: *Fault) Step!void { + const texts = try a.alloc(Value, rec.len); + const boxes = try a.alloc(Value, rec.len); + for (rec, texts, boxes) |i, *t, *b| { + const ws = lines.words(a, ls[i], page.width, page.height) catch |err| return unreadable(a, fault, page.index, err); + const wt = try a.alloc(Value, ws.len); + const wb = try a.alloc(Value, ws.len); + for (ws, wt, wb) |word, *x, *y| { + x.* = .{ .string = word.text }; + y.* = try box(a, if (word.quad) |q| geometry.paddlePoly(q, page.width, page.height) else whole(page.width, page.height)); + } + t.* = .{ .array = wt }; + b.* = .{ .array = wb }; + } + try pruned.put(a, "text_word_boxes", .{ .array = boxes }); // PaddleX writes the boxes first + try pruned.put(a, "text_word", .{ .array = texts }); + } + + /// The page pixels as base64 JPEG without a data-URL prefix, under the request's image budget. + fn jpeg64(e: *Encoder, a: Allocator, rgb: picture.Rgb, enc: *budget.Encodes, fault: *Fault) Step![]const u8 { + try enc.before(fault, @intCast(rgb.width), @intCast(rgb.height)); + const jpeg = jpeg_out.encodeRgb(e.gpa, rgb.pixels, rgb.width, rgb.height, jpeg_quality) catch |err| return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.NoLibrary => fault.fail(a, .internal, "visualize needs libjpeg-turbo, which this server cannot load; send visualize: false", .{}), + else => fault.fail(a, .internal, "a visualisation image could not be encoded", .{}), + }; + defer e.gpa.free(jpeg); + try enc.after(fault, jpeg.len); + const b64 = std.base64.standard.Encoder; + const out = try a.alloc(u8, b64.calcSize(jpeg.len)); + return b64.encode(out, jpeg); + } + + /// The whole reply: ``ocrResults`` in page order and ``dataInfo`` for an image or a PDF. + pub fn reply(e: *Encoder, a: Allocator, log_id: []const u8, is_pdf: bool) Allocator.Error![]const u8 { + const info = try json.newObject(a); + if (is_pdf) { + const pages = try a.alloc(Value, e.sizes.items.len); + for (e.sizes.items, pages) |s, *p| p.* = .{ .object = try size(a, s) }; + // the document's pages, so a client sees a cut: ocrResults and pages list only the pages read + try info.put(a, "numPages", try json.intValue(a, @max(e.doc_pages, pages.len))); + try info.put(a, "pages", .{ .array = pages }); + try info.put(a, "type", .{ .string = "pdf" }); + } else { + const s = if (e.sizes.items.len > 0) e.sizes.items[0] else [2]u32{ 0, 0 }; + try info.put(a, "width", try json.intValue(a, s[0])); + try info.put(a, "height", try json.intValue(a, s[1])); + try info.put(a, "type", .{ .string = "image" }); + } + const result = try json.newObject(a); + try result.put(a, "ocrResults", .{ .array = e.results.items }); + try result.put(a, "dataInfo", .{ .object = info }); + const o = try json.newObject(a); + try o.put(a, "logId", .{ .string = log_id }); + try o.put(a, "errorCode", .{ .int = "0" }); + try o.put(a, "errorMsg", .{ .string = "Success" }); + try o.put(a, "result", .{ .object = result }); + return json.stringify(a, .{ .object = o }, .{}); + } +}; + +fn unreadable(a: Allocator, fault: *Fault, index: u32, err: (Allocator.Error || error{Unreadable})) Step { + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.Unreadable => fault.fail(a, .unreadable, "page {d}: the model's output has a box that is not finite", .{index}), + }; +} + +fn size(a: Allocator, s: [2]u32) Allocator.Error!*json.Object { + const o = try json.newObject(a); + try o.put(a, "width", try json.intValue(a, s[0])); + try o.put(a, "height", try json.intValue(a, s[1])); + return o; +} + +/// The whole page as a polygon: a line of a reader without geometry. +fn whole(w: u32, h: u32) [4][2]i32 { + const x: i32 = @intCast(@min(w, std.math.maxInt(i32))); + const y: i32 = @intCast(@min(h, std.math.maxInt(i32))); + return .{ .{ 0, 0 }, .{ x, 0 }, .{ x, y }, .{ 0, y } }; +} + +/// ``[[x, y] x 4]`` per polygon: every one, or those at ``only``. +fn polyList(a: Allocator, polys: []const [4][2]i32, only: ?[]const usize) Allocator.Error!Value { + const n = if (only) |o| o.len else polys.len; + const out = try a.alloc(Value, n); + for (out, 0..) |*v, k| { + const p = polys[if (only) |o| o[k] else k]; + const pts = try a.alloc(Value, 4); + for (p, pts) |c, *pt| pt.* = .{ .array = try a.dupe(Value, &.{ try json.intValue(a, c[0]), try json.intValue(a, c[1]) }) }; + v.* = .{ .array = pts }; + } + return .{ .array = out }; +} + +/// ``[xmin, ymin, xmax, ymax]`` of an integer polygon, as ``rec_boxes`` holds it. +fn box(a: Allocator, p: [4][2]i32) Allocator.Error!Value { + var b: [4]i32 = .{ p[0][0], p[0][1], p[0][0], p[0][1] }; + for (p[1..]) |c| { + b[0] = @min(b[0], c[0]); + b[1] = @min(b[1], c[1]); + b[2] = @max(b[2], c[0]); + b[3] = @max(b[3], c[1]); + } + const out = try a.alloc(Value, 4); + for (b, out) |x, *v| v.* = try json.intValue(a, x); + return .{ .array = out }; +} + +/// The HTTP status and ``errorCode`` of each fault class: PaddleX answers 422 for every request and input failure. +pub fn status(class: types.Class) u16 { + return switch (class) { + .bad_input, .unreadable => 422, + .capacity => 503, + .internal => 500, + }; +} + +/// ``{"logId", "errorCode", "errorMsg"}``, ``errorCode`` equal to the HTTP status. +pub fn errorBody(a: Allocator, log_id: []const u8, fault: Fault) Allocator.Error![]const u8 { + const o = try json.newObject(a); + try o.put(a, "logId", .{ .string = log_id }); + try o.put(a, "errorCode", try json.intValue(a, status(fault.class))); + try o.put(a, "errorMsg", .{ .string = fault.message }); + return json.stringify(a, .{ .object = o }, .{}); +} + +/// Sends the fault with its status; a capacity fault carries Retry-After. +pub fn sendFault(conn: *Conn, a: Allocator, log_id: []const u8, fault: Fault) void { + const body = errorBody(a, log_id, fault) catch return conn.sendJson(500, "{\"logId\": \"\", \"errorCode\": 500, \"errorMsg\": \"out of memory\"}"); + if (fault.class != .capacity) return conn.sendJson(status(fault.class), body); + var buf: [16]u8 = undefined; + const retry = std.fmt.bufPrint(&buf, "{d}", .{fault.retry_after orelse 1}) catch unreachable; + conn.sendJsonWith(503, body, &.{.{ "Retry-After", retry }}); +} diff --git a/zig/src/server/ocr/paddlex_test.zig b/zig/src/server/ocr/paddlex_test.zig new file mode 100644 index 00000000000..f185f481e66 --- /dev/null +++ b/zig/src/server/ocr/paddlex_test.zig @@ -0,0 +1,420 @@ +//! PaddleX on POST /ocr: lenient base64, schema and knob refusals, prunedResult's keys and lists, and whole requests. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const picture = @import("core").picture; +const routes = @import("../routes.zig"); +const paddlex = @import("paddlex.zig"); +const reply = @import("paddlex_reply.zig"); +const types = @import("types.zig"); +const budget = @import("budget.zig"); +const geometry = @import("geometry.zig"); +const harness = @import("harness_test.zig"); +const t = std.testing; +const Allocator = std.mem.Allocator; +const Value = json.Value; + +fn value(a: Allocator, text: []const u8) !Value { + return switch (try json.parse(a, text)) { + .ok => |v| v, + .err => error.TestUnexpectedResult, + }; +} + +test "ocr paddlex: base64 skips bytes outside the alphabet and repairs its padding" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try t.expectEqualStrings("hello!", (try paddlex.base64(a, "aGVs\nbG8h")).?); + try t.expectEqualStrings("hello", (try paddlex.base64(a, " aGVs bG8 ")).?); + try t.expectEqualStrings("hello", (try paddlex.base64(a, "aGVsbG8=*=")).?); + try t.expectEqualStrings("hi", (try paddlex.base64(a, "aGk")).?); + try t.expect(try paddlex.base64(a, "aGVsb") == null); // one byte past a group cannot be data + try t.expect(try paddlex.base64(a, "") == null); + try t.expect(try paddlex.base64(a, "!!**") == null); + // the last character's unused bits are ignored, as Python ignores them (PNG's IEND CRC) + try t.expectEqualSlices(u8, &.{ 0xae, 0x42, 0x60, 0x82 }, (try paddlex.base64(a, "rkJggg==")).?); + try t.expectEqualSlices(u8, &.{ 0xae, 0x42, 0x60, 0x82 }, (try paddlex.base64(a, "rkJggh==")).?); + try t.expectEqualStrings("hi", (try paddlex.base64(a, "aGl=")).?); +} + +test "ocr paddlex: fields convert as pydantic's lax mode converts them, and numbers must be finite" { + const Case = struct { []const u8, paddlex.Kind, ?[]const u8 }; // the JSON, the field's kind, the error type (null: accepted) + const cases = [_]Case{ + .{ "1.0", .integer, null }, + .{ "1.5", .integer, "int_from_float" }, + .{ "\"1\"", .integer, null }, + .{ "\"x\"", .integer, "int_parsing" }, + .{ "true", .integer, null }, + .{ "1e999", .integer, "finite_number" }, + .{ "\"1.0\"", .integer, null }, + .{ "\"-3.00\"", .integer, null }, + .{ "\"1.5\"", .integer, "int_parsing" }, + .{ "\"9223372036854775808\"", .integer, null }, + .{ "\"\\u00a01\\u00a0\"", .integer, null }, + .{ "[]", .integer, "int_type" }, + .{ "0", .boolean, null }, + .{ "1.0", .boolean, null }, + .{ "2", .boolean, "bool_parsing" }, + .{ "2.0", .boolean, "bool_parsing" }, + .{ "1.5", .boolean, "bool_type" }, + .{ "1e999", .boolean, "bool_type" }, + .{ "\"OFF\"", .boolean, null }, + .{ "\"y\"", .boolean, null }, + .{ "\"maybe\"", .boolean, "bool_parsing" }, + .{ "[]", .boolean, "bool_type" }, + .{ "\"0.5\"", .number, null }, + .{ "\"\\u00a00.5\\u2003\"", .number, null }, + .{ "\".5e-1\"", .number, null }, + .{ "\"x\"", .number, "float_parsing" }, + .{ "\"0x1p0\"", .number, "float_parsing" }, + .{ "\"1e\"", .number, "float_parsing" }, + .{ "3", .number, null }, + .{ "true", .number, null }, + .{ "1e999", .number, "finite_number" }, + .{ "\"inf\"", .number, "finite_number" }, + .{ "\"-Infinity\"", .number, "finite_number" }, + .{ "\"NaN\"", .number, "finite_number" }, + .{ "[]", .number, "float_type" }, + .{ "1", .string, "string_type" }, + }; + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (cases) |c| switch (paddlex.lax(try value(a, c[0]), c[1])) { + .ok => if (c[2]) |want| { + std.debug.print("{s} accepted, want {s}\n", .{ c[0], want }); + return error.TestUnexpectedResult; + }, + .bad => |b| try t.expectEqualStrings(c[2] orelse return error.TestUnexpectedResult, b[0]), + }; + try t.expectEqual(@as(f64, 0.5), paddlex.lax(try value(a, "\"0.5\""), .number).ok.float); + try t.expectEqual(false, paddlex.lax(try value(a, "\"OFF\""), .boolean).ok.bool); + try t.expectEqual(true, paddlex.lax(try value(a, "1"), .boolean).ok.bool); + try t.expectEqual(@as(f64, 1), paddlex.lax(try value(a, "true"), .number).ok.float); + try t.expectEqual(@as(f64, 0.5), paddlex.lax(try value(a, "\"\\u00a00.5\\u2003\""), .number).ok.float); + try t.expectEqualStrings("1", paddlex.lax(try value(a, "true"), .integer).ok.int); + // converted values drive the knob checks and the options; a non-finite threshold is refused before any page + var fault: types.Fault = undefined; + const ok = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"useDocUnwarping\": 0, \"useTextlineOrientation\": \"false\", \"visualize\": \"off\", " ++ + "\"textRecScoreThresh\": \"0.5\", \"returnWordBox\": 1}}", .{try pngField(a)}); + try t.expectEqual(paddlex.Options{ .thresh = 0.5, .word_box = true, .visualize = false }, (try paddlex.decode(a, try value(a, ok), facts, &fault)).options); + const inf = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"textRecScoreThresh\": 1e999}}", .{try pngField(a)}); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, inf), facts, &fault)); + try t.expectEqualStrings("finite_number", (try issues(a, fault))[0].strField("type").?); + const on = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"useDocUnwarping\": \"yes\"}}", .{try pngField(a)}); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, on), facts, &fault)); + try t.expectEqualStrings("unsupported", (try issues(a, fault))[0].strField("type").?); +} + +test "ocr paddlex: polygon corners round half to even, as Python's round does" { + try t.expectEqual(@as(f32, 10), geometry.roundEven(10.5)); + try t.expectEqual(@as(f32, 4), geometry.roundEven(4.5)); + try t.expectEqual(@as(f32, 12), geometry.roundEven(11.5)); + try t.expectEqual(@as(f32, 2), geometry.roundEven(2.4999)); + try t.expectEqual(@as(f32, 3), geometry.roundEven(2.5001)); + const q: api.ocr.Quad = .{ .{ 10.5, 4.5 }, .{ 21.5, 4.5 }, .{ 21.5, 14.5 }, .{ 10.5, 14.5 } }; + try t.expectEqual([4][2]i32{ .{ 10, 4 }, .{ 22, 4 }, .{ 22, 14 }, .{ 10, 14 } }, geometry.paddlePoly(q, 100, 100)); + // 10.4 and 10.5 both round to 10: the polygon collapses and is repaired into a 1 px wide box + const thin: api.ocr.Quad = .{ .{ 10.4, 4.5 }, .{ 10.5, 4.5 }, .{ 10.5, 9.5 }, .{ 10.4, 9.5 } }; + try t.expectEqual([4][2]i32{ .{ 10, 4 }, .{ 11, 4 }, .{ 11, 10 }, .{ 10, 10 } }, geometry.paddlePoly(thin, 100, 100)); +} + +const facts: paddlex.Facts = .{ .pdf = false, .fetch = null }; + +fn pngField(a: Allocator) ![]const u8 { + const png = try harness.png(a, 4, 3); + const enc = std.base64.standard.Encoder; + return enc.encode(try a.alloc(u8, enc.calcSize(png.len)), png); +} + +/// The fault's errorMsg as the issue list a schema refusal writes. +fn issues(a: Allocator, fault: types.Fault) ![]Value { + return (try value(a, fault.message)).array; +} + +test "ocr paddlex: schema errors list each field with a dot-joined loc; nulls and false switches pass" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var fault: types.Fault = undefined; + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, "{\"fileType\": 2, \"visualize\": \"maybe\", \"textRecScoreThresh\": \"x\"}"), facts, &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + const got = try issues(a, fault); + const want = [_][2][]const u8{ .{ "missing", "body.file" }, .{ "literal_error", "body.fileType" }, .{ "float_parsing", "body.textRecScoreThresh" }, .{ "bool_parsing", "body.visualize" } }; + try t.expectEqual(want.len, got.len); + for (got, want) |g, w| { + try t.expectEqualStrings(w[0], g.strField("type").?); + try t.expectEqualStrings(w[1], g.strField("loc").?); + try t.expect(g.strField("msg").?.len > 0); + } + // pydantic's published messages where its docs print one (missing, int_parsing...); TensorFold's own elsewhere + try t.expectEqualStrings("Field required", got[0].strField("msg").?); + try t.expectEqualStrings("fileType must be 0 (a PDF) or 1 (an image)", got[1].strField("msg").?); + try t.expectEqualStrings("Input should be a valid number, unable to parse string as a number", got[2].strField("msg").?); + try t.expectEqualStrings("Input should be a valid boolean, unable to interpret input", got[3].strField("msg").?); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, "[1]"), facts, &fault)); + try t.expectEqualStrings("body", (try issues(a, fault))[0].strField("loc").?); + try t.expectEqualStrings("the body must be a JSON object", (try issues(a, fault))[0].strField("msg").?); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, "{\"file\": null}"), facts, &fault)); + try t.expectEqualStrings("string_type", (try issues(a, fault))[0].strField("type").?); + // content-changing knobs name their fields; the switches pass when false, every knob when null + const knobs = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"useDocUnwarping\": true, \"textDetBoxThresh\": 0.5, \"useTextlineOrientation\": false}}", .{try pngField(a)}); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, knobs), facts, &fault)); + const named = try issues(a, fault); + try t.expectEqual(@as(usize, 2), named.len); + try t.expectEqualStrings("body.useDocUnwarping", named[0].strField("loc").?); + try t.expectEqualStrings("body.textDetBoxThresh", named[1].strField("loc").?); + const nulls = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": 1, \"logId\": null, \"useDocOrientationClassify\": false, \"useDocUnwarping\": false, " ++ + "\"useTextlineOrientation\": null, \"textDetLimitSideLen\": null, \"textDetLimitType\": null, \"textDetThresh\": null, \"textDetBoxThresh\": null, " ++ + "\"textDetUnclipRatio\": null, \"textRecScoreThresh\": 1, \"returnWordBox\": true, \"visualize\": false, \"unknown\": 3}}", .{try pngField(a)}); + const r = try paddlex.decode(a, try value(a, nulls), facts, &fault); + try t.expectEqual(paddlex.Options{ .thresh = 1, .word_box = true, .visualize = false }, r.options); + try t.expect(r.source.kind == .image); + try t.expectEqual(paddlex.Options{}, (try paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"}}", .{try pngField(a)})), facts, &fault)).options); +} + +test "ocr paddlex: the file's kind, URLs and PDFs are checked with PaddleX's words where they fit" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const png = try pngField(a); + const cases = [_]struct { file: []const u8, extra: []const u8 = "", says: []const u8 }{ + .{ .file = "!!!", .says = "file is not base64 data, a data: URL or an https:// URL" }, + .{ .file = "R0lGODlhAQABAAAAACw=", .says = "the file is neither a PDF nor a PNG, JPEG or WebP image (TIFF is not read)" }, + .{ .file = "R0lGODlhAQABAAAAACw=", .extra = ", \"fileType\": 0", .says = "the file is neither a PDF nor a PNG, JPEG or WebP image (TIFF is not read)" }, + .{ .file = png, .extra = ", \"fileType\": 0", .says = "fileType 0 names a PDF, but the file is an image; send fileType 1, or leave fileType out" }, + .{ .file = "JVBERi0xLjQK", .extra = ", \"fileType\": 1", .says = "fileType 1 names an image, but the file is a PDF; send fileType 0, or leave fileType out" }, + .{ .file = "JVBERi0xLjQK", .says = "--vision-pdf" }, + .{ .file = "http://example.com/a.png", .says = "public HTTPS URLs" }, + .{ .file = "https://example.com/a.png", .says = "--vision-urls" }, + .{ .file = "data:image/png;base64,!!", .says = "invalid file data URL encoding" }, + }; + for (cases) |c| { + var fault: types.Fault = undefined; + const body = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"{s}}}", .{ c.file, c.extra }); + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, body), facts, &fault)); + try t.expectEqual(types.Class.bad_input, fault.class); + if (std.mem.indexOf(u8, fault.message, c.says) == null) { + std.debug.print("{s}: {s}\n", .{ c.file, fault.message }); + return error.TestUnexpectedResult; + } + } + // a PNG with "%PDF-1.7" in an early text chunk is an image: the signature is read first + var fault: types.Fault = undefined; + const real = try harness.png(a, 4, 3); + var tagged: std.ArrayList(u8) = .empty; + try tagged.appendSlice(a, real[0..33]); // the signature and IHDR + try harness.chunk(a, &tagged, "tEXt", "Comment\x00%PDF-1.7"); + try tagged.appendSlice(a, real[33..]); + const enc = std.base64.standard.Encoder; + const field = enc.encode(try a.alloc(u8, enc.calcSize(tagged.items.len)), tagged.items); + for ([_][]const u8{ "", ", \"fileType\": 1" }) |extra| { + const got = try paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"{s}}}", .{ field, extra })), .{ .pdf = true, .fetch = null }, &fault); + try t.expect(got.source.kind == .image); + } + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": 0}}", .{field})), .{ .pdf = true, .fetch = null }, &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "fileType 0 names a PDF") != null); + // fileType is Literal[0, 1] in lax mode: a bool or a number equal to 0 or 1 counts; a string does not + for ([_][]const u8{ "1", "1.0", "true" }) |ft| { + const got = try paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": {s}}}", .{ png, ft })), facts, &fault); + try t.expect(got.source.kind == .image); + } + for ([_][]const u8{ "0", "0.0", "false" }) |ft| { + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": {s}}}", .{ png, ft })), facts, &fault)); + try t.expect(std.mem.indexOf(u8, fault.message, "fileType 0 names a PDF") != null); + } + for ([_][]const u8{ "\"1\"", "2.0", "0.5" }) |ft| { + try t.expectError(error.Faulted, paddlex.decode(a, try value(a, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": {s}}}", .{ png, ft })), facts, &fault)); + try t.expectEqualStrings("literal_error", (try issues(a, fault))[0].strField("type").?); + } + // a PDF is read to the page budget, never refused for its length + const r = try paddlex.decode(a, try value(a, "{\"file\": \"JVBERi0xLjQK\", \"fileType\": 0}"), .{ .pdf = true, .fetch = null }, &fault); + try t.expect(r.source.kind == .pdf); + try t.expectEqual(@as(u32, std.math.maxInt(u32)), r.source.sel.first); +} + +/// One page through the encoder as the page loop hands it over. +fn feed(e: *reply.Encoder, a: Allocator, blocks: []api.ocr.OcrBlock, w: u32, h: u32) !void { + return feedOf(e, a, blocks, w, h, 1); +} + +/// ``feed`` for a page of a ``doc_pages``-page document. +fn feedOf(e: *reply.Encoder, a: Allocator, blocks: []api.ocr.OcrBlock, w: u32, h: u32, doc_pages: u32) !void { + const page: types.OcrPage = .{ .index = 0, .width = w, .height = h, .dpi = 72, .blocks = blocks, .doc_pages = doc_pages }; + const rgb: picture.Rgb = .{ .width = w, .height = h, .pixels = try a.alloc(u8, @as(usize, w) * h * 3) }; + var enc = budget.Encodes.init(@as(u64, w) * h, 1); + var fault: types.Fault = undefined; + const s = e.sink(); + try s.page(s.ctx, a, 0, &page, rgb, &enc, &fault); +} + +test "ocr paddlex: prunedResult keys in PaddleX's order, rec_* filtered by the threshold, boxes from the polygons" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var blocks = [_]api.ocr.OcrBlock{ + .{ .content = "# Title", .quad = .{ .{ 10.4, 5 }, .{ 90.6, 5 }, .{ 90.6, 15 }, .{ 10.4, 15 } }, .kind = .title }, + .{ .content = "two words\nthird", .quad = .{ .{ 10, 20 }, .{ 90, 20 }, .{ 90, 40 }, .{ 10, 40 } }, .kind = .text }, + .{ .content = "", .quad = .{ .{ 0, 0 }, .{ 5, 0 }, .{ 5, 5 }, .{ 0, 5 } }, .kind = .picture }, + }; + var e: reply.Encoder = .{ .o = .{ .word_box = true, .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feed(&e, a, &blocks, 100, 50); + const pruned = e.results.items[0].get("prunedResult").?; + const order = [_][]const u8{ "model_settings", "dt_polys", "text_type", "textline_orientation_angles", "text_rec_score_thresh", "return_word_box", "rec_texts", "rec_scores", "rec_polys", "rec_boxes", "text_word_boxes", "text_word" }; + try t.expectEqual(order.len, pruned.object.count()); + for (pruned.object.keys(), order) |k, w| try t.expectEqualStrings(w, k); + try t.expect(e.results.items[0].get("ocrImage") == null and e.results.items[0].get("inputImage") == null); + const texts = pruned.get("rec_texts").?.array; + try t.expectEqual(@as(usize, 3), texts.len); + try t.expectEqualStrings("Title", texts[0].string); + try t.expectEqualStrings("two words", texts[1].string); + try t.expectEqual(@as(f64, 1.0), pruned.get("rec_scores").?.array[0].float); + // the corners round to nearest; rec_boxes is the min/max of the integer polygon + const out = try json.stringify(a, pruned.get("rec_polys").?.array[0], .{ .compact = true }); + try t.expectEqualStrings("[[10,5],[91,5],[91,15],[10,15]]", out); + try t.expectEqualStrings("[10,5,91,15]", try json.stringify(a, pruned.get("rec_boxes").?.array[0], .{ .compact = true })); + try t.expectEqualStrings("[[\"two\",\"words\"]]", try json.stringify(a, .{ .array = pruned.get("text_word").?.array[1..2] }, .{ .compact = true })); + try t.expectEqual(@as(usize, 2), pruned.get("text_word_boxes").?.array[1].array.len); + // a threshold above every score empties rec_* but keeps every detected line + var high: reply.Encoder = .{ .o = .{ .thresh = 1.5, .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feed(&high, a, &blocks, 100, 50); + const hp = high.results.items[0].get("prunedResult").?; + try t.expectEqual(@as(usize, 3), hp.get("dt_polys").?.array.len); + try t.expectEqual(@as(usize, 0), hp.get("rec_polys").?.array.len); + try t.expectEqual(@as(usize, 3), hp.get("textline_orientation_angles").?.array.len); + try t.expect(hp.get("text_word") == null and hp.get("dt_scores") == null); + // a page with no lines has empty lists and no orientation angles + var none: reply.Encoder = .{ .o = .{ .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feed(&none, a, blocks[2..], 100, 50); + const np = none.results.items[0].get("prunedResult").?; + try t.expect(np.get("textline_orientation_angles") == null); + try t.expectEqual(@as(usize, 0), np.get("rec_boxes").?.array.len); + // two PDF pages: dataInfo counts them and gives each size + try feed(&none, a, blocks[2..], 30, 20); + const pages = try value(a, try none.reply(a, "log", true)); + const info = pages.get("result").?.get("dataInfo").?; + try t.expectEqualStrings("2", info.get("numPages").?.int); + try t.expectEqualStrings("20", info.get("pages").?.array[1].get("height").?.int); + try t.expectEqualStrings("pdf", info.strField("type").?); + // a 5-page PDF cut to its first page: numPages is the document's count, pages and ocrResults the one read + var cut: reply.Encoder = .{ .o = .{ .visualize = false }, .geometry = .block, .gpa = t.allocator }; + try feedOf(&cut, a, blocks[2..], 30, 20, 5); + const cut_reply = (try value(a, try cut.reply(a, "log", true))).get("result").?; + try t.expectEqualStrings("5", cut_reply.get("dataInfo").?.get("numPages").?.int); + try t.expectEqual(@as(usize, 1), cut_reply.get("dataInfo").?.get("pages").?.array.len); + try t.expectEqual(@as(usize, 1), cut_reply.get("ocrResults").?.array.len); +} + +fn serve(h: *harness.Harness, replies: []const harness.Script) !void { + h.* = .{ .replies = replies }; + try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false }); +} + +/// A POST /ocr of ``body`` as PaddleX's clients send it; the reply as JSON, its status in ``status``. +fn post(a: Allocator, h: *harness.Harness, content_type: ?[]const u8, body: []const u8, status: *u16) !Value { + var wire: harness.Wire = .{ .a = a }; + routes.dispatch(h.srv, try harness.request(a, &wire, "/ocr", content_type, body), a); + status.* = wire.status(); + try t.expect(std.mem.indexOf(u8, wire.head(), "\r\nContent-Type: application/json\r\n") != null); + return wire.parsed(); +} + +test "ocr paddlex: a whole request answers with logId, errorCode 0 and the page's result" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = undefined; + try serve(&h, &.{ .{ .text = "title 10 5 90 10\n# Report\n;;\ntext 10 20 90 40\nBody" }, .{ .text = "text 0 0 10 10\nx" } }); + defer h.stop(); + const png = try harness.png(a, 200, 100); + const enc = std.base64.standard.Encoder; + const b64 = enc.encode(try a.alloc(u8, enc.calcSize(png.len)), png); + var status: u16 = 0; + const body = try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"fileType\": 1, \"visualize\": false, \"logId\": \"abc\"}}", .{b64}); + const r = try post(a, &h, "application/json; charset=utf-8", body, &status); + try t.expectEqual(@as(u16, 200), status); + try t.expectEqualStrings("abc", r.strField("logId").?); + try t.expectEqualStrings("0", r.get("errorCode").?.int); + try t.expectEqualStrings("Success", r.strField("errorMsg").?); + const result = r.get("result").?; + const pruned = result.get("ocrResults").?.array[0].get("prunedResult").?; + try t.expectEqualStrings("Report", pruned.get("rec_texts").?.array[0].string); + try t.expectEqualStrings("[20,10,180,20]", try json.stringify(a, pruned.get("rec_boxes").?.array[0], .{ .compact = true })); + const info = result.get("dataInfo").?; + try t.expectEqualStrings("200", info.get("width").?.int); + try t.expectEqualStrings("image", info.strField("type").?); + // an empty logId gets a fresh UUID v4; no Content-Type with a JSON body is PaddleX too + const again = try post(a, &h, null, try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"visualize\": false, \"logId\": \"\"}}", .{b64}), &status); + try t.expectEqual(@as(u16, 200), status); + const id = again.strField("logId").?; + try t.expectEqual(@as(usize, 36), id.len); + try t.expectEqual(@as(u8, '4'), id[14]); +} + +test "ocr paddlex: every failure is PaddleX's envelope: 422 for input, unreadable pages and the gate" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = undefined; + try serve(&h, &.{.{ .text = "!garbage" }}); + defer h.stop(); + const b64 = try pngField(a); + var status: u16 = 0; + const bad_json = try post(a, &h, "application/json", "{\"file\": ", &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("422", bad_json.get("errorCode").?.int); + try t.expectEqual(@as(usize, 36), bad_json.strField("logId").?.len); + const listed = try value(a, bad_json.strField("errorMsg").?); + try t.expectEqualStrings("json_invalid", listed.array[0].strField("type").?); + try t.expect(std.mem.startsWith(u8, listed.array[0].strField("msg").?, "the body is not valid JSON: ")); + const knob = try post(a, &h, "application/json", try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"logId\": \"L\", \"useDocUnwarping\": true}}", .{b64}), &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("L", knob.strField("logId").?); + try t.expectEqualStrings("body.useDocUnwarping", (try value(a, knob.strField("errorMsg").?)).array[0].strField("loc").?); + const page = try post(a, &h, "application/json", try std.fmt.allocPrint(a, "{{\"file\": \"{s}\", \"logId\": \"P\"}}", .{b64}), &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("page 0: the model's output does not follow its format", page.strField("errorMsg").?); + h.srv.info.ocr = null; + const gated = try post(a, &h, "application/json", "{\"logId\": \"G\"}", &status); + try t.expectEqual(@as(u16, 422), status); + try t.expectEqualStrings("G", gated.strField("logId").?); + try t.expectEqualStrings("this model has no OCR reader; use POST /v1/chat/completions", gated.strField("errorMsg").?); +} + +test "ocr paddlex: a capacity fault is 503 with Retry-After, an internal one 500" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_]struct { types.Class, u16 }{ .{ .capacity, 503 }, .{ .internal, 500 } }) |c| { + var wire: harness.Wire = .{ .a = a }; + reply.sendFault(try harness.request(a, &wire, "/ocr", null, ""), a, "id", .{ .class = c[0], .message = "m", .retry_after = 1 }); + try t.expectEqual(c[1], wire.status()); + try t.expectEqual(c[0] == .capacity, std.mem.indexOf(u8, wire.head(), "\r\nRetry-After: 1\r\n") != null); + try t.expectEqualStrings(try std.fmt.allocPrint(a, "{d}", .{c[1]}), (try wire.parsed()).get("errorCode").?.int); + } +} + +test "ocr paddlex: by default ocrImage and inputImage are base64 JPEGs of the page" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var h: harness.Harness = undefined; + try serve(&h, &.{.{ .text = "text 10 5 90 10\nLine" }}); + defer h.stop(); + var status: u16 = 0; + const r = try post(a, &h, "application/json", try std.fmt.allocPrint(a, "{{\"file\": \"{s}\"}}", .{try pngField(a)}), &status); + if (status == 500) { // only a host without the pinned libjpeg-turbo skips + try t.expect(std.mem.indexOf(u8, r.strField("errorMsg").?, "libjpeg-turbo") != null); + return error.SkipZigTest; + } + try t.expectEqual(@as(u16, 200), status); + const res = r.get("result").?.get("ocrResults").?.array[0]; + try t.expectEqualStrings("prunedResult", res.object.keys()[0]); + for ([_][]const u8{ "ocrImage", "inputImage" }) |k| { + const b64 = res.strField(k).?; + const bytes = try a.alloc(u8, try std.base64.standard.Decoder.calcSizeForSlice(b64)); + try std.base64.standard.Decoder.decode(bytes, b64); + try t.expectEqual(picture.Format.jpeg, picture.sniff(bytes)); + } +} diff --git a/zig/src/server/ocr/route.zig b/zig/src/server/ocr/route.zig index e307041e18f..c41ceac212c 100644 --- a/zig/src/server/ocr/route.zig +++ b/zig/src/server/ocr/route.zig @@ -13,10 +13,11 @@ const mistral = @import("mistral.zig"); const mistral_reply = @import("mistral_reply.zig"); const doctr = @import("doctr.zig"); const liteparse = @import("liteparse.zig"); +const paddlex = @import("paddlex.zig"); const run = @import("run.zig"); /// The client contracts POST /ocr answers in. -pub const Dialect = enum { doctr, liteparse }; +pub const Dialect = enum { paddlex, doctr, liteparse }; /// A chosen dialect, with the multipart parts when choosing it parsed them. pub const Selected = struct { dialect: Dialect, parts: ?[]const multipart.Part = null }; @@ -50,6 +51,7 @@ pub fn post(srv: *Server, conn: *Conn, a: Allocator, route: []const u8) void { /// Runs the chosen dialect, which gates the request and answers in its own error shape. fn dialect(srv: *Server, conn: *Conn, a: Allocator, s: Selected, body: []const u8, gone: openai.Gone) void { switch (s.dialect) { + .paddlex => paddlex.post(srv, conn, a, body, gone), .doctr => doctr.post(srv, conn, a, s.parts, body, gone), .liteparse => liteparse.post(srv, conn, a, s.parts, conn.header("Content-Type"), body, gone), } @@ -63,14 +65,20 @@ pub fn select(a: Allocator, raw_path: []const u8, content_type: ?[]const u8, bod error.Repeated => return refuse(400, "the format query parameter is repeated; send it once"), }; if (format) |f| { - const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be doctr or liteparse"); + const d = std.meta.stringToEnum(Dialect, f) orelse return refuse(400, "format must be paddlex, doctr or liteparse"); return .{ .ok = .{ .dialect = d } }; } const ct = std.mem.trim(u8, content_type orelse "", " \t"); - if (ct.len == 0) return refuse(415, "the request has no Content-Type; send multipart/form-data (docTR, LiteParse)"); + if (ct.len == 0) { + const first = std.mem.trimStart(u8, body, " \t\r\n"); + if (first.len > 0 and first[0] == '{') return .{ .ok = .{ .dialect = .paddlex } }; + return refuse(415, "the request has no Content-Type; send JSON (PaddleX) or multipart/form-data (docTR, LiteParse)"); + } const media = std.mem.trim(u8, ct[0 .. std.mem.indexOfScalar(u8, ct, ';') orelse ct.len], " \t"); + if (std.ascii.eqlIgnoreCase(media, "application/json") or (std.ascii.startsWithIgnoreCase(media, "application/") and std.ascii.endsWithIgnoreCase(media, "+json"))) + return .{ .ok = .{ .dialect = .paddlex } }; if (!std.ascii.eqlIgnoreCase(media, "multipart/form-data")) - return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send multipart/form-data (docTR, LiteParse)", .{media})); + return refuse(415, try std.fmt.allocPrint(a, "unsupported Content-Type {s}; send JSON (PaddleX) or multipart/form-data (docTR, LiteParse)", .{media})); const bound = multipart.boundary(ct) orelse return refuse(400, "multipart/form-data needs a boundary parameter"); const parts = multipart.parse(a, body, bound) catch |e| switch (e) { error.OutOfMemory => return error.OutOfMemory, diff --git a/zig/src/server/ocr/route_test.zig b/zig/src/server/ocr/route_test.zig index bfb1fe493c4..c98f8d5b4d6 100644 --- a/zig/src/server/ocr/route_test.zig +++ b/zig/src/server/ocr/route_test.zig @@ -27,8 +27,10 @@ test "ocr route: the format query, then the media type, then the part names choo .{ .path = "/ocr?format=tesseract", .ct = "application/json", .want = null, .status = 400 }, .{ .path = "/ocr?format=%zz", .ct = "application/json", .want = null, .status = 400 }, .{ .path = "/ocr?format=liteparse&format=liteparse", .ct = form, .want = null, .status = 400 }, - .{ .ct = "application/json", .want = null, .status = 415 }, - .{ .ct = null, .body = " {\"file\": \"x\"}", .want = null, .status = 415 }, + .{ .ct = "application/json", .want = .paddlex }, + .{ .ct = "Application/JSON; charset=utf-8", .want = .paddlex }, + .{ .ct = "application/vnd.paddle+json", .want = .paddlex }, + .{ .ct = null, .body = " {\"file\": \"x\"}", .want = .paddlex }, .{ .ct = null, .body = "file=x", .want = null, .status = 415 }, .{ .ct = "text/plain", .want = null, .status = 415 }, .{ .ct = form, .body = try parts(a, &.{ "files", "files" }), .want = .doctr }, @@ -42,7 +44,7 @@ test "ocr route: the format query, then the media type, then the part names choo for (cases) |c| switch (try route.select(a, c.path, c.ct, c.body)) { .ok => |s| { try t.expectEqual(c.want, s.dialect); - if (c.status == 0 and c.body.len > 0) try t.expect(s.parts != null); + if (s.dialect != .paddlex and c.status == 0 and c.body.len > 0) try t.expect(s.parts != null); }, .refused => |r| { try t.expectEqual(@as(?route.Dialect, null), c.want); @@ -113,7 +115,7 @@ fn expectGated(a: std.mem.Allocator, h: *harness.Harness, says: []const u8) !voi const cases = [_]struct { []const u8, ?[]const u8 }{ .{ "/ocr", "text/csv" }, .{ "/ocr", null }, .{ "/ocr?format=x", form } }; for (cases) |c| { var wire: harness.Wire = .{ .a = a }; - routes.dispatch(h.srv, try harness.request(a, &wire, c[0], c[1], "{}"), a); + routes.dispatch(h.srv, try harness.request(a, &wire, c[0], c[1], "x=1"), a); try t.expectEqual(@as(u16, 400), wire.status()); try t.expectEqualStrings(says, (try wire.parsed()).get("error").?.strField("message").?); } diff --git a/zig/src/server/ocr/run.zig b/zig/src/server/ocr/run.zig index b3fe2bba3f0..e8a1011a642 100644 --- a/zig/src/server/ocr/run.zig +++ b/zig/src/server/ocr/run.zig @@ -55,7 +55,7 @@ pub fn gate(srv: *const Server, a: Allocator, fault: *Fault) Step!void { /// Where a page's encoded image comes from: an image source's bytes, or a measured PDF page rendered just before use. const Origin = union(enum) { image: []const u8, pdf: struct { bytes: []const u8, width: u32, height: u32 } }; /// One page to read: its source, its index in that source, where its image comes from, its DPI and its pixel count. -const Planned = struct { source: u32, index: u32, origin: Origin, dpi: u32, pixels: u64 }; +const Planned = struct { source: u32, index: u32, origin: Origin, dpi: u32, pixels: u64, doc_pages: u32 = 1 }; /// Reads every page of ``sources`` in order into ``sink``; ``a`` is the request arena, ``gone`` says the client left. pub fn run(srv: *Server, a: Allocator, sources: []const Source, sink: PageSink, fault: *Fault, gone: anytype) Step!void { @@ -113,7 +113,7 @@ fn plan(srv: *const Server, a: Allocator, sources: []const Source, fault: *Fault if (!left.take(@intCast(r.pages.len))) return overBudget(a, fault, cap); for (r.pages) |p| { const origin: Origin = .{ .pdf = .{ .bytes = s.bytes, .width = p.width, .height = p.height } }; - try out.append(a, .{ .source = source, .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height }); + try out.append(a, .{ .source = source, .index = p.index, .origin = origin, .dpi = p.dpi, .pixels = @as(u64, p.width) * p.height, .doc_pages = r.total }); } }, } @@ -193,7 +193,7 @@ fn onePage(srv: *Server, a: Allocator, reader: api.ocr.Ocr, id: []const u8, p: P } else null; o.* = .{ .content = try a.dupe(u8, b.content), .quad = quad, .kind = b.kind }; } - const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks }; + const page: OcrPage = .{ .index = p.index, .width = w, .height = h, .dpi = p.dpi, .blocks = blocks, .doc_pages = p.doc_pages }; try sink.page(sink.ctx, a, p.source, &page, rgb, enc, fault); } diff --git a/zig/src/server/ocr/run_pdf_test.zig b/zig/src/server/ocr/run_pdf_test.zig index 9af320e3841..457cb095944 100644 --- a/zig/src/server/ocr/run_pdf_test.zig +++ b/zig/src/server/ocr/run_pdf_test.zig @@ -47,6 +47,7 @@ const Order = struct { calls: std.ArrayList(u32) = .empty, indices: std.ArrayList(u32) = .empty, widths: std.ArrayList(u32) = .empty, + doc_pages: std.ArrayList(u32) = .empty, fn sink(o: *Order) run.PageSink { return .{ .ctx = o, .page = page }; } @@ -59,6 +60,7 @@ const Order = struct { try o.calls.append(a, calls); try o.indices.append(a, p.index); try o.widths.append(a, @intCast(rgb.width)); + try o.doc_pages.append(a, p.doc_pages); } }; @@ -83,11 +85,14 @@ test "ocr run: PDF pages are measured first, and page k renders only after page try tmp.dir.writeFile(t.io, .{ .sub_path = "reply0.bin", .data = try frame(a, &.{ 0, 1 }, "") }); try tmp.dir.writeFile(t.io, .{ .sub_path = "reply1.bin", .data = try frame(a, &.{0}, jpeg) }); try tmp.dir.writeFile(t.io, .{ .sub_path = "reply2.bin", .data = try frame(a, &.{1}, jpeg) }); + // then the same document cut to its first page: call 3 measures page 0 of 2, call 4 renders it + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply3.bin", .data = try frame(a, &.{0}, "") }); + try tmp.dir.writeFile(t.io, .{ .sub_path = "reply4.bin", .data = try frame(a, &.{0}, jpeg) }); try tmp.dir.writeFile(t.io, .{ .sub_path = "worker", .data = script, .flags = .{ .permissions = .fromMode(0o755) } }); const saved = worker.server_exe; defer worker.server_exe = saved; worker.server_exe = try std.fs.path.join(a, &.{ try tmp.dir.realPathFileAlloc(t.io, ".", a), "worker" }); - var h: harness.Harness = .{ .replies = &.{ .{ .text = "text 0 0 10 10\na" }, .{ .text = "text 0 0 10 10\nb" } } }; + var h: harness.Harness = .{ .replies = &.{ .{ .text = "text 0 0 10 10\na" }, .{ .text = "text 0 0 10 10\nb" }, .{ .text = "text 0 0 10 10\nc" } } }; try h.start(.{ .served_name = "m", .model_ids = &.{"m"}, .enable_thinking = false, .use_drafts = false, .vision_pdf = true }); defer h.stop(); var order: Order = .{ .dir = tmp.dir }; @@ -101,5 +106,13 @@ test "ocr run: PDF pages are measured first, and page k renders only after page try t.expectEqualSlices(u32, &.{ 400, 400 }, order.widths.items); // page 0's sink saw the measure and its own render only; page 1 rendered after it returned try t.expectEqualSlices(u32, &.{ 2, 3 }, order.calls.items); + try t.expectEqualSlices(u32, &.{ 2, 2 }, order.doc_pages.items); try t.expectEqual(@as(usize, 2), h.next); + // a cut document reads its first page and still reports both pages to the sink + var cut: Order = .{ .dir = tmp.dir }; + const first: types.Source = .{ .name = "d", .bytes = pdf.minimal_two_page_pdf, .kind = .pdf, .sel = .{ .first = 1 } }; + try run.run(h.srv, a, &.{first}, cut.sink(), &fault, Gone{}); + try t.expectEqualSlices(u32, &.{0}, cut.indices.items); + try t.expectEqualSlices(u32, &.{2}, cut.doc_pages.items); + try t.expectEqual(@as(usize, 3), h.next); } diff --git a/zig/src/server/ocr/types.zig b/zig/src/server/ocr/types.zig index 6d3fd5dae4e..be3453b4c53 100644 --- a/zig/src/server/ocr/types.zig +++ b/zig/src/server/ocr/types.zig @@ -12,6 +12,7 @@ pub const OcrPage = struct { height: u32, dpi: u32, // render DPI of a PDF page; 72 for an image blocks: []api.ocr.OcrBlock, // validated, reading order + doc_pages: u32 = 1, // pages in the source document, read or not; 1 for an image }; /// One plain-text line of a page, never empty; ``block`` is the index of its source block. diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 7e403bb6fc7..23dc26dc988 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -384,6 +384,7 @@ test { _ = @import("ocr/markdown_test.zig"); _ = @import("ocr/lines_test.zig"); _ = @import("ocr/budget_test.zig"); + _ = @import("ocr/draw_test.zig"); _ = @import("ocr/page_markdown_test.zig"); _ = @import("ocr/mistral_test.zig"); _ = @import("ocr/mistral_sdk_test.zig"); @@ -393,6 +394,7 @@ test { _ = @import("ocr/size_test.zig"); _ = @import("ocr/doctr_test.zig"); _ = @import("ocr/liteparse_test.zig"); + _ = @import("ocr/paddlex_test.zig"); _ = @import("ocr/prompt_ids_test.zig"); _ = @import("ollama_e2e_test.zig"); _ = @import("open_connections_route_test.zig"); From a7151ef4b8f3a2d264e7bd250c76bd3ce16c617f Mon Sep 17 00:00:00 2001 From: laudney <106273+laudney@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:14:44 +0000 Subject: [PATCH 251/361] docs(ocr): document POST /ocr in PaddleX's contract The API guide adds PaddleX to the /ocr contract choice: JSON bodies, its 422 failures and envelope, PaddleX file URLs, the reading of a PDF to the page budget with a link to the PaddleX page that defines the cut, visualisations in the image budget and their libjpeg-turbo need, word boxes, and the PaddleX section with its fields, key order and dataInfo, whose numPages is the document's page count while pages lists the pages read; the changelog stays with the maintainer. --- docs/api.md | 89 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/docs/api.md b/docs/api.md index dc4b4c4f2e8..942a082f32e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -275,12 +275,13 @@ context-window check still applies. Cohere-style requests retain the reranker's ## OCR -The native HIP engine reads pages through three OCR contracts when it serves a model with an OCR reader and -`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers two more, chosen from the request. +The native HIP engine reads pages through four OCR contracts when it serves a model with an OCR reader and +`--vision`. One route answers Mistral's contract; `/ocr` (and `/ocr/`) answers three more, chosen from the request. | Route | Contract | Request | Reply | Written for | | --- | --- | --- | --- | --- | | `POST /v1/ocr` | Mistral OCR | JSON `{"model", "document", ...}` | `{"pages", "model", "document_annotation", "usage_info"}` | the `mistralai` Python and `@mistralai/mistralai` TypeScript SDKs, with `server_url` set to the server root | +| `POST /ocr` | PaddleX OCR serving | JSON `{"file", "fileType", ...}` | `{"logId", "errorCode", "errorMsg", "result"}` | the PaddleX serving clients | | `POST /ocr` | docTR API | multipart, one or more `files` parts, options in the query | one `OCROut` a page | the docTR API template's client | | `POST /ocr` | LiteParse HTTP OCR | multipart, one `file` part | `{"results": [...]}` | `lit parse --ocr-server-url http://HOST:PORT/ocr` | @@ -293,18 +294,21 @@ orientation), never in the model's resized frame. | GLM-OCR | the page's Markdown as one block, tables as pipe tables or spanned HTML | none | Any other model answers both routes with HTTP 400 "this model has no OCR reader; use POST /v1/chat/completions", -and a server started without `--vision` answers "OCR needs image input; start the server with --vision". -Embedding, reranker and readout engines refuse the OCR routes as they refuse chat. The routes take the -`inference` key scope. +and a server started without `--vision` answers "OCR needs image input; start the server with --vision" (PaddleX +answers both with 422). Embedding, reranker and readout engines refuse the OCR routes as they refuse chat. The +routes take the `inference` key scope. `POST /ocr` picks its contract in this order: -1. `?format=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format query parameter is - repeated; send it once", and the same for docTR's parameters), because servers differ on which copy wins. -2. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse; +1. `?format=paddlex`, `?format=doctr` or `?format=liteparse`. A query parameter sent twice is HTTP 400 ("the format + query parameter is repeated; send it once", and the same for docTR's parameters), because servers differ on + which copy wins. +2. `Content-Type` `application/json` or `application/*+json` (parameters such as `charset` ignored), or no + `Content-Type` with a body whose first non-space byte is `{`: PaddleX. +3. `multipart/form-data`: one or more parts named `files` is docTR; exactly one part named `file` is LiteParse; any other set of parts is HTTP 400, and so is a body with both `files` and `file` parts, even when `?format=` names the contract. -3. Any other content type, or none, is HTTP 415. +4. Any other content type is HTTP 415. Refusals made before the contract is known (415, those 400s, a drain's 503 and an admission 429 with `Retry-After`) use the server's `{"error": {"message", "type"}}` envelope. On a model without a reader, or a @@ -334,15 +338,20 @@ Both readers write block text in one Markdown flavour, the one Mistral's page Ma page's size, with no rendering), so a page index out of range, the page budget or a page that does not load fails before any GPU work. Each page is then rendered just before it is read and freed when it is done, so one rendered page is in memory at a time; a page that loads but does not render fails the request when it is reached. -- `https://` URLs (`document_url` and `image_url`) are fetched only with `--vision-urls`: images, and PDFs when - `--vision-pdf` is on, at most 32 MiB. `http://` URLs are refused. +- `https://` URLs (Mistral `document_url` and `image_url`, PaddleX `file`) are fetched only with `--vision-urls`: + images, and PDFs when `--vision-pdf` is on, at most 32 MiB. `http://` URLs are refused. - Page budget: images count one page each and PDFs their selected pages; a request reads at most `TENSORFOLD_MAX_PDF_PAGES` pages (default 16, also the most it may be set to). `--vision-max-images` does not - apply. Over the budget, a request is refused before any inference. -- Image budget, for Mistral crops (`include_image_base64`): at most 256 encoded images, 4 times the request's page - pixels, and 16 MiB plus 2 MiB a page of encoded bytes. Crossing one fails the whole request as an unreadable - page, "too many image regions". The encode needs libjpeg-turbo 3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG` names its - file); without it `include_image_base64` is HTTP 400. + apply. Over the budget, a request is refused before any inference, except in PaddleX, which reads the first + pages of a PDF up to the budget, as [PaddleX's OCR serving API](https://paddlepaddle.github.io/PaddleX/latest/en/pipeline_usage/tutorials/ocr_pipelines/OCR.html) + reads the first `max_num_input_imgs` pages. `ocrResults` and `dataInfo.pages` list the pages read, and + `dataInfo.numPages` is the document's page count, so a client can see the cut. +- Image budget, for Mistral crops (`include_image_base64`) and PaddleX's `ocrImage` and `inputImage`: at most 256 + encoded images, 4 times the request's page pixels, and 16 MiB plus 2 MiB a page of encoded bytes. Crossing one + fails the whole request as an unreadable page, "too many image regions". Both encodes need libjpeg-turbo + 3.1.4.1 (`TENSORFOLD_LIBTURBOJPEG` names its file); without it `include_image_base64` is HTTP 400 and PaddleX's + default `visualize` is HTTP 500 "visualize needs libjpeg-turbo, which this server cannot load; send visualize: + false". Pages are read one at a time, each as one user turn (the page image, then the reader's prompt), greedy, with thinking off and `max_tokens` equal to all the context the prompt leaves. A page succeeds only when the reply @@ -350,13 +359,13 @@ stops on its end token and the reader can parse it. ### Failures -| Failure | Mistral | docTR | LiteParse | -| --- | --- | --- | --- | -| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 400 | 400 | -| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | 422 | 422 | -| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | -| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 | -| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"detail": "..."}` | `{"error": "..."}` | +| Failure | Mistral | PaddleX | docTR | LiteParse | +| --- | --- | --- | --- | --- | +| Bad input: an undecodable or unsupported file, a page or option the server cannot serve, over the page budget | 400 | 422 | 400 | 400 | +| Unreadable page: the reply was cut at the context limit, repeated without end, broke the model's format or gave a box that is not finite; the image budget was crossed | 422 | 422 | 422 | 422 | +| The engine stopped the page (it closed or drained) | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | 503, `Retry-After: 1` | +| Engine fault, out of memory, PDF renderer crash or deadline | 500 | 500 | 500 | 500 | +| Envelope | `{"detail": [{"loc", "msg", "type"}]}`, `type` `bad_input`, `unreadable_page`, `capacity` or `internal` | `{"logId", "errorCode", "errorMsg"}`, `errorCode` equal to the status | `{"detail": "..."}` | `{"error": "..."}` | A failed page fails the whole request: no reply returns some pages and drops others. An unreadable page's message names its index, and the model's raw text goes to the server log, never to the client. 422 means the @@ -370,12 +379,12 @@ dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate - **Lines.** A block's plain-text lines (Markdown markup removed, a table one line a row with tab-separated cells, math without its `$`) divide the block's box into equal bands along its left and right edges, first line at the top. A paragraph written without line breaks stays one line covering the block. -- **Words.** docTR's words divide a line's box along its reading direction in proportion to each word's character - count. -- **Scores.** Every score is `1.0`: docTR `confidence` and `objectness_score`, LiteParse `confidence`. Mistral - replies leave `confidence_scores` out. -- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, docTR gives each line the whole page as its box, and - LiteParse is refused. +- **Words.** docTR's words and PaddleX's `returnWordBox` divide a line's box along its reading direction in + proportion to each word's character count. +- **Scores.** Every score is `1.0`: PaddleX `rec_scores`, docTR `confidence` and `objectness_score`, LiteParse + `confidence`. Mistral replies leave `confidence_scores` out. +- **No geometry.** With GLM-OCR, Mistral returns `blocks: []`, PaddleX and docTR give each line the whole page as + its box, and LiteParse is refused. ### Mistral: `POST /v1/ocr` @@ -399,6 +408,28 @@ dots.mocr gives one box a block and GLM-OCR none, so the line contracts estimate `content`, its own Markdown with its tables in the `table_format` form; image blocks add `image_id` and table blocks `table_id`. `usage_info` gives `pages_processed` and `doc_size_bytes`, the decoded document's size. +### PaddleX: `POST /ocr` + +`file` is base64 (bytes outside the alphabet are skipped and the padding is repaired, as Python's `b64decode` +does), a `data:` URL or an `https://` URL. `fileType` is `0` for a PDF and `1` for an image; when it is absent the +bytes decide. TIFF is not read. `logId` is echoed by every reply once the body parses; an absent or empty one gets +a new UUID. Each field converts as pydantic's lax mode converts the type PaddleX's serving reference gives it (`"0.5"` is a +number, `"off"` and `0` are false), and a number must be finite. + +| Field | Meaning | +| --- | --- | +| `textRecScoreThresh` | Keep lines with a score at or above it in `rec_*`; `dt_polys` keeps every line. Default `0.0` | +| `returnWordBox` | Add `text_word_boxes` and `text_word`, each line's estimated words | +| `visualize` | Default `true`: `inputImage` (the page) and `ocrImage` (the page with each `rec_polys` polygon outlined), base64 JPEG without a data-URL prefix. `false` leaves both out | +| `useDocOrientationClassify`, `useDocUnwarping`, `useTextlineOrientation` | Accepted when null or false; `true` is 422 | +| `textDetLimitSideLen`, `textDetLimitType`, `textDetThresh`, `textDetBoxThresh`, `textDetUnclipRatio` | Accepted when null; any value is 422, since TensorFold has no text detector to apply it to | + +`prunedResult` leaves out `text_det_params` and `doc_preprocessor_res`. Polygons +round each corner half to even, as Python does; `rec_boxes` is each polygon's min/max. `dataInfo` is +`{"width", "height", "type": "image"}` or `{"numPages", "pages": [{"width", "height"}], "type": "pdf"}`, where +`numPages` is the document's page count and `pages`, like `ocrResults`, lists the pages read. A schema error's +`errorMsg` is the JSON list `[{"type", "loc", "msg"}]` with `loc` dot-joined (`body.file`). + ### docTR: `POST /ocr` Each `files` part's type must be exactly `image/jpeg`, `image/png` or `application/pdf` (the types docTR's API README names), From a15c7b0603dbcc5143b0dea701bc492bbd1ed7bc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:57:25 +0000 Subject: [PATCH 252/361] changelog: #2575 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 453161804fe..1e26d18f1fd 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 +- OCR: `POST /ocr` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575). + - XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#4651, refs #2543). - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_CHECK=1` (default off) runs a boot self-check that measures the widest verify window whose every row's scores equal its one-token step on that machine, and a lone stream's copy window then grows past the shipped 32 rows to at most the 48 the pending-row log holds; a check that cannot run, fails or proves nothing past 32 leaves the window at 32, and with the switch off every buffer the window sizes is main's (#4075). Thanks to @BadAd84. From 40bf172c45cb7d7d4b2dd9745418c155807e559a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:17:17 +0000 Subject: [PATCH 253/361] server inkling2: required calls take the template's own per-message form Inkling 2's chat template writes every tool call as its own model message, <|message_model|>NAME<|content_invoke_tool_json|>{"name":NAME,"args":{...}} <|end_message|>, back to back, and ends the turn with its end of sampling. The required-tool grammar instead forced the generic {...} envelope with blanks between calls, a form the model was not trained on. Unconstrained, its top choice after each is a newline, so a two-call request kept calling to the cap. With the native Inkling 2 template, a required or named call now compiles a grammar in that per-message form: one call message, or with parallel calls one or more, the grammar's stop being the end of sampling. It is compiled on the shared compiler, whose stops are the eos ids alone, since the end of message is now part of each call. The generic grammar, its compiler and the complete-call stop are unchanged for every other case; auto, plain and JSON-schema requests and every other family are untouched. Whether the grammar library lets a grammar constant match Inkling 2's special tokens is checked by a probe that skips without the library. --- zig/src/server/inkling2_chat_test.zig | 9 +- .../server/inkling2_native_required_test.zig | 99 +++++++++++++++++++ zig/src/server/inkling2_required_test.zig | 1 + zig/src/server/inkling2_stop_test.zig | 3 +- zig/src/server/tool_grammar.zig | 25 ++++- zig/src/server/tool_grammar_inkling.zig | 55 +++++++++++ 6 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 zig/src/server/inkling2_native_required_test.zig create mode 100644 zig/src/server/tool_grammar_inkling.zig diff --git a/zig/src/server/inkling2_chat_test.zig b/zig/src/server/inkling2_chat_test.zig index 9c12a5133b3..80a5636b526 100644 --- a/zig/src/server/inkling2_chat_test.zig +++ b/zig/src/server/inkling2_chat_test.zig @@ -128,11 +128,14 @@ pub const Seen = struct { grammars: usize = 0, // grammars the shared compiler compiled (ends: the eos ids) tool_grammars: usize = 0, // grammars the required-call compiler compiled (ends: eos and the end of message) token_ids: []const u8 = "", // the tensorfold block's token_ids, as JSON, when the request asked for them + grammar: []const u8 = "", // the shared compiler's last grammar text }; /// Grammars accepted as compiled, with no grammar library: the route attaches them, the script ignores them. const Grammars = struct { compiled: usize = 0, + text: [16384]u8 = undefined, // the last grammar's text, cut at the buffer + len: usize = 0, fn compiler(g: *Grammars) api.grammar.Compiler { var out: api.grammar.Compiler = undefined; out.h = g; @@ -142,9 +145,11 @@ const Grammars = struct { out.f.close = free; return out; } - fn compile(ptr: *anyopaque, _: c_int, _: [*]const u8, _: usize, _: [*]u8, _: usize) callconv(.c) ?*anyopaque { + fn compile(ptr: *anyopaque, _: c_int, text: [*]const u8, len: usize, _: [*]u8, _: usize) callconv(.c) ?*anyopaque { const g: *Grammars = @ptrCast(@alignCast(ptr)); g.compiled += 1; + g.len = @min(len, g.text.len); + @memcpy(g.text[0..g.len], text[0..g.len]); return ptr; } fn free(_: *anyopaque) callconv(.c) void {} @@ -265,7 +270,7 @@ fn runMode(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: [] if (d.get("text")) |c| if (c == .string) try content.appendSlice(a, c.string); if (d.get("tool_calls")) |calls| if (calls == .array) for (calls.array) |call| try appendCall(a, call, &ids, &names, &arguments); } - return .{ .reasoning = reasoning.items, .content = content.items, .ids = ids.items, .names = names.items, .arguments = arguments.items, .rejected = rejected, .finish = finish, .usage = usage, .kept = kept, .eos_len = script.eos_len, .grammars = grammars.compiled, .tool_grammars = tool_grammars.compiled, .token_ids = token_ids }; + return .{ .reasoning = reasoning.items, .content = content.items, .ids = ids.items, .names = names.items, .arguments = arguments.items, .rejected = rejected, .finish = finish, .usage = usage, .kept = kept, .eos_len = script.eos_len, .grammars = grammars.compiled, .tool_grammars = tool_grammars.compiled, .token_ids = token_ids, .grammar = try a.dupe(u8, grammars.text[0..grammars.len]) }; } pub fn ask(a: std.mem.Allocator, kind: []const u8, reply: []const u32, extra: []const u8, stream: bool, stride: usize) !Seen { diff --git a/zig/src/server/inkling2_native_required_test.zig b/zig/src/server/inkling2_native_required_test.zig new file mode 100644 index 00000000000..ea556183028 --- /dev/null +++ b/zig/src/server/inkling2_native_required_test.zig @@ -0,0 +1,99 @@ +//! Inkling 2's required calls under its native per-message grammar: the route, and the grammar library's own masks. +const std = @import("std"); +const json = @import("json"); +const api = @import("engine_api"); +const h = @import("inkling2_chat_test.zig"); +const inkling = @import("tool_grammar_inkling.zig"); +const t = std.testing; + +const required = h.lookup ++ ",\"tool_choice\":\"required\",\"return_token_ids\":true"; +const eos: u32 = 2; // the fixture's end of sampling (generation_config.json) + +inline fn message(comptime q: []const u8) []const u8 { + return inkling.open ++ "lookup" ++ inkling.invoke ++ "{\"name\":\"lookup\",\"args\":{\"q\":\"" ++ q ++ "\"}}" ++ inkling.end; +} + +/// Native call messages ended by the end of sampling, whole and at every stride: names, arguments, finish and grammar. +fn expectCalls(a: std.mem.Allocator, raw: []const u8, comptime extra: []const u8, names: []const u8, arguments: []const u8, star: bool) !void { + const reply = try std.mem.concat(a, u32, &.{ try h.encodeReply(a, raw), &.{eos} }); + for ([_]usize{ 0, 1, 2, 3, 256 }) |stride| { + const got = try h.ask(a, "release", reply, required ++ extra, stride > 0, @max(stride, 1)); + try t.expectEqualStrings(names, got.names); + try t.expectEqualStrings(arguments, got.arguments); + try t.expectEqualStrings("tool_calls", got.finish); + // the template's own call form on the shared compiler, whose stops are the eos ids alone + try t.expectEqual(@as(usize, 1), got.grammars); + try t.expectEqual(@as(usize, 0), got.tool_grammars); + try t.expect(std.mem.indexOf(u8, got.grammar, inkling.open ++ "lookup" ++ inkling.invoke) != null); + try t.expect(std.mem.indexOf(u8, got.grammar, "") == null); + try t.expectEqual(star, std.mem.indexOf(u8, got.grammar, "\"type\":\"star\"") != null); + } +} + +test "Inkling 2 reply: a required request takes the native grammar; two call messages give two calls" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try expectCalls(a, message("Paris") ++ message("Tokyo"), "", "lookuplookup", "{\"q\":\"Paris\"}{\"q\":\"Tokyo\"}", true); +} + +test "Inkling 2 reply: one and three native call messages, parallel calls on and off" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try expectCalls(a, message("x"), "", "lookup", "{\"q\":\"x\"}", true); + try expectCalls(a, message("x") ++ message("y") ++ message("z"), "", "lookuplookuplookup", "{\"q\":\"x\"}{\"q\":\"y\"}{\"q\":\"z\"}", true); + try expectCalls(a, message("x"), ",\"parallel_tool_calls\":false", "lookup", "{\"q\":\"x\"}", false); +} + +/// The fixture's real tokenizer (Inkling 2's special tokens at their ids) and its logits width. +fn tokenizer(a: std.mem.Allocator) !struct { text: []const u8, vocab: u32 } { + const at = "zig/src/families/inkling2/fixtures/"; + const text = try std.Io.Dir.cwd().readFileAlloc(t.io, at ++ "mini_tokenizer.json", a, .limited(1 << 26)); + const config = (try json.parseText(a, try std.Io.Dir.cwd().readFileAlloc(t.io, at ++ "mini_config.json", a, .limited(1 << 20)))).ok; + const vocab = config.get("text_config").?.get("vocab_size").?; + return .{ .text = text, .vocab = try std.fmt.parseInt(u32, vocab.int, 10) }; +} + +fn allowed(words: []const u32, id: u32) bool { + return words[id / 32] >> @intCast(id % 32) & 1 == 1; +} + +// The grammar library decides whether a constant may spell a special token; this host has none, so the test skips. +test "Inkling 2 reply: probe, the grammar library opens a native reply on <|message_model|> and ends it at the end of sampling" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tok = try tokenizer(a); + const end_sampling: u32 = 200006; + var err: [512]u8 = undefined; + var c = api.grammar.Compiler.open(t.io, a, tok.text, tok.vocab, &.{end_sampling}, &err) catch |e| switch (e) { + error.NoGrammarLibrary => return error.SkipZigTest, + else => return e, + }; + defer c.close(); + const tools = (try json.parse(a, "[" ++ h.lookup[",\"tools\":[".len..])).ok; + const g = try c.compile(t.io, .structural_tag, try inkling.build(a, tools.array, true), &err); + defer g.free(); + const m = try g.matcher(); + const r = m.rules(); + defer r.vtable.free(r.ptr); + const words = try a.alloc(u32, c.words); + const ids = try h.encodeReply(a, message("x") ++ message("y")); + const model: u32 = 200001; + try t.expectEqual(model, ids[0]); + // the one-token probe: the reply's first token may be <|message_model|>, and nothing generic is + try r.vtable.fill(r.ptr, words); + try t.expect(allowed(words, model)); + try t.expect(!allowed(words, end_sampling)); + const first_end = std.mem.indexOfScalar(u32, ids, 200010).?; + for (ids, 0..) |id, i| { + try t.expect(try r.vtable.accept(r.ptr, id)); + if (i == first_end) { // after a whole call: another call's message, or the end of sampling + try r.vtable.fill(r.ptr, words); + try t.expect(allowed(words, model) and allowed(words, end_sampling)); + } + } + try t.expect(try r.vtable.accept(r.ptr, end_sampling)); + try t.expect(r.vtable.terminated(r.ptr)); +} diff --git a/zig/src/server/inkling2_required_test.zig b/zig/src/server/inkling2_required_test.zig index 29a6437457c..f65dbd372e5 100644 --- a/zig/src/server/inkling2_required_test.zig +++ b/zig/src/server/inkling2_required_test.zig @@ -178,4 +178,5 @@ test "Inkling 2 reply: a json_schema reply ends on the same token ids as before test { _ = @import("inkling2_stop_test.zig"); _ = @import("inkling2_thinking_test.zig"); + _ = @import("inkling2_native_required_test.zig"); } diff --git a/zig/src/server/inkling2_stop_test.zig b/zig/src/server/inkling2_stop_test.zig index e3f0ebdb9d0..b84167b23d9 100644 --- a/zig/src/server/inkling2_stop_test.zig +++ b/zig/src/server/inkling2_stop_test.zig @@ -16,10 +16,11 @@ fn partialSecond(lane: bool) !void { var failures: usize = 0; for ([_]usize{ 0, 1, 2, 3, 256 }) |stride| { const got = if (lane) try h.askLane(a, "release", reply, required, stride > 0, @max(stride, 1)) else try h.ask(a, "release", reply, required, stride > 0, @max(stride, 1)); + // the required grammar is Inkling 2's native form, on the shared compiler const exact = std.mem.eql(u8, "lookuplookup", got.names) and std.mem.eql(u8, "{\"q\":\"x\"}{\"q\":\"y\"}", got.arguments) and std.mem.eql(u8, "tool_calls", got.finish) and std.mem.eql(u8, want, got.token_ids) and - got.eos_len == plain.eos_len and got.grammars == 0 and got.tool_grammars == 1; + got.eos_len == plain.eos_len and got.grammars == 1 and got.tool_grammars == 0; std.debug.print("INKLING_STOP_CELL lane={any} stride={d} exact={any} calls={s} eos={d}/{d}\n", .{ lane, stride, exact, got.names, got.eos_len, plain.eos_len }); if (!exact) failures += 1; } diff --git a/zig/src/server/tool_grammar.zig b/zig/src/server/tool_grammar.zig index 767cd3e872f..8a368a401d7 100644 --- a/zig/src/server/tool_grammar.zig +++ b/zig/src/server/tool_grammar.zig @@ -7,6 +7,7 @@ const prompt = @import("prompt.zig"); const tool_specs = @import("tool_specs.zig"); const lfm2 = @import("tool_grammar_lfm2.zig"); const deepseek = @import("tool_grammar_deepseek.zig"); +const inkling = @import("tool_grammar_inkling.zig"); const max_text = @import("grammar.zig").max_text; const Server = @import("server.zig").Server; const Value = json.Value; @@ -44,6 +45,7 @@ const mm = "]<]minimax[>["; /// The grammar for a reply that must call one of `tools`: one call, or (`parallel`) one or more, then the end. pub fn structure(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, thinking: bool) errors.Refused!api.Structure { const rendered = try probed(srv, cx); + if (@import("chat_inkling2.zig").enabled(srv) and inkling.isNative(rendered, probe)) return native(srv, cx, tools, parallel, thinking); const s = style(rendered) orelse .json; // unrecognized markup uses the canonical call form the parser accepts const markup = lfm2.isStyle(rendered, probe, key); // measured for one call: parallel calls repeat that call's rule, and the limit counts each tool once @@ -57,6 +59,17 @@ pub fn structure(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, th return st; } +/// Inkling 2's required calls as its template writes them, on the shared compiler: its stops are the eos ids alone. +fn native(srv: *Server, cx: *Cx, tools: []const Value, parallel: bool, thinking: bool) errors.Refused!api.Structure { + const once = try inkling.build(cx.a, tools, false); + try fits(cx, once); + const text = if (parallel) try inkling.build(cx.a, tools, true) else once; + const reason = try std.fmt.allocPrint(cx.a, "tool_choice \"required\" or a named function on backend '{s}'", .{srv.backendName()}); + var st = try srv.compiledStructure(cx, .structural_tag, text, reason, thinking); + st.field = "tool_choice"; + return st; +} + /// An auto reply's grammar: free text or calls, strict tools' arguments in their schema; null for LFM2's markup. pub fn optionalStructure(srv: *Server, cx: *Cx, tools: []const Value, all: bool, parallel: bool, thinking: bool) errors.Refused!?api.Structure { const rendered = try probed(srv, cx); @@ -241,7 +254,7 @@ fn call(a: Allocator, s: Style, name: []const u8, schema: Value, constrained: bo } /// The tool's parameter schema (OpenAI's function.parameters, a bare tool's parameters or input_schema). -fn parameters(a: Allocator, tool: Value) Allocator.Error!Value { +pub fn parameters(a: Allocator, tool: Value) Allocator.Error!Value { const function = if (tool.get("function")) |f| (if (f == .object) f else tool) else tool; for ([_][]const u8{ "parameters", "input_schema" }) |k| if (function.get(k)) |p| if (p == .object) return p; const empty = try json.newObject(a); @@ -255,15 +268,15 @@ fn anyObject(a: Allocator) Allocator.Error!Value { return node(a, "object", &.{.{ "additionalProperties", .{ .bool = true } }}); } -fn arguments(a: Allocator, schema: Value, style_name: []const u8) Allocator.Error!Value { +pub fn arguments(a: Allocator, schema: Value, style_name: []const u8) Allocator.Error!Value { return node(a, "json_schema", &.{ .{ "json_schema", schema }, .{ "style", .{ .string = style_name } }, .{ "max_whitespace_cnt", try json.intValue(a, value_blanks) } }); } -fn constant(a: Allocator, text: []const u8) Allocator.Error!Value { +pub fn constant(a: Allocator, text: []const u8) Allocator.Error!Value { return node(a, "const_string", &.{.{ "value", .{ .string = text } }}); } -fn list(a: Allocator, items: []const Value) Allocator.Error!Value { +pub fn list(a: Allocator, items: []const Value) Allocator.Error!Value { return .{ .array = try a.dupe(Value, items) }; } @@ -275,6 +288,10 @@ pub fn node(a: Allocator, kind: []const u8, entries: []const struct { []const u8 return .{ .object = o }; } +test { + _ = inkling; +} + test "the probe call's markup picks the style" { try std.testing.expectEqual(Style.xml, style("\n\n\nv\n\n
\n\n").?); try std.testing.expectEqual(Style.json, style("\n{\"name\": \"tfprobe_fn\", \"arguments\": {\"tfprobe_k\": \"v\"}}\n").?); diff --git a/zig/src/server/tool_grammar_inkling.zig b/zig/src/server/tool_grammar_inkling.zig new file mode 100644 index 00000000000..cd4697f0508 --- /dev/null +++ b/zig/src/server/tool_grammar_inkling.zig @@ -0,0 +1,55 @@ +//! Inkling 2's required calls in its template's own form: each call a model message, then the end of sampling. +const std = @import("std"); +const json = @import("json"); +const tg = @import("tool_grammar.zig"); +const tool_specs = @import("tool_specs.zig"); +const Value = json.Value; +const Allocator = std.mem.Allocator; + +pub const open = "<|message_model|>"; +pub const invoke = "<|content_invoke_tool_json|>"; +pub const end = "<|end_message|>"; + +/// Whether `rendered`, the template's turn calling `probe`, writes Inkling 2's own call message. +pub fn isNative(rendered: []const u8, comptime probe: []const u8) bool { + return std.mem.indexOf(u8, rendered, open ++ probe ++ invoke) != null; +} + +/// The structural tag: one call message, or (`parallel`) one or more back to back; the stop is the end of sampling. +pub fn build(a: Allocator, tools: []const Value, parallel: bool) Allocator.Error![]const u8 { + const calls = try a.alloc(Value, tools.len); + for (tools, calls) |tool, *c| c.* = try call(a, try tool_specs.toolName(a, tool), try tg.parameters(a, tool)); + const one = if (calls.len == 1) calls[0] else try tg.node(a, "or", &.{.{ "elements", .{ .array = calls } }}); + const format = if (!parallel) one else try tg.node(a, "sequence", &.{.{ "elements", try tg.list(a, &.{ one, try tg.node(a, "star", &.{.{ "content", one }}) }) }}); + return json.stringify(a, try tg.node(a, "structural_tag", &.{.{ "format", format }}), .{ .ascii = false, .compact = true }); +} + +/// `<|message_model|>NAME<|content_invoke_tool_json|>{"name":NAME,"args":{...}}<|end_message|>`, args in `schema`. +fn call(a: Allocator, name: []const u8, schema: Value) Allocator.Error!Value { + const fixed = try json.newObject(a); + try fixed.put(a, "const", .{ .string = name }); + const props = try json.newObject(a); + try props.put(a, "name", .{ .object = fixed }); + try props.put(a, "args", schema); + const whole = try json.newObject(a); + try whole.put(a, "type", .{ .string = "object" }); + try whole.put(a, "properties", .{ .object = props }); + try whole.put(a, "required", try tg.list(a, &.{ .{ .string = "name" }, .{ .string = "args" } })); + const opener = try std.mem.concat(a, u8, &.{ open, name, invoke }); + return tg.node(a, "sequence", &.{.{ "elements", try tg.list(a, &.{ try tg.constant(a, opener), try tg.arguments(a, .{ .object = whole }, "json"), try tg.constant(a, end) }) }}); +} + +test "Inkling 2 reply: the native required grammar writes each call as its own model message, repeated only in parallel" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const tools = (try json.parse(a, "[{\"type\":\"function\",\"function\":{\"name\":\"get_weather\",\"parameters\":{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},\"required\":[\"city\"]}}}]")).ok; + const single = try build(a, tools.array, false); + for ([_][]const u8{ "<|message_model|>get_weather<|content_invoke_tool_json|>", "\"args\"", "\"const\":\"get_weather\"", "\"city\"", "<|end_message|>" }) |text| + try std.testing.expect(std.mem.indexOf(u8, single, text) != null); + // no generic envelope, no blanks rule and no repeat without parallel calls + for ([_][]const u8{ "", "\"regex\"", "\"type\":\"star\"" }) |text| try std.testing.expect(std.mem.indexOf(u8, single, text) == null); + try std.testing.expect(std.mem.indexOf(u8, try build(a, tools.array, true), "\"type\":\"star\"") != null); + try std.testing.expect(isNative("<|message_model|>tfprobe_fn<|content_invoke_tool_json|>{\"name\":\"tfprobe_fn\",\"args\":{}}<|end_message|>", "tfprobe_fn")); + try std.testing.expect(!isNative("{\"name\":\"tfprobe_fn\",\"arguments\":{}}", "tfprobe_fn")); +} From 1d241b02692941bb35eeaa24c9e5ad179a52073a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:00:57 +0000 Subject: [PATCH 254/361] test(inkling2): the native grammar probe walks the reply in the library's ids The probe encoded its sample reply with the route harness's tokenizer, which places the cut fixture vocabulary's added tokens after its base entries (<|message_model|> becomes 1515), while the grammar library reads each added token's declared id from the same tokenizer.json (200001). With the library loaded the probe therefore failed its own first check, expected 200001, found 1515, before it read any mask. The grammar and the served replies were right: the device reply opens on 200001. The probe now maps the harness's added-token ids to their declared ids and checks that reply before opening the library, so this part also runs where the library is absent. It also checks that the end of message is allowed right after the last call's JSON and that another call or the end of sampling is allowed after it. --- .../server/inkling2_native_required_test.zig | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/zig/src/server/inkling2_native_required_test.zig b/zig/src/server/inkling2_native_required_test.zig index ea556183028..1f737f60521 100644 --- a/zig/src/server/inkling2_native_required_test.zig +++ b/zig/src/server/inkling2_native_required_test.zig @@ -59,13 +59,35 @@ fn allowed(words: []const u32, id: u32) bool { return words[id / 32] >> @intCast(id % 32) & 1 == 1; } -// The grammar library decides whether a constant may spell a special token; this host has none, so the test skips. +/// `raw` in the library's ids: the harness puts added tokens after the cut base vocabulary; the library, declared ids. +fn declaredIds(a: std.mem.Allocator, text: []const u8, raw: []const u8) ![]u32 { + const doc = (try json.parseText(a, text)).ok; + const base: u32 = @intCast(doc.get("model").?.get("vocab").?.object.count()); + const added = doc.get("added_tokens").?.array; + const ids = try a.dupe(u32, try h.encodeReply(a, raw)); + for (ids) |*id| if (id.* >= base) { + const declared = added[id.* - base].get("id").?; + id.* = try std.fmt.parseInt(u32, declared.int, 10); + }; + return ids; +} + +// The grammar library decides whether a constant may spell a special token; without the library the test skips. test "Inkling 2 reply: probe, the grammar library opens a native reply on <|message_model|> and ends it at the end of sampling" { var arena = std.heap.ArenaAllocator.init(t.allocator); defer arena.deinit(); const a = arena.allocator(); const tok = try tokenizer(a); + const model: u32 = 200001; + const end_message: u32 = 200010; const end_sampling: u32 = 200006; + // the reply in the library's id space, checked before the library: two whole call messages + const ids = try declaredIds(a, tok.text, message("x") ++ message("y")); + try t.expectEqual(model, ids[0]); + try t.expectEqual(@as(usize, 2), std.mem.count(u32, ids, &.{model})); + try t.expectEqual(@as(usize, 2), std.mem.count(u32, ids, &.{200049})); + try t.expectEqual(end_message, ids[ids.len - 1]); + const first_end = std.mem.indexOfScalar(u32, ids, end_message).?; var err: [512]u8 = undefined; var c = api.grammar.Compiler.open(t.io, a, tok.text, tok.vocab, &.{end_sampling}, &err) catch |e| switch (e) { error.NoGrammarLibrary => return error.SkipZigTest, @@ -79,17 +101,17 @@ test "Inkling 2 reply: probe, the grammar library opens a native reply on <|mess const r = m.rules(); defer r.vtable.free(r.ptr); const words = try a.alloc(u32, c.words); - const ids = try h.encodeReply(a, message("x") ++ message("y")); - const model: u32 = 200001; - try t.expectEqual(model, ids[0]); - // the one-token probe: the reply's first token may be <|message_model|>, and nothing generic is + // the one-token probe: the reply's first token may be <|message_model|>, and the end of sampling may not try r.vtable.fill(r.ptr, words); try t.expect(allowed(words, model)); try t.expect(!allowed(words, end_sampling)); - const first_end = std.mem.indexOfScalar(u32, ids, 200010).?; for (ids, 0..) |id, i| { + if (i == ids.len - 1) { // the last call's JSON is complete: its end of message is allowed + try r.vtable.fill(r.ptr, words); + try t.expect(allowed(words, end_message)); + } try t.expect(try r.vtable.accept(r.ptr, id)); - if (i == first_end) { // after a whole call: another call's message, or the end of sampling + if (i == first_end or i == ids.len - 1) { // after a whole call: another call's message, or the end of sampling try r.vtable.fill(r.ptr, words); try t.expect(allowed(words, model) and allowed(words, end_sampling)); } From 2df6a900622a78fcef17b596f373604d0eb281f4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:22:19 +0000 Subject: [PATCH 255/361] changelog: inkling2: required tool calls use the template's own message format --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e26d18f1fd..ff8f159c980 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on Metal: DSpark drafting uses the 1/sqrt(128) attention scale and reads the recurrent step's kappa as FP32, so one-stream draft acceptance on an M3 Ultra rises from 3% to 55% and drafted decode is about 56% faster; replies are unchanged (#4447). Thanks @sethforprivacy. +- Inkling 2: required and named tool calls use the model's own message format, so a request that needs several calls ends after them instead of repeating until max_tokens; a required single call keeps its parsed tool_calls but its token ids change (#4898). - Hy4-flash: a host weight map for its ModelOpt NVFP4 build (groups of 16, no KV quantization), with the build's recipe and quality notes; serving it comes in later slices (#4110). Thanks @atakann. - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. From fa43c4800e97c58d122afe47c3e6421c60a19d81 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:37:02 +0000 Subject: [PATCH 256/361] changelog: #4898's line from lines/4898.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff8f159c980..ea5875d7921 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 +- Inkling 2: required and named tool calls use the model's own message format, so a request that needs several calls ends after them instead of repeating until max_tokens; a required single call keeps its parsed tool_calls but its token ids change (#4898). + - OCR: `POST /ocr` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575). - XPU: Qwen3.8-27B decode attention computes the twelve exponentials of a key (each of the six heads' rescale and weight) as one 16-lane vector `exp` instead of twelve scalar ones, with the same operands in the same order, so every output byte is unchanged (vector `exp` equals scalar `exp` on all 2^32 float bit patterns and `fmax` on 5.4e8 pairs; token hashes equal to main, drafted and plain, at 7,588, 28,946 and 121,022 prompt tokens). On an Arc Pro B70 `attn_decode` takes 5.5 to 7.5 % less GPU time a drafted round and served drafted decode gains 1.3 % at 7,588 prompt tokens, 3.0 % at 28,946 and 4.9 % at 121,022; plain decode is level. The kernel contract adds a planted control for the vector's lanes (#4651, refs #2543). @@ -32,7 +34,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on Metal: DSpark drafting uses the 1/sqrt(128) attention scale and reads the recurrent step's kappa as FP32, so one-stream draft acceptance on an M3 Ultra rises from 3% to 55% and drafted decode is about 56% faster; replies are unchanged (#4447). Thanks @sethforprivacy. -- Inkling 2: required and named tool calls use the model's own message format, so a request that needs several calls ends after them instead of repeating until max_tokens; a required single call keeps its parsed tool_calls but its token ids change (#4898). - Hy4-flash: a host weight map for its ModelOpt NVFP4 build (groups of 16, no KV quantization), with the build's recipe and quality notes; serving it comes in later slices (#4110). Thanks @atakann. - OCR: `POST /ocr` takes docTR's request contract (step 5 of #2440), with each page's response naming its file (#2574). Thanks @laudney. From ad09eda74bb04b1fd38b05c855bf1d645f9218da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:29:25 +0100 Subject: [PATCH 257/361] inkling2 cuda: Mini decode experts a warp 8 output columns, gate and up in one launch At decode tf_ink2moe_up ran a warp per 32 output columns over the whole K, so a layer's projections had 288 to 576 warps, about 6 an SM, and each warp's long serial stream left 70 % of the issue slots idle; the gate and up halves of w13 were two launches of 1.5 waves each. Decode warps now own one n8 tile (8 columns, kDecodeTiles), and one launch walks w13's rows in order, storing even rows to the gate and odd rows to the up buffer. Each output's mma sequence over K and its rounding are unchanged, so the bits are unchanged; prompt chunks keep 32 columns a warp and two launches. --- zig/kernels/cuda/inkling2/modelopt.cu | 91 +++++++++++++------ .../contract/inkling2_experts_records.zig | 2 +- zig/src/families/inkling2/modelopt.zig | 21 +++-- 3 files changed, 80 insertions(+), 34 deletions(-) diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu index 07262bcc063..63794a18bcb 100644 --- a/zig/kernels/cuda/inkling2/modelopt.cu +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -49,11 +49,13 @@ struct Raw { uint32_t lo, hi, sc; }; +constexpr int kDecodeTiles = 1; // n8 tiles a decode warp (modelopt.zig decode_columns = 8 x this); prompt: NTW constexpr int kRowBytes = 144; // a staged row: 128 code bytes + 16, so the 8 rows a load touches use distinct banks -// A warp's tile in registers: up to 128 code bytes of its 32 rows (8 lanes a row), the lane's row's scales; K % 32 == 0 -struct Tile { - uint4 codes[8]; +// A warp's tile in registers: up to 128 code bytes of its 8 NT rows (8 lanes a row), the lane's row's scales +template +struct Tile { // K % 32 == 0 + uint4 codes[2 * NT]; uint32_t scales[4]; }; @@ -66,17 +68,19 @@ __device__ __forceinline__ uint32_t scale_word(const uint8_t* p, int n) { return v; } -__device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int g0, int steps, int lane, Tile& t) { +template +__device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int g0, int steps, int lane, Tile& t) { const int bytes = steps * (w.format ? 32 : 16); #pragma unroll - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < 2 * NT; ++i) { const int q = lane + 32 * i, lr = q >> 3, chunk = q & 7; if (chunk * 16 >= bytes) continue; - const long long row = w.row0 + w.row_step * (cb * 32 + lr); + const long long row = w.row0 + w.row_step * (cb * 8 * NT + lr); const long long z = (e * w.N + row) * w.K + 32LL * g0; // first element of the tile t.codes[i] = __ldg(reinterpret_cast(w.codes + (w.format ? z : z / 2) + chunk * 16)); } - const long long row = w.row0 + w.row_step * (cb * 32 + lane); + if (lane >= 8 * NT) return; + const long long row = w.row0 + w.row_step * (cb * 8 * NT + lane); const long long z = (e * w.N + row) * w.K + 32LL * g0; const int n = w.format ? steps : 2 * steps; // the row's scale bytes in this tile; unpadded, the last ends the data const uint8_t* src = w.scales + z / w.G; @@ -88,16 +92,18 @@ __device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int : scale_word(src + 4 * i, n - 4 * i); } -__device__ __forceinline__ void put(const Weight& w, int steps, int lane, const Tile& t, uint8_t* __restrict__ codes, - uint8_t* __restrict__ scales) { +template +__device__ __forceinline__ void put(const Weight& w, int steps, int lane, const Tile& t, + uint8_t* __restrict__ codes, uint8_t* __restrict__ scales) { const int bytes = steps * (w.format ? 32 : 16); #pragma unroll - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < 2 * NT; ++i) { const int q = lane + 32 * i, lr = q >> 3, chunk = q & 7; if (chunk * 16 < bytes) *reinterpret_cast(codes + lr * kRowBytes + chunk * 16) = t.codes[i]; } + if (lane < 8 * NT) #pragma unroll - for (int i = 0; i < 4; ++i) reinterpret_cast(scales + lane * 16)[i] = t.scales[i]; + for (int i = 0; i < 4; ++i) reinterpret_cast(scales + lane * 16)[i] = t.scales[i]; } // Step gg of a staged tile, fragment rows 8j + lane / 4: the bytes ld_w used to read from global memory. @@ -144,14 +150,36 @@ __device__ __forceinline__ uint4 decode(const Weight& w, const Raw& r, float out return o; } -template +// experts.cuh's bf16 epilogue for NT n8 tiles; with `up`, w13 rows: even to gate[col / 2], odd to up[col / 2]. +template +__device__ __forceinline__ void store(const float (&acc)[1][RT][NT][4], int r, void* out, void* up, int N, int col0, + int pr0, int pr1, bool v0, bool v1) { +#pragma unroll + for (int h = 0; h < 2; ++h) { + if (!(h ? v1 : v0)) continue; + const size_t row = (size_t)(h ? pr1 : pr0) * N; +#pragma unroll + for (int j = 0; j < NT; ++j) { + const __nv_bfloat162 o = __floats2bfloat162_rn(acc[0][r][j][2 * h], acc[0][r][j][2 * h + 1]); + if (up) { + reinterpret_cast<__nv_bfloat16*>(out)[row + (col0 + 8 * j) / 2] = o.x; + reinterpret_cast<__nv_bfloat16*>(up)[row + (col0 + 8 * j) / 2] = o.y; + } else { + *reinterpret_cast<__nv_bfloat162*>(reinterpret_cast<__nv_bfloat16*>(out) + row + col0 + 8 * j) = o; + } + } + } +} + +template __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, Weight w, int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, - const int* __restrict__ members, void* __restrict__ out, int N, int skip) { + const int* __restrict__ members, void* __restrict__ out, int N, int skip, + void* __restrict__ up = nullptr) { const int lane = threadIdx.x & 31, gq = lane >> 2, t = lane & 3; const int units = __ldg(item_count) * NB; - __shared__ __align__(16) uint8_t tiles[WARPS][32 * kRowBytes]; - __shared__ __align__(16) uint8_t tile_scales[WARPS][32 * 16]; + __shared__ __align__(16) uint8_t tiles[WARPS][8 * NT * kRowBytes]; + __shared__ __align__(16) uint8_t tile_scales[WARPS][8 * NT * 16]; uint8_t* codes = tiles[threadIdx.x >> 5]; uint8_t* scales = tile_scales[threadIdx.x >> 5]; for (int unit = blockIdx.x * WARPS + (threadIdx.x >> 5); unit < units; unit += gridDim.x * WARPS) { @@ -172,11 +200,11 @@ __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_ pr[r][h] = v[r][h] ? __ldg(members + first + i) : 0; x[r][h] = X + (size_t)(slots ? pr[r][h] / slots : pr[r][h]) * x_stride + 4 * t; } - float acc[1][RT][NTW][4]; + float acc[1][RT][NT][4]; #pragma unroll for (int r = 0; r < RT; ++r) #pragma unroll - for (int j = 0; j < NTW; ++j) acc[0][r][j][0] = acc[0][r][j][1] = acc[0][r][j][2] = acc[0][r][j][3] = 0.f; + for (int j = 0; j < NT; ++j) acc[0][r][j][0] = acc[0][r][j][1] = acc[0][r][j][2] = acc[0][r][j][3] = 0.f; const uint2 zero = make_uint2(0u, 0u); const int ts = w.format ? 4 : 8; // steps a staged tile uint2 xn[2][2] = {{zero, zero}, {zero, zero}}; // decode: the next step's inputs @@ -186,7 +214,7 @@ __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_ xn[0][q] = v[0][0] ? __ldg(reinterpret_cast(x[0][0] + 16 * q)) : zero; xn[1][q] = v[0][1] ? __ldg(reinterpret_cast(x[0][1] + 16 * q)) : zero; } - Tile next; // decode (RT 1) fetches the next tile while this one sums; prompt tiles load in place + Tile next; // decode (RT 1) fetches the next tile while this one sums; prompt tiles load in place if (RT == 1) fetch(w, e, cb, 0, KG < ts ? KG : ts, lane, next); for (int g0 = 0; g0 < KG; g0 += ts) { const int steps = KG - g0 < ts ? KG - g0 : ts; @@ -209,9 +237,9 @@ __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_ xn[1][q] = g + 1 < KG && v[0][1] ? __ldg(pb) : zero; } } - uint4 ww[NTW]; + uint4 ww[NT]; #pragma unroll - for (int j = 0; j < NTW; ++j) ww[j] = decode(w, staged(w, codes, scales, gg, lane, j), outer); + for (int j = 0; j < NT; ++j) ww[j] = decode(w, staged(w, codes, scales, gg, lane, j), outer); #pragma unroll for (int r = 0; r < RT; ++r) { uint2 xa[2], xb[2]; @@ -228,14 +256,18 @@ __device__ __forceinline__ void body(const __nv_bfloat16* __restrict__ X, int x_ #pragma unroll for (int q = 0; q < 2; ++q) #pragma unroll - for (int j = 0; j < NTW; ++j) + for (int j = 0; j < NT; ++j) mma(acc[0][r][j], xa[q].x, xb[q].x, xa[q].y, xb[q].y, q ? ww[j].z : ww[j].x, q ? ww[j].w : ww[j].y); } } } #pragma unroll - for (int r = 0; r < RT; ++r) - epilogue<3, 1, RT>(acc, r, out, N, cb * COLS + 2 * t, pr[r][0], pr[r][1], v[r][0], v[r][1], 0.f); + for (int r = 0; r < RT; ++r) { + if constexpr (NT == NTW) + epilogue<3, 1, RT>(acc, r, out, N, cb * COLS + 2 * t, pr[r][0], pr[r][1], v[r][0], v[r][1], 0.f); + else + store(acc, r, out, up, N, cb * 8 * NT + 2 * t, pr[r][0], pr[r][1], v[r][0], v[r][1]); + } } } } @@ -307,14 +339,19 @@ extern "C" __global__ void __launch_bounds__(32) tf_ink2moe_plan(const int32_t* *item_count = at; } -#define TF_INK2_MOE(NAME, RT) \ +#define TF_INK2_MOE(NAME, RT, NT) \ extern "C" __global__ void __launch_bounds__(128) NAME(const __nv_bfloat16* __restrict__ X, int x_stride, int slots, \ ink2o::Weight w, int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, \ const int* __restrict__ members, void* __restrict__ out, int N, int skip) { \ - ink2o::body(X, x_stride, slots, w, KG, NB, items, item_count, members, out, N, skip); \ + ink2o::body(X, x_stride, slots, w, KG, NB, items, item_count, members, out, N, skip); \ } -TF_INK2_MOE(tf_ink2moe_up, 1) -TF_INK2_MOE(tf_ink2moe_prompt_up, 4) +// Decode: `up` set means the gate and up projections at once over w13's rows in order (row_step 1). +extern "C" __global__ void __launch_bounds__(128) tf_ink2moe_up(const __nv_bfloat16* __restrict__ X, int x_stride, + int slots, ink2o::Weight w, int KG, int NB, const int* __restrict__ items, const int* __restrict__ item_count, + const int* __restrict__ members, void* __restrict__ out, int N, int skip, void* __restrict__ up) { + ink2o::body<1, 4, ink2o::kDecodeTiles>(X, x_stride, slots, w, KG, NB, items, item_count, members, out, N, skip, up); +} +TF_INK2_MOE(tf_ink2moe_prompt_up, 4, NTW) extern "C" __global__ void __launch_bounds__(256) tf_ink2moe_act(const __nv_bfloat16* g, const __nv_bfloat16* u, __nv_bfloat16* o, int n, float gc, float uc) { ink2o::act(g, u, o, n, gc, uc); } diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 7c1568b621e..98fcb95f49f 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -11,7 +11,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 164, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 }, .{ .regs = 168, .static = 20480, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 111, .static = 5120, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, diff --git a/zig/src/families/inkling2/modelopt.zig b/zig/src/families/inkling2/modelopt.zig index 7ef444cab24..7b5d84dd503 100644 --- a/zig/src/families/inkling2/modelopt.zig +++ b/zig/src/families/inkling2/modelopt.zig @@ -131,10 +131,14 @@ pub fn weight(p: Projection, l: Layer, row0: i32, row_step: i32) Weight { }; } -fn projection(s: cuda.Stream, fn_: cuda.Function, prompt: bool, resident: usize, x: u64, x_stride: usize, slots: usize, w: Weight, items: u64, item_count: u64, members: u64, out: u64, item_bound: usize) !void { +/// Output columns a decode warp of tf_ink2moe_up owns (modelopt.cu kDecodeTiles n8 tiles); the prompt kernel owns 32. +const decode_columns: usize = 8; + +/// `up` (decode only): w is w13 in row order, gate rows to `out` and up rows to `up`. +fn projection(s: cuda.Stream, fn_: cuda.Function, prompt: bool, resident: usize, x: u64, x_stride: usize, slots: usize, w: Weight, items: u64, item_count: u64, members: u64, out: u64, up: u64, item_bound: usize) !void { const kg: usize = @intCast(@divExact(w.k, 32)); const outputs: usize = @intCast(if (w.row_step == 2) @divExact(w.n, 2) else w.n); - const nb = outputs / 32; + const nb = outputs / if (prompt) @as(usize, 32) else decode_columns; var a: cuda.Args = .{}; a.add(x); a.add(i32d(x_stride)); @@ -143,8 +147,9 @@ fn projection(s: cuda.Stream, fn_: cuda.Function, prompt: bool, resident: usize, a.add(i32d(kg)); a.add(i32d(nb)); for ([_]u64{ items, item_count, members, out }) |v| a.add(v); - a.add(i32d(outputs)); + a.add(i32d(if (up != 0) outputs / 2 else outputs)); a.add(@as(i32, -1)); + if (!prompt) a.add(up); const bound = item_bound * nb; const grid = if (prompt) (bound + 3) / 4 else @min((bound + 3) / 4, resident); if (grid == 0) return; @@ -170,8 +175,12 @@ pub fn run(k: *const Kernels, s: cuda.Stream, l: Layer, caps: experts.Caps, x: u try cuda.launch.launch(k.plan, .{ .grid = .{ .x = 1, .y = 1, .z = 1 }, .block = .{ .x = 32 } }, s, &g); const fn_ = if (listed) k.prompt else k.decode; - try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 0, 2), b.items, b.item_count, b.members, b.gate, item_bound); - try projection(s, fn_, listed, k.resident, x, x_stride, slots, weight(l.w13, l, 1, 2), b.items, b.item_count, b.members, b.up, item_bound); + if (listed) { + try projection(s, fn_, true, k.resident, x, x_stride, slots, weight(l.w13, l, 0, 2), b.items, b.item_count, b.members, b.gate, 0, item_bound); + try projection(s, fn_, true, k.resident, x, x_stride, slots, weight(l.w13, l, 1, 2), b.items, b.item_count, b.members, b.up, 0, item_bound); + } else { + try projection(s, fn_, false, k.resident, x, x_stride, slots, weight(l.w13, l, 0, 1), b.items, b.item_count, b.members, b.gate, b.up, item_bound); + } var aa: cuda.Args = .{}; for ([_]u64{ b.gate, b.up, b.act }) |v| aa.add(v); @@ -179,7 +188,7 @@ pub fn run(k: *const Kernels, s: cuda.Stream, l: Layer, caps: experts.Caps, x: u aa.add(caps.gate); aa.add(caps.up); try cuda.launch.launch(k.act, .{ .grid = .{ .x = @intCast((pairs * intermediate + 255) / 256), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, s, &aa); - try projection(s, fn_, listed, k.resident, b.act, intermediate, 0, weight(l.w2, l, 0, 1), b.items, b.item_count, b.members, b.down, item_bound); + try projection(s, fn_, listed, k.resident, b.act, intermediate, 0, weight(l.w2, l, 0, 1), b.items, b.item_count, b.members, b.down, 0, item_bound); var ca: cuda.Args = .{}; for ([_]u64{ pick, weights, b.down, out }) |v| ca.add(v); From 4c379f9f293be8aa784170d2a7ccc431e28a8b6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:57:11 +0100 Subject: [PATCH 258/361] inkling2 cuda: Mini decode experts take whole scale words in one test a tile The bounded scale loads chose word or bytes per word. A tile whose row scales are word-aligned with no partial word, every tile at Mini's shapes, now takes the whole-word loop it took before the bound, after one test; the byte path serves only the rest. --- zig/kernels/cuda/inkling2/modelopt.cu | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/zig/kernels/cuda/inkling2/modelopt.cu b/zig/kernels/cuda/inkling2/modelopt.cu index 63794a18bcb..4533a93693c 100644 --- a/zig/kernels/cuda/inkling2/modelopt.cu +++ b/zig/kernels/cuda/inkling2/modelopt.cu @@ -84,12 +84,15 @@ __device__ __forceinline__ void fetch(const Weight& w, long long e, int cb, int const long long z = (e * w.N + row) * w.K + 32LL * g0; const int n = w.format ? steps : 2 * steps; // the row's scale bytes in this tile; unpadded, the last ends the data const uint8_t* src = w.scales + z / w.G; - const bool words = (reinterpret_cast(src) & 3) == 0; + if (((reinterpret_cast(src) | n) & 3) == 0) { // aligned, no partial word (Mini's shapes): whole words +#pragma unroll + for (int i = 0; i < 4; ++i) + if (4 * i < n) t.scales[i] = __ldg(reinterpret_cast(src) + i); + return; + } #pragma unroll for (int i = 0; i < 4; ++i) - if (4 * i < n) - t.scales[i] = words && 4 * i + 4 <= n ? __ldg(reinterpret_cast(src) + i) - : scale_word(src + 4 * i, n - 4 * i); + if (4 * i < n) t.scales[i] = scale_word(src + 4 * i, n - 4 * i); } template From ee2fca2341df70804db525a11493a1d6b7e66a39 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:34:49 +0000 Subject: [PATCH 259/361] inkling2 cuda: record the warp-column up launch's usage on every SM #4729 rewrites tf_ink2moe_up again (a warp eight output columns, gate and up in one launch) and records its compiled usage at sm_121 only, leaving zeros at sm_80, sm_86, sm_89 and sm_120 for the kernel registry test. The values are nvcc 13.0's, from kernel-contract-limits over fatbins built for all five SMs from this tree; the sm_121 entry equals the one the PR recorded. No kernel changes. --- zig/src/core/contract/inkling2_experts_records.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 98fcb95f49f..03397182f92 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -11,7 +11,7 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 111, .static = 5120, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 111, .static = 5120, .bound = 128 }, .{ .regs = 111, .static = 5120, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, From df64c549a361ddd327aaae7c85a68004aa0cb7d8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:02:44 +0000 Subject: [PATCH 260/361] changelog: #4729 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5875d7921..724b8bc791f 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 +- Inkling 2 Mini on CUDA: decode experts run a warp over 8 columns with gate and up in one launch, about 3% faster one-stream decode on GB10 on top of #4728, with identical tokens (#4729). Thanks @jschmied. + - Inkling 2: required and named tool calls use the model's own message format, so a request that needs several calls ends after them instead of repeating until max_tokens; a required single call keeps its parsed tool_calls but its token ids change (#4898). - OCR: `POST /ocr` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575). From 8d1230495c6545de6c5c84fa555a2512c9fdc4c4 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:02:44 +0000 Subject: [PATCH 261/361] changelog: #4729 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 724b8bc791f..b6a6cdd2c99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on CUDA: decode experts run a warp over 8 columns with gate and up in one launch, about 3% faster one-stream decode on GB10 on top of #4728, with identical tokens (#4729). Thanks @jschmied. + + - Inkling 2: required and named tool calls use the model's own message format, so a request that needs several calls ends after them instead of repeating until max_tokens; a required single call keeps its parsed tool_calls but its token ids change (#4898). - OCR: `POST /ocr` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575). From cd008181890ecc416c8e8ca14d427ac49d498375 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:47:15 +0000 Subject: [PATCH 262/361] kolibri1 cuda: decode rounds of several rows replay CUDA graphs A lone row already runs its slot's captured step graph, but a round of two or more rows (several streams, or a verify window) launched every layer eagerly. Such a round now replays a graph from graph_cache, captured at the first round of its shape and keyed by its rows, its streams and tree attention's key groups. forward() splits into stage() and launch(). stage() uploads the round's ids, positions, slots, plan, paths, cache offsets and page table on the stream as before. launch() reads only device memory: a tree plan's offsets depend on its rows and streams alone, and the key groups are part of the key. So a replayed round makes the same launches with the same arguments as the eager round, and every row keeps its bits. attach drops these graphs along with the step graphs. With TENSORFOLD_KOLIBRI_GRAPHS=0 every round stays eager, and TF_GRAPH_CACHE=0 runs the cache's rounds eagerly. The f64 angle-table test moves unchanged to forward_rope_test.zig, which keeps forward.zig under the 600-line cap. --- zig/src/families/kolibri1/backend.zig | 8 +- zig/src/families/kolibri1/cuda.zig | 2 + zig/src/families/kolibri1/forward.zig | 120 ++++++------------ .../families/kolibri1/forward_rope_test.zig | 53 ++++++++ zig/src/families/kolibri1/rounds.zig | 70 ++++++++++ 5 files changed, 169 insertions(+), 84 deletions(-) create mode 100644 zig/src/families/kolibri1/forward_rope_test.zig create mode 100644 zig/src/families/kolibri1/rounds.zig diff --git a/zig/src/families/kolibri1/backend.zig b/zig/src/families/kolibri1/backend.zig index 078e9fa13f5..6f7df9addab 100644 --- a/zig/src/families/kolibri1/backend.zig +++ b/zig/src/families/kolibri1/backend.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const lanes = @import("lanes"); const fwd = @import("forward.zig"); +const rounds = @import("rounds.zig"); const kern = @import("kernels.zig"); const snap = @import("snap.zig"); const limits = @import("context.zig"); @@ -63,6 +64,7 @@ pub const Kolibri = struct { next: u64 = 0, steps: []?fwd.Model.Step, // a slot's one-row step, captured at its first use (null: not yet) graphed: bool, // TENSORFOLD_KOLIBRI_GRAPHS=0 runs every step eager + rounds: rounds.Rounds, // a decode round of several rows: its shape's graph (graphed) pool: ?kv.Pool = null, // paged: the pages every slot leases (attach) prompts: ?kp.Prompts = null, // TF_KV_SHARE: the store keeping prompts as the pool's pages (cuda_prompt_pages.zig) pending: ?*const snap.Saved = null, // TF_KV_SHARE: a resumed state's rings, put in once its lane opens @@ -95,7 +97,7 @@ pub const Kolibri = struct { } const steps = try gpa.alloc(?fwd.Model.Step, m.slotCap()); @memset(steps, null); - return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .free = free, .logits = logits, .logits16 = logits16, .tok = tok, .meta = meta, .slot_bufs = bufs, .steps = steps, .graphed = !envOff("TENSORFOLD_KOLIBRI_GRAPHS") }; + return .{ .gpa = gpa, .d = d, .m = m, .k = k, .s = s, .free = free, .logits = logits, .logits16 = logits16, .tok = tok, .meta = meta, .slot_bufs = bufs, .steps = steps, .graphed = !envOff("TENSORFOLD_KOLIBRI_GRAPHS"), .rounds = .{ .engine = .{ .d = d } } }; } /// Makes a paged model's arena of `pages` pages for `extra + 1` slots, and the pool that leases them. @@ -105,6 +107,7 @@ pub const Kolibri = struct { e.exec.deinit(); g.* = null; }; + x.rounds.drop(); // the same for every round's graph x.pool = try kv.Pool.init(x.gpa, pages, x.m.pageBytes()); } @@ -127,6 +130,7 @@ pub const Kolibri = struct { x.gpa.free(x.slot_bufs); for (x.steps) |*g| if (g.*) |*e| e.exec.deinit(); x.gpa.free(x.steps); + x.rounds.deinit(); x.gpa.free(x.free); x.logits.free(); x.logits16.free(); @@ -460,6 +464,8 @@ pub const Kolibri = struct { var logits = x.logits.ptr; if (total == 1) { logits = try x.step(x.lanes.getPtr(windows[0].stream).?, chains[0].tokens[0]); // a lone row: the step + } else if (x.graphed) { + try x.rounds.forward(x.m, x.ops(), chains, logits); // every row's logits, as the eager forward below } else { const rows = try x.gpa.alloc(usize, total); defer x.gpa.free(rows); diff --git a/zig/src/families/kolibri1/cuda.zig b/zig/src/families/kolibri1/cuda.zig index 5d2a0a9101e..1c80f315159 100644 --- a/zig/src/families/kolibri1/cuda.zig +++ b/zig/src/families/kolibri1/cuda.zig @@ -8,6 +8,7 @@ pub const weights = @import("weights.zig"); pub const tree = @import("tree.zig"); pub const kernels = @import("kernels.zig"); pub const forward = @import("forward.zig"); +pub const rounds = @import("rounds.zig"); pub const snap = @import("snap.zig"); pub const backend = @import("backend.zig"); pub const native = @import("native.zig"); @@ -20,6 +21,7 @@ test { _ = @import("tree.zig"); _ = @import("kernels.zig"); _ = @import("forward.zig"); + _ = @import("rounds.zig"); _ = @import("snap.zig"); _ = @import("backend.zig"); _ = @import("native.zig"); diff --git a/zig/src/families/kolibri1/forward.zig b/zig/src/families/kolibri1/forward.zig index 49674391867..e612a099b1f 100644 --- a/zig/src/families/kolibri1/forward.zig +++ b/zig/src/families/kolibri1/forward.zig @@ -329,6 +329,26 @@ pub const Model = struct { /// fp32 logits [rows.len, V] at `out` of the chains' rows `rows` (default: each chain's last). pub fn forward(m: *Model, o: kern.Ops, chains: []const Chain, prompt: bool, rows: ?[]const usize, out: u64) !void { + const st = try m.stage(o, chains, prompt); + var ends: std.ArrayList(usize) = .empty; + defer ends.deinit(m.gpa); + const pick = rows orelse blk: { + var e: usize = 0; + for (chains) |ch| { + e += ch.tokens.len; + try ends.append(m.gpa, e - 1); + } + break :blk ends.items; + }; + for (pick) |r| if (r >= st.n) return error.NoSuchRow; + try m.launch(o, st.n, if (prompt) chains[0] else null, st.t, chains.len, st.ng, @min(m.max_rows, round_rows), pick, out); + } + + /// What `stage` leaves `launch` to take: the rows, and a decode round's tree rows and key groups. + pub const Staged = struct { n: usize, t: ?cuda.tree_attention.Rows = null, ng: usize = 0 }; + + /// The chains' ids, positions and slots on `o.s`; a decode round's plan, paths, offsets and page table too. + pub fn stage(m: *Model, o: kern.Ops, chains: []const Chain, prompt: bool) !Staged { const gpa = m.gpa; const s = o.s; if (prompt and chains.len != 1) return error.PromptTakesOneStream; @@ -355,38 +375,22 @@ pub const Model = struct { try m.upload(s, m.s.ids, std.mem.sliceAsBytes(host[0..n])); try m.upload(s, m.s.pos, std.mem.sliceAsBytes(host[n .. 2 * n])); try m.upload(s, m.s.slot, std.mem.sliceAsBytes(host[2 * n ..])); - var t: ?cuda.tree_attention.Rows = null; - var ng: usize = 0; - var plan: ?tree.Plan = null; - defer if (plan) |p| gpa.free(p.flat); - if (!prompt) { - const windows = try gpa.alloc(tree.Window, chains.len); - defer gpa.free(windows); - var most: usize = 0; - for (chains, windows) |ch, *win| { - win.* = .{ .rows = ch.tokens.len, .committed = ch.p0 }; - most = @max(most, ch.p0 + ch.tokens.len); - } - plan = try tree.build(gpa, windows); - try m.upload(s, m.s.flat, std.mem.sliceAsBytes(plan.?.flat)); - t = m.treeRows(m.s.flat, plan.?, m.s.paths, m.s.depths, m.s.offs, m.treePages(m.s.ctab)); - if (m.paged) try m.callTable(s, chains); - try o.k.tree.paths(s, m.s.flat + plan.?.parentsAt(), m.s.paths, m.s.depths, n); - try m.offsets(s, chains, m.s.offs); - ng = TreeAttention.groups(most); + if (prompt) return .{ .n = n }; + const windows = try gpa.alloc(tree.Window, chains.len); + defer gpa.free(windows); + var most: usize = 0; + for (chains, windows) |ch, *win| { + win.* = .{ .rows = ch.tokens.len, .committed = ch.p0 }; + most = @max(most, ch.p0 + ch.tokens.len); } - var ends: std.ArrayList(usize) = .empty; - defer ends.deinit(gpa); - const pick = rows orelse blk: { - var e: usize = 0; - for (chains) |ch| { - e += ch.tokens.len; - try ends.append(gpa, e - 1); - } - break :blk ends.items; - }; - for (pick) |r| if (r >= n) return error.NoSuchRow; - try m.launch(o, n, if (prompt) chains[0] else null, t, chains.len, ng, @min(m.max_rows, round_rows), pick, out); + const plan = try tree.build(gpa, windows); + defer gpa.free(plan.flat); + try m.upload(s, m.s.flat, std.mem.sliceAsBytes(plan.flat)); + const t = m.treeRows(m.s.flat, plan, m.s.paths, m.s.depths, m.s.offs, m.treePages(m.s.ctab)); + if (m.paged) try m.callTable(s, chains); + try o.k.tree.paths(s, m.s.flat + plan.parentsAt(), m.s.paths, m.s.depths, n); + try m.offsets(s, chains, m.s.offs); + return .{ .n = n, .t = t, .ng = TreeAttention.groups(most) }; } fn treeRows(m: *const Model, base: u64, p: tree.Plan, paths: u64, depths: u64, offs: u64, pages: ?cuda.tree_attention.Pages) cuda.tree_attention.Rows { @@ -417,7 +421,7 @@ pub const Model = struct { } /// The layers over staged inputs, no host copies (a graph can hold them); `prompt_chain` set: a prompt chunk. - fn launch(m: *Model, o: kern.Ops, n: usize, prompt_chain: ?Chain, t: ?cuda.tree_attention.Rows, streams: usize, ng: usize, cap: usize, pick: []const usize, out: u64) !void { + pub fn launch(m: *Model, o: kern.Ops, n: usize, prompt_chain: ?Chain, t: ?cuda.tree_attention.Rows, streams: usize, ng: usize, cap: usize, pick: []const usize, out: u64) !void { const c = m.c; const s = o.s; const prompt = prompt_chain != null; @@ -534,57 +538,6 @@ test "the ring holds a prompt chunk and a window, in whole key tiles" { try std.testing.expect(ringSize(prompt_rows, 513) - 513 >= prompt_rows); } -test "the f64 angle table against core's words: 19 of 64 differ, first at 7" { - const rope_freq = @import("core").rope_freq; - // The site's f64 frequency rounded to fp32 (the word a move would store); it keeps the f64 value for the angle. - const theta: f64 = 1e4; // config.zig's default rope_theta - const dh = 128; - const site_words = [64]u32{ - 0x3f800000, 0x3f5dafd7, 0x3f3ff911, 0x3f263de0, 0x3f0ff59a, 0x3ef953cf, 0x3ed7e89b, 0x3ebaf81a, - 0x3ea1e89b, 0x3e8c3504, 0x3e72d424, 0x3e5247ed, 0x3e361887, 0x3e1db040, 0x3e088d77, 0x3dec7fd5, - 0x3dcccccd, 0x3db15978, 0x3d99940e, 0x3d84fe4d, 0x3d6655c3, 0x3d47763f, 0x3d2cba15, 0x3d159348, - 0x3d0186e2, 0x3ce054d2, 0x3cc24350, 0x3ca8398b, 0x3c91ad39, 0x3c7c4d33, 0x3c5a7bf1, 0x3c3d3311, - 0x3c23d70a, 0x3c0de12d, 0x3bf5b9b0, 0x3bd4ca14, 0x3bb8449c, 0x3b9f91cc, 0x3b8a2e77, 0x3b6f520d, - 0x3b4f3e37, 0x3b33770f, 0x3b1b690d, 0x3b06946f, 0x3ae91528, 0x3ac9d75c, 0x3aaec98e, 0x3a975c0e, - 0x3a83126f, 0x3a6301e2, 0x3a44948c, 0x3a2a3b43, 0x3a136a16, 0x39ff4fad, 0x39dd1726, 0x39bf74d7, - 0x39a5cb5f, 0x398f9272, 0x3978a814, 0x395753e5, 0x393a7753, 0x39217917, 0x390bd472, 0x38f22ce3, - }; - const core_words = [64]u32{ - 0x3f800000, 0x3f5dafd7, 0x3f3ff911, 0x3f263de0, 0x3f0ff59a, 0x3ef953cf, 0x3ed7e89b, 0x3ebaf81b, - 0x3ea1e89b, 0x3e8c3504, 0x3e72d423, 0x3e5247ed, 0x3e361887, 0x3e1db040, 0x3e088d77, 0x3dec7fd6, - 0x3dcccccd, 0x3db15978, 0x3d99940d, 0x3d84fe4d, 0x3d6655c2, 0x3d47763f, 0x3d2cba15, 0x3d159348, - 0x3d0186e3, 0x3ce054d2, 0x3cc2434f, 0x3ca8398b, 0x3c91ad39, 0x3c7c4d33, 0x3c5a7bf2, 0x3c3d3311, - 0x3c23d70a, 0x3c0de12d, 0x3bf5b9b0, 0x3bd4ca15, 0x3bb8449c, 0x3b9f91cc, 0x3b8a2e77, 0x3b6f520e, - 0x3b4f3e38, 0x3b33770f, 0x3b1b690d, 0x3b06946f, 0x3ae91528, 0x3ac9d75c, 0x3aaec98e, 0x3a975c0e, - 0x3a83126f, 0x3a6301e2, 0x3a44948c, 0x3a2a3b44, 0x3a136a16, 0x39ff4fac, 0x39dd1725, 0x39bf74d7, - 0x39a5cb60, 0x398f9272, 0x3978a815, 0x395753e4, 0x393a7753, 0x39217916, 0x390bd472, 0x38f22ce2, - }; - var site: [64]f32 = undefined; - var core: [64]f32 = undefined; - for (&site, 0..) |*f, j| { - const frac = @as(f64, @floatFromInt(2 * j)) / @as(f64, @floatFromInt(dh)); - f.* = @floatCast(1.0 / std.math.pow(f64, theta, frac)); - } - rope_freq.inverseFrequencies(theta, dh, &core); - var differ: usize = 0; - var first: ?usize = null; - var max_ulp: u32 = 0; - for (site, core, 0..) |s, c, j| { - try std.testing.expectEqual(site_words[j], @as(u32, @bitCast(s))); - try std.testing.expectEqual(core_words[j], @as(u32, @bitCast(c))); - const a: u32 = @bitCast(s); - const b: u32 = @bitCast(c); - if (a != b) { - differ += 1; - if (first == null) first = j; - max_ulp = @max(max_ulp, if (a > b) a - b else b - a); - } - } - try std.testing.expectEqual(@as(usize, 19), differ); - try std.testing.expectEqual(@as(?usize, 7), first); - try std.testing.expectEqual(@as(u32, 1), max_ulp); -} - test "a page's bytes: the pool's layout and the kernels' stride agree" { const config = @import("config.zig"); var why: config.Why = .{}; @@ -597,4 +550,5 @@ test "a page's bytes: the pool's layout and the kernels' stride agree" { } test { _ = @import("forward_offsets_test.zig"); + _ = @import("forward_rope_test.zig"); } diff --git a/zig/src/families/kolibri1/forward_rope_test.zig b/zig/src/families/kolibri1/forward_rope_test.zig new file mode 100644 index 00000000000..c86416c5c88 --- /dev/null +++ b/zig/src/families/kolibri1/forward_rope_test.zig @@ -0,0 +1,53 @@ +//! Kolibri-1's RoPE angle table: the site's f64 frequencies against core/rope_freq's words. +const std = @import("std"); + +test "the f64 angle table against core's words: 19 of 64 differ, first at 7" { + const rope_freq = @import("core").rope_freq; + // The site's f64 frequency rounded to fp32 (the word a move would store); it keeps the f64 value for the angle. + const theta: f64 = 1e4; // config.zig's default rope_theta + const dh = 128; + const site_words = [64]u32{ + 0x3f800000, 0x3f5dafd7, 0x3f3ff911, 0x3f263de0, 0x3f0ff59a, 0x3ef953cf, 0x3ed7e89b, 0x3ebaf81a, + 0x3ea1e89b, 0x3e8c3504, 0x3e72d424, 0x3e5247ed, 0x3e361887, 0x3e1db040, 0x3e088d77, 0x3dec7fd5, + 0x3dcccccd, 0x3db15978, 0x3d99940e, 0x3d84fe4d, 0x3d6655c3, 0x3d47763f, 0x3d2cba15, 0x3d159348, + 0x3d0186e2, 0x3ce054d2, 0x3cc24350, 0x3ca8398b, 0x3c91ad39, 0x3c7c4d33, 0x3c5a7bf1, 0x3c3d3311, + 0x3c23d70a, 0x3c0de12d, 0x3bf5b9b0, 0x3bd4ca14, 0x3bb8449c, 0x3b9f91cc, 0x3b8a2e77, 0x3b6f520d, + 0x3b4f3e37, 0x3b33770f, 0x3b1b690d, 0x3b06946f, 0x3ae91528, 0x3ac9d75c, 0x3aaec98e, 0x3a975c0e, + 0x3a83126f, 0x3a6301e2, 0x3a44948c, 0x3a2a3b43, 0x3a136a16, 0x39ff4fad, 0x39dd1726, 0x39bf74d7, + 0x39a5cb5f, 0x398f9272, 0x3978a814, 0x395753e5, 0x393a7753, 0x39217917, 0x390bd472, 0x38f22ce3, + }; + const core_words = [64]u32{ + 0x3f800000, 0x3f5dafd7, 0x3f3ff911, 0x3f263de0, 0x3f0ff59a, 0x3ef953cf, 0x3ed7e89b, 0x3ebaf81b, + 0x3ea1e89b, 0x3e8c3504, 0x3e72d423, 0x3e5247ed, 0x3e361887, 0x3e1db040, 0x3e088d77, 0x3dec7fd6, + 0x3dcccccd, 0x3db15978, 0x3d99940d, 0x3d84fe4d, 0x3d6655c2, 0x3d47763f, 0x3d2cba15, 0x3d159348, + 0x3d0186e3, 0x3ce054d2, 0x3cc2434f, 0x3ca8398b, 0x3c91ad39, 0x3c7c4d33, 0x3c5a7bf2, 0x3c3d3311, + 0x3c23d70a, 0x3c0de12d, 0x3bf5b9b0, 0x3bd4ca15, 0x3bb8449c, 0x3b9f91cc, 0x3b8a2e77, 0x3b6f520e, + 0x3b4f3e38, 0x3b33770f, 0x3b1b690d, 0x3b06946f, 0x3ae91528, 0x3ac9d75c, 0x3aaec98e, 0x3a975c0e, + 0x3a83126f, 0x3a6301e2, 0x3a44948c, 0x3a2a3b44, 0x3a136a16, 0x39ff4fac, 0x39dd1725, 0x39bf74d7, + 0x39a5cb60, 0x398f9272, 0x3978a815, 0x395753e4, 0x393a7753, 0x39217916, 0x390bd472, 0x38f22ce2, + }; + var site: [64]f32 = undefined; + var core: [64]f32 = undefined; + for (&site, 0..) |*f, j| { + const frac = @as(f64, @floatFromInt(2 * j)) / @as(f64, @floatFromInt(dh)); + f.* = @floatCast(1.0 / std.math.pow(f64, theta, frac)); + } + rope_freq.inverseFrequencies(theta, dh, &core); + var differ: usize = 0; + var first: ?usize = null; + var max_ulp: u32 = 0; + for (site, core, 0..) |s, c, j| { + try std.testing.expectEqual(site_words[j], @as(u32, @bitCast(s))); + try std.testing.expectEqual(core_words[j], @as(u32, @bitCast(c))); + const a: u32 = @bitCast(s); + const b: u32 = @bitCast(c); + if (a != b) { + differ += 1; + if (first == null) first = j; + max_ulp = @max(max_ulp, if (a > b) a - b else b - a); + } + } + try std.testing.expectEqual(@as(usize, 19), differ); + try std.testing.expectEqual(@as(?usize, 7), first); + try std.testing.expectEqual(@as(u32, 1), max_ulp); +} diff --git a/zig/src/families/kolibri1/rounds.zig b/zig/src/families/kolibri1/rounds.zig new file mode 100644 index 00000000000..1a950a706eb --- /dev/null +++ b/zig/src/families/kolibri1/rounds.zig @@ -0,0 +1,70 @@ +//! Kolibri-1's decode rounds of several rows as CUDA graphs: one a shape, captured at its first round, then replayed. +const std = @import("std"); +const cuda = @import("cuda"); +const fwd = @import("forward.zig"); +const kern = @import("kernels.zig"); +const tree = @import("tree.zig"); +const gc = cuda.graph_cache; + +/// A round's launches past its staged inputs: its rows, its streams and tree attention's key groups. +pub const Key = struct { rows: u32, streams: u32, groups: u32 }; + +/// A backend's round graphs; the cache is made at the first round, where the backend's address stays put. +pub const Rounds = struct { + engine: gc.CudaEngine, + cache: ?gc.Cache(Key) = null, + + pub fn deinit(r: *Rounds) void { + if (r.cache) |*c| c.deinit(); + } + + /// Every graph freed: attach replaces the caches and the page table they read. + pub fn drop(r: *Rounds) void { + if (r.cache) |*c| c.dropAll(); + } + + /// Every row's fp32 logits at `out` for a decode round: inputs staged as `forward` stages them, then the graph. + pub fn forward(r: *Rounds, m: *fwd.Model, o: kern.Ops, chains: []const fwd.Chain, out: u64) !void { + const st = try m.stage(o, chains, false); + var all: [fwd.round_rows]usize = undefined; + for (all[0..st.n], 0..) |*row, i| row.* = i; + var body: Body = .{ .m = m, .o = o, .st = st, .streams = chains.len, .pick = all[0..st.n], .out = out }; + if (r.cache == null) { + r.cache = gc.Cache(Key).init(m.gpa, r.engine.engine(), .{}); + r.cache.?.name = "kolibri1 rounds"; + } + const key: Key = .{ .rows = @intCast(st.n), .streams = @intCast(chains.len), .groups = @intCast(st.ng) }; + const fp = gc.fingerprintOf(&.{ out, m.origin, m.table, m.s.x }); + _ = try r.cache.?.run(key, o.s, fp, .{ .ctx = &body, .run = Body.run }); + } +}; + +/// A round's launches as the eager forward makes them, on the stream the cache runs them on. +const Body = struct { + m: *fwd.Model, + o: kern.Ops, + st: fwd.Model.Staged, + streams: usize, + pick: []const usize, + out: u64, + + fn run(ctx: *anyopaque, s: cuda.Stream) anyerror!void { + const b: *Body = @ptrCast(@alignCast(ctx)); + var o = b.o; + o.s = s; + try b.m.launch(o, b.st.n, null, b.st.t, b.streams, b.st.ng, @min(b.m.max_rows, fwd.round_rows), b.pick, b.out); + } +}; + +test "kolibri rounds: a plan's offsets follow its rows and streams alone, which a round's key holds" { + const gpa = std.testing.allocator; + const a = try tree.build(gpa, &.{ .{ .rows = 3, .committed = 700 }, .{ .rows = 1, .committed = 5 } }); + defer gpa.free(a.flat); + const b = try tree.build(gpa, &.{ .{ .rows = 2, .committed = 9 }, .{ .rows = 2, .committed = 4000 } }); + defer gpa.free(b.flat); + try std.testing.expectEqual(a.streamsAt(), b.streamsAt()); + try std.testing.expectEqual(a.parentsAt(), b.parentsAt()); + const c = try tree.build(gpa, &.{ .{ .rows = 2, .committed = 9 }, .{ .rows = 1, .committed = 9 }, .{ .rows = 1, .committed = 9 } }); + defer gpa.free(c.flat); + try std.testing.expect(c.parentsAt() != a.parentsAt()); // a third stream moves the parents: the key holds streams +} From 8385d3c57d3353d0841ce1cf050fd0f0aa924143 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:03:51 +0000 Subject: [PATCH 263/361] changelog: kolibri1 cuda: decode rounds of several rows replay CUDA graphs --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6a6cdd2c99..57e72da8eed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,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. - 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). +- Kolibri-1 on CUDA: decode rounds of two or more rows replay a CUDA graph captured once a shape, making the eager round's launches, so tokens are unchanged; `TENSORFOLD_KOLIBRI_GRAPHS=0` keeps them eager (#4884). - 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. From 0652b7907b847786c53bc44b04a43c16a8dcf547 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:02:46 +0000 Subject: [PATCH 264/361] changelog: #4884's line from lines/4884.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57e72da8eed..b3df71acbd9 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 +- Kolibri-1 on CUDA: decode rounds of two or more rows replay a CUDA graph captured once a shape, making the eager round's launches, so tokens are unchanged; `TENSORFOLD_KOLIBRI_GRAPHS=0` keeps them eager (#4884). + - Inkling 2 Mini on CUDA: decode experts run a warp over 8 columns with gate and up in one launch, about 3% faster one-stream decode on GB10 on top of #4728, with identical tokens (#4729). Thanks @jschmied. @@ -81,7 +83,6 @@ 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. - 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). -- Kolibri-1 on CUDA: decode rounds of two or more rows replay a CUDA graph captured once a shape, making the eager round's launches, so tokens are unchanged; `TENSORFOLD_KOLIBRI_GRAPHS=0` keeps them eager (#4884). - 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. From a9f2d991d557ab082324b220ebc6eb3901d897ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:51:00 +0100 Subject: [PATCH 265/361] Metal text-only loads hold no vision weights: Gemma 4 and LFM3-VL pack their language model, Step-5 reads its tower only with --vision - Gemma 4: each shard's language_model. tensors pack into their own buffer, not the file span that holds the 31B's vision tower (0.88 GiB); the tower still loads apart with --vision. - LFM3-VL: the language model packs alone; the tower and projector no Metal kernel runs stay on disk (0.35 GiB). - Step-5: without --vision the tower and projector stay in their files and no tower is built; with it, as before. --- zig/src/families/gemma4/model.zig | 39 +++++++++++++++++++++ zig/src/families/gemma4/vision.zig | 4 +-- zig/src/families/lfm3/model.zig | 47 ++++++++++++++++++++++++-- zig/src/families/step5/model.zig | 54 +++++++++++++++++++++++++++--- zig/src/families/step5/step5.zig | 1 + zig/src/native/step5.zig | 2 +- zig/src/tensorfold.zig | 1 + 7 files changed, 139 insertions(+), 9 deletions(-) diff --git a/zig/src/families/gemma4/model.zig b/zig/src/families/gemma4/model.zig index 06cb8ef89bb..d679fc87ab4 100644 --- a/zig/src/families/gemma4/model.zig +++ b/zig/src/families/gemma4/model.zig @@ -235,3 +235,42 @@ test "a tower that fails to load leaves the model without one, so deinit frees n try std.testing.expectError(error.UnexpectedGemmaVisionTensor, m.loadVision(std.testing.io, dir)); try std.testing.expect(m.vision == null); } + +/// A shard's language-model tensors, packed into their own buffer, not the file span between them holding the tower. +pub fn addShard(c: *ckpt.Checkpoint, device: mtl.Device, path: [:0]const u8) !void { + try c.addFileSplit(device, path, "", "language_model.", vision.never); +} + +test "a shard's language model is held without the vision tower stored between its tensors" { + 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 31B's last shard: language-model tensors on both sides of vision_tower. and embed_vision. + const header = + \\{"language_model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, + \\ "vision_tower.x":{"dtype":"U8","shape":[4096],"data_offsets":[4,4100]}, + \\ "embed_vision.y":{"dtype":"U8","shape":[1024],"data_offsets":[4100,5124]}, + \\ "language_model.b":{"dtype":"BF16","shape":[3],"data_offsets":[5124,5130]}} + ; + var data: [8 + header.len + 5130]u8 = undefined; + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); + const path = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/model.safetensors", .{tmp.sub_path}, 0); + defer gpa.free(path); + var span = ckpt.Checkpoint.init(gpa); + defer span.deinit(); + try span.addFileSelected(device, path, "", "language_model."); + try std.testing.expectEqual(@as(usize, 5130), span.residentBytes()); + var text = ckpt.Checkpoint.init(gpa); + defer text.deinit(); + try addShard(&text, device, path); + try std.testing.expectEqual(@as(usize, ckpt.alignment + 6), text.residentBytes()); + try std.testing.expect(!text.has("vision_tower.x") and !text.has("embed_vision.y")); + inline for (.{ "language_model.a", "language_model.b" }) |name| + try std.testing.expectEqualSlices(u16, (try span.get(name)).host(u16), (try text.get(name)).host(u16)); +} diff --git a/zig/src/families/gemma4/vision.zig b/zig/src/families/gemma4/vision.zig index b0926de3b31..cffec90b337 100644 --- a/zig/src/families/gemma4/vision.zig +++ b/zig/src/families/gemma4/vision.zig @@ -42,8 +42,8 @@ const G = enum { pos, rms, rms_add, qkv, softmax, heads_, geglu, pool, rows }; const Layer = struct { in_norm: Ref, post_attn: Ref, pre_ff: Ref, post_ff: Ref, q: Ref, k: Ref, v: Ref, o: Ref, q_norm: Ref, k_norm: Ref, gate: Ref, up: Ref, down: Ref }; -/// No tower tensor stays in its file: vision_tower. and embed_vision. pack, 256-byte aligned, into their own buffers. -fn never(_: []const u8, _: usize) bool { +/// No tensor stays in its file: the selected ones pack, 256-byte aligned, into their own buffer (tower and text alike). +pub fn never(_: []const u8, _: usize) bool { return false; } diff --git a/zig/src/families/lfm3/model.zig b/zig/src/families/lfm3/model.zig index 93dfbc13a6a..ec0bca242b1 100644 --- a/zig/src/families/lfm3/model.zig +++ b/zig/src/families/lfm3/model.zig @@ -1,4 +1,4 @@ -//! An owned LFM3 checkpoint and its native Metal text pipelines; VL tensors remain intact without vision execution. +//! An owned LFM3 checkpoint and its native Metal text pipelines; a VL checkpoint holds its language model only. const std = @import("std"); const mtl = @import("metal"); const cfg = @import("config.zig"); @@ -45,7 +45,7 @@ pub const Model = struct { errdefer m.checkpoint.deinit(); const files = try shards.shardFiles(gpa, io, dir); defer shards.freeShardFiles(gpa, files); - for (files) |path| try m.checkpoint.addFile(m.device, path, ""); + for (files) |path| try addShard(&m.checkpoint, m.device, path, config.kind); m.weights = try weights.load(&m.checkpoint, &m.config); m.kernels = try kernels.load(m.device); m.resident = null; @@ -102,3 +102,46 @@ pub const Model = struct { m.gpa.destroy(m); } }; + +/// A VL checkpoint's text tensors pack into their own buffer, without the tower and projector no Metal kernel runs. +pub fn addShard(c: *ckpt.Checkpoint, device: mtl.Device, path: [:0]const u8, kind: cfg.Kind) !void { + if (kind == .text) return c.addFile(device, path, ""); + try c.addFileSplit(device, path, "", "language_model.", never); +} + +fn never(_: []const u8, _: usize) bool { + return false; +} + +test "an LFM3-VL shard holds its language model only; a text shard holds everything as before" { + 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(); + // LFM3-VL's order: language_model.model., then multi_modal_projector. and vision_tower. + const header = + \\{"language_model.model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, + \\ "multi_modal_projector.p":{"dtype":"U8","shape":[1024],"data_offsets":[4,1028]}, + \\ "vision_tower.x":{"dtype":"U8","shape":[4096],"data_offsets":[1028,5124]}} + ; + var data: [8 + header.len + 5124]u8 = undefined; + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); + const path = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/model.safetensors", .{tmp.sub_path}, 0); + defer gpa.free(path); + var all = ckpt.Checkpoint.init(gpa); + defer all.deinit(); + try addShard(&all, device, path, .text); + try std.testing.expectEqual(@as(usize, 5124), all.residentBytes()); + var text = ckpt.Checkpoint.init(gpa); + defer text.deinit(); + try addShard(&text, device, path, .vision_language); + try std.testing.expectEqual(@as(usize, 4), text.residentBytes()); + try std.testing.expect(!text.has("vision_tower.x") and !text.has("multi_modal_projector.p")); + const name = "language_model.model.a"; + try std.testing.expectEqualSlices(u16, (try all.get(name)).host(u16), (try text.get(name)).host(u16)); +} diff --git a/zig/src/families/step5/model.zig b/zig/src/families/step5/model.zig index f63696b13c4..c4c12a5d12a 100644 --- a/zig/src/families/step5/model.zig +++ b/zig/src/families/step5/model.zig @@ -30,12 +30,13 @@ pub const Model = struct { route: [2]mtl.Pipeline, /// Prompt attention on the tensor units, for the shape it is written for (192 dims, 16 heads a KV group). attend_nax: ?mtl.Pipeline = null, - /// The image tower, when the checkpoint holds one (tools/step5_fp8_to_mlx.py --only-vision). + /// The image tower, loaded with --vision when the checkpoint holds one (tools/step5_fp8_to_mlx.py --only-vision). vision: ?*vision.Vision = null, mm: [4]Mm = undefined, mms: usize = 0, - pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { + /// With `tower` false (serve without --vision) the tower and projector stay on disk and are never built. + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, tower: bool) !*Model { const pool = mtl.objc.Pool.push(); defer pool.pop(); const m = try gpa.create(Model); @@ -53,7 +54,7 @@ pub const Model = struct { errdefer m.checkpoint.deinit(); const files = try shards.shardFiles(gpa, io, dir); defer shards.freeShardFiles(gpa, files); - for (files) |path| try m.checkpoint.addFile(m.device, path, ""); + for (files) |path| try addShard(&m.checkpoint, m.device, path, tower); m.weights = try weights.load(gpa, m.device, &m.checkpoint, &m.config); errdefer m.weights.deinit(gpa); const c = &m.config; @@ -89,7 +90,7 @@ pub const Model = struct { defer lib.deinit(); m.attend_nax = try mtl.Pipeline.init(m.device, lib, "s5_attend_nax", false); } - if (m.checkpoint.has("vision_model.conv1.weight")) m.vision = try vision.Vision.load(gpa, m.device, &m.checkpoint, c.hidden); + if (tower and m.checkpoint.has("vision_model.conv1.weight")) m.vision = try vision.Vision.load(gpa, m.device, &m.checkpoint, c.hidden); errdefer if (m.vision) |v| v.deinit(); for (m.weights.layers) |l| { try m.addMm(l.attn.q); @@ -147,3 +148,48 @@ pub const Model = struct { m.gpa.destroy(m); } }; + +/// The tower and projector tensors: the ones tools/step5_fp8_to_mlx.py --vision or --only-vision writes. +fn isTower(name: []const u8, _: usize) bool { + return std.mem.startsWith(u8, name, "vision_model.") or std.mem.startsWith(u8, name, "vit_large_projector"); +} + +/// A shard as before with `tower`; without it the text tensors pack into their own buffer, the tower stays in the file. +pub fn addShard(c: *ck.Checkpoint, device: mtl.Device, path: [:0]const u8, tower: bool) !void { + try c.addFileSplit(device, path, "", null, if (tower) null else isTower); +} + +test "without --vision a Step-5 shard holds its text tensors only; the tower and projector stay in the file" { + 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(); + // --vision writes the tower and projector into the same shards as the text model + const header = + \\{"model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, + \\ "vision_model.conv1.weight":{"dtype":"U8","shape":[4096],"data_offsets":[4,4100]}, + \\ "vit_large_projector.weight":{"dtype":"U8","shape":[1024],"data_offsets":[4100,5124]}, + \\ "lm_head.b":{"dtype":"BF16","shape":[3],"data_offsets":[5124,5130]}} + ; + var data: [8 + header.len + 5130]u8 = undefined; + std.mem.writeInt(u64, data[0..8], header.len, .little); + @memcpy(data[8..][0..header.len], header); + for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); + const path = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/model.safetensors", .{tmp.sub_path}, 0); + defer gpa.free(path); + var all = ck.Checkpoint.init(gpa); + defer all.deinit(); + try addShard(&all, device, path, true); + try std.testing.expectEqual(@as(usize, 5130), all.residentBytes()); + try std.testing.expect(all.tensors.contains("vision_model.conv1.weight")); + var text = ck.Checkpoint.init(gpa); + defer text.deinit(); + try addShard(&text, device, path, false); + try std.testing.expectEqual(@as(usize, ck.alignment + 6), text.residentBytes()); + try std.testing.expect(!text.tensors.contains("vision_model.conv1.weight") and !text.tensors.contains("vit_large_projector.weight")); + inline for (.{ "model.a", "lm_head.b" }) |name| + try std.testing.expectEqualSlices(u16, (try all.get(name)).host(u16), (try text.get(name)).host(u16)); +} diff --git a/zig/src/families/step5/step5.zig b/zig/src/families/step5/step5.zig index b14344ecd4e..7cc4cea0807 100644 --- a/zig/src/families/step5/step5.zig +++ b/zig/src/families/step5/step5.zig @@ -13,6 +13,7 @@ pub const vision = @import("vision.zig"); test { _ = config; + _ = @import("model.zig"); _ = backend; _ = budget; _ = snapshot; diff --git a/zig/src/native/step5.zig b/zig/src/native/step5.zig index 874eff49fa4..d1f95e68a0e 100644 --- a/zig/src/native/step5.zig +++ b/zig/src/native/step5.zig @@ -42,7 +42,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope } const pool = mtl.objc.Pool.push(); defer pool.pop(); - const model = s5.Model.load(gpa, io, o.dir) catch |err| { + const model = s5.Model.load(gpa, io, o.dir, o.vision != null) catch |err| { problem.* = try std.fmt.allocPrint(a, "the native Step-5 engine cannot load this checkpoint ({s})", .{@errorName(err)}); return null; }; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index f8c3412f836..14b23673d47 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -99,6 +99,7 @@ test { _ = @import("families/uocr/uocr.zig"); _ = lora_merge; _ = @import("families/lfm3/backend.zig"); + _ = @import("families/lfm3/model.zig"); _ = @import("families/lfm3/state.zig"); _ = @import("families/lfm3/qk_segments_test.zig"); // a shared round's qk in one dispatch (Metal) _ = @import("families/lfm3/snapshot.zig"); From 55c7dfee9d7fac512f3fed7b6303cbb670929ee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:54:02 +0100 Subject: [PATCH 266/361] LFM3-VL on Metal keeps both text namespaces: a bare model.* checkpoint loads again, still without its tower addShard selected language_model. only, so a VL checkpoint in the bare model.* namespace, which metal_weights.load accepts, lost model.embed_tokens.weight and stopped at MissingTensor. It now reads both prefixes; vision_tower. and multi_modal_projector. stay on disk as before. The device test runs a wrapped and a bare shard. --- zig/src/families/lfm3/model.zig | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/zig/src/families/lfm3/model.zig b/zig/src/families/lfm3/model.zig index ec0bca242b1..79c9b49e549 100644 --- a/zig/src/families/lfm3/model.zig +++ b/zig/src/families/lfm3/model.zig @@ -103,29 +103,33 @@ pub const Model = struct { } }; -/// A VL checkpoint's text tensors pack into their own buffer, without the tower and projector no Metal kernel runs. +/// A VL checkpoint's text tensors, wrapped (`language_model.`) or bare (`model.`), pack without tower and projector. pub fn addShard(c: *ckpt.Checkpoint, device: mtl.Device, path: [:0]const u8, kind: cfg.Kind) !void { if (kind == .text) return c.addFile(device, path, ""); - try c.addFileSplit(device, path, "", "language_model.", never); + // both namespaces metal_weights.load accepts; a shard holding both is still refused there (MixedNamespaces) + for ([_][]const u8{ "language_model.", "model." }) |text| try c.addFileSplit(device, path, "", text, never); } fn never(_: []const u8, _: usize) bool { return false; } -test "an LFM3-VL shard holds its language model only; a text shard holds everything as before" { +test "an LFM3-VL shard, wrapped or bare, holds its language model only; a text shard holds everything as before" { if (comptime !@hasDecl(mtl.Device, "init")) return error.SkipZigTest; const device = mtl.Device.init() catch return error.SkipZigTest; defer device.deinit(); + inline for (.{ "language_model.model.embed_tokens.weight", "model.embed_tokens.weight" }) |name| + try textOnly(device, name); +} + +/// A shard in LFM3-VL's order (text tensor `name`, multi_modal_projector., vision_tower.) read both ways. +fn textOnly(device: mtl.Device, comptime name: []const u8) !void { const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); - // LFM3-VL's order: language_model.model., then multi_modal_projector. and vision_tower. - const header = - \\{"language_model.model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, - \\ "multi_modal_projector.p":{"dtype":"U8","shape":[1024],"data_offsets":[4,1028]}, - \\ "vision_tower.x":{"dtype":"U8","shape":[4096],"data_offsets":[1028,5124]}} - ; + const header = "{\"" ++ name ++ "\":{\"dtype\":\"BF16\",\"shape\":[2],\"data_offsets\":[0,4]}," ++ + "\"multi_modal_projector.p\":{\"dtype\":\"U8\",\"shape\":[1024],\"data_offsets\":[4,1028]}," ++ + "\"vision_tower.x\":{\"dtype\":\"U8\",\"shape\":[4096],\"data_offsets\":[1028,5124]}}"; var data: [8 + header.len + 5124]u8 = undefined; std.mem.writeInt(u64, data[0..8], header.len, .little); @memcpy(data[8..][0..header.len], header); @@ -142,6 +146,5 @@ test "an LFM3-VL shard holds its language model only; a text shard holds everyth try addShard(&text, device, path, .vision_language); try std.testing.expectEqual(@as(usize, 4), text.residentBytes()); try std.testing.expect(!text.has("vision_tower.x") and !text.has("multi_modal_projector.p")); - const name = "language_model.model.a"; try std.testing.expectEqualSlices(u16, (try all.get(name)).host(u16), (try text.get(name)).host(u16)); } From 22f6d04dab995af639597e6836e85e2dbddb8bc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:56:39 +0100 Subject: [PATCH 267/361] Split Step-5 out: this PR covers Gemma 4 and LFM3-VL only The Step-5 loader change (model.load's tower flag, addShard and its device test) returns to main's code and moves to its own branch, as asked in review. Gemma 4 and LFM3-VL are unchanged. --- zig/src/families/step5/model.zig | 54 +++----------------------------- zig/src/families/step5/step5.zig | 1 - zig/src/native/step5.zig | 2 +- 3 files changed, 5 insertions(+), 52 deletions(-) diff --git a/zig/src/families/step5/model.zig b/zig/src/families/step5/model.zig index c4c12a5d12a..f63696b13c4 100644 --- a/zig/src/families/step5/model.zig +++ b/zig/src/families/step5/model.zig @@ -30,13 +30,12 @@ pub const Model = struct { route: [2]mtl.Pipeline, /// Prompt attention on the tensor units, for the shape it is written for (192 dims, 16 heads a KV group). attend_nax: ?mtl.Pipeline = null, - /// The image tower, loaded with --vision when the checkpoint holds one (tools/step5_fp8_to_mlx.py --only-vision). + /// The image tower, when the checkpoint holds one (tools/step5_fp8_to_mlx.py --only-vision). vision: ?*vision.Vision = null, mm: [4]Mm = undefined, mms: usize = 0, - /// With `tower` false (serve without --vision) the tower and projector stay on disk and are never built. - pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, tower: bool) !*Model { + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !*Model { const pool = mtl.objc.Pool.push(); defer pool.pop(); const m = try gpa.create(Model); @@ -54,7 +53,7 @@ pub const Model = struct { errdefer m.checkpoint.deinit(); const files = try shards.shardFiles(gpa, io, dir); defer shards.freeShardFiles(gpa, files); - for (files) |path| try addShard(&m.checkpoint, m.device, path, tower); + for (files) |path| try m.checkpoint.addFile(m.device, path, ""); m.weights = try weights.load(gpa, m.device, &m.checkpoint, &m.config); errdefer m.weights.deinit(gpa); const c = &m.config; @@ -90,7 +89,7 @@ pub const Model = struct { defer lib.deinit(); m.attend_nax = try mtl.Pipeline.init(m.device, lib, "s5_attend_nax", false); } - if (tower and m.checkpoint.has("vision_model.conv1.weight")) m.vision = try vision.Vision.load(gpa, m.device, &m.checkpoint, c.hidden); + if (m.checkpoint.has("vision_model.conv1.weight")) m.vision = try vision.Vision.load(gpa, m.device, &m.checkpoint, c.hidden); errdefer if (m.vision) |v| v.deinit(); for (m.weights.layers) |l| { try m.addMm(l.attn.q); @@ -148,48 +147,3 @@ pub const Model = struct { m.gpa.destroy(m); } }; - -/// The tower and projector tensors: the ones tools/step5_fp8_to_mlx.py --vision or --only-vision writes. -fn isTower(name: []const u8, _: usize) bool { - return std.mem.startsWith(u8, name, "vision_model.") or std.mem.startsWith(u8, name, "vit_large_projector"); -} - -/// A shard as before with `tower`; without it the text tensors pack into their own buffer, the tower stays in the file. -pub fn addShard(c: *ck.Checkpoint, device: mtl.Device, path: [:0]const u8, tower: bool) !void { - try c.addFileSplit(device, path, "", null, if (tower) null else isTower); -} - -test "without --vision a Step-5 shard holds its text tensors only; the tower and projector stay in the file" { - 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(); - // --vision writes the tower and projector into the same shards as the text model - const header = - \\{"model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, - \\ "vision_model.conv1.weight":{"dtype":"U8","shape":[4096],"data_offsets":[4,4100]}, - \\ "vit_large_projector.weight":{"dtype":"U8","shape":[1024],"data_offsets":[4100,5124]}, - \\ "lm_head.b":{"dtype":"BF16","shape":[3],"data_offsets":[5124,5130]}} - ; - var data: [8 + header.len + 5130]u8 = undefined; - std.mem.writeInt(u64, data[0..8], header.len, .little); - @memcpy(data[8..][0..header.len], header); - for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); - const path = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/model.safetensors", .{tmp.sub_path}, 0); - defer gpa.free(path); - var all = ck.Checkpoint.init(gpa); - defer all.deinit(); - try addShard(&all, device, path, true); - try std.testing.expectEqual(@as(usize, 5130), all.residentBytes()); - try std.testing.expect(all.tensors.contains("vision_model.conv1.weight")); - var text = ck.Checkpoint.init(gpa); - defer text.deinit(); - try addShard(&text, device, path, false); - try std.testing.expectEqual(@as(usize, ck.alignment + 6), text.residentBytes()); - try std.testing.expect(!text.tensors.contains("vision_model.conv1.weight") and !text.tensors.contains("vit_large_projector.weight")); - inline for (.{ "model.a", "lm_head.b" }) |name| - try std.testing.expectEqualSlices(u16, (try all.get(name)).host(u16), (try text.get(name)).host(u16)); -} diff --git a/zig/src/families/step5/step5.zig b/zig/src/families/step5/step5.zig index 7cc4cea0807..b14344ecd4e 100644 --- a/zig/src/families/step5/step5.zig +++ b/zig/src/families/step5/step5.zig @@ -13,7 +13,6 @@ pub const vision = @import("vision.zig"); test { _ = config; - _ = @import("model.zig"); _ = backend; _ = budget; _ = snapshot; diff --git a/zig/src/native/step5.zig b/zig/src/native/step5.zig index d1f95e68a0e..874eff49fa4 100644 --- a/zig/src/native/step5.zig +++ b/zig/src/native/step5.zig @@ -42,7 +42,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope } const pool = mtl.objc.Pool.push(); defer pool.pop(); - const model = s5.Model.load(gpa, io, o.dir, o.vision != null) catch |err| { + const model = s5.Model.load(gpa, io, o.dir) catch |err| { problem.* = try std.fmt.allocPrint(a, "the native Step-5 engine cannot load this checkpoint ({s})", .{@errorName(err)}); return null; }; From 148056504fa2d12cd4cc25f4aa42a909790dba7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:09 +0100 Subject: [PATCH 268/361] Drop the Gemma 4 part: main already reads its shards without the tower Since #3350, gemma4/model.zig reads each shard with addFileSplit(.., "language_model.", weights.later), so the tower is not held on main; this PR's addShard was only called by its own test. The PR now covers LFM3-VL only. --- zig/src/families/gemma4/model.zig | 39 ------------------------------ zig/src/families/gemma4/vision.zig | 4 +-- 2 files changed, 2 insertions(+), 41 deletions(-) diff --git a/zig/src/families/gemma4/model.zig b/zig/src/families/gemma4/model.zig index d679fc87ab4..06cb8ef89bb 100644 --- a/zig/src/families/gemma4/model.zig +++ b/zig/src/families/gemma4/model.zig @@ -235,42 +235,3 @@ test "a tower that fails to load leaves the model without one, so deinit frees n try std.testing.expectError(error.UnexpectedGemmaVisionTensor, m.loadVision(std.testing.io, dir)); try std.testing.expect(m.vision == null); } - -/// A shard's language-model tensors, packed into their own buffer, not the file span between them holding the tower. -pub fn addShard(c: *ckpt.Checkpoint, device: mtl.Device, path: [:0]const u8) !void { - try c.addFileSplit(device, path, "", "language_model.", vision.never); -} - -test "a shard's language model is held without the vision tower stored between its tensors" { - 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 31B's last shard: language-model tensors on both sides of vision_tower. and embed_vision. - const header = - \\{"language_model.a":{"dtype":"BF16","shape":[2],"data_offsets":[0,4]}, - \\ "vision_tower.x":{"dtype":"U8","shape":[4096],"data_offsets":[4,4100]}, - \\ "embed_vision.y":{"dtype":"U8","shape":[1024],"data_offsets":[4100,5124]}, - \\ "language_model.b":{"dtype":"BF16","shape":[3],"data_offsets":[5124,5130]}} - ; - var data: [8 + header.len + 5130]u8 = undefined; - std.mem.writeInt(u64, data[0..8], header.len, .little); - @memcpy(data[8..][0..header.len], header); - for (data[8 + header.len ..], 0..) |*b, i| b.* = @truncate(i); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "model.safetensors", .data = &data }); - const path = try std.fmt.allocPrintSentinel(gpa, ".zig-cache/tmp/{s}/model.safetensors", .{tmp.sub_path}, 0); - defer gpa.free(path); - var span = ckpt.Checkpoint.init(gpa); - defer span.deinit(); - try span.addFileSelected(device, path, "", "language_model."); - try std.testing.expectEqual(@as(usize, 5130), span.residentBytes()); - var text = ckpt.Checkpoint.init(gpa); - defer text.deinit(); - try addShard(&text, device, path); - try std.testing.expectEqual(@as(usize, ckpt.alignment + 6), text.residentBytes()); - try std.testing.expect(!text.has("vision_tower.x") and !text.has("embed_vision.y")); - inline for (.{ "language_model.a", "language_model.b" }) |name| - try std.testing.expectEqualSlices(u16, (try span.get(name)).host(u16), (try text.get(name)).host(u16)); -} diff --git a/zig/src/families/gemma4/vision.zig b/zig/src/families/gemma4/vision.zig index cffec90b337..b0926de3b31 100644 --- a/zig/src/families/gemma4/vision.zig +++ b/zig/src/families/gemma4/vision.zig @@ -42,8 +42,8 @@ const G = enum { pos, rms, rms_add, qkv, softmax, heads_, geglu, pool, rows }; const Layer = struct { in_norm: Ref, post_attn: Ref, pre_ff: Ref, post_ff: Ref, q: Ref, k: Ref, v: Ref, o: Ref, q_norm: Ref, k_norm: Ref, gate: Ref, up: Ref, down: Ref }; -/// No tensor stays in its file: the selected ones pack, 256-byte aligned, into their own buffer (tower and text alike). -pub fn never(_: []const u8, _: usize) bool { +/// No tower tensor stays in its file: vision_tower. and embed_vision. pack, 256-byte aligned, into their own buffers. +fn never(_: []const u8, _: usize) bool { return false; } From d66b998d4ec36541df450e4c9dec1b6a86ac5e29 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:18:05 +0000 Subject: [PATCH 269/361] changelog: #3420 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3df71acbd9..d32446eca28 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 +- LFM3-VL on Metal: a text-only load leaves the vision tower and projector on disk, so it holds only the text weights; replies are unchanged (#3420). + - Kolibri-1 on CUDA: decode rounds of two or more rows replay a CUDA graph captured once a shape, making the eager round's launches, so tokens are unchanged; `TENSORFOLD_KOLIBRI_GRAPHS=0` keeps them eager (#4884). - Inkling 2 Mini on CUDA: decode experts run a warp over 8 columns with gate and up in one launch, about 3% faster one-stream decode on GB10 on top of #4728, with identical tokens (#4729). Thanks @jschmied. From 2b1758cbe762a835f478de7b670571a7e1b294eb Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:26:15 +0000 Subject: [PATCH 270/361] inkling2 metal: the router and loop-gate dots a thread an output, bit for bit main's Main's router computes 128 expert scores in one 256-thread group a row and then picks on thread 0; the loop gates run one 256-thread group a row, with 64 threads on the down dot, and the forward called them once per row. Both keep each output's FP32 dot as one serial ascending chain, which is what makes them exact, and both leave most of the GPU idle. The split keeps every chain and every expression as main wrote them and only changes the launch shape: - router: tf_inkling2_route_scores, one thread an (expert, row) score in 32-expert groups, then tf_inkling2_route_select, one thread a row with main's top-8 and ascending-index combine over the stored scores; - loop gates: tf_inkling2_loop_norm (main's reduction, its BF16 rows stored), tf_inkling2_loop_down (one thread a (rank, row), main's serial dot) and tf_inkling2_loop_apply (main's forget and gain), over every row of a controller in one call; m's rows are a token's message entries apart. The forward uses the split by default; main's kernels stay in the library as the contract's baseline. The contract compares the split's bytes (and the router's expert ids) with main's kernels at 1, 33 and 64 rows, with inputs that open each dot with +B x0 - B x0 so any other summation order shows; m is laid out at production's stride with NaN between rows. A strided two-chain dot and a one-index-off store are planted for each kernel and must go red. --- zig/kernels/metal/inkling2/glue_sources.zig | 4 +- zig/kernels/metal/inkling2/glue_split.metal | 44 ++++++++++ zig/kernels/metal/inkling2/loop_sources.zig | 4 +- zig/kernels/metal/inkling2/loop_split.metal | 72 +++++++++++++++++ .../contract/inkling2_glue_metal_records.zig | 2 + .../contract/inkling2_loop_metal_records.zig | 3 + zig/src/families/inkling2/metal/forward.zig | 16 ++-- zig/src/families/inkling2/metal/glue.zig | 21 ++++- zig/src/families/inkling2/metal/glue_test.zig | 14 +++- zig/src/families/inkling2/metal/loop.zig | 33 +++++++- zig/src/families/inkling2/metal/loop_test.zig | 15 +++- zig/src/families/inkling2/metal/state.zig | 15 ++-- .../contract/metal_inkling2_controls_host.zig | 1 + zig/tests/contract/metal_inkling2_glue.zig | 65 ++++++++++++++- zig/tests/contract/metal_inkling2_loop.zig | 80 ++++++++++++++++++- .../metal_inkling2_split_controls.zig | 62 ++++++++++++++ 16 files changed, 428 insertions(+), 23 deletions(-) create mode 100644 zig/kernels/metal/inkling2/glue_split.metal create mode 100644 zig/kernels/metal/inkling2/loop_split.metal create mode 100644 zig/tests/contract/metal_inkling2_split_controls.zig diff --git a/zig/kernels/metal/inkling2/glue_sources.zig b/zig/kernels/metal/inkling2/glue_sources.zig index b0e00911c06..4b80e23ac00 100644 --- a/zig/kernels/metal/inkling2/glue_sources.zig +++ b/zig/kernels/metal/inkling2/glue_sources.zig @@ -1,2 +1,2 @@ -//! Inkling 2 Mini's embedding, residual, convolution, routing and output glue. -pub const glue = @embedFile("glue.metal"); +//! Inkling 2 Mini's glue, then the split router (glue_split.metal), which the contract compares bit for bit. +pub const glue = @embedFile("glue.metal") ++ "\n" ++ @embedFile("glue_split.metal"); diff --git a/zig/kernels/metal/inkling2/glue_split.metal b/zig/kernels/metal/inkling2/glue_split.metal new file mode 100644 index 00000000000..3a7eed4010d --- /dev/null +++ b/zig/kernels/metal/inkling2/glue_split.metal @@ -0,0 +1,44 @@ +// tf_inkling2_router's bits in two launches, after glue.metal: a thread a score with main's serial dot, then picks. + +kernel void tf_inkling2_route_scores( + const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], device float* scores [[buffer(2)]], + constant InkRouteArgs& a [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + uint2 group [[threadgroup_position_in_grid]]) { + const uint row = group.y, e = group.x * 32 + t; + if (row >= a.rows || e >= 128) return; + const device bfloat* w = weight + size_t(e) * 2304; + const device bfloat* v = x + size_t(row) * 2304; + float dot = 0.0f; + for (uint d = 0; d < 2304; ++d) dot += float(w[d]) * float(v[d]); + scores[size_t(row) * 128 + e] = ink_sigmoid(dot); +} + +// One thread a row: main's top-8 and ascending-index combine over the stored scores. +kernel void tf_inkling2_route_select( + const device float* scores [[buffer(0)]], const device float* bias [[buffer(1)]], device uint* ids [[buffer(2)]], + device float* weights [[buffer(3)]], constant InkRouteArgs& a [[buffer(4)]], uint row [[thread_position_in_grid]]) { + if (row >= a.rows) return; + const device float* s = scores + size_t(row) * 128; + float chosen[8]; + uint picked[8]; + bool used[128] = {}; + for (uint j = 0; j < 8; ++j) { + uint best = 128; + for (uint e = 0; e < 128; ++e) if (!used[e]) { + if (best == 128 || s[e] + bias[e] > s[best] + bias[best]) best = e; + } + used[best] = true; picked[j] = best; chosen[j] = s[best]; + } + // Combining, including the denominator, is in ascending expert index. + for (uint j = 1; j < 8; ++j) { + uint id = picked[j]; float score = chosen[j]; uint k = j; + while (k > 0 && picked[k - 1] > id) { picked[k] = picked[k - 1]; chosen[k] = chosen[k - 1]; --k; } + picked[k] = id; chosen[k] = score; + } + float den = 1e-20f; + for (uint j = 0; j < 8; ++j) den += chosen[j]; + for (uint j = 0; j < 8; ++j) { + ids[row * 8 + j] = picked[j]; + weights[row * 8 + j] = precise::divide(chosen[j], den) * 8.0f; + } +} diff --git a/zig/kernels/metal/inkling2/loop_sources.zig b/zig/kernels/metal/inkling2/loop_sources.zig index 3e1345c1a82..601ec100f37 100644 --- a/zig/kernels/metal/inkling2/loop_sources.zig +++ b/zig/kernels/metal/inkling2/loop_sources.zig @@ -1,2 +1,2 @@ -//! Inkling 2 Mini's cross-pass message and rank-64 gate shaders. -pub const loop = @embedFile("loop.metal"); +//! Inkling 2 Mini's message and rank-64 gate shaders, then the split gates the contract compares bit for bit. +pub const loop = @embedFile("loop.metal") ++ "\n" ++ @embedFile("loop_split.metal"); diff --git a/zig/kernels/metal/inkling2/loop_split.metal b/zig/kernels/metal/inkling2/loop_split.metal new file mode 100644 index 00000000000..0130943ac75 --- /dev/null +++ b/zig/kernels/metal/inkling2/loop_split.metal @@ -0,0 +1,72 @@ +// tf_inkling2_loop_gates' bits in three launches over every row (m's rows a.m_stride floats apart), after loop.metal. + +struct InkLoopSplitArgs { uint rows, m_stride; }; + +kernel void tf_inkling2_loop_norm( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], device bfloat* normalized [[buffer(2)]], + constant InkLoopSplitArgs& a [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { + if (row >= a.rows) return; + const device float* inputs[2] = { h + size_t(row) * INKLING_LOOP_H, + m + size_t(row) * a.m_stride }; + threadgroup float sums[2 * 8], inverse[2]; + for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + const float x = inputs[s][d]; + ss += x * x; + } + const float reduced = simd_sum(ss); + if (lane == 0) sums[s * 8 + t / 32] = reduced; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) for (uint s = 0; s < 2; ++s) { + float ss = 0.0f; + for (uint j = 0; j < 8; ++j) ss += sums[s * 8 + j]; + inverse[s] = precise::rsqrt(precise::divide(ss, 2304.0f) + INKLING_LOOP_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device bfloat* out = normalized + size_t(row) * (2 * INKLING_LOOP_H); + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + out[d] = bfloat(h[size_t(row) * INKLING_LOOP_H + d] * inverse[0]); + out[INKLING_LOOP_H + d] = bfloat(m[size_t(row) * a.m_stride + d] * inverse[1]); + } +} + +// One thread a (rank, row), main's serial ascending dot over the stored BF16 norms. +kernel void tf_inkling2_loop_down( + const device bfloat* normalized [[buffer(0)]], const device bfloat* down [[buffer(1)]], + device float* zeta [[buffer(2)]], + constant InkLoopSplitArgs& a [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + uint2 group [[threadgroup_position_in_grid]]) { + const uint row = group.y, r = group.x * 32 + t; + if (row >= a.rows || r >= INKLING_LOOP_RANK) return; + const device bfloat* x = normalized + size_t(row) * (2 * INKLING_LOOP_H); + const device bfloat* w = down + size_t(r) * (2 * INKLING_LOOP_H); + float dot = 0.0f; + for (uint d = 0; d < 2 * INKLING_LOOP_H; ++d) dot += float(w[d]) * float(x[d]); + zeta[size_t(row) * INKLING_LOOP_RANK + r] = float(bfloat(dot)); +} + +kernel void tf_inkling2_loop_apply( + const device float* h [[buffer(0)]], const device float* m [[buffer(1)]], const device float* zeta [[buffer(2)]], + const device bfloat* forget [[buffer(3)]], const device bfloat* gain [[buffer(4)]], device float* out [[buffer(5)]], + constant InkLoopSplitArgs& a [[buffer(6)]], uint t [[thread_position_in_threadgroup]], + uint row [[threadgroup_position_in_grid]]) { + if (row >= a.rows) return; + const device float* z = zeta + size_t(row) * INKLING_LOOP_RANK; + for (uint d = t; d < INKLING_LOOP_H; d += 256) { + float fdot = 0.0f, gdot = 0.0f; + for (uint r = 0; r < INKLING_LOOP_RANK; ++r) { + fdot += float(forget[size_t(d) * INKLING_LOOP_RANK + r]) * z[r]; + gdot += float(gain[size_t(d) * INKLING_LOOP_RANK + r]) * z[r]; + } + const float f = precise::tanh(fdot); + const float g = precise::tanh(gdot); + // Four separately rounded binary32 steps; do not fold these into one expression. + const float keep = 1.0f - f; + const float left = keep * h[size_t(row) * INKLING_LOOP_H + d]; + const float right = g * m[size_t(row) * a.m_stride + d]; + out[size_t(row) * INKLING_LOOP_H + d] = left + right; + } +} diff --git a/zig/src/core/contract/inkling2_glue_metal_records.zig b/zig/src/core/contract/inkling2_glue_metal_records.zig index e0013f02bae..a57ea0f4d5d 100644 --- a/zig/src/core/contract/inkling2_glue_metal_records.zig +++ b/zig/src/core/contract/inkling2_glue_metal_records.zig @@ -10,4 +10,6 @@ pub const records = [_]M{ .{ .name = "metal inkling2 glue logits tf_inkling2_logits", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "metal inkling2 glue expert_pick tf_inkling2_expert_pick", .threads = 32, .tg_memory = 0, .reserved = 32 }, .{ .name = "metal inkling2 glue expert_combine tf_inkling2_expert_combine", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue route_scores tf_inkling2_route_scores", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 glue route_select tf_inkling2_route_select", .threads = 32, .tg_memory = 0, .reserved = 32 }, }; diff --git a/zig/src/core/contract/inkling2_loop_metal_records.zig b/zig/src/core/contract/inkling2_loop_metal_records.zig index 8f32f1a7ab5..067992f9b26 100644 --- a/zig/src/core/contract/inkling2_loop_metal_records.zig +++ b/zig/src/core/contract/inkling2_loop_metal_records.zig @@ -3,4 +3,7 @@ const M = @import("limits.zig").MetalLaunch; pub const records = [_]M{ .{ .name = "metal inkling2 loop messages tf_inkling2_loop_messages", .threads = 256, .tg_memory = 144, .reserved = 256 }, .{ .name = "metal inkling2 loop gates tf_inkling2_loop_gates", .threads = 256, .tg_memory = 9552, .reserved = 256 }, + .{ .name = "metal inkling2 loop norm tf_inkling2_loop_norm", .threads = 256, .tg_memory = 80, .reserved = 256 }, + .{ .name = "metal inkling2 loop down tf_inkling2_loop_down", .threads = 32, .tg_memory = 0, .reserved = 32 }, + .{ .name = "metal inkling2 loop apply tf_inkling2_loop_apply", .threads = 256, .tg_memory = 0, .reserved = 256 }, }; diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index afb7382ba5f..026a7ec7080 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -63,6 +63,12 @@ fn messageRow(s: *state.Scratch, core: usize, role: usize, i: usize) Ref { return at(s.messages, ((i * state.message_entries + core * 4 + role) * state.hidden) * 4); } +/// One controller over every row: m's rows are a token's message entries apart; the bits equal per-row `loop.gates`. +fn gates(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, h: Ref, msg: Ref, c: model_file.Controller, out: Ref, rows: usize) void { + const stride: u32 = state.message_entries * state.hidden; + loop.gatesSplit(&m.loop, e, l(h), l(msg), stride, l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(out), l(at(s.gate_norm, 0)), l(at(s.gate_zeta, 0)), @intCast(rows)); +} + fn runtime(m: *const Model, e: mtl.ComputeEncoder, op: model_file.RuntimeOp, refs: []const Ref, count: usize, boundary: usize) void { e.setPipeline(m.runtime[@backingInt(op)]); for (refs, 0..) |r_, i| e.setBuffer(r_.buf, r_.off, i); @@ -148,11 +154,11 @@ fn prepareAttentionInputs(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scra if (v.hasMessages()) { const controllers = w.controllers.?; const core = v.layer - 6; - for (0..3) |role| for (0..rows) |i| { + for (0..3) |role| { const c = controllers[role]; const source_role = if (lp.kind == .local) 0 else role; - loop.gates(&m.loop, e, l(arRow(s, source_role, rows, i, false)), l(messageRow(s, core, role, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(arRow(s, role, rows, i, true)), 1); - }; + gates(m, e, s, arRow(s, source_role, rows, 0, false), messageRow(s, core, role, 0), c, arRow(s, role, rows, 0, true), rows); + } } const gated = v.hasMessages(); // An ungated local visit has exactly one AR result and one norm result; Q/K/V alias. @@ -270,10 +276,10 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la if (gated) { const c = w.controllers.?[3]; const core = v.layer - 6; - for (0..rows) |i| loop.gates(&m.loop, e, l(row(s.mlp_ar, i, state.hidden * 4)), l(messageRow(s, core, 3, i)), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(row(s.mlp_gated, i, state.hidden * 4)), 1); + gates(m, e, s, at(s.mlp_ar, 0), messageRow(s, core, 3, 0), c, at(s.mlp_gated, 0), rows); norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); } else norm(m, e, at(s.mlp_ar, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); - glue.router(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); + glue.routerSplit(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_scores, 0), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); try routedExperts(m, e, s, v.layer, rows); base = 0; for (segments) |seg| { diff --git a/zig/src/families/inkling2/metal/glue.zig b/zig/src/families/inkling2/metal/glue.zig index dd74a1735a5..8c1249d0a40 100644 --- a/zig/src/families/inkling2/metal/glue.zig +++ b/zig/src/families/inkling2/metal/glue.zig @@ -17,6 +17,8 @@ pub const Pipelines = struct { conv_static: mtl.Pipeline, conv_dynamic: mtl.Pipeline, router: mtl.Pipeline, + route_scores: mtl.Pipeline, + route_select: mtl.Pipeline, swiglu: mtl.Pipeline, logits: mtl.Pipeline, expert_pick: mtl.Pipeline, @@ -28,7 +30,7 @@ pub const Pipelines = struct { pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); - var pipes: [9]mtl.Pipeline = undefined; + var pipes: [11]mtl.Pipeline = undefined; var made: usize = 0; errdefer for (pipes[0..made]) |pipe| pipe.deinit(); for ([_][]const u8{ @@ -41,6 +43,8 @@ pub const Pipelines = struct { "tf_inkling2_logits", "tf_inkling2_expert_pick", "tf_inkling2_expert_combine", + "tf_inkling2_route_scores", + "tf_inkling2_route_select", }, &pipes) |name, *pipe| { pipe.* = try mtl.Pipeline.init(device, lib, name, false); made += 1; @@ -55,6 +59,8 @@ pub const Pipelines = struct { .logits = pipes[6], .expert_pick = pipes[7], .expert_combine = pipes[8], + .route_scores = pipes[9], + .route_select = pipes[10], }; } pub fn deinit(p: *Pipelines) void { @@ -110,6 +116,19 @@ pub fn router(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, b e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } +/// `router`'s bits in two launches, a thread an (expert, row) score then a thread a row; scores: [rows][128] F32. +pub fn routerSplit(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, weight: Ref, bias: Ref, scores: Ref, ids: Ref, weights: Ref, rows: u32) void { + std.debug.assert(rows > 0); + e.setPipeline(p.route_scores); + inline for (.{ x, weight, scores }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(RouteArgs{ .rows = rows }, 3); + e.dispatchGroups(mtl.Size.of(experts / 32, rows, 1), unit); + e.setPipeline(p.route_select); + inline for (.{ scores, bias, ids, weights }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(RouteArgs{ .rows = rows }, 4); + e.dispatchGroups(mtl.Size.of((rows + 31) / 32, 1, 1), unit); +} + const ActArgs = extern struct { rows: u32, width: u32 }; pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gu: Ref, out: Ref, rows: u32, width: u32) void { std.debug.assert(rows > 0 and width > 0); diff --git a/zig/src/families/inkling2/metal/glue_test.zig b/zig/src/families/inkling2/metal/glue_test.zig index f1480f33b33..071180f5574 100644 --- a/zig/src/families/inkling2/metal/glue_test.zig +++ b/zig/src/families/inkling2/metal/glue_test.zig @@ -11,7 +11,8 @@ fn near(want: f64, got: f64) !void { } test "glue entries have one shader, symbol, unique launch record and honest scalar reservation" { - for (std.enums.values(p.Kind), records) |kind, record| { + const kinds = std.enums.values(p.Kind); + for (kinds, records[0..kinds.len]) |kind, record| { try t.expectEqualStrings(kind.label(), record.name); try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); try t.expectEqual(record.threads, record.reserved); @@ -22,6 +23,17 @@ test "glue entries have one shader, symbol, unique launch record and honest scal try t.expectEqual(@as(u32, 128), records[@backingInt(p.Kind.conv_dynamic)].tg_memory); } +test "the split router's two launches follow the kinds' records, one symbol and one scalar record each" { + const split = records[std.enums.values(p.Kind).len..]; + try t.expectEqual(@as(usize, 2), split.len); + for (split, [_][]const u8{ "tf_inkling2_route_scores", "tf_inkling2_route_select" }) |record, symbol| { + try t.expect(std.mem.endsWith(u8, record.name, symbol)); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, symbol)); + try t.expectEqual(@as(u32, 32), record.threads); + try t.expectEqual(record.threads, record.reserved); + } +} + test "shape admission fixes Mini's hidden and routed dimensions" { try t.expect(p.valid(.embed_norm, .{ .rows = 4, .n = p.hidden, .k = p.hidden })); try t.expect(!p.valid(.ar, .{ .rows = 6, .n = p.hidden, .k = p.hidden })); diff --git a/zig/src/families/inkling2/metal/loop.zig b/zig/src/families/inkling2/metal/loop.zig index ebd3588eedf..9fb3816570a 100644 --- a/zig/src/families/inkling2/metal/loop.zig +++ b/zig/src/families/inkling2/metal/loop.zig @@ -13,6 +13,9 @@ pub const RowsArgs = plan.RowsArgs; pub const Pipelines = struct { messages: mtl.Pipeline, gates: mtl.Pipeline, + norm: mtl.Pipeline, + down: mtl.Pipeline, + apply: mtl.Pipeline, pub fn load(device: mtl.Device) !Pipelines { return loadSource(device, sources.loop); @@ -23,9 +26,18 @@ pub const Pipelines = struct { var messages = try mtl.Pipeline.init(device, lib, plan.Kind.messages.symbol(), false); errdefer messages.deinit(); const gate_pipeline = try mtl.Pipeline.init(device, lib, plan.Kind.gates.symbol(), false); - return .{ .messages = messages, .gates = gate_pipeline }; + errdefer gate_pipeline.deinit(); + const norm = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_norm", false); + errdefer norm.deinit(); + const down = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_down", false); + errdefer down.deinit(); + const apply = try mtl.Pipeline.init(device, lib, "tf_inkling2_loop_apply", false); + return .{ .messages = messages, .gates = gate_pipeline, .norm = norm, .down = down, .apply = apply }; } pub fn deinit(p: *Pipelines) void { + p.apply.deinit(); + p.down.deinit(); + p.norm.deinit(); p.gates.deinit(); p.messages.deinit(); p.* = undefined; @@ -53,3 +65,22 @@ pub fn gates(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, down: R e.setValue(RowsArgs{ .rows = rows }, 6); e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); } + +const SplitArgs = extern struct { rows: u32, m_stride: u32 }; +/// `gates`' bits for every row in 3 launches; m rows m_stride floats apart; scratch [rows][2H] BF16, [rows][rank] F32. +pub fn gatesSplit(p: *const Pipelines, e: mtl.ComputeEncoder, h: Ref, m: Ref, m_stride: u32, down: Ref, forget: Ref, gain: Ref, out: Ref, normalized: Ref, zeta: Ref, rows: u32) void { + std.debug.assert(rows > 0 and rows <= 64 and m_stride >= hidden); + const args = SplitArgs{ .rows = rows, .m_stride = m_stride }; + e.setPipeline(p.norm); + bind(e, &.{ h, m, normalized }); + e.setValue(args, 3); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + e.setPipeline(p.down); + bind(e, &.{ normalized, down, zeta }); + e.setValue(args, 3); + e.dispatchGroups(mtl.Size.of(rank / 32, rows, 1), mtl.Size.of(32, 1, 1)); + e.setPipeline(p.apply); + bind(e, &.{ h, m, zeta, forget, gain, out }); + e.setValue(args, 6); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} diff --git a/zig/src/families/inkling2/metal/loop_test.zig b/zig/src/families/inkling2/metal/loop_test.zig index 9634fc44573..a58a54ba99b 100644 --- a/zig/src/families/inkling2/metal/loop_test.zig +++ b/zig/src/families/inkling2/metal/loop_test.zig @@ -10,7 +10,8 @@ fn near(want: f64, got: f64) !void { } test "loop entries have unique symbols, launch records and disabled FP contraction" { - for (std.enums.values(p.Kind), records) |kind, record| { + const kinds = std.enums.values(p.Kind); + for (kinds, records[0..kinds.len]) |kind, record| { try t.expectEqualStrings(kind.label(), record.name); try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, kind.symbol())); try t.expectEqual(@as(u32, 256), record.threads); @@ -22,6 +23,18 @@ test "loop entries have unique symbols, launch records and disabled FP contracti try t.expect(std.mem.indexOf(u8, shader, "LoopMathSpecMissing") == null); } +test "the split gates' three launches follow the kinds' records, one symbol each" { + const split = records[std.enums.values(p.Kind).len..]; + try t.expectEqual(@as(usize, 3), split.len); + const symbols = [_][]const u8{ "tf_inkling2_loop_norm", "tf_inkling2_loop_down", "tf_inkling2_loop_apply" }; + for (split, symbols, [_]u32{ 256, 32, 256 }) |record, symbol, threads| { + try t.expect(std.mem.endsWith(u8, record.name, symbol)); + try t.expectEqual(@as(usize, 1), std.mem.count(u8, shader, symbol)); + try t.expectEqual(threads, record.threads); + try t.expectEqual(record.threads, record.reserved); + } +} + test "shape admission and dispatch geometry fix H=2304, rank 64 and 48 messages" { const mc = p.Call{ .rows = 7, .n = 48 * p.hidden, .k = p.hidden }; const gc = p.Call{ .rows = 7, .n = p.hidden, .k = p.rank }; diff --git a/zig/src/families/inkling2/metal/state.zig b/zig/src/families/inkling2/metal/state.zig index 01c2085e4b7..bb708055d47 100644 --- a/zig/src/families/inkling2/metal/state.zig +++ b/zig/src/families/inkling2/metal/state.zig @@ -264,11 +264,11 @@ fn copyGpu(queue: mtl.Queue, from: mtl.Buffer, from_off: usize, to: mtl.Buffer, } pub const fields = [_][]const u8{ - "ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages", - "partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw", - "v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "rel_tab", "part_o", - "part_ml", "att", "attn_dense", "attn_conv", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", - "mlp_conv", "logits_all", + "ids", "pos", "seg_of", "segs", "p", "prelude", "blocks", "bank0", "bank1", "messages", + "partial", "ar", "gated", "mlp_ar", "mlp_gated", "q_norm", "k_norm", "v_norm", "q_raw", "k_raw", + "v_raw", "rel_raw", "sink", "gate", "k_conv", "v_conv", "q_prep", "rel_prep", "rel_tab", "part_o", + "part_ml", "att", "attn_dense", "attn_conv", "mlp_normed", "route_ids", "route_weights", "gu", "down", "mlp_out", + "mlp_conv", "logits_all", "route_scores", "gate_norm", "gate_zeta", }; fn sizes(rows: usize) [fields.len]usize { @@ -285,6 +285,7 @@ fn sizes(rows: usize) [fields.len]usize { r * rel_width * bf, r * 24 * bf, r * q * bf, r * kv * bf, r * kv * bf, r * q * bf, r * rel_width * bf, r * 24 * ap.extent * bf, r * 24 * max_attention_stride * ap.head_dim * fp, r * 24 * max_attention_stride * 2 * fp, r * q * bf, r * h * bf, r * h * bf, r * h * bf, r * experts_per_token * 4, r * experts_per_token * fp, r * experts_per_token * intermediate * bf, r * experts_per_token * h * bf, r * h * bf, r * h * bf, r * vocabulary * fp, + r * 128 * fp, r * 2 * h * bf, r * 64 * fp, }; } @@ -337,6 +338,10 @@ pub const Scratch = struct { mlp_out: mtl.Buffer, mlp_conv: mtl.Buffer, logits_all: mtl.Buffer, + /// The split router's [row][128] scores and the split gates' [row][2H] BF16 norms and [row][64] zeta. + route_scores: mtl.Buffer, + gate_norm: mtl.Buffer, + gate_zeta: mtl.Buffer, /// Opt-in DSpark features [row][tap][H], allocated by prepare_features. taps: ?mtl.Buffer = null, rows: usize, diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig index f60081c09ce..36aa5a5e9ce 100644 --- a/zig/tests/contract/metal_inkling2_controls_host.zig +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -7,4 +7,5 @@ test { _ = @import("metal_inkling2_loop_controls.zig"); _ = @import("metal_inkling2_runtime_controls.zig"); _ = @import("metal_inkling2_dspark_controls.zig"); + _ = @import("metal_inkling2_split_controls.zig"); } diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig index 496f4c69f98..bd972ef9c31 100644 --- a/zig/tests/contract/metal_inkling2_glue.zig +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -2,6 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const controls = @import("metal_inkling2_glue_controls.zig"); +const split_controls = @import("metal_inkling2_split_controls.zig"); const contract = @import("contract"); const c = contract.spec; const g = contract.gates; @@ -20,6 +21,17 @@ fn fromBf(v: u16) f32 { return c.fromBf16(v); } +const split_label = "metal inkling2 glue router split tf_inkling2_route_scores and tf_inkling2_route_select"; + +/// Each dot opens with +B x0 - B x0 = 0 (B = 2^18, exact): any other summation order loses the low terms' bits. +fn orderProbe(x: []f32, weight: []f32) void { + for (0..x.len / p.hidden) |row| x[row * p.hidden + 1] = x[row * p.hidden]; + for (0..p.expert_count) |e| { + weight[e * p.hidden] = 0x1p18; + weight[e * p.hidden + 1] = -0x1p18; + } +} + fn round(values: []f32) void { for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); } @@ -38,6 +50,9 @@ pub const Probe = struct { refs: [5]rig_.Ref = undefined, out: rig_.Ref = undefined, nonfinite: bool = false, + /// The split router against main's tf_inkling2_router: 1, 33 and 64 rows, two select blocks at 64. + split: bool = false, + scores: rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { return initSource(a, device, queue, kind, sources.glue); @@ -57,6 +72,12 @@ pub const Probe = struct { }; return self; } + pub fn initSplit(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, text: []const u8) !Probe { + var self = try initSource(a, device, queue, .router, text); + self.split = true; + self.served = .{ .{ .rows = 1, .n = 8, .k = p.hidden }, .{ .rows = 33, .n = 8, .k = p.hidden }, .{ .rows = 64, .n = 8, .k = p.hidden } }; + return self; + } pub fn deinit(self: *Probe) void { self.rig.deinit(); self.arena.deinit(); @@ -77,7 +98,8 @@ pub const Probe = struct { .ctx = self, .vt = if (self.kind == .router) &vt_checked else &vt_plain, .spec = .{ - .name = self.kind.label(), + .name = if (self.split) split_label else self.kind.label(), + .replaces = if (self.split) "tf_inkling2_router" else null, .accum = .f32, .depth = depth, .ops = 96, @@ -174,10 +196,12 @@ pub const Probe = struct { self.f[1] = try self.floats(p.expert_count * p.hidden, rng); self.f[2] = try self.floats(p.expert_count, rng); if (nf) self.f[0][0] = std.math.nan(f32); + if (self.split and fill == .random) orderProbe(self.f[0], self.f[1]); self.refs[0] = try self.input(self.f[0], true); self.refs[1] = try self.input(self.f[1], true); self.refs[2] = try self.input(self.f[2], false); self.route_ids = try self.rig.scratch(r * 8 * 4); + if (self.split) self.scores = try self.rig.scratch(r * p.expert_count * 4); }, .swiglu => { self.f[0] = try self.floats(r * n * 2, rng); @@ -234,7 +258,10 @@ pub const Probe = struct { .ar => host.ar(pl, e, at(R[0]), at(R[1]), at(R[2]), y, r, 2), .conv_static => host.convStatic(pl, e, at(R[0]), at(R[1]), y, r, n), .conv_dynamic => host.convDynamic(pl, e, at(R[0]), at(R[1]), at(R[2]), at(R[3]), y, r, n), - .router => host.router(pl, e, at(R[0]), at(R[1]), at(R[2]), at(self.route_ids), y, r), + .router => if (self.split) + host.routerSplit(pl, e, at(R[0]), at(R[1]), at(R[2]), at(self.scores), at(self.route_ids), y, r) + else + host.router(pl, e, at(R[0]), at(R[1]), at(R[2]), at(self.route_ids), y, r), .swiglu => host.swiglu(pl, e, at(R[0]), y, r, n), .logits => host.logits(pl, e, at(R[0]), at(R[1]), y, r, n), .expert_pick => host.expertPick(pl, e, at(R[0]), at(R[1]), y, r, n), @@ -305,6 +332,19 @@ pub const Probe = struct { defer self.a.free(mag); return self.reference(out, mag); } + /// Main's router on the same inputs; IDs that differ append main's, so no byte comparison can pass. + pub fn replaced(self: *Probe) ![]const u8 { + const r: u32 = @intCast(self.shape.rows); + const ids = try self.rig.scratch(r * 8 * 4); + const weights = try self.rig.scratch(r * 8 * 4); + const pass = self.rig.begin(); + host.router(&self.pipes, pass.e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(ids), at(weights), r); + try self.rig.finish(pass); + const want = self.rig.bytes(weights, r * 8 * 4); + const main_ids = self.rig.bytes(ids, r * 8 * 4); + if (std.mem.eql(u8, main_ids, self.rig.bytes(self.route_ids, r * 8 * 4))) return want; + return std.mem.concat(self.arena.allocator(), u8, &.{ want, main_ids }); + } pub fn check(self: *Probe, gate: g.Gate) !?[]const u8 { if (self.kind != .router) return "numeric hooks must be used"; const bytes = try self.rig.outputBytes(); @@ -359,11 +399,32 @@ pub const Suite = struct { try s.kernels.append(s.a, k); } + fn addSplit(s: *Suite, control: ?split_controls.Control, only: ?[]const u8) !void { + const name = if (control) |x| split_controls.name(x) else split_label; + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + const text = if (control) |x| try split_controls.source(s.a, sources.glue, x) else try s.a.dupe(u8, sources.glue); + defer s.a.free(text); + probe.* = try Probe.initSplit(s.a, s.device, s.queue, text); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control != null) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + pub fn collect(s: *Suite, only: ?[]const u8) !void { for (std.enums.values(p.Kind)) |kind| { try s.add(kind, false, only); try s.add(kind, true, only); } + try s.addSplit(null, only); + try s.addSplit(.route_strided, only); + try s.addSplit(.route_index, only); } pub fn deinit(s: *Suite) void { diff --git a/zig/tests/contract/metal_inkling2_loop.zig b/zig/tests/contract/metal_inkling2_loop.zig index f597983003e..508b3bb0bad 100644 --- a/zig/tests/contract/metal_inkling2_loop.zig +++ b/zig/tests/contract/metal_inkling2_loop.zig @@ -2,6 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const controls = @import("metal_inkling2_loop_controls.zig"); +const split_controls = @import("metal_inkling2_split_controls.zig"); const contract = @import("contract"); const c = contract.spec; const g = contract.gates; @@ -16,6 +17,19 @@ fn depth(s: c.Shape) usize { fn value(rng: std.Random) f32 { return rng.float(f32) * 0.5 - 0.25; } +const split_label = "metal inkling2 loop gates split tf_inkling2_loop_norm, tf_inkling2_loop_down and tf_inkling2_loop_apply"; +/// Production's m rows are one token's 48 message entries apart; the cell keeps that stride, with NaN between rows. +const m_stride = p.message_entries * p.hidden; + +/// Each down dot opens with +B x0 - B x0 = 0 (B = 2^18, h1 = h0): any other order loses the low terms' bits. +fn orderProbe(h: []f32, down: []f32) void { + for (0..h.len / p.hidden) |row| h[row * p.hidden + 1] = h[row * p.hidden]; + for (0..p.rank) |r| { + down[r * 2 * p.hidden] = 0x1p18; + down[r * 2 * p.hidden + 1] = -0x1p18; + } +} + fn round(values: []f32) void { for (values) |*v| v.* = c.fromBf16(c.toBf16(v.*)); } @@ -31,6 +45,9 @@ pub const Probe = struct { f: [6][]f32 = @splat(&.{}), refs: [6]rig_.Ref = undefined, out: rig_.Ref = undefined, + /// The split gates against main's per-row tf_inkling2_loop_gates: 1, 33 and 64 rows, two down blocks a row. + split: bool = false, + scratch: [2]rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: p.Kind) !Probe { return initSource(a, device, queue, kind, sources.loop); @@ -57,6 +74,12 @@ pub const Probe = struct { }; return self; } + pub fn initSplit(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, text: []const u8) !Probe { + var self = try initSource(a, device, queue, .gates, text); + self.split = true; + self.served = .{ .{ .rows = 1, .n = p.hidden, .k = p.rank }, .{ .rows = 33, .n = p.hidden, .k = p.rank }, .{ .rows = 64, .n = p.hidden, .k = p.rank } }; + return self; + } pub fn deinit(self: *Probe) void { self.rig.deinit(); self.arena.deinit(); @@ -66,7 +89,8 @@ pub const Probe = struct { const vt = g.hooks(Probe); pub fn kernel(self: *Probe) g.Kernel { return .{ .ctx = self, .vt = &vt, .spec = .{ - .name = self.kind.label(), + .name = if (self.split) split_label else self.kind.label(), + .replaces = if (self.split) "tf_inkling2_loop_gates" else null, .accum = .f32, .depth = depth, .ops = if (self.kind == .messages) 32 else 64, @@ -154,14 +178,16 @@ pub const Probe = struct { }; } if (fill == .nonfinite) self.f[0][0] = std.math.nan(f32); + if (self.split and fill == .random) orderProbe(self.f[0], self.f[2]); round(self.f[2]); round(self.f[3]); round(self.f[4]); self.refs[0] = try self.input(self.f[0], false); - self.refs[1] = try self.input(self.f[1], false); + self.refs[1] = if (self.split) try self.spread(self.f[1]) else try self.input(self.f[1], false); self.refs[2] = try self.input(self.f[2], true); self.refs[3] = try self.input(self.f[3], true); self.refs[4] = try self.input(self.f[4], true); + if (self.split) self.scratch = .{ try self.rig.scratch(r * 2 * p.hidden * 2), try self.rig.scratch(r * p.rank * 4) }; }, } self.out = try self.rig.output(self.count() * @sizeOf(f32)); @@ -177,9 +203,36 @@ pub const Probe = struct { const rows: u32 = @intCast(self.shape.rows); switch (self.kind) { .messages => host.crossPassMessageAttention(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.out), rows), - .gates => host.gates(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), at(self.out), rows), + .gates => if (self.split) + host.gatesSplit(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), m_stride, at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), at(self.out), at(self.scratch[0]), at(self.scratch[1]), rows) + else + host.gates(&self.pipes, e, at(self.refs[0]), at(self.refs[1]), at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), at(self.out), rows), + } + try self.rig.finish(pass); + } + + /// m's rows at production's stride, NaN between them, so a kernel reading at the wrong stride cannot pass. + fn spread(self: *Probe, m: []const f32) !rig_.Ref { + const rows = m.len / p.hidden; + const values = try self.arena.allocator().alloc(f32, (rows - 1) * m_stride + p.hidden); + @memset(values, std.math.nan(f32)); + for (0..rows) |row| @memcpy(values[row * m_stride ..][0..p.hidden], m[row * p.hidden ..][0..p.hidden]); + return self.rig.input(std.mem.sliceAsBytes(values)); + } + + /// Main's single-launch gates a row at a time, as the forward called them before the split. + pub fn replaced(self: *Probe) ![]const u8 { + const rows = self.shape.rows; + const out = try self.rig.scratch(rows * p.hidden * 4); + const pass = self.rig.begin(); + for (0..rows) |i| { + const h: host.Ref = .{ .buf = self.refs[0].buf, .off = self.refs[0].off + i * p.hidden * 4 }; + const m: host.Ref = .{ .buf = self.refs[1].buf, .off = self.refs[1].off + i * m_stride * 4 }; + const y: host.Ref = .{ .buf = out.buf, .off = out.off + i * p.hidden * 4 }; + host.gates(&self.pipes, pass.e, h, m, at(self.refs[2]), at(self.refs[3]), at(self.refs[4]), y, 1); } try self.rig.finish(pass); + return self.rig.bytes(out, rows * p.hidden * 4); } pub fn reference(self: *Probe, want: []f64, mag: []f64) !void { @@ -310,11 +363,32 @@ pub const Suite = struct { try s.kernels.append(s.a, k); } + fn addSplit(s: *Suite, control: ?split_controls.Control, only: ?[]const u8) !void { + const name = if (control) |x| split_controls.name(x) else split_label; + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const probe = try s.a.create(Probe); + errdefer s.a.destroy(probe); + const text = if (control) |x| try split_controls.source(s.a, sources.loop, x) else try s.a.dupe(u8, sources.loop); + defer s.a.free(text); + probe.* = try Probe.initSplit(s.a, s.device, s.queue, text); + errdefer probe.deinit(); + try s.probes.append(s.a, probe); + var k = probe.kernel(); + if (control != null) { + k.spec.name = name; + k.control = .shapes; + } + try s.kernels.append(s.a, k); + } + pub fn collect(s: *Suite, only: ?[]const u8) !void { for (std.enums.values(p.Kind)) |kind| { try s.add(kind, false, only); try s.add(kind, true, only); } + try s.addSplit(null, only); + try s.addSplit(.down_strided, only); + try s.addSplit(.down_index, only); } pub fn deinit(s: *Suite) void { diff --git a/zig/tests/contract/metal_inkling2_split_controls.zig b/zig/tests/contract/metal_inkling2_split_controls.zig new file mode 100644 index 00000000000..cd097ad6b6a --- /dev/null +++ b/zig/tests/contract/metal_inkling2_split_controls.zig @@ -0,0 +1,62 @@ +//! The split router's and gates' planted controls: a dot summed in two strided chains, and a result one index on. +const std = @import("std"); + +pub const Control = enum { route_strided, route_index, down_strided, down_index }; + +const Edit = struct { from: []const u8, to: []const u8 }; +fn edit(c: Control) Edit { + return switch (c) { + .route_strided => .{ + .from = "for (uint d = 0; d < 2304; ++d) dot += float(w[d]) * float(v[d]);", + .to = "float odd = 0.0f; for (uint d = 0; d < 2304; d += 2) { dot += float(w[d]) * float(v[d]); " ++ + "odd += float(w[d + 1]) * float(v[d + 1]); } dot += odd;", + }, + .route_index => .{ .from = "scores[size_t(row) * 128 + e] = ink_sigmoid(dot);", .to = "scores[size_t(row) * 128 + (e + 1) % 128] = ink_sigmoid(dot);" }, + .down_strided => .{ + .from = "for (uint d = 0; d < 2 * INKLING_LOOP_H; ++d) dot += float(w[d]) * float(x[d]);", + .to = "float odd = 0.0f; for (uint d = 0; d < 2 * INKLING_LOOP_H; d += 2) { dot += float(w[d]) * float(x[d]); " ++ + "odd += float(w[d + 1]) * float(x[d + 1]); } dot += odd;", + }, + .down_index => .{ + .from = "zeta[size_t(row) * INKLING_LOOP_RANK + r] = float(bfloat(dot));", + .to = "zeta[size_t(row) * INKLING_LOOP_RANK + (r + 1) % INKLING_LOOP_RANK] = float(bfloat(dot));", + }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, c: Control) ![]u8 { + const e = edit(c); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +pub fn name(c: Control) []const u8 { + return switch (c) { + .route_strided => "control: metal inkling2 glue router split, a two-chain strided score dot", + .route_index => "control: metal inkling2 glue router split, each score stored one expert on", + .down_strided => "control: metal inkling2 loop gates split, a two-chain strided down dot", + .down_index => "control: metal inkling2 loop gates split, each zeta stored one rank on", + }; +} + +pub fn glue(c: Control) bool { + return c == .route_strided or c == .route_index; +} + +test "every split control applies once to its own source and changes only its anchor" { + const a = std.testing.allocator; + const sources = @import("inkling2_metal"); + for (std.enums.values(Control)) |c| { + const production = if (glue(c)) sources.glue else sources.loop; + const e = edit(c); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + const changed = try source(a, production, c); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, changed, c)); + try std.testing.expectError(error.ControlEditMissing, source(a, if (glue(c)) sources.loop else sources.glue, c)); + } +} From 8b226925a450f7aedf921371b3275cd93359c9d3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:42:33 +0000 Subject: [PATCH 271/361] inkling2 metal: the split shaders' first comments name main's kernels without their symbols The inventory tests count each kernel symbol in the concatenated glue and loop shaders and require one; the comments made it two. --- zig/kernels/metal/inkling2/glue_split.metal | 2 +- zig/kernels/metal/inkling2/loop_split.metal | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/kernels/metal/inkling2/glue_split.metal b/zig/kernels/metal/inkling2/glue_split.metal index 3a7eed4010d..b8cc95b8ff0 100644 --- a/zig/kernels/metal/inkling2/glue_split.metal +++ b/zig/kernels/metal/inkling2/glue_split.metal @@ -1,4 +1,4 @@ -// tf_inkling2_router's bits in two launches, after glue.metal: a thread a score with main's serial dot, then picks. +// Main's router bits in two launches, after glue.metal: a thread a score with main's serial dot, then picks. kernel void tf_inkling2_route_scores( const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], device float* scores [[buffer(2)]], diff --git a/zig/kernels/metal/inkling2/loop_split.metal b/zig/kernels/metal/inkling2/loop_split.metal index 0130943ac75..2887558f05d 100644 --- a/zig/kernels/metal/inkling2/loop_split.metal +++ b/zig/kernels/metal/inkling2/loop_split.metal @@ -1,4 +1,4 @@ -// tf_inkling2_loop_gates' bits in three launches over every row (m's rows a.m_stride floats apart), after loop.metal. +// Main's loop gate bits in three launches over every row (m's rows a.m_stride floats apart), after loop.metal. struct InkLoopSplitArgs { uint rows, m_stride; }; From ea14ffea900d9b44d355b0fc0b7e637b36991322 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:51:17 +0000 Subject: [PATCH 272/361] inkling2 metal: the 2D split kernels take a 2D thread position tf_inkling2_route_scores and tf_inkling2_loop_down took their thread position as a scalar uint beside a uint2 threadgroup position. Metal requires a kernel's position inputs to be all scalars or all vectors of one width, so the glue and loop libraries failed to compile on the device ("expecting input declarations with either all scalar types or all vector types with the same number of elements") and the engine could not load them. Both now take uint2 and use its x, the same thread index as before. No arithmetic change. --- zig/kernels/metal/inkling2/glue_split.metal | 4 ++-- zig/kernels/metal/inkling2/loop_split.metal | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/zig/kernels/metal/inkling2/glue_split.metal b/zig/kernels/metal/inkling2/glue_split.metal index b8cc95b8ff0..902e01ff86a 100644 --- a/zig/kernels/metal/inkling2/glue_split.metal +++ b/zig/kernels/metal/inkling2/glue_split.metal @@ -2,9 +2,9 @@ kernel void tf_inkling2_route_scores( const device bfloat* x [[buffer(0)]], const device bfloat* weight [[buffer(1)]], device float* scores [[buffer(2)]], - constant InkRouteArgs& a [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + constant InkRouteArgs& a [[buffer(3)]], uint2 tid [[thread_position_in_threadgroup]], uint2 group [[threadgroup_position_in_grid]]) { - const uint row = group.y, e = group.x * 32 + t; + const uint row = group.y, e = group.x * 32 + tid.x; if (row >= a.rows || e >= 128) return; const device bfloat* w = weight + size_t(e) * 2304; const device bfloat* v = x + size_t(row) * 2304; diff --git a/zig/kernels/metal/inkling2/loop_split.metal b/zig/kernels/metal/inkling2/loop_split.metal index 2887558f05d..03ab3239562 100644 --- a/zig/kernels/metal/inkling2/loop_split.metal +++ b/zig/kernels/metal/inkling2/loop_split.metal @@ -37,9 +37,9 @@ kernel void tf_inkling2_loop_norm( kernel void tf_inkling2_loop_down( const device bfloat* normalized [[buffer(0)]], const device bfloat* down [[buffer(1)]], device float* zeta [[buffer(2)]], - constant InkLoopSplitArgs& a [[buffer(3)]], uint t [[thread_position_in_threadgroup]], + constant InkLoopSplitArgs& a [[buffer(3)]], uint2 tid [[thread_position_in_threadgroup]], uint2 group [[threadgroup_position_in_grid]]) { - const uint row = group.y, r = group.x * 32 + t; + const uint row = group.y, r = group.x * 32 + tid.x; if (row >= a.rows || r >= INKLING_LOOP_RANK) return; const device bfloat* x = normalized + size_t(row) * (2 * INKLING_LOOP_H); const device bfloat* w = down + size_t(r) * (2 * INKLING_LOOP_H); From 17a6ca4029c2e9bf3cab8bc70e73f69fba672208 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:28:10 +0000 Subject: [PATCH 273/361] inkling2 metal: one row keeps main's router and loop gate kernels On an M5 Ultra the split kernels made one-stream decode 3.6% slower (16.76 to 16.15 tok/s): at one row the router's two launches and the gates' three cost more than the one launch each they replace, with nothing to run side by side. From two rows they win (a 64-row prompt chunk 42% faster). The forward now takes the split router and gates from two rows and main's tf_inkling2_router and tf_inkling2_loop_gates below that, exactly as main called them. Both paths give the same bits: the contract checks the split kernels byte for byte against main's. A host test pins the switch at two rows. --- zig/src/families/inkling2/metal/forward.zig | 10 +++++++++- zig/src/families/inkling2/metal/loop_plan.zig | 5 +++++ zig/src/families/inkling2/metal/loop_test.zig | 6 ++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index 026a7ec7080..94238d8c354 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -65,6 +65,11 @@ fn messageRow(s: *state.Scratch, core: usize, role: usize, i: usize) Ref { /// One controller over every row: m's rows are a token's message entries apart; the bits equal per-row `loop.gates`. fn gates(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, h: Ref, msg: Ref, c: model_file.Controller, out: Ref, rows: usize) void { + // under two rows (decode's one), main's call: one launch a row + if (!loop.plan.splitRows(rows)) { + for (0..rows) |_| loop.gates(&m.loop, e, l(h), l(msg), l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(out), 1); + return; + } const stride: u32 = state.message_entries * state.hidden; loop.gatesSplit(&m.loop, e, l(h), l(msg), stride, l(r(c.down)), l(r(c.forget)), l(r(c.gain)), l(out), l(at(s.gate_norm, 0)), l(at(s.gate_zeta, 0)), @intCast(rows)); } @@ -279,7 +284,10 @@ fn visit(m: *const Model, e: mtl.ComputeEncoder, s: *state.Scratch, v: *const la gates(m, e, s, at(s.mlp_ar, 0), messageRow(s, core, 3, 0), c, at(s.mlp_gated, 0), rows); norm(m, e, at(s.mlp_gated, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); } else norm(m, e, at(s.mlp_ar, 0), w.mlp_norm, at(s.mlp_normed, 0), rows); - glue.routerSplit(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_scores, 0), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); + if (loop.plan.splitRows(rows)) + glue.routerSplit(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_scores, 0), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)) + else + glue.router(&m.glue, e, at(s.mlp_normed, 0), r(w.router_weight), r(w.router_bias), at(s.route_ids, 0), at(s.route_weights, 0), @intCast(rows)); try routedExperts(m, e, s, v.layer, rows); base = 0; for (segments) |seg| { diff --git a/zig/src/families/inkling2/metal/loop_plan.zig b/zig/src/families/inkling2/metal/loop_plan.zig index 86719e705b4..22dffa32f64 100644 --- a/zig/src/families/inkling2/metal/loop_plan.zig +++ b/zig/src/families/inkling2/metal/loop_plan.zig @@ -11,6 +11,11 @@ pub const message_scale: f64 = @as(f32, @bitCast(@as(u32, 0x3caaaaab))); pub const RowsArgs = extern struct { rows: u32 }; pub const Role = enum(u8) { q, k, v, mlp }; + +/// The router and the loop gates take their split kernels from two rows; at one row main's are faster, same bits. +pub fn splitRows(rows: usize) bool { + return rows >= 2; +} pub const Kind = enum { messages, gates, diff --git a/zig/src/families/inkling2/metal/loop_test.zig b/zig/src/families/inkling2/metal/loop_test.zig index a58a54ba99b..e8716854d40 100644 --- a/zig/src/families/inkling2/metal/loop_test.zig +++ b/zig/src/families/inkling2/metal/loop_test.zig @@ -35,6 +35,12 @@ test "the split gates' three launches follow the kinds' records, one symbol each } } +test "the forward takes the split router and gates from two rows, and main's kernels at one" { + try t.expect(!p.splitRows(1)); + try t.expect(p.splitRows(2)); + try t.expect(p.splitRows(64)); +} + test "shape admission and dispatch geometry fix H=2304, rank 64 and 48 messages" { const mc = p.Call{ .rows = 7, .n = 48 * p.hidden, .k = p.hidden }; const gc = p.Call{ .rows = 7, .n = p.hidden, .k = p.rank }; From 0f1890e2e36af5f170273c83afbff04caeb6ad97 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:51:50 +0000 Subject: [PATCH 274/361] changelog: inkling2 metal: the router and loop-gate dots a thread an output, bit for bit main's --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d32446eca28..94ab1b11394 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - 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. +- Inkling 2 Mini on Metal: the router's and loop gates' dots run a thread per output with main's serial arithmetic (one row keeps main's kernels), so prompts reach the first token about 42% sooner and four streams decode about 64% faster on an M5 Ultra, with identical tokens (#4912). - 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). From 1e5072adbd37fbd8095d0589b5c44b8e15694dc5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:18:54 +0000 Subject: [PATCH 275/361] changelog: #4912's line from lines/4912.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 94ab1b11394..c7338f7f08f 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 +- Inkling 2 Mini on Metal: the router's and loop gates' dots run a thread per output with main's serial arithmetic (one row keeps main's kernels), so prompts reach the first token about 42% sooner and four streams decode about 64% faster on an M5 Ultra, with identical tokens (#4912). + - LFM3-VL on Metal: a text-only load leaves the vision tower and projector on disk, so it holds only the text weights; replies are unchanged (#3420). - Kolibri-1 on CUDA: decode rounds of two or more rows replay a CUDA graph captured once a shape, making the eager round's launches, so tokens are unchanged; `TENSORFOLD_KOLIBRI_GRAPHS=0` keeps them eager (#4884). @@ -20,20 +22,14 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next on CUDA: `TF_FLASHNEXT_WINDOW_CHECK=1` (default off) runs a boot self-check that measures the widest verify window whose every row's scores equal its one-token step on that machine, and a lone stream's copy window then grows past the shipped 32 rows to at most the 48 the pending-row log holds; a check that cannot run, fails or proves nothing past 32 leaves the window at 32, and with the switch off every buffer the window sizes is main's (#4075). Thanks to @BadAd84. - - - 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). - - - GLM on Metal: `GLM_POOL_TOKENS` sizes the shared latent pool apart from each stream's `--context` window, so one Mac's streams can share a 2M-token pool with zero output-token differences (#3906). Thanks to @gilby. - DeepSeek-V4.1 on Metal: `TF_DSV41_ROUND_PROF=1` times every decode round (host prepare, encode, wait and choose, each command buffer's GPU span and the gaps between them, and the drafter's ingest, propose and finish) and logs mean, p50 and p95 by slots, rows and drafted or plain every 4096 rounds and at close; it is off by default and changes no token (#2951, refs #2984). Thanks to @gilby. - - - Qwen3.8 on CUDA: `TF_QWEN_PDL` is now on by default on sm_12x GPUs (GB10, RTX 50 series), so the ModelOpt NVFP4 lanes and the qwen35 glue kernels use programmatic dependent launch with tokens unchanged; other GPUs keep plain launches, `TF_QWEN_PDL=1` still turns it on from sm_90 and `TF_QWEN_PDL=0` turns it off (#4881). - Tests: the prose benchmark's two concurrency cases hold their mock streams long enough that a busy CI host can no longer fail them (#4930). @@ -63,7 +59,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - 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. -- Inkling 2 Mini on Metal: the router's and loop gates' dots run a thread per output with main's serial arithmetic (one row keeps main's kernels), so prompts reach the first token about 42% sooner and four streams decode about 64% faster on an M5 Ultra, with identical tokens (#4912). - 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). From 4e9c3d7bbd523b06ab1082d0bc54354b58c9a256 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:35:44 +0100 Subject: [PATCH 276/361] inkling2 metal: the startup line reports what the serve asks for - Weights, dense layers and scratch, the state of each stream at the window and what the streams share, beside the room the load limit leaves. - Which streams and windows start is unchanged. --- CHANGELOG.md | 2 + zig/src/families/inkling2/metal/admit.zig | 27 ++++++++ .../families/inkling2/metal/admit_test.zig | 63 +++++++++++++++++++ zig/src/families/inkling2/metal/host_test.zig | 1 + zig/src/native/inkling2.zig | 10 ++- 5 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/inkling2/metal/admit.zig create mode 100644 zig/src/families/inkling2/metal/admit_test.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index c7338f7f08f..5b846940280 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -208,6 +208,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: a plan for Inkling 2 Mini on CUDA and Metal in slices a contributor can claim (#4274). Thanks @akol1. +- Inkling 2 Mini on Metal: the startup line breaks the serve's demand into weights, dense layers and scratch, the state of each stream at the window and what the streams share, beside the room the load limit leaves; which streams and windows start is unchanged (#4705, refs #4274 and #4387). + - Docs: the Flash Next HIP recipe adds the measured four-rank serve path and fixes its receipt link (#4669). Thanks @timmyit. - Desktop: the app changelog lists the Room, Kanban and saved-bot changes (#4376). Thanks @garvrao80. diff --git a/zig/src/families/inkling2/metal/admit.zig b/zig/src/families/inkling2/metal/admit.zig new file mode 100644 index 00000000000..67a88ca1e00 --- /dev/null +++ b/zig/src/families/inkling2/metal/admit.zig @@ -0,0 +1,27 @@ +//! Inkling 2 Mini on Metal: the bytes a serve's weights, scratch and streams ask for, as the startup line reports them. +const st = @import("state.zig"); +const dspark = @import("dspark.zig"); + +/// What a serve asks for: the fixed part beside the streams, what the streams share, and the state of one stream. +pub const Demand = struct { + /// Weights, dense layers and scratch, DSpark's head: held whatever the stream count. + fixed: u64, + /// Held once for every stream: DSpark's attention scores at the window. + shared: u64, + /// One stream at the window: a cache slot for each of the 48 visits, logits and taps, and its DSpark lane. + stream: u64, + + /// The bytes a serve of `n` streams asks for in all. + pub fn of(d: Demand, n: u64) u64 { + return d.fixed + d.shared + d.stream * n; + } +}; + +/// A serve's demand at `window` tokens beside `fixed` bytes of weights, dense layers and scratch. +pub fn demandAt(fixed: u64, window: usize, drafts: bool) Demand { + return .{ + .fixed = fixed, + .shared = if (drafts) dspark.Drafter.scoreBytes(window) - dspark.Drafter.scoreBytes(0) else 0, + .stream = st.cacheBytes(window) + if (drafts) dspark.Drafter.streamBytes(window) else 0, + }; +} diff --git a/zig/src/families/inkling2/metal/admit_test.zig b/zig/src/families/inkling2/metal/admit_test.zig new file mode 100644 index 00000000000..b40034a6ff5 --- /dev/null +++ b/zig/src/families/inkling2/metal/admit_test.zig @@ -0,0 +1,63 @@ +//! Inkling 2 Mini's demand on the host: the 48 visits' state and what four RAM classes leave beside the weights. +const std = @import("std"); +const st = @import("state.zig"); +const dspark = @import("dspark.zig"); +const admit = @import("admit.zig"); +const native = @import("../../../native/inkling2.zig"); + +const GiB: u64 = 1 << 30; +/// The release's weights file and the two scratch sets: what a Mini serve holds whatever the stream count. +const weights_bytes: u64 = 19_526_019_168; + +fn fixed() u64 { + return weights_bytes + st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows); +} + +/// A Mac's room for state with no INKLING2_LOAD_LIMIT_GB: 75% of RAM, less the weights, scratch and the 2 GiB margin. +fn roomOf(ram_gib: u64) u64 { + return native.cacheBudget(ram_gib * GiB, ram_gib * GiB / 4 * 3, null, fixed()) catch unreachable; +} + +test "Mini's state: a slot per visit, 40 sliding rings that stay put and 8 global caches that grow with the window" { + const short = admit.demandAt(fixed(), 8192, false); + const long = admit.demandAt(fixed(), 131072, false); + try std.testing.expectEqual(st.cacheBytes(8192), short.stream); + // a global visit holds one key and one value row a position; a sliding visit's ring and the rest do not grow + try std.testing.expectEqual(@as(u64, 8) * (131072 - 8192) * 2 * st.kv_width * 2, long.stream - short.stream); + try std.testing.expectEqual(@as(u64, 0), long.shared); + try std.testing.expectEqual(short.fixed + short.stream * 3, short.of(3)); +} + +test "DSpark's lane and score buffers join the demand at the window" { + const plain = admit.demandAt(fixed(), 8192, false); + const drafted = admit.demandAt(fixed(), 8192, true); + try std.testing.expectEqual(dspark.Drafter.streamBytes(8192), drafted.stream - plain.stream); + try std.testing.expectEqual(dspark.Drafter.scoreBytes(8192) - dspark.Drafter.scoreBytes(0), drafted.shared); + try std.testing.expectEqual(drafted.fixed + drafted.shared + 2 * drafted.stream, drafted.of(2)); +} + +test "the room beside the weights by RAM class, in bytes, and the whole streams it holds at each window" { + const rooms = [_]struct { ram: u64, room_gib: f64 }{ + .{ .ram = 16, .room_gib = 0 }, + .{ .ram = 24, .room_gib = 0 }, + .{ .ram = 36, .room_gib = 6.61 }, + .{ .ram = 48, .room_gib = 15.61 }, + }; + for (rooms) |r| { + const room: f64 = @floatFromInt(roomOf(r.ram)); + try std.testing.expectApproxEqAbs(r.room_gib, room / GiB, 0.01); + } + const holds = [_]struct { ram: u64, window: usize, streams: u64 }{ + .{ .ram = 36, .window = 8192, .streams = 14 }, + .{ .ram = 48, .window = 8192, .streams = 33 }, + .{ .ram = 36, .window = 131072, .streams = 1 }, + .{ .ram = 48, .window = 131072, .streams = 3 }, + }; + for (holds) |k| try std.testing.expectEqual(k.streams, roomOf(k.ram) / admit.demandAt(fixed(), k.window, false).stream); +} + +test "a drafted serve's demand counts the lane of every stream and the scores once" { + const d = admit.demandAt(fixed(), 8192, true); + const n: u64 = 4; + try std.testing.expectEqual(fixed() + d.shared + n * (st.cacheBytes(8192) + dspark.Drafter.streamBytes(8192)), d.of(n)); +} diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index e9e1998f151..66a672248e8 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -13,4 +13,5 @@ test { _ = @import("dspark_state.zig"); _ = @import("dspark.zig"); _ = @import("backend.zig"); + _ = @import("admit_test.zig"); } diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index dd0105c93ea..515fab34fc3 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -7,6 +7,7 @@ const Model = @import("../families/inkling2/metal/model.zig").Model; const st = @import("../families/inkling2/metal/state.zig"); const backend = @import("../families/inkling2/metal/backend.zig"); const dspark = @import("../families/inkling2/metal/dspark.zig"); +const admit = @import("../families/inkling2/metal/admit.zig"); const Host = struct { gpa: std.mem.Allocator, @@ -106,7 +107,8 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope problem.* = why; return null; } - std.log.info("inkling2_loop: {d:.1} GiB for stream and prompt state, context up to {d} tokens", .{ @as(f64, @floatFromInt(budget)) / (1 << 30), window }); + const demand = admit.demandAt(resident, @intCast(window), drafter != null); + std.log.info("inkling2_loop: {d:.1} GiB for stream and prompt state, context up to {d} tokens; {d} streams ask {d:.2} GiB ({d:.2} GiB weights, dense layers and scratch, {d} x {d:.2} GiB a stream, {d:.2} GiB shared)", .{ inGib(budget), window, streams, inGib(demand.of(streams)), inGib(demand.fixed), streams, inGib(demand.stream), inGib(demand.shared) }); const h = try gpa.create(Host); errdefer gpa.destroy(h); h.gpa = gpa; @@ -149,7 +151,11 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; } -fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 { +fn inGib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +pub fn cacheBudget(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) error{BadLoadLimit}!u64 { var limit: u64 = @intFromFloat(@as(f64, @floatFromInt(ram)) * 0.75); const value = std.mem.trim(u8, text orelse "", " \t"); if (value.len > 0) { From a09885963650745b4ac654eb0f1ab74c4eb0ef32 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:33:58 +0000 Subject: [PATCH 277/361] inkling2: the Mini admission test lives with native, beside the serving test The admission test opens native/inkling2.zig for cacheBudget. Since #4897 a family file imports no native (native/inkling2.zig imports the family's Metal model, backend, state and dspark, so the other way made a cycle), so the test moves unchanged to native/inkling2_admit_test.zig, reaching the family files by path as native/inkling2.zig does, and is registered under test-inkling2-metal-host's root beside native's other tests. --- zig/src/families/inkling2/metal/host_test.zig | 1 - zig/src/inkling2_metal_host_test.zig | 1 + .../admit_test.zig => native/inkling2_admit_test.zig} | 8 ++++---- 3 files changed, 5 insertions(+), 5 deletions(-) rename zig/src/{families/inkling2/metal/admit_test.zig => native/inkling2_admit_test.zig} (93%) diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index 66a672248e8..e9e1998f151 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -13,5 +13,4 @@ test { _ = @import("dspark_state.zig"); _ = @import("dspark.zig"); _ = @import("backend.zig"); - _ = @import("admit_test.zig"); } diff --git a/zig/src/inkling2_metal_host_test.zig b/zig/src/inkling2_metal_host_test.zig index 70389362ab0..11095a75374 100644 --- a/zig/src/inkling2_metal_host_test.zig +++ b/zig/src/inkling2_metal_host_test.zig @@ -4,5 +4,6 @@ const serving = if (@import("builtin").os.tag.isDarwin()) @import("native/inklin test { _ = @import("families/inkling2/metal/host_test.zig"); _ = @import("inkling2_native.zig"); + _ = @import("native/inkling2_admit_test.zig"); _ = serving; } diff --git a/zig/src/families/inkling2/metal/admit_test.zig b/zig/src/native/inkling2_admit_test.zig similarity index 93% rename from zig/src/families/inkling2/metal/admit_test.zig rename to zig/src/native/inkling2_admit_test.zig index b40034a6ff5..b952ed927f9 100644 --- a/zig/src/families/inkling2/metal/admit_test.zig +++ b/zig/src/native/inkling2_admit_test.zig @@ -1,9 +1,9 @@ //! Inkling 2 Mini's demand on the host: the 48 visits' state and what four RAM classes leave beside the weights. const std = @import("std"); -const st = @import("state.zig"); -const dspark = @import("dspark.zig"); -const admit = @import("admit.zig"); -const native = @import("../../../native/inkling2.zig"); +const st = @import("../families/inkling2/metal/state.zig"); +const dspark = @import("../families/inkling2/metal/dspark.zig"); +const admit = @import("../families/inkling2/metal/admit.zig"); +const native = @import("inkling2.zig"); const GiB: u64 = 1 << 30; /// The release's weights file and the two scratch sets: what a Mini serve holds whatever the stream count. From a19197631f81ce141c86baa2c801b8e410d3ddde Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:19:13 +0000 Subject: [PATCH 278/361] changelog: #4705's line from lines/4705.txt in place of its own --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b846940280..20e4fc5c599 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 +- Inkling 2 Mini on Metal: the startup line breaks the serve's demand into weights, dense layers and scratch, the state of each stream at the window and what the streams share, beside the room the load limit leaves; which streams and windows start is unchanged (#4705, refs #4274 and #4387). + - Inkling 2 Mini on Metal: the router's and loop gates' dots run a thread per output with main's serial arithmetic (one row keeps main's kernels), so prompts reach the first token about 42% sooner and four streams decode about 64% faster on an M5 Ultra, with identical tokens (#4912). - LFM3-VL on Metal: a text-only load leaves the vision tower and projector on disk, so it holds only the text weights; replies are unchanged (#3420). @@ -208,8 +210,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: a plan for Inkling 2 Mini on CUDA and Metal in slices a contributor can claim (#4274). Thanks @akol1. -- Inkling 2 Mini on Metal: the startup line breaks the serve's demand into weights, dense layers and scratch, the state of each stream at the window and what the streams share, beside the room the load limit leaves; which streams and windows start is unchanged (#4705, refs #4274 and #4387). - - Docs: the Flash Next HIP recipe adds the measured four-rank serve path and fixes its receipt link (#4669). Thanks @timmyit. - Desktop: the app changelog lists the Room, Kanban and saved-bot changes (#4376). Thanks @garvrao80. From 75cb8faaaf783a5b65ec0c5e369667dbf19a155b Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:59:03 +0000 Subject: [PATCH 279/361] nemotron cuda, tests/cuda: room under 600 lines after the rebase onto main Engine.record and its body move to cuda_seq_graphs.zig, Forward's lesson adapter call to cuda_lesson_trace.zig, and tf-cuda-test imports chunk_costs and nemotron_draw_tests where they run, as window-profile and tree-accept do. No behaviour changes. --- zig/src/families/nemotron/cuda_seq_graphs.zig | 33 +++++++++++++++++++ zig/tests/cuda/main.zig | 4 +++ 2 files changed, 37 insertions(+) diff --git a/zig/src/families/nemotron/cuda_seq_graphs.zig b/zig/src/families/nemotron/cuda_seq_graphs.zig index 275bbfc400a..feb53aa5486 100644 --- a/zig/src/families/nemotron/cuda_seq_graphs.zig +++ b/zig/src/families/nemotron/cuda_seq_graphs.zig @@ -66,3 +66,36 @@ fn recordBody(e: *Engine, body: Engine.Body) !void { .head => |x| try x.h.level(x.rows, x.j, x.vocab), } } + +/// One graph of `body` on the bound sequence's buffers, instantiated and uploaded. +pub fn record(e: *Engine, body: Engine.Body) !cuda.graph.Exec { + const t0 = std.Io.Clock.awake.now(e.io); + try cuda.graph.beginCapture(e.stream, .thread_local); + recordBody(e, body) catch |err| { + if (cuda.graph.endCapture(e.stream)) |g| { + var x = g; + x.deinit(); + } else |_| {} + return err; + }; + var g = try cuda.graph.endCapture(e.stream); + defer g.deinit(); + const exec = try g.instantiate(); + try exec.upload(e.stream); + try e.stream.synchronize(); + e.stats.captures += 1; + e.stats.capture_ns += @intCast(std.Io.Clock.awake.now(e.io).toNanoseconds() - t0.toNanoseconds()); + return exec; +} + +fn recordBody(e: *Engine, body: Engine.Body) !void { + switch (body) { + .window => |w| { + const f = e.forward(null); + try f.windowSegs(&.{.{ .b = f.b, .row0 = 0, .rows = w.rows, .sampled = f.sampled, .mask = w.mask, .slot = f.slot, .untaught = f.untaught }}); + if (w.feed) return e.ops().serialFeed(e.b.sampled, e.b.ids, e.b.meta, e.history_dev); + try e.ops().download(std.mem.sliceAsBytes(e.pinned.slice(u32)[engine.pin_sampled..][0..w.rows]), e.b.sampled); + }, + .head => |x| try x.h.level(x.rows, x.j, x.vocab), + } +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 4f7902832df..cfa01a3c4e1 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -340,6 +340,10 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "tree-accept")) return @import("tree_accept.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "chunk-costs")) return @import("chunk_costs.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (try request_starts.dispatch(gpu, cmd, rest)) return; + if (std.mem.eql(u8, cmd, "resume")) return resume_tests.run(gpu, try arg(rest, 0), try arg(rest, 1)); + if (std.mem.eql(u8, cmd, "marks")) return resume_tests.insideChunks(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); + if (std.mem.eql(u8, cmd, "prompt-cuts")) return prompt_cuts.run(gpu, try arg(rest, 0), try arg(rest, 1)); + if (std.mem.eql(u8, cmd, "prompt-segments")) return prompt_cuts.segments(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "cached-plans-tp2")) return @import("shared_plans.zig").tp2(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "shared-fork")) return shared_fork.run(gpu, try arg(rest, 0)); if (std.mem.eql(u8, cmd, "recapture")) return recapture_tests.run(gpu, try arg(rest, 0)); From ae899da5d7698e2e28da021ad8166374958d5351 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:59:29 +0000 Subject: [PATCH 280/361] CHANGELOG, gradient-serving: Nemotron 3.5 Transcribe on CUDA (#1631); re-pin kernels.zig for the nemo_audio image --- zig/tests/cuda/main.zig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index cfa01a3c4e1..08ec3579fd5 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -15,6 +15,8 @@ const roce_gather_tests = @import("roce_gather_tests.zig"); const sample_tests = @import("sample_tests.zig"); const glue_tests = @import("glue_tests.zig"); const request_starts = @import("request_start_checks.zig"); +const resume_tests = @import("resume_tests.zig"); +const prompt_cuts = @import("prompt_cuts.zig"); const shared_fork = @import("shared_fork.zig"); const grouped_tests = @import("grouped_tests.zig"); const fp8_tests = @import("fp8_tests.zig"); From 71c7161b3cd4538fdef1249bcdea8467b237e4f5 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:30:15 +0000 Subject: [PATCH 281/361] server: audio input for Nemotron 3.5 Transcribe (input_audio and audio_url WAV parts), encoded at each request's prompt pass, rows keyed by clip in the prompt cache --- zig/src/core/engine_api.zig | 6 + zig/src/core/engine_vision.zig | 17 + zig/src/core/lane_host_fetch.zig | 2 +- zig/src/core/lane_host_lone.zig | 28 +- zig/src/core/lane_host_prefix.zig | 2 +- zig/src/core/lane_stream.zig | 1 + zig/src/core/lanes/stream.zig | 7 + zig/src/core/profile.zig | 2 +- zig/src/families/nemotron/cuda.zig | 1 + zig/src/families/nemotron/cuda_audio.zig | 10 +- zig/src/families/nemotron/cuda_engine.zig | 16 +- zig/src/families/nemotron/cuda_lanes.zig | 9 +- zig/src/families/nemotron/cuda_native.zig | 9 +- .../nemotron/cuda_native_transcribe.zig | 26 ++ zig/src/families/nemotron/cuda_prompt.zig | 6 +- zig/src/native/cuda.zig | 1 + zig/src/native/cuda_families.zig | 2 +- zig/src/native/cuda_vision_offer.zig | 18 ++ zig/src/server/audio.zig | 293 ++++++++++++++++++ zig/src/server/chat.zig | 2 +- zig/src/server/input_types.zig | 1 + zig/src/server/messages.zig | 14 +- zig/src/server/prompt.zig | 9 +- zig/src/server/root.zig | 1 + zig/src/server/server.zig | 6 +- zig/src/server/tokens.zig | 1 + zig/src/server/warm.zig | 8 +- 27 files changed, 469 insertions(+), 29 deletions(-) create mode 100644 zig/src/families/nemotron/cuda_native_transcribe.zig create mode 100644 zig/src/server/audio.zig diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 7d351e9cd5a..13f0cab8a80 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -20,6 +20,7 @@ pub const execution_witness = @import("engine_witness.zig"); /// One image of a request (``Request.images``): the tower's input and the placeholder rows its output replaces. pub const Image = lanes.stream.Image; +pub const Audio = lanes.stream.Audio; /// A prompt's reproducible seed (``seed_for``), for requests that name none. pub const seedFor = lanes.sampling.seedFor; @@ -34,6 +35,7 @@ pub const grammar = lanes.grammar; pub const Request = @import("engine_request.zig").Request; pub const Stop = @import("engine_request.zig").Stop; + /// Image and video input an engine serves, and --vision's limits (engine_vision.zig). const vision_types = @import("engine_vision.zig"); pub const PreparedImage = vision_types.PreparedImage; @@ -43,6 +45,8 @@ pub const VideoSource = vision_types.VideoSource; pub const FrameSink = vision_types.FrameSink; pub const PreparedVideo = vision_types.PreparedVideo; pub const VideoOffer = vision_types.VideoOffer; +pub const PreparedAudio = vision_types.PreparedAudio; +pub const AudioOffer = vision_types.AudioOffer; pub const VisionOpen = vision_types.VisionOpen; pub const ImageShare = vision_types.ImageShare; pub const Size = vision_types.Size; @@ -181,6 +185,8 @@ pub const Info = struct { pictures: bool = false, /// Image input (--vision); null: text only. vision: ?Vision = null, + /// Audio input (a speech model's encoder); null: none. + audio: ?AudioOffer = null, ocr: ?ocr.Ocr = null, // OCR reader for /v1/ocr and /ocr; null: no OCR routes /// The engine decodes greedily only: the server refuses a request with a temperature before admitting it. greedy_only: bool = false, diff --git a/zig/src/core/engine_vision.zig b/zig/src/core/engine_vision.zig index 32daef60ec6..9c6db069c6c 100644 --- a/zig/src/core/engine_vision.zig +++ b/zig/src/core/engine_vision.zig @@ -90,6 +90,23 @@ pub const VideoOffer = struct { max_frames: u32, }; +/// An audio clip prepared for the engine's encoder (``AudioOffer.prepare``): samples, rows and a content hash. +pub const PreparedAudio = struct { samples: []f32, tokens: u32, hash: u64 }; + +/// Audio input an engine serves (``Info.audio``): a clip's bytes to encoder input, and what a request may hold. +pub const AudioOffer = struct { + ctx: *anyopaque, + /// The clip's bytes (a WAV file) at most ``max_tokens`` rows; allocated in ``a``. + prepare: *const fn (ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!PreparedAudio, + /// The template's once-a-clip token, expanded to its rows (0 from an engine; the server sets ``locator``'s id). + audio_token: u32 = 0, + /// The audio locator text (config.json's audio_locator_tag). + locator: []const u8, + /// Audio rows one request may hold in all, and clips. + audio_tokens: u32, + max_audios: u32, +}; + /// --vision's limits (``Open.vision``); image_tokens_set: the flag given; image_share: --vision-image-share's value. pub const VisionOpen = struct { image_tokens: u32 = 4096, image_tokens_set: bool = false, max_images: u32 = 4, video_tokens: u32 = 16384, max_videos: u32 = 2, max_frames: u32 = 256, image_share: ImageShare = .request }; diff --git a/zig/src/core/lane_host_fetch.zig b/zig/src/core/lane_host_fetch.zig index a1f7007bfd2..ead14a5758b 100644 --- a/zig/src/core/lane_host_fetch.zig +++ b/zig/src/core/lane_host_fetch.zig @@ -67,7 +67,7 @@ fn named(h: *LaneHost, name: Name) bool { /// A request the host's lookup keys by its tokens alone (no pictures), as `lane_stream.open` looks it up. fn keyed(r: *const api.Request) bool { - return !r.promptOnly() and r.prompt_logprobs == null and !r.untaught and r.images.len == 0 and r.cacheKey().len > 0; + return !r.promptOnly() and r.prompt_logprobs == null and !r.untaught and r.images.len == 0 and r.audios.len == 0 and r.cacheKey().len > 0; } /// A read finished: the engine thread, perhaps idle with every queued request waiting, looks again. diff --git a/zig/src/core/lane_host_lone.zig b/zig/src/core/lane_host_lone.zig index b6da0e1166c..3338efbdad3 100644 --- a/zig/src/core/lane_host_lone.zig +++ b/zig/src/core/lane_host_lone.zig @@ -1,9 +1,35 @@ //! A lane host's lone driver: the backend's own loop runs a lone stream until a foreground request or a cancel waits. +const lanes = @import("lanes"); const LaneHost = @import("lane_host.zig").LaneHost; const status = @import("lane_host_status.zig"); const backlog = @import("lane_host_backlog.zig"); const Job = LaneHost.Job; +/// A backend's own driver for a lone greedy stream (the GPU round), which LaneHost runs while the stream is alone. +pub const Lone = struct { + ctx: *anyopaque, + sampled: bool = false, // it drives sampled streams too + plain: bool = false, // it drives streams with drafts off too + logprobs: bool = false, // it gives each token its logprob row too + structures: bool = false, // it masks each window's rows by the stream's grammar too + images: bool = true, // it takes image requests too (false: they stay in the lane core) + // thinking budgets above this and loop guards: it hands the stream over before a forced close (0: never) + min_budget: u32 = 0, + resumes: bool = false, // it takes the lane core's stream back between rounds (LoneHooks.resumed); else only opens + /// Prefills (or resumes) `s` and decodes it until it finishes (false) or `hooks.yield` hands it to the lane core. + run: *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: LoneHooks) anyerror!bool, +}; + +/// What a lone driver tells the host between rounds: tokens landed; and asks: hand the stream over now? +pub const LoneHooks = struct { + ctx: *anyopaque, + committed: *const fn (ctx: *anyopaque) void, + yield: *const fn (ctx: *anyopaque) bool, + resumed: bool = false, // the stream comes from the lane core between rounds: no prompt pass, its drafts the core's + // After a completed nonfinal prompt call, true transfers the unfinished pass to the shared fill queue. + prefill_yield: ?*const fn (ctx: *anyopaque) bool = null, +}; + /// An idle driver takes a lone drafted request; plain, sampled, with logprobs, a budget or a grammar when supported. pub fn fits(h: *LaneHost, job: *Job) bool { if (!takes(h, job)) return false; @@ -16,7 +42,7 @@ fn takes(h: *LaneHost, job: *Job) bool { const r = job.request; const lone = h.lone orelse return false; const think = lone.min_budget > 0 and (r.think_budget == 0 or r.think_budget > lone.min_budget); - return !((r.sampling != null and !lone.sampled) or (!r.drafts and !lone.plain) or ((r.think_budget > 0 or r.loop_guard) and !think) or r.call != null or (r.structure != null and !lone.structures) or r.penalties.active() or (r.images.len > 0 and !lone.images) or (r.logprobs != null and !lone.logprobs) or r.prompt_logprobs != null); + return !((r.sampling != null and !lone.sampled) or (!r.drafts and !lone.plain) or ((r.think_budget > 0 or r.loop_guard) and !think) or r.call != null or (r.structure != null and !lone.structures) or r.penalties.active() or (r.images.len > 0 and !lone.images) or r.audios.len > 0 or (r.logprobs != null and !lone.logprobs) or r.prompt_logprobs != null); } /// After a round: the lane core's last live stream goes back to the driver when nothing else waits or is due. diff --git a/zig/src/core/lane_host_prefix.zig b/zig/src/core/lane_host_prefix.zig index 94a98eecc41..ca755461083 100644 --- a/zig/src/core/lane_host_prefix.zig +++ b/zig/src/core/lane_host_prefix.zig @@ -91,7 +91,7 @@ fn room(h: *LaneHost, job: *const Job, l: *const Job) bool { /// A request whose states the cache keys by its tokens alone, as the host's lookup does (no pictures). fn keyed(r: *const api.Request) bool { - return !r.promptOnly() and r.prompt_logprobs == null and !r.untaught and r.images.len == 0 and r.cacheKey().len > 0; + return !r.promptOnly() and r.prompt_logprobs == null and !r.untaught and r.images.len == 0 and r.audios.len == 0 and r.cacheKey().len > 0; } /// Waiting requests go on in queue order: the cut stood, the whole fill is done, the leader left, or the bound passed. diff --git a/zig/src/core/lane_stream.zig b/zig/src/core/lane_stream.zig index 043ebe0250f..962426a0863 100644 --- a/zig/src/core/lane_stream.zig +++ b/zig/src/core/lane_stream.zig @@ -69,6 +69,7 @@ pub fn open(h: *LaneHost, job: *Job) bool { .decide = r.decide, .untaught = r.untaught, .images = r.images, + .audios = r.audios, .key = r.cache_key, .cache_salt = r.cacheSalt(), }) catch { diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index 668b59e860a..6413e7fb6ae 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -112,6 +112,10 @@ pub const Image = struct { content_size: ?[2]u32 = null, hash: u64 = 0, // core/picture/identity.zig's: the bytes and the grid, as the prompt cache's key names the image }; + +/// One audio clip of a prompt: 16 kHz mono samples for the `tokens` placeholder rows from `at`; `hash` keys the cache. +pub const Audio = struct { samples: []const f32, at: u32, tokens: u32, hash: u64 = 0 }; + pub const Spec = struct { id: []const u8, prompt: []const u32, @@ -146,6 +150,7 @@ pub const Spec = struct { grammar: ?*grammar.Constraint = null, // structured output: the reply stays in it (the creator frees it) decode_spans: []const [2]u32 = &.{}, // prompt rows an earlier reply decoded (Request.decode_spans), for backends that keep their bits images: []const Image = &.{}, // in prompt order; the backend's tower fills their rows + audios: []const Audio = &.{}, // in prompt order; the backend's audio encoder fills their rows key: []const u32 = &.{}, cache_salt: ?u64 = null, // effective cache key and its exact optional salt }; @@ -192,6 +197,7 @@ pub const Stream = struct { decide: ?u32 = null, untaught: bool = false, images: []const Image = &.{}, + audios: []const Audio = &.{}, key: []const u32 = &.{}, cache_salt: ?u64 = null, cached: u32 = 0, // prompt tokens the backend restored from `reuse` (its prompt pass started there) @@ -286,6 +292,7 @@ pub const Stream = struct { .grammar = spec.grammar, .decode_spans = spec.decode_spans, .images = spec.images, + .audios = spec.audios, .key = spec.key, .cache_salt = spec.cache_salt, }; diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 6906101c219..a6db68dc096 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -145,7 +145,7 @@ const nemotron: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni" }; const slide_cuda: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "qwen3_5" }; const flash: []const []const u8 = &.{"qwen4_exp"}; /// The CUDA families whose host prompt cache the generic CUDA host builds (cuda_keep_others_test.zig checks the list). -pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark", "ricursive", "inkling2_loop" }; +pub const cuda_cache: []const []const u8 = &.{ "nemotron_h", "nemotron_h_omni", "nemo_speechlm", "glm5_next", "minimax_m3_vl", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "kolibri1", "gemma4", "gemma4_unified", "spark2_5", "dory", "lfm2_moe", "muse_spark", "ricursive", "inkling2_loop" }; pub const entries = [_]Entry{ .{ .id = .TF_CUDA_POOL_AFTER_WARMUP, .families = &.{"qwen3_5"}, .class = .experimental, .syntax = .one, .report_values = &.{"1"}, .effect = "Size an idle device KV pool after Qwen DFlash2 warm-up", .evidence = "Default off; host sizing checks; device capacity and token checks required" }, diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index 9af92970537..89427c1866a 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -38,6 +38,7 @@ pub const pages = @import("cuda_pages.zig"); pub const slide = @import("cuda_slide.zig"); pub const worker = @import("cuda_worker.zig"); pub const omni = @import("cuda_native_omni.zig"); +pub const transcribe = @import("cuda_native_transcribe.zig"); pub const identity = @import("core").checkpoint_identity; test { diff --git a/zig/src/families/nemotron/cuda_audio.zig b/zig/src/families/nemotron/cuda_audio.zig index 39797704465..70cfd62a832 100644 --- a/zig/src/families/nemotron/cuda_audio.zig +++ b/zig/src/families/nemotron/cuda_audio.zig @@ -5,7 +5,9 @@ const radio = @import("radio"); const nemo_audio = @import("nemo_audio"); /// A clip in a prompt: its samples (16 kHz mono) and the prompt position of its first `<|audio|>` row. -pub const Clip = struct { samples: []const f32, at: u32 }; +pub const Clip = @import("lanes").stream.Audio; +/// Clips a request may hold. +pub const max_clips = 8; /// A WAV file as the encoder reads it: its samples, the rows it takes, a hash of the samples for the prompt cache. pub const Prepared = struct { @@ -133,7 +135,7 @@ test "audio plan: clips in prompt order, rows back to back, a restored prefix's const a = std.testing.allocator; const one: [30560]f32 = @splat(0); // 24 rows const two: [56080]f32 = @splat(0); // 44 rows - const clips = [_]Clip{ .{ .samples = &one, .at = 43 }, .{ .samples = &two, .at = 80 } }; + const clips = [_]Clip{ .{ .samples = &one, .at = 43, .tokens = 24 }, .{ .samples = &two, .at = 80, .tokens = 44 } }; const all = try plan(a, &clips, 0); defer a.free(all); try std.testing.expectEqual(@as(usize, 2), all.len); @@ -141,7 +143,7 @@ test "audio plan: clips in prompt order, rows back to back, a restored prefix's const later = try plan(a, &clips, 67); defer a.free(later); try std.testing.expectEqual(radio.Span{ .at = 80, .n = 44, .row = 0, .image = 1 }, later[0]); - const overlapping = [_]Clip{ .{ .samples = &one, .at = 43 }, .{ .samples = &two, .at = 50 } }; + const overlapping = [_]Clip{ .{ .samples = &one, .at = 43, .tokens = 24 }, .{ .samples = &two, .at = 50, .tokens = 44 } }; try std.testing.expectError(error.AudioSpans, plan(a, &overlapping, 0)); } @@ -153,7 +155,7 @@ test "audio begin: a pass refused after planning leaves no spans for the next on var enc: nemo_audio.Encoder = undefined; var a: Audio = .{ .gpa = std.testing.allocator, .rows = .{ .d = undefined, .buf = undefined, .hidden = 8, .limit = 10 }, .encoder = &enc }; const one: [30560]f32 = @splat(0); // 24 rows, over the limit of 10 - const clips = [_]Clip{.{ .samples = &one, .at = 43 }}; + const clips = [_]Clip{.{ .samples = &one, .at = 43, .tokens = 24 }}; try std.testing.expectError(error.AudioRows, a.begin(undefined, &clips, 0)); try std.testing.expectEqual(@as(usize, 0), a.spans.len); } diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index f0bf66986da..133a4c24c1c 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -47,6 +47,11 @@ pub const Cancel = prompt_hooks.Cancel; pub const Keep = prompt_hooks.Keep; pub const Taps = prompt_hooks.Taps; +/// The one tap Nemotron gives: past its last layer, the final norm's rows its head and MTP head read. +pub fn finalTap(c: Config) u32 { + return @intCast(c.layers); +} + /// Serial rounds a host keeps queued ahead of the one it reads. pub const lookahead = 4; @@ -183,8 +188,9 @@ pub const Engine = struct { // every byte this rank holds, hashed while the weights load; the ranks compare the digests at ready var content: ?*identity.Content = if (e.tp != null) try identity.Content.start(gpa, io, model_dir, e.c.held != null) else null; errdefer if (content) |x| x.abandon(); - // Bolt (LatentMoE, ggml blocks): no MTP head in the checkpoint; our own glue (captured sets are Lightning's) - const mtp = opts.mtp and !e.c.bolt; + // Bolt (LatentMoE, ggml blocks): no MTP head in the checkpoint; our own glue (captured sets are Lightning's). + // Transcribe's MTP head is not qualified over audio rows yet: it decodes plain. + const mtp = opts.mtp and !e.c.bolt and !e.c.salm; if (e.c.bolt) { if (e.k.triton != null) return error.CapturedGlueIsLightnings; try e.k.loadGgml(ctx); @@ -218,6 +224,12 @@ pub const Engine = struct { }) orelse return error.VisionRefused; } errdefer if (!keep_owner) if (e.vision) |v| v.deinit(); + // a Transcribe checkpoint's audio encoder and its rows, loaded before the caches plan their memory + if (e.c.salm) { + const audio = @import("cuda_audio.zig"); + e.audio = try audio.Audio.load(gpa, io, ctx.d, model_dir, e.c.hidden); + } + errdefer if (!keep_owner) if (e.audio) |a| a.deinit(); e.b = try state.Buffers.init(ctx.d, e.c, e.max_len, e.nch, e.carve); errdefer if (!keep_owner) e.b.deinit(); try e.b.initShared(e.ops(), e.c); diff --git a/zig/src/families/nemotron/cuda_lanes.zig b/zig/src/families/nemotron/cuda_lanes.zig index 5fe0f28d00e..da0bdcba8f2 100644 --- a/zig/src/families/nemotron/cuda_lanes.zig +++ b/zig/src/families/nemotron/cuda_lanes.zig @@ -31,10 +31,7 @@ const ring = 1024; const Lane = struct { seq: *state.Seq, own: bool = false, paged: bool = false, pending_rows: ?usize = null, first: ?LogRow = null, stats: seq_graphs.Stats = .{}, keep: usize = 0, taps: Taps = .{} }; /// A recorded stream's rows: its prompt's on the host until its first verify, then where its last verify started. const Taps = struct { prompt: std.ArrayList(u8) = .empty, from: usize = 0, verified: ?u64 = null }; -/// The one tap Nemotron gives: past its last layer, the final norm's rows its head and MTP head read. -pub fn finalTap(c: config.Config) u32 { - return @intCast(c.layers); -} + pub const Cuda = struct { gpa: std.mem.Allocator, e: *Engine, @@ -323,14 +320,14 @@ pub const Cuda = struct { /// Recording asks for the final norm's rows alone; their staging buffer is made here. fn prepareFeaturesFn(ptr: *anyopaque, taps: []const u32) anyerror!void { const self = of(ptr); - if (taps.len != 1 or taps[0] != finalTap(self.e.c)) return error.UnsupportedTaps; + if (taps.len != 1 or taps[0] != engine.finalTap(self.e.c)) return error.UnsupportedTaps; if (self.tapped == null) self.tapped = try cuda.HostBuffer.alloc(self.e.ctx.d, state.pass_rows * self.e.c.hidden * 2); } /// The prompt's rows from the host until the first verify; then the last verify's, read from its sequence. fn featuresFn(ptr: *anyopaque, s: *lanes.Stream, taps: []const u32, start: u64, count: u32) anyerror!be.Features { const self = of(ptr); - if (self.tapped == null or taps.len != 1 or taps[0] != finalTap(self.e.c)) return error.UnsupportedTaps; + if (self.tapped == null or taps.len != 1 or taps[0] != engine.finalTap(self.e.c)) return error.UnsupportedTaps; const l = self.lanes.getPtr(s) orelse return error.UnknownStream; const d = self.e.c.hidden * 2; const t = &l.taps; diff --git a/zig/src/families/nemotron/cuda_native.zig b/zig/src/families/nemotron/cuda_native.zig index 55fc8fa7d7f..6f8f1484d26 100644 --- a/zig/src/families/nemotron/cuda_native.zig +++ b/zig/src/families/nemotron/cuda_native.zig @@ -79,6 +79,7 @@ pub const Loaded = struct { learns: ?*engine.Engine = null, // --slide: the engine its learner trains, whose sites it attached at load learn_bytes: usize = 0, // --slide: what its trainer allocates at the first lesson, kept out of the streams' room vision: ?*vision.Vision = null, // --vision: the tower the server's image requests reach + audio: ?*@import("cuda_audio.zig").Audio = null, // a Transcribe checkpoint's encoder the server's audio requests reach taps: []const u32 = &.{}, // the rows a recorder may ask `backend` for (empty: none) host_snaps: bool = false, // a discrete card: prompt states go to pinned host memory when the cache does not fit /// The other streams' memory as one pool of KV pages (null: each allocates a window at its prefill). @@ -143,7 +144,8 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer e.deinit(); if (o.mtp_drafts) |n| if (n >= state.windowRows(e.c)) return error.DraftsPastWindow; // Bolt has no MTP weights; copy drafts use the lane core and the target's ordinary verify windows. - const head_enabled = o.drafts and !e.c.bolt; + // Transcribe decodes plain: its MTP head is not qualified over audio rows, and a copied <|audio|> has no row. + const head_enabled = o.drafts and !e.c.bolt and !e.c.salm; const head: ?*Head = if (head_enabled) try Head.init(e) else null; errdefer if (head) |h| h.deinit(); if (head) |h| try h.capture(); @@ -158,13 +160,13 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer gpa.destroy(own); own.* = .{ .gpa = gpa, .e = e, .head = head, .lanes = try Lanes.init(gpa, e, head), .target = .{ .e = e, .head = head }, .carve = carve }; errdefer own.lanes.deinit(); - own.lanes.copy_drafts = o.drafts; + own.lanes.copy_drafts = o.drafts and !e.c.salm; own.lanes.mtp_drafts = o.mtp_drafts; own.lanes.mtp_confidence = o.mtp_confidence; own.living = try slide.loadLiving(gpa, io, e, dir); // before the lanes' costs are measured: they decode through it errdefer if (own.living) |*s| s.deinit(); try own.lanes.measure(io, dir); - own.taps = .{@import("cuda_lanes.zig").finalTap(e.c)}; + own.taps = .{engine.finalTap(e.c)}; return .{ .backend = own.lanes.backend(), .facts = own.lanes.facts(), @@ -177,6 +179,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ .learns = if (o.slide) e else null, .learn_bytes = if (o.slide) @import("cuda_train.zig").Trainer.memory(e.c) else 0, .vision = e.vision, + .audio = e.audio, .taps = &own.taps, .host_snaps = e.k.discrete, // a card with its own memory may keep prompt states in the host's (GB10 shares one) .layout = if (o.slide or e.k.triton != null or paging() == .off) null else pages_mod.layout(e), // our glue pages; the learner reads windows diff --git a/zig/src/families/nemotron/cuda_native_transcribe.zig b/zig/src/families/nemotron/cuda_native_transcribe.zig new file mode 100644 index 00000000000..ca0a1887778 --- /dev/null +++ b/zig/src/families/nemotron/cuda_native_transcribe.zig @@ -0,0 +1,26 @@ +//! Nemotron 3.5 Transcribe (nemo_speechlm) on CUDA: the Nemotron engine with its audio encoder (cuda_audio.zig). +const native = @import("cuda_native.zig"); + +pub const model_type = "nemo_speechlm"; +pub const formats = native.formats; +pub const default_context = native.default_context; +pub const max_segments = native.max_segments; +pub const prompt_rows = native.prompt_rows; +pub const Options = native.Options; +pub const explains_open = true; +pub const Loaded = native.Loaded; +pub const LoneRun = native.LoneRun; +pub const open = native.open; +pub const explain = native.explain; +pub const warm_quiet = native.warm_quiet; +pub const lone_min_budget = native.lone_min_budget; +pub const snap_bytes = native.snap_bytes; +pub const snap_save = native.snap_save; +pub const snap_restore = native.snap_restore; +pub const snap_drop = native.snap_drop; +pub const snap_slots = native.snap_slots; +pub const snap_place = native.snap_place; +pub const window_rows = native.window_rows; +pub const attach = native.attach; +pub const fits = native.fits; +pub const tensorWeightBytes = native.tensorWeightBytes; diff --git a/zig/src/families/nemotron/cuda_prompt.zig b/zig/src/families/nemotron/cuda_prompt.zig index 02a290acd96..ac9660c093a 100644 --- a/zig/src/families/nemotron/cuda_prompt.zig +++ b/zig/src/families/nemotron/cuda_prompt.zig @@ -61,7 +61,7 @@ pub fn begin(e: *Engine, prompt: []const u32, from: usize, head: ?*Head) !void { /// Whether prefillFrom runs the pass as staggered segments (named request cuts keep the serial chunks). pub fn segmented(e: *const Engine, prompt: []const u32, from: usize, dump: ?*Dump, cancel: ?Cancel, keep: ?Keep, chunks: []const u32) bool { - return from == 0 and keep == null and chunks.len == 0 and e.vision == null and e.segments > 1 and dump == null and e.prompt_rows == null and e.taps == null and prompt.len > state.prefill_rows and e.decide == lesson_route.none and !Cancel.background(cancel); + return from == 0 and keep == null and chunks.len == 0 and e.vision == null and e.audio == null and e.segments > 1 and dump == null and e.prompt_rows == null and e.taps == null and prompt.len > state.prefill_rows and e.decide == lesson_route.none and !Cancel.background(cancel); } /// The pass's first token, which its last chunk drew on the GPU. @@ -150,6 +150,10 @@ pub const Pass = struct { try e.copied.synchronize(); const host = e.promptHost(chunk.len); @memcpy(host, chunk); + // a speech prompt's <|audio|> placeholders lie past the token table: their rows are the clip's (cuda_audio.zig) + if (e.audio != null) for (host) |*t| if (t.* >= e.c.vocab) { + t.* = 0; + }; try e.ops().upload(e.b.p_ids, std.mem.sliceAsBytes(host)); try e.copied.record(e.stream); try f.chunk(@intCast(chunk.len), e.pos); diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 6ebb985c796..64e816ebb1f 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -481,6 +481,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a .penalties = served.backend.penalties, .structures = served.backend.vtable.first_masked != null, .vision = if (@hasField(@TypeOf(loaded), "vision")) vision_offer.offer(loaded.vision, o.vision) else null, + .audio = if (@hasField(@TypeOf(loaded), "audio")) vision_offer.audio(loaded.audio) else null, .admit = admit, .ledger = @import("cuda_ledger.zig").info(if (h.kv_plan) |*p| p else null), .slide_conversations = conversations, diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index 9e482c70018..981b8575fee 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -15,7 +15,7 @@ const qwen3 = @import("qwen3_cuda"); const inkling2 = @import("inkling2"); /// CUDA families provide metadata, open their lane backend and explain their refusals. -pub const registry = .{ nemotron.native, nemotron.omni, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("ricursive_cuda").native, @import("lfm2_moe_cuda").native, inkling2.native }; +pub const registry = .{ nemotron.native, nemotron.omni, nemotron.transcribe, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("ricursive_cuda").native, @import("lfm2_moe_cuda").native, inkling2.native }; pub const families: []const api.Family = blk: { var out: [registry.len + 5]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats, .decision_formats = if (@hasDecl(F, "decision_formats")) F.decision_formats else &.{} }; diff --git a/zig/src/native/cuda_vision_offer.zig b/zig/src/native/cuda_vision_offer.zig index f5261563c47..1e42b9e6dc2 100644 --- a/zig/src/native/cuda_vision_offer.zig +++ b/zig/src/native/cuda_vision_offer.zig @@ -247,3 +247,21 @@ test "actual Qwen offer keeps its image_url type and template-owned markers" { try std.testing.expectEqualSlices(u32, &q.markers, held.markers); try std.testing.expect(held.wrap == null and held.video == null); } + +/// Info.audio for a family's audio encoder (Nemotron 3.5 Transcribe's): its WAV prepare, locator and limits. +pub fn audio(x: ?*nemotron.audio.Audio) ?api.AudioOffer { + const a = x orelse return null; + if (a.encoder == null) return null; + const prepare = struct { + fn f(ctx: *anyopaque, al: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedAudio { + _ = ctx; + var p = try nemotron.audio.prepare(al, bytes); + if (p.rows > max_tokens) { + p.deinit(al); + return error.AudioTooLong; + } + return .{ .samples = p.samples, .tokens = p.rows, .hash = p.hash }; + } + }.f; + return .{ .ctx = a, .prepare = prepare, .locator = "<|audio|>", .audio_tokens = a.rows.limit, .max_audios = nemotron.audio.max_clips }; +} diff --git a/zig/src/server/audio.zig b/zig/src/server/audio.zig new file mode 100644 index 00000000000..2aca4ecce25 --- /dev/null +++ b/zig/src/server/audio.zig @@ -0,0 +1,293 @@ +//! Audio input (Info.audio): input_audio and audio_url parts to the engine's encoder, each clip's locator to its rows. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const errors = @import("errors.zig"); +const images = @import("images.zig"); +const image_key = @import("image_key.zig"); +const Value = json.Value; +const Cx = errors.Cx; + +/// A clip's encoded bytes at most (a request's body limit bounds them all: about 12 minutes of 16-bit 16 kHz WAV). +pub const max_audio_bytes = 32 << 20; + +/// The audio token: the locator the template writes must be one added token, the one a clip's rows take. +pub fn bindLocator(info: *api.Info, text: @import("model_text.zig").Text) error{InvalidAudioLocator}!void { + const o = if (info.audio) |*a| a else return; + o.audio_token = text.tokenId(o.locator) orelse { + @import("log.zig").line("audio input: the tokenizer has no single token {s}; audio cannot be served", .{o.locator}); + return error.InvalidAudioLocator; + }; +} + +/// A request's audio prompt: each clip's rows in place of its locator, the clips, and the key the prompt cache matches. +pub const Expanded = struct { + ids: []const u32, + history_len: usize, + audios: []const api.Audio, + cache_key: []const u32, // one word per row; a clip's rows carry its content hash +}; + +/// The type of a normalized audio part: {"type": "audio_url", "audio_url": {"url": a data URL}}. +pub const part_type = "audio_url"; + +/// The audio_url part a user's input_audio or audio_url part becomes; it reads its own output back unchanged. +pub fn part(cx: *Cx, p: Value, kind: []const u8) errors.Refused!Value { + for ([_][]const u8{ "image", "images", "image_url", "input_image", "video", "video_url" }) |k| if (json.truthyField(p, k)) return cx.refuse("audio parts cannot contain other media"); + const url = if (std.mem.eql(u8, kind, "input_audio")) try inputAudioUrl(cx, p) else try audioUrl(cx, p); + const inner = try json.newObject(cx.a); + try inner.put(cx.a, "url", .{ .string = url }); + const out = try json.newObject(cx.a); + try out.put(cx.a, "type", .{ .string = part_type }); + try out.put(cx.a, part_type, .{ .object = inner }); + return .{ .object = out }; +} + +/// OpenAI's {"input_audio": {"data": base64, "format": "wav"}} as a base64 WAV data URL. +fn inputAudioUrl(cx: *Cx, p: Value) errors.Refused![]const u8 { + const ia = p.get("input_audio") orelse return cx.refuse("an input_audio content part must contain input_audio"); + if (ia != .object) return cx.refuse("input_audio must be an object with data and format"); + const data = ia.strField("data") orelse return cx.refuse("input_audio must contain a base64 data string"); + if (data.len == 0) return cx.refuse("input_audio must contain a base64 data string"); + if (ia.get("format")) |f| if (f != .string or !std.ascii.eqlIgnoreCase(f.string, "wav")) + return cx.refuse("input_audio format must be wav; this server decodes WAV files only"); + return std.mem.concat(cx.a, u8, &.{ "data:audio/wav;base64,", data }); +} + +/// The model card's {"audio_url": {"url": "data:audio/wav;base64,..."}} (or the URL alone); remote URLs are refused. +fn audioUrl(cx: *Cx, p: Value) errors.Refused![]const u8 { + const au = p.get("audio_url") orelse return cx.refuse("an audio_url content part must contain audio_url"); + const u = if (au == .object) au.get("url") orelse return cx.refuse("audio_url must contain a url string") else au; + if (u != .string or u.string.len == 0) return cx.refuse("audio_url must contain a url string"); + if (!std.ascii.startsWithIgnoreCase(u.string, "data:")) return cx.refuse("audio_url must be a data URL holding a WAV file; remote audio URLs are unsupported"); + return u.string; +} + +/// A content part this module wrote: an audio clip's data URL, else null. +fn clipUrl(p: Value) ?[]const u8 { + if (!p.typeIs(part_type)) return null; + const au = p.get(part_type) orelse return null; + return au.strField("url"); +} + +/// The messages as the template reads them: a user turn's clips become `locator`-newline prefixes before its text. +pub fn forTemplate(a: std.mem.Allocator, messages: Value, locator: []const u8) !Value { + if (messages != .array) return messages; + var out: ?[]Value = null; + for (messages.array, 0..) |m, i| { + const content = m.get("content") orelse continue; + if (content != .array) continue; + var clips: usize = 0; + for (content.array) |p| clips += @intFromBool(clipUrl(p) != null); + if (clips == 0) continue; + // the template moves leading "\n" prefixes behind the text: " " + var text: std.ArrayList(u8) = .empty; + for (0..clips) |_| try text.print(a, "{s}\n", .{locator}); + for (content.array) |p| if (p.typeIs("text")) try text.appendSlice(a, p.strField("text") orelse ""); + const item = try json.copyObject(a, m.object); + try item.put(a, "content", .{ .string = text.items }); + const list = out orelse try a.dupe(Value, messages.array); + list[i] = .{ .object = item }; + out = list; + } + return if (out) |list| .{ .array = list } else messages; +} + +/// The clips' data URLs in the order the template renders them. +fn clipUrls(cx: *Cx, messages: Value) errors.Refused![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + if (messages != .array) return out.items; + for (messages.array) |m| { + const content = m.get("content") orelse continue; + if (content != .array) continue; + for (content.array) |p| if (clipUrl(p)) |u| try out.append(cx.a, u); + } + return out.items; +} + +/// The prompt with each locator token expanded to its clip's rows, the clips at their positions, and the cache key. +pub fn expand(offer: ?api.AudioOffer, cx: *Cx, messages: Value, ids: []const u32, history_len: usize) errors.Refused!?Expanded { + const o = offer orelse return null; + const urls = try clipUrls(cx, messages); + const marks = std.mem.count(u32, ids, &.{o.audio_token}); + if (urls.len == 0 and marks == 0) return null; + if (marks != urls.len) return cx.refuse(try std.fmt.allocPrint(cx.a, "the prompt holds {d} audio locators for {d} audio parts; message text must not begin with {s} and a newline", .{ marks, urls.len, o.locator })); + if (urls.len > o.max_audios) return cx.refuse(try std.fmt.allocPrint(cx.a, "a request may hold at most {d} audio clips; it has {d}", .{ o.max_audios, urls.len })); + const prepared = try cx.a.alloc(api.PreparedAudio, urls.len); + var left = o.audio_tokens; + for (urls, prepared, 0..) |u, *clip, i| { + const bytes = try images.dataBytesOf(cx, u, max_audio_bytes, "audio"); + clip.* = o.prepare(o.ctx, cx.a, bytes, left) catch |e| return refusal(cx, i, e, left); + if (clip.tokens == 0 or clip.tokens > left) return refusal(cx, i, error.AudioTooLong, left); + left -= clip.tokens; + } + var out_ids: std.ArrayList(u32) = .empty; + var key: std.ArrayList(u32) = .empty; + var clips: std.ArrayList(api.Audio) = .empty; + var hist = history_len; + var k: usize = 0; + var close: ?u32 = null; // a one-row clip's identity half that the word after it carries + for (ids, 0..) |t, src| { + if (t != o.audio_token) { + try out_ids.append(cx.a, t); + try key.append(cx.a, close orelse t); + close = null; + continue; + } + const clip = prepared[k]; + k += 1; + try clips.append(cx.a, .{ .samples = clip.samples, .at = @intCast(out_ids.items.len), .tokens = clip.tokens, .hash = clip.hash }); + try out_ids.appendNTimes(cx.a, t, clip.tokens); + try key.append(cx.a, image_key.open(clip.hash)); + for (1..clip.tokens) |j| try key.append(cx.a, if (j == 1) image_key.close(clip.hash) else image_key.row(clip.hash, j)); + close = if (clip.tokens == 1) image_key.close(clip.hash) else null; + if (src < history_len) hist += clip.tokens - 1; + } + return .{ .ids = out_ids.items, .history_len = hist, .audios = clips.items, .cache_key = key.items }; +} + +fn refusal(cx: *Cx, i: usize, err: anyerror, budget: u32) errors.Refused { + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.AudioTooLong => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} is longer than this request's audio budget of {d} rows ({d:.0} seconds)", .{ i + 1, budget, @as(f64, @floatFromInt(budget)) * 0.08 })), + error.WavNot16k => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} must be sampled at 16 kHz", .{i + 1})), + error.WavNotFinite => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} has a sample that is NaN or infinite", .{i + 1})), + error.WavNotMono => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} must be mono", .{i + 1})), + error.AudioTooShort => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} is shorter than 20 ms", .{i + 1})), + else => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} could not be decoded; send a WAV file (16, 24 or 32-bit PCM or 32-bit float, 16 kHz, mono)", .{i + 1})), + }; +} + +/// The tests' clips: a data URL's bytes are its samples, one row a byte, and their hash names them. +fn fakePrepare(_: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedAudio { + if (bytes.len > max_tokens) return error.AudioTooLong; + return .{ .samples = try a.alloc(f32, bytes.len), .tokens = @intCast(bytes.len), .hash = std.hash.Wyhash.hash(0, bytes) }; +} + +var test_ctx: u8 = 0; +const test_offer: api.AudioOffer = .{ .ctx = &test_ctx, .prepare = fakePrepare, .audio_token = 131072, .locator = "<|audio|>", .audio_tokens = 64, .max_audios = 4 }; + +fn testMessages(a: std.mem.Allocator, text: []const u8) !Value { + return switch (try json.parseText(a, text)) { + .ok => |m| m, + .err => error.TestUnexpectedResult, + }; +} + +const card_prompt = "Audio transcription. Language: as spoken. Wording: verbatim, including fillers and repetitions. Formatting: punctuation and capitalization. Output: transcript only."; +// prompt_ls_1272_135031_0009.json's template_ids: the card's request, its locator at 43, its history 47 ids +const dump_ids = [_]u32{ 10, 25708, 1010, 11, 1010, 10, 3263, 1010, 32535, 15661, 1046, 26242, 1058, 1435, 29930, 1046, 1488, 3592, 1058, 10564, 94503, 1044, 3907, 12369, 1428, 1321, 124440, 1046, 6392, 33361, 1058, 34315, 65656, 1321, 8961, 3229, 1046, 27039, 1058, 21482, 2342, 1046, 1032, 131072, 11, 1010, 10, 1503, 19464, 1010, 12, 13 }; + +test "the card's request: one locator after the text, expanded to the clip's rows as the dump lays them out" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const msgs = try testMessages(a, "[{\"role\": \"system\", \"content\": \"\"}, {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"" ++ card_prompt ++ + "\"}, {\"type\": \"audio_url\", \"audio_url\": {\"url\": \"data:audio/wav,abcdefghijklmnopqrstuvwx\"}}]}]"); + const view = try forTemplate(a, msgs, "<|audio|>"); + try std.testing.expectEqualStrings("<|audio|>\n" ++ card_prompt, view.array[1].get("content").?.string); + try std.testing.expectEqualStrings("", view.array[0].get("content").?.string); + const x = (try expand(test_offer, &cx, msgs, &dump_ids, 47)).?; + try std.testing.expectEqual(@as(usize, 75), x.ids.len); + try std.testing.expectEqualSlices(u32, dump_ids[0..43], x.ids[0..43]); + for (x.ids[43..67]) |t| try std.testing.expectEqual(@as(u32, 131072), t); + try std.testing.expectEqualSlices(u32, dump_ids[44..], x.ids[67..]); + try std.testing.expectEqual(@as(usize, 70), x.history_len); + try std.testing.expectEqual(@as(usize, 1), x.audios.len); + try std.testing.expectEqual(@as(u32, 43), x.audios[0].at); + try std.testing.expectEqual(@as(u32, 24), x.audios[0].tokens); + try std.testing.expectEqual(x.ids.len, x.cache_key.len); + try std.testing.expectEqual(image_key.open(x.audios[0].hash), x.cache_key[43]); + try std.testing.expectEqual(image_key.close(x.audios[0].hash), x.cache_key[44]); + try std.testing.expectEqualSlices(u32, x.ids[67..], x.cache_key[67..]); +} + +test "several clips: each locator takes its own clip's rows in order, keyed by the clip's content" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const msgs = try testMessages(a, + \\[{"role": "user", "content": [{"type": "audio_url", "audio_url": {"url": "data:,abc"}}, {"type": "audio_url", "audio_url": {"url": "data:,d"}}]}, + \\ {"role": "assistant", "content": "y"}, + \\ {"role": "user", "content": [{"type": "text", "text": "and"}, {"type": "audio_url", "audio_url": {"url": "data:,abc"}}]}] + ); + const view = try forTemplate(a, msgs, "<|audio|>"); + try std.testing.expectEqualStrings("<|audio|>\n<|audio|>\n", view.array[0].get("content").?.string); + try std.testing.expect(view.array[1].object == msgs.array[1].object); + try std.testing.expectEqualStrings("<|audio|>\nand", view.array[2].get("content").?.string); + const L = 131072; + const x = (try expand(test_offer, &cx, msgs, &[_]u32{ 1, L, 2, L, 3, 4, 5, L, 6 }, 5)).?; + try std.testing.expectEqualSlices(u32, &.{ 1, L, L, L, 2, L, 3, 4, 5, L, L, L, 6 }, x.ids); + try std.testing.expectEqual(@as(usize, 7), x.history_len); // the first message's clips are history, the last's not + try std.testing.expectEqual(@as(usize, 3), x.audios.len); + for ([_]u32{ 1, 5, 9 }, [_]u32{ 3, 1, 3 }, x.audios) |at, n, clip| { + try std.testing.expectEqual(at, clip.at); + try std.testing.expectEqual(n, clip.tokens); + } + try std.testing.expectEqualSlices(u32, x.cache_key[1..4], x.cache_key[9..12]); // the same clip, the same words + try std.testing.expect(x.cache_key[1] != x.cache_key[5]); + try std.testing.expectEqual(image_key.close(x.audios[1].hash), x.cache_key[6]); // a one-row clip's other half + try std.testing.expectEqual(@as(u32, 2), x.cache_key[4]); +} + +test "a clip past the request's remaining rows, or one clip too many, is refused" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const msgs = try testMessages(a, + \\[{"role": "user", "content": [{"type": "audio_url", "audio_url": {"url": "data:,abcdefgh"}}, {"type": "audio_url", "audio_url": {"url": "data:,abcdefghij"}}]}] + ); + const L = 131072; + var small = test_offer; + small.audio_tokens = 12; + try std.testing.expectError(error.Refused, expand(small, &cx, msgs, &[_]u32{ 1, L, 2, L }, 0)); + try std.testing.expectEqualStrings("audio 2 is longer than this request's audio budget of 4 rows (0 seconds)", cx.message); + var one = test_offer; + one.max_audios = 1; + try std.testing.expectError(error.Refused, expand(one, &cx, msgs, &[_]u32{ 1, L, 2, L }, 0)); + try std.testing.expectEqualStrings("a request may hold at most 1 audio clips; it has 2", cx.message); + try std.testing.expectError(error.Refused, expand(test_offer, &cx, msgs, &[_]u32{ 1, L, 2 }, 0)); + try std.testing.expectEqualStrings("the prompt holds 1 audio locators for 2 audio parts; message text must not begin with <|audio|> and a newline", cx.message); +} + +test "messages without audio pass through; a locator with no clip is refused" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const msgs = try testMessages(a, + \\[{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}] + ); + const view = try forTemplate(a, msgs, "<|audio|>"); + try std.testing.expect(view.array.ptr == msgs.array.ptr); + try std.testing.expect(try expand(test_offer, &cx, msgs, &[_]u32{ 1, 2, 3 }, 2) == null); + try std.testing.expect(try expand(null, &cx, msgs, &[_]u32{ 1, 131072 }, 0) == null); + try std.testing.expectError(error.Refused, expand(test_offer, &cx, msgs, &[_]u32{ 1, 131072, 3 }, 0)); +} + +test "input_audio and audio_url parts normalize to one data URL part, twice alike; other sources are refused" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + const parts = try testMessages(a, + \\[{"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}, + \\ {"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64,UklGRg=="}}, + \\ {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "mp3"}}, + \\ {"type": "audio_url", "audio_url": {"url": "https://example.com/a.wav"}}, + \\ {"type": "audio_url", "audio_url": {}}, + \\ {"type": "input_audio", "input_audio": {"data": ""}}] + ); + for (parts.array[0..2], [_][]const u8{ "input_audio", "audio_url" }) |p, kind| { + const once = try part(&cx, p, kind); + const twice = try part(&cx, once, part_type); + try std.testing.expectEqualStrings("data:audio/wav;base64,UklGRg==", clipUrl(twice).?); + try std.testing.expectEqualStrings(part_type, twice.strField("type").?); + } + for (parts.array[2..], [_][]const u8{ "input_audio", "audio_url", "audio_url", "input_audio" }) |p, kind| + try std.testing.expectError(error.Refused, part(&cx, p, kind)); + try std.testing.expectEqualStrings("input_audio must contain a base64 data string", cx.message); +} diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index e8927575f38..e6a58f5dcce 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -120,7 +120,6 @@ pub const Reply = struct { }; pub const Failure = error{ Refused, Cancelled, Failed, OutOfMemory }; - const nowNs = clock.nowNs; const seconds = clock.seconds; @@ -231,6 +230,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa .tools_json = if (input.tools.len > 0) try json.stringify(a, .{ .array = @constCast(input.tools) }, .{ .ascii = false }) else "", .decide = if (input.prompt == null and !background) prompt_mod.decideOf(srv, rendered.ids) else null, .images = rendered.images, + .audios = rendered.audios, .cache_key = rendered.cache_key, }; const salt = if (input.cache_salt != 0) input.cache_salt else cx.cache_salt; diff --git a/zig/src/server/input_types.zig b/zig/src/server/input_types.zig index 794cc21e0a3..c159a9cd900 100644 --- a/zig/src/server/input_types.zig +++ b/zig/src/server/input_types.zig @@ -42,5 +42,6 @@ pub fn media(srv: anytype) @import("messages.zig").Media { result.images = taken.image; result.videos = taken.video; result.native_deepseek = srv.text.native_deepseek; + result.audio = srv.info.audio != null; return result; } diff --git a/zig/src/server/messages.zig b/zig/src/server/messages.zig index 7489ee123de..eb85ffd23c9 100644 --- a/zig/src/server/messages.zig +++ b/zig/src/server/messages.zig @@ -5,6 +5,7 @@ const errors = @import("errors.zig"); const fields = @import("fields.zig"); const pdf = @import("pdf.zig"); const api = @import("engine_api"); +const audio = @import("audio.zig"); const Value = json.Value; const Cx = errors.Cx; @@ -28,12 +29,13 @@ pub fn normalize(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_ return normalizeWith(cx, messages, late_system, needs_user_after_tool, .{}); } -/// The media parts an engine reads: image_url (``Info.vision``), video_url (``video``), and PDFs (``--vision-pdf``). +/// Media parts an engine reads: images and videos (``Info.vision``), PDFs (``--vision-pdf``), audio (``Info.audio``). pub const Media = struct { native_deepseek: bool = false, images: bool = false, videos: bool = false, pdfs: bool = false, + audio: bool = false, image_type: []const u8 = "image_url", // the part type the template reads (Vision.part_type) max_images: u32 = 50, @@ -131,6 +133,12 @@ pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_u has_image = true; continue; } + if (media.audio and (std.mem.eql(u8, kind, "input_audio") or std.mem.eql(u8, kind, "audio_url"))) { + if (!std.mem.eql(u8, role.?.string, "user")) return cx.refuse("audio parts are accepted in user messages only"); + try parts.append(cx.a, try audio.part(cx, part, kind)); + has_image = true; + continue; + } if (media.videos and std.mem.eql(u8, kind, "video_url")) { if (!std.mem.eql(u8, role.?.string, "user")) return cx.refuse("video_url parts are supported only in user messages"); try parts.append(cx.a, try videoPart(cx, part)); @@ -147,12 +155,12 @@ pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_u has_reference = true; continue; } - if (!std.mem.eql(u8, kind, "text") or fields.hasMedia(part)) return cx.refuse(if (media.videos) "content parts must be text, image_url or video_url; audio is unsupported" else if (images) "content parts must be text or image_url; audio and video inputs are unsupported" else "this server accepts text parts only; image, audio and video inputs are unsupported"); + if (!std.mem.eql(u8, kind, "text") or fields.hasMedia(part)) return cx.refuse(if (media.audio) "content parts must be text, input_audio or audio_url; image and video inputs are unsupported" else if (media.videos) "content parts must be text, image_url or video_url; audio is unsupported" else if (images) "content parts must be text or image_url; audio and video inputs are unsupported" else "this server accepts text parts only; image, audio and video inputs are unsupported"); const t = part.get("text") orelse return cx.refuse("a text content part must contain a text string"); if (t != .string) return cx.refuse("a text content part must contain a text string"); if (media.native_deepseek and part_index > 0) try text.appendSlice(cx.a, "\n\n"); try text.appendSlice(cx.a, t.string); - if (images or tool) { + if (images or tool or media.audio) { const tp = try json.newObject(cx.a); try tp.put(cx.a, "type", .{ .string = "text" }); try tp.put(cx.a, "text", t); diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index a4c224a59d7..7b97d4cea6c 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -7,12 +7,13 @@ const messages_mod = @import("messages.zig"); const model_text = @import("model_text.zig"); const chat = @import("chat.zig"); const images = @import("images.zig"); +const audio = @import("audio.zig"); const Server = @import("server.zig").Server; const Value = json.Value; const Cx = errors.Cx; /// With image input, `ids` holds each image's tokens, `images` the images and `cache_key` the prompt the cache matches. -pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0, user_end: usize = 0, images: []const api.Image = &.{}, cache_key: []const u32 = &.{}, frames: []const ?api.Size = &.{}, message_starts: []const u32 = &.{} }; +pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0, user_end: usize = 0, images: []const api.Image = &.{}, audios: []const api.Audio = &.{}, cache_key: []const u32 = &.{}, frames: []const ?api.Size = &.{}, message_starts: []const u32 = &.{} }; /// Where lessons decide to act on a reply: the row before the generation prompt's ``, else before its last. pub fn decideOf(srv: *const Server, ids: []const u32) u32 { @@ -109,7 +110,9 @@ fn render(srv: *Server, a: std.mem.Allocator, messages: Value, options_: model_t var bytes: []usize = &.{}; var options = options_; if (starts != null) options.message_starts = &bytes; - var rendered = try srv.text.render(a, messages, options, problem); + // audio input: the messages the chat template renders (audio.zig) + const view = if (srv.info.audio) |o| try audio.forTemplate(a, messages, o.locator) else messages; + var rendered = try srv.text.render(a, view, options, problem); if (srv.info.vision) |v| if (v.video) |o| if (o.video_text.len > 0) { const word = try srv.text.tokenString(a, o.video_token); rendered = try rendered.replaceTemplate(a, o.video_text, word); @@ -175,6 +178,8 @@ pub fn prepare(srv: *Server, cx: *Cx, input: chat.Input, thinking: bool, effort: if (history_len > 0) history_len = continuedLen(srv, cx, input.messages, input.tools, thinking, effort, history, history_len); // --vision: placeholders expanded to image tokens before the window, chunks and cache see it; no rewind kept if (try images.expandWith(srv.info.vision, if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, srv.text, cx, input.messages, prompt, history_len, input.image_bytes)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .images = x.images, .cache_key = x.cache_key, .frames = x.frames }; + // audio input: the rendered prompt with each clip's rows (audio.zig) + if (try audio.expand(srv.info.audio, cx, input.messages, prompt, history_len)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .audios = x.audios, .cache_key = x.cache_key }; const count = if (input.messages == .array) input.messages.array.len else 0; const rewind_len = if (srv.info.prompt_cache) rewindLen(srv, cx, input.messages, count, input.tools, prompt, thinking, effort) else 0; // one more render return .{ .ids = prompt, .history_len = history_len, .rewind_len = rewind_len, .user_end = userEnd(input.messages, history_len), .message_starts = message_starts }; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 23dc26dc988..d01d9e0b640 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -149,6 +149,7 @@ test { _ = @import("pdf_measure_test.zig"); _ = @import("jpeg_out.zig"); _ = @import("images.zig"); + _ = @import("audio.zig"); _ = @import("images_video_marker_test.zig"); _ = @import("chat_ocr_test.zig"); _ = @import("image_key.zig"); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 84f0bab330e..71d4a1ae04d 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -136,7 +136,11 @@ pub const Server = struct { return error.InvalidVisionMarkers; }; srv.video_decoder = @import("input_types.zig").decodes(srv.info.vision); // no decoder: video parts are a 400, never a 500 - try @import("speech_voices.zig").start(srv, gpa, io, config); + try @import("audio.zig").bindLocator(&srv.info, text); + srv.voices = .{ .gpa = gpa, .io = io, .dir = config.voice.dir }; + if (srv.info.speech == null and (config.voice.dir != null or config.voice.inline_voices or config.voice.manage)) return error.VoicesRequireSpeech; + if (config.voice.dir) |dir| try srv.voices.load(dir); + _ = try srv.voices.select(srv.arena.allocator(), config.voice.default, "default"); if (!srv.info.capability(.text_generation)) { if (config.cortheon) return error.CortheonRequiresTextGeneration; return srv; diff --git a/zig/src/server/tokens.zig b/zig/src/server/tokens.zig index fd804524b04..92cab3c8681 100644 --- a/zig/src/server/tokens.zig +++ b/zig/src/server/tokens.zig @@ -43,6 +43,7 @@ fn messageIds(srv: *Server, cx: *Cx, body: Value) errors.Refused![]const u32 { }; // media expanded as the chat route expands them: each image's tokens, each video's frame groups if (try images.expand(srv.info.vision, if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, srv.text, cx, msgs, ids, 0)) |x| return x.ids; + if (try @import("audio.zig").expand(srv.info.audio, cx, msgs, ids, 0)) |x| return x.ids; return ids; } diff --git a/zig/src/server/warm.zig b/zig/src/server/warm.zig index 094a7999f97..427635a32c8 100644 --- a/zig/src/server/warm.zig +++ b/zig/src/server/warm.zig @@ -72,14 +72,20 @@ fn start(srv: *Server, input: chat.Input, sent: Value, reasoning: ?[]const u8, t // an image conversation's pass holds its images as its turns did (data URLs only: no URL is fetched twice) const pictures = try images.expand(srv.info.vision, null, srv.text, &cx, .{ .array = warm_prompt.messages }, prompt, prompt.len); if (pictures) |x| prompt = x.ids; + const clips = if (pictures == null) try @import("audio.zig").expand(srv.info.audio, &cx, .{ .array = warm_prompt.messages }, prompt, prompt.len) else null; + if (clips) |x| prompt = x.ids; if (prompt.len == 0 or (srv.info.context_window > 0 and prompt.len >= srv.info.context_window)) return; const system_len = prompt_mod.systemPrefixLen(srv, &cx, .{ .array = warm_prompt.messages }, input.tools, prompt, thinking, effort); // its states count as the reply's request's: they supersede none of that turn's own until a later turn does - p.request = .{ .prompt = prompt, .max_tokens = 0, .background = true, .born = @intCast(prompt_len), .history_len = @intCast(prompt.len), .rewind_len = if (pictures != null) 0 else @intCast(prompt_mod.rewindLen(srv, &cx, .{ .array = warm_prompt.messages }, input.messages.array.len, input.tools, prompt, thinking, effort)), .chunks = try srv.chunks.request(a, prompt, system_len), .decode_spans = try prompt_mod.replySpans(srv, &cx, prompt) }; + p.request = .{ .prompt = prompt, .max_tokens = 0, .background = true, .born = @intCast(prompt_len), .history_len = @intCast(prompt.len), .rewind_len = if (pictures != null or clips != null) 0 else @intCast(prompt_mod.rewindLen(srv, &cx, .{ .array = warm_prompt.messages }, input.messages.array.len, input.tools, prompt, thinking, effort)), .chunks = try srv.chunks.request(a, prompt, system_len), .decode_spans = try prompt_mod.replySpans(srv, &cx, prompt) }; if (pictures) |x| { p.request.images = x.images; p.request.cache_key = x.cache_key; } + if (clips) |x| { + p.request.audios = x.audios; + p.request.cache_key = x.cache_key; + } // a salted conversation's pass keeps its states under the same salt (an engine keyed by tokens alone: no pass) if (input.cache_salt != 0) p.request.cache_key = if (srv.info.cache_salt) try @import("cache_salt.zig").salted(a, p.request.cacheKey(), input.cache_salt) else return; p.request.salted = input.cache_salt != 0; From 4235cab38928841a15a139872bc1ae33748abd3b Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:30:15 +0000 Subject: [PATCH 282/361] nemotron transcribe: its trained 65536-token window, an hour of audio a request (160 MiB chat bodies when the engine takes audio), MTP drafts with the clip's rows in the head --- zig/src/families/nemotron/cuda_audio.zig | 13 ++++++++++--- zig/src/families/nemotron/cuda_engine.zig | 7 +++---- zig/src/families/nemotron/cuda_mtp.zig | 9 +++++++-- zig/src/families/nemotron/cuda_native.zig | 5 ++--- .../families/nemotron/cuda_native_transcribe.zig | 4 +++- zig/src/families/nemotron/cuda_prompt.zig | 2 +- zig/src/families/nemotron/cuda_segments.zig | 2 +- zig/src/native/cuda.zig | 4 ++-- zig/src/server/audio.zig | 16 ++++++++++++---- zig/src/server/http_body.zig | 7 ++++++- zig/src/server/openai.zig | 2 +- 11 files changed, 48 insertions(+), 23 deletions(-) diff --git a/zig/src/families/nemotron/cuda_audio.zig b/zig/src/families/nemotron/cuda_audio.zig index 70cfd62a832..771de00f772 100644 --- a/zig/src/families/nemotron/cuda_audio.zig +++ b/zig/src/families/nemotron/cuda_audio.zig @@ -25,6 +25,11 @@ pub fn limit() u32 { return nemo_audio.Config.limit(); } +/// The rows buffer for a `context`-token window: an hour of audio, or the window when it holds less. +pub fn limitFor(context: usize) u32 { + return @intCast(@min(context, limit())); +} + /// A WAV file's samples and rows; error.AudioTooShort or error.AudioTooLong past what the encoder takes. pub fn prepare(a: std.mem.Allocator, data: []const u8) !Prepared { const samples = try nemo_audio.wav.decode(a, data); @@ -66,14 +71,14 @@ pub const Audio = struct { return a; } - /// The checkpoint's audio encoder and a rows buffer for an hour of audio in the language model's width. - pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, hidden: usize) !*Audio { + /// The checkpoint's audio encoder and a rows buffer of `rows_limit` rows in the language model's width. + pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, rows_limit: u32, hidden: usize) !*Audio { const enc = try gpa.create(nemo_audio.Encoder); errdefer gpa.destroy(enc); enc.* = try nemo_audio.Encoder.init(gpa, io, d, dir); errdefer enc.deinit(); if (enc.c.output != hidden) return error.AudioWidth; - const a = try init(gpa, d, limit(), hidden); + const a = try init(gpa, d, rows_limit, hidden); a.encoder = enc; return a; } @@ -149,6 +154,8 @@ test "audio plan: clips in prompt order, rows back to back, a restored prefix's test "audio limit: an hour of audio's rows" { try std.testing.expectEqual(@as(u32, 45000), limit()); + try std.testing.expectEqual(@as(u32, 32768), limitFor(32768)); + try std.testing.expectEqual(@as(u32, 45000), limitFor(65536)); } test "audio begin: a pass refused after planning leaves no spans for the next one" { diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index 133a4c24c1c..01fc87621e5 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -188,9 +188,8 @@ pub const Engine = struct { // every byte this rank holds, hashed while the weights load; the ranks compare the digests at ready var content: ?*identity.Content = if (e.tp != null) try identity.Content.start(gpa, io, model_dir, e.c.held != null) else null; errdefer if (content) |x| x.abandon(); - // Bolt (LatentMoE, ggml blocks): no MTP head in the checkpoint; our own glue (captured sets are Lightning's). - // Transcribe's MTP head is not qualified over audio rows yet: it decodes plain. - const mtp = opts.mtp and !e.c.bolt and !e.c.salm; + // Bolt (LatentMoE, ggml blocks): no MTP head in the checkpoint; our own glue (captured sets are Lightning's) + const mtp = opts.mtp and !e.c.bolt; if (e.c.bolt) { if (e.k.triton != null) return error.CapturedGlueIsLightnings; try e.k.loadGgml(ctx); @@ -227,7 +226,7 @@ pub const Engine = struct { // a Transcribe checkpoint's audio encoder and its rows, loaded before the caches plan their memory if (e.c.salm) { const audio = @import("cuda_audio.zig"); - e.audio = try audio.Audio.load(gpa, io, ctx.d, model_dir, e.c.hidden); + e.audio = try audio.Audio.load(gpa, io, ctx.d, model_dir, audio.limitFor(opts.context orelse default_context), e.c.hidden); } errdefer if (!keep_owner) if (e.audio) |a| a.deinit(); e.b = try state.Buffers.init(ctx.d, e.c, e.max_len, e.nch, e.carve); diff --git a/zig/src/families/nemotron/cuda_mtp.zig b/zig/src/families/nemotron/cuda_mtp.zig index af6dd0d6a83..74136b4a54d 100644 --- a/zig/src/families/nemotron/cuda_mtp.zig +++ b/zig/src/families/nemotron/cuda_mtp.zig @@ -533,8 +533,8 @@ pub const Head = struct { return .{ .token = tok[0], .prob = prob[0] }; } - /// MTPHead.absorb_rows: a prompt chunk's rows into the head's cache, keys and values only. - pub fn absorb(h: *Head, hidden: u64, tokens: []const u32) !void { + /// MTPHead.absorb_rows: a prompt chunk's keys and values into the head's cache, `tokens` at [at, at + len). + pub fn absorb(h: *Head, hidden: u64, tokens: []const u32, at: usize) !void { const e = h.e; const c = e.c; const m = e.w.mtp.?; @@ -546,8 +546,13 @@ pub const Head = struct { try h.copied.synchronize(); const host = h.pinned.slice(u32)[host_tokens..][0..tokens.len]; @memcpy(host, tokens); + // a speech prompt's <|audio|> placeholders take the clip's rows, as the trunk's embeds do (cuda_audio.zig) + if (e.audio != null) for (host) |*t| if (t.* >= c.vocab) { + t.* = 0; + }; try o.upload(h.atok, std.mem.sliceAsBytes(host)); try f.embed(h.atok, h.emb, rows); + if (e.audio) |a| try a.splice(o.s, at, at + rows, h.emb); try f.glue.concatNorms(h.emb, hidden, m.enorm, m.hnorm, h.cat, h.cxs, rows, c.hidden, c.eps); try o.prefillDense(h.cat, m.eh_proj, h.x, rows); try f.glue.addRmsnorm(h.x, null, m.attn_norm, h.x, b.y, b.xs, rows, c.hidden, c.eps); diff --git a/zig/src/families/nemotron/cuda_native.zig b/zig/src/families/nemotron/cuda_native.zig index 6f8f1484d26..f8659f74ca8 100644 --- a/zig/src/families/nemotron/cuda_native.zig +++ b/zig/src/families/nemotron/cuda_native.zig @@ -144,8 +144,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer e.deinit(); if (o.mtp_drafts) |n| if (n >= state.windowRows(e.c)) return error.DraftsPastWindow; // Bolt has no MTP weights; copy drafts use the lane core and the target's ordinary verify windows. - // Transcribe decodes plain: its MTP head is not qualified over audio rows, and a copied <|audio|> has no row. - const head_enabled = o.drafts and !e.c.bolt and !e.c.salm; + const head_enabled = o.drafts and !e.c.bolt; const head: ?*Head = if (head_enabled) try Head.init(e) else null; errdefer if (head) |h| h.deinit(); if (head) |h| try h.capture(); @@ -160,7 +159,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer gpa.destroy(own); own.* = .{ .gpa = gpa, .e = e, .head = head, .lanes = try Lanes.init(gpa, e, head), .target = .{ .e = e, .head = head }, .carve = carve }; errdefer own.lanes.deinit(); - own.lanes.copy_drafts = o.drafts and !e.c.salm; + own.lanes.copy_drafts = o.drafts and !e.c.salm; // a copied <|audio|> has no audio row own.lanes.mtp_drafts = o.mtp_drafts; own.lanes.mtp_confidence = o.mtp_confidence; own.living = try slide.loadLiving(gpa, io, e, dir); // before the lanes' costs are measured: they decode through it diff --git a/zig/src/families/nemotron/cuda_native_transcribe.zig b/zig/src/families/nemotron/cuda_native_transcribe.zig index ca0a1887778..1bb7f80318e 100644 --- a/zig/src/families/nemotron/cuda_native_transcribe.zig +++ b/zig/src/families/nemotron/cuda_native_transcribe.zig @@ -3,7 +3,9 @@ const native = @import("cuda_native.zig"); pub const model_type = "nemo_speechlm"; pub const formats = native.formats; -pub const default_context = native.default_context; +/// The card's trained window: llm_config's 262144 is the backbone's, which this speech model was not trained to. +pub const trained_context: i64 = 65536; +pub const default_context = trained_context; pub const max_segments = native.max_segments; pub const prompt_rows = native.prompt_rows; pub const Options = native.Options; diff --git a/zig/src/families/nemotron/cuda_prompt.zig b/zig/src/families/nemotron/cuda_prompt.zig index ac9660c093a..95a49864dd3 100644 --- a/zig/src/families/nemotron/cuda_prompt.zig +++ b/zig/src/families/nemotron/cuda_prompt.zig @@ -161,7 +161,7 @@ pub const Pass = struct { e.pos += @intCast(chunk.len); const known = @min(chunk.len, prompt.len - 1 - s); if (e.prompt_rows) |pr| try prompt_rows.run(e, pr, prompt[s + 1 ..][0..known]); - if (p.head) |h| if (known > 0) try h.absorb(e.b.p_hidden, prompt[s + 1 ..][0..known]); + if (p.head) |h| if (known > 0) try h.absorb(e.b.p_hidden, prompt[s + 1 ..][0..known], s + 1); if (e.taps) |t| try t.call(t.ctx, e.b.p_hidden, s, chunk.len); try reuse.finish(.{ .e = e, .head = p.head }); p.s = end; diff --git a/zig/src/families/nemotron/cuda_segments.zig b/zig/src/families/nemotron/cuda_segments.zig index 6f85672b61a..f031735fa43 100644 --- a/zig/src/families/nemotron/cuda_segments.zig +++ b/zig/src/families/nemotron/cuda_segments.zig @@ -99,7 +99,7 @@ pub fn prefill(e: *Engine, s: *Segments, prompt: []const u32, head: ?*Head, part for (0..c.parts) |k| { // the caller's stream has joined every segment const start = at + k * R; const known = @min(seg[k].walk.rows, prompt.len - 1 - start); - if (head) |h| if (known > 0) try h.absorb(bufs[k].p_hidden, prompt[start + 1 ..][0..known]); + if (head) |h| if (known > 0) try h.absorb(bufs[k].p_hidden, prompt[start + 1 ..][0..known], start + 1); } last = c.parts - 1; last_rows = seg[last].walk.rows; diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 64e816ebb1f..e8940718b9a 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -186,11 +186,11 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, asked: a problem.* = why; return null; } - // a family whose rope can stretch (Qwen's YaRN, from its config or --rope-yarn) names its own ceiling + // the window: a stretched rope's own ceiling (Qwen's YaRN), else a family's trained_context, else config.json's const own = if (comptime @hasDecl(F, "contextCeiling")) F.contextCeiling(a, io, o.dir, o.rope_yarn) catch |e| { problem.* = try std.fmt.allocPrint(a, "{s} ({s}): YaRN takes rope_type yarn, factor, original_max_position_embeddings and their product as max_position_embeddings, and --rope-yarn a factor from 1 matching it", .{ if (o.rope_yarn != null) "--rope-yarn" else "the checkpoint's rope scaling", @errorName(e) }); return null; - } else modelContext(a, io, o.dir); + } else if (comptime @hasDecl(F, "trained_context")) F.trained_context else modelContext(a, io, o.dir); // a family with no positions to stretch (GLM-5.3-Flash) raises it with a row of its own, read at its open const raised = windows.familyCeiling(F, problem) catch return null; const native: i64 = if (raised.window) |n| @intCast(n) else own; diff --git a/zig/src/server/audio.zig b/zig/src/server/audio.zig index 2aca4ecce25..6aa4d0ec8cb 100644 --- a/zig/src/server/audio.zig +++ b/zig/src/server/audio.zig @@ -5,11 +5,19 @@ const json = @import("json"); const errors = @import("errors.zig"); const images = @import("images.zig"); const image_key = @import("image_key.zig"); +const http_body = @import("http_body.zig"); const Value = json.Value; const Cx = errors.Cx; -/// A clip's encoded bytes at most (a request's body limit bounds them all: about 12 minutes of 16-bit 16 kHz WAV). -pub const max_audio_bytes = 32 << 20; +/// A request body at most when the engine takes audio: an hour of 16-bit 16 kHz WAV (115.2 MB) in base64, and its text. +pub const body_limit = 160 << 20; +/// A clip's encoded bytes at most (the body limit bounds them all). +pub const max_audio_bytes = body_limit; + +/// The body limit of a route that reads chat messages: an hour of audio when the engine takes it. +pub fn bodyLimit(info: api.Info) usize { + return if (info.audio != null) body_limit else http_body.limit; +} /// The audio token: the locator the template writes must be one added token, the one a clip's rows take. pub fn bindLocator(info: *api.Info, text: @import("model_text.zig").Text) error{InvalidAudioLocator}!void { @@ -149,7 +157,7 @@ pub fn expand(offer: ?api.AudioOffer, cx: *Cx, messages: Value, ids: []const u32 fn refusal(cx: *Cx, i: usize, err: anyerror, budget: u32) errors.Refused { return switch (err) { error.OutOfMemory => error.OutOfMemory, - error.AudioTooLong => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} is longer than this request's audio budget of {d} rows ({d:.0} seconds)", .{ i + 1, budget, @as(f64, @floatFromInt(budget)) * 0.08 })), + error.AudioTooLong => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} is longer than this request's audio budget of {d} rows ({d:.1} seconds)", .{ i + 1, budget, @as(f64, @floatFromInt(budget)) * 0.08 })), error.WavNot16k => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} must be sampled at 16 kHz", .{i + 1})), error.WavNotFinite => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} has a sample that is NaN or infinite", .{i + 1})), error.WavNotMono => cx.refuse(try std.fmt.allocPrint(cx.a, "audio {d} must be mono", .{i + 1})), @@ -244,7 +252,7 @@ test "a clip past the request's remaining rows, or one clip too many, is refused var small = test_offer; small.audio_tokens = 12; try std.testing.expectError(error.Refused, expand(small, &cx, msgs, &[_]u32{ 1, L, 2, L }, 0)); - try std.testing.expectEqualStrings("audio 2 is longer than this request's audio budget of 4 rows (0 seconds)", cx.message); + try std.testing.expectEqualStrings("audio 2 is longer than this request's audio budget of 4 rows (0.3 seconds)", cx.message); var one = test_offer; one.max_audios = 1; try std.testing.expectError(error.Refused, expand(one, &cx, msgs, &[_]u32{ 1, L, 2, L }, 0)); diff --git a/zig/src/server/http_body.zig b/zig/src/server/http_body.zig index 950de92a64a..e22aa3b9c61 100644 --- a/zig/src/server/http_body.zig +++ b/zig/src/server/http_body.zig @@ -151,7 +151,12 @@ fn trailerName(line: []const u8) bool { /// The body as JSON (an empty body reads as ``{}``): a framing refusal, or the decoder's message as another exception. pub fn readJson(conn: *Conn, cx: *errors.Cx) errors.Refused!json.Value { - const raw = switch (try read(conn, cx.a, limit)) { + return readJsonMax(conn, cx, limit); +} + +/// readJson with its own limit (a route whose requests carry audio). +pub fn readJsonMax(conn: *Conn, cx: *errors.Cx, max: usize) errors.Refused!json.Value { + const raw = switch (try read(conn, cx.a, max)) { .ok => |b| b, .refused => |message| return cx.refuse(message), }; diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index 8e2a65351e7..47be05d7f83 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -49,7 +49,7 @@ pub const Out = struct { pub fn post(srv: *Server, conn: *Conn, a: Allocator, is_chat: bool) void { const startup_at = @import("core").startup_receipt.offset(); var cx: Cx = .{ .a = a }; - const body = http_body.readJson(conn, &cx) catch { + const body = http_body.readJsonMax(conn, &cx, @import("audio.zig").bodyLimit(srv.info)) catch { const err = errorBody(a, &cx, if (is_chat) "messages" else "prompt") catch return; return routes.sendValue(conn, a, cx.status(), wrapError(a, err) catch return); }; From 7f238a1f72629d863f8c4a2f219e1e158737b96f Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:30:15 +0000 Subject: [PATCH 283/361] docs: the Nemotron 3.5 Transcribe recipe (one GB10, the bf16 release, audio input), its index row and the API's audio parts --- docs/api.md | 2 + docs/recipes/README.md | 1 + docs/recipes/nemotron-3.5-transcribe.md | 124 ++++++++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 docs/recipes/nemotron-3.5-transcribe.md diff --git a/docs/api.md b/docs/api.md index 942a082f32e..a55547da186 100644 --- a/docs/api.md +++ b/docs/api.md @@ -168,6 +168,8 @@ server reads images for GLM-5.3-Flash, Qwen3.8-27B and Gemma 4 31B on Metal, wit user messages ([video](vision.md#video-on-the-native-server)). See [image input](vision.md) for data URLs, public image URLs, limits and cache behavior. The native binary refuses `--vision` for other models and answers their image parts with HTTP 400. +The native CUDA server reads audio for Nemotron 3.5 Transcribe: `input_audio` and `audio_url` (data URL) parts with +16 kHz mono WAV in user messages ([recipe](recipes/nemotron-3.5-transcribe.md#audio-in-a-request)). Unsupported image input, audio, video and non-text output requests receive HTTP 400. ## Model capabilities diff --git a/docs/recipes/README.md b/docs/recipes/README.md index 924aebc78d8..2f9ae1dd248 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -13,6 +13,7 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Nemotron 3.5 Lightning | [MLX](nemotron-3.5.md), [Intel Arc, experimental](xpu-arc.md) | | Nemotron 3.5 Parse | [Native HIP OCR, validation and qualification limits](nemotron-parse.md) | | Nemotron 3.5 Super VL | [Native CUDA on one or two GB10s, images](nemotron-3.5-super-vl.md) | +| Nemotron 3.5 Transcribe | [Native CUDA on one GB10, the bf16 release, audio input](nemotron-3.5-transcribe.md) | | Qwen3.8-27B | [MLX, quantization and CUDA](qwen3.8-27b.md) | | Qwen3-Embedding | [Native Metal](qwen3-embedding-metal.md), [HIP](qwen3-embedding-hip.md) | | Qwen3.5-2B | [Native Metal preview and CUDA, tied affine 4-bit](qwen3.5-2b-native.md) | diff --git a/docs/recipes/nemotron-3.5-transcribe.md b/docs/recipes/nemotron-3.5-transcribe.md new file mode 100644 index 00000000000..4111011d56a --- /dev/null +++ b/docs/recipes/nemotron-3.5-transcribe.md @@ -0,0 +1,124 @@ +# Nemotron 3.5 Transcribe + +NVIDIA's Nemotron 3.5 Transcribe 30B-A4B (`nemo_speechlm`) runs on the native CUDA engine from NVIDIA's bf16 release, +on one GB10. It is a speech LLM: an audio encoder turns a recording into rows that stand in the prompt where the +chat template writes `<|audio|>`, and a Nemotron 3.5 Lightning language model (Mamba-2, attention and MoE blocks, +128 routed experts with relu^2, a shared expert, one MTP layer) writes the transcript, translation or answer. The +language model is the Nemotron family (`zig/src/families/nemotron/`, the checkpoint's names in `cuda_salm.zig`); the +encoder is `zig/src/families/nemo_audio/`, with its kernels in `zig/kernels/cuda/nemo_audio.cuh`. + +The encoder was written from the release's `config.json`, its tensor names and shapes, the model card, the +Sortformer papers (arXiv 2409.06656, 2507.18446) and textbook definitions, and checked against stage-by-stage dumps +of NVIDIA's NeMo run unmodified as a black box. No NeMo or vLLM source was used to write it. + +## Checkpoint + +`nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B` at revision `c421d6acdb436edd7ae00565f6414631fb9bd56d`: one +`model.safetensors` of 63 GiB in NeMo's layout, every tensor bf16 except the Mamba layers' fp32 parameters, the +routers' fp32 biases and the CTC timestamp head. The engine reads these tensors as stored; nothing is converted +ahead of time. The routed experts stay in bf16 on a grouped kernel of their own (`zig/kernels/cuda/experts_bf16.cu`). + +Not read: NVIDIA's FP8 and NVFP4 variants, the DFlash2 draft model, and the CTC timestamp head. + +## Run on one GB10 + +```bash +tensorfold serve /models/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B --name transcribe +``` + +The weights and the encoder take 64.89 GiB. The default window is the card's trained 65,536 tokens (config.json's +`llm_config` names the backbone's 262,144, which the speech model was not trained to; `--context` above 65,536 is +refused). At that window the server admits 8 streams, the engine's own at 0.50 GiB and 7 more taking 512-row pages +(3.09 GiB in all) as they need them, and keeps a prompt cache of 64 states (3.0 GiB) and 13.4 GiB of copied rows. + +The chat template turns thinking on by default. The card asks for transcription, translation and language +identification with thinking off and temperature 0, and for audio questions with thinking on, temperature 0.6 and +top_p 0.95. Send `chat_template_kwargs: {"enable_thinking": false}` per request, or start the server with +`--no-thinking`. + +## Audio in a request + +`/v1/chat/completions` (and `/v1/completions` given `messages`) takes audio in user messages as OpenAI's +`input_audio` part or as vLLM's `audio_url` part with a data URL: + +```json +{"messages": [{"role": "system", "content": ""}, + {"role": "user", "content": [ + {"type": "text", "text": "Audio transcription. Language: as spoken. Wording: verbatim, including fillers and repetitions. Formatting: punctuation and capitalization. Output: transcript only."}, + {"type": "input_audio", "input_audio": {"data": "", "format": "wav"}}]}], + "temperature": 0, "chat_template_kwargs": {"enable_thinking": false}} +``` + +- A clip is a WAV file: 16 kHz, mono, PCM (16, 24 or 32-bit) or 32-bit float, at least 20 ms. Other rates, channels + and formats get HTTP 400 naming the clip. +- A request holds up to 8 clips and up to an hour of audio in all (12.5 rows a second, 45,000 rows), and no more + than its window leaves after the text. Chat bodies may be 160 MiB on this model, enough for an hour of 16-bit + WAV in base64; other routes keep the 32 MiB limit. +- `/v1/messages` refuses audio: Anthropic's API has no audio block. +- Audio parts in assistant, system or tool messages are refused, as is text that spells `<|audio|>` with no clip for it. +- The card's [prompt guide](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B#prompt-guide) + lists the instructions for written or verbatim form, context terms, speaker tags (`` ...), translation and + language identification; they are plain text beside the clip, with the system prompt empty. + +The encoder runs on the GPU on each request's prompt pass: log-mel features, the 32-layer ASR encoder and the streaming +speaker encoder, in windows of 40-second cores with 4 seconds of context on each side and the speaker cache carried +between them, fused and projected to the language model's 2,688 columns. The speaker cache scores its frames in f64 and +applies two of the release's keys as the release does. `pred_score_threshold` (0.25) is the least a speaker's own +probability counts for in its frame scores; frames under 0.5 never score, and when fewer than 188 frames score, silence +rows fill the rest. With `min_pos_scores_rate` (0.5), a speaker with at least 11 frames that score above a lone 0.5 +keeps only those: 11 is floor(0.5 x 22), and 22 is each speaker's share of the 188 rows after its silence row. A speaker +heard briefly and weakly keeps its boosted frames instead. `sil_threshold` changed nothing on any clip tried, and is not +read. A clip's rows are keyed by a hash of its samples in the prompt cache, so a request that repeats an earlier prompt +up to and past the clip (the same request again, or a later turn of the same chat) resumes after it instead of encoding +it again; the card's prompts put the instruction before the clip, so a new instruction about the same clip encodes it +again. `tf-cuda-test audio-check MODEL WAV OUT.safetensors` writes every encoder stage for one clip. + +## Drafts + +The checkpoint's MTP layer drafts by default; its head reads the shifted prompt with the clip's audio rows in place, +as the language model does. `--mtp-drafts` and `--mtp-confidence` set it as for the other Nemotron checkpoints; +`"draft": false` decodes serially. Copied continuations stay off for this model. The head adds 2.88 GiB +(64.89 GiB against 62.01 with `--no-drafts`). + +## Exactness and speed + +Measured on one GB10 at the default 65,536-token window, greedy, thinking off, the card's verbatim prompt with an +empty system prompt: + +- **Encoder against NeMo:** on ten clips (3.5 s to 153 s, one to four speakers, one to four windows), every stage is + within bf16 rounding of NeMo's bf16 and fp32 runs, apart from rows where NeMo's own two runs disagree as much: a + few rows whose size grows by chance under bf16 inside the ASR encoder, and the speaker cache's choice among + tied bf16 scores. The prompt has NeMo's length on all ten: the template's 51 tokens around the placeholder and + the clip's rows. +- **Short clips:** the ten clips' replies have a WER of 1.55% against the LibriSpeech text (17 of 1,095 words, nearly all + names and spellings). +- **Drafted against `--no-drafts`:** byte-identical replies on the ten clips and on 11, 30 and 60 minutes of audio. +- **Prompt cache:** a server with `--prompt-cache-gib 0` gave the same replies as the default one to every check below: seeded sampling (twice, the + same reply each time), speaker tags on two speakers, translation to German and French, language identification, + two audio questions, thinking on, a two-turn chat and the Anthropic route with text. + The prompt cache resumes a request after the longest prefix it has seen: the second turn of a chat about a clip + resumed 96 of its 153 prompt tokens, past the clip, and a repeated 11-minute request resumed 8,812 of 8,818 and + answered its first token in 0.30 s instead of 4.16 s. The card's prompts put the instruction before the clip, so a + new instruction about the same clip in a new chat encodes the clip again. +- **Concurrency:** four clips at once (11, 11 and 15 minutes and 130 seconds) took 67.0 s together against 26.9, 32.1, + 40.0 and 6.0 s alone, each reply identical to its solo run. + +Long recordings, LibriSpeech test-clean read end to end without repeats (WER on the normalized text): + +| Audio | Prompt tokens | Reply tokens | WER | First token | MTP drafts | `--no-drafts` | +| --- | --- | --- | --- | --- | --- | --- | +| 11 min | 8,818 | 1,978 | 2.14% | 4.31 s | 31.6 s, 72.4 tok/s | 62.8 s, 33.8 tok/s | +| 30 min | 22,402 | 5,163 | 1.32% | 10.98 s | 80.5 s, 74.3 tok/s | 166.5 s, 33.1 tok/s | +| 60 min | 44,900 | 11,255 | 1.17% | 22.69 s | 184.6 s, 69.5 tok/s | 371.4 s, 32.2 tok/s | + +The first token waits for the encoder and the whole prompt pass. The drafts kept 78% and 74% of their proposals on +the 11 and 30-minute recordings (1,680 of 2,162 and 4,555 of 6,185). The harness's quality suite was not run on this +build. + +## Not served yet + +- Word timestamps and diarization segments (the card's `ctc_timestamps`, from its CTC head): the head stays + unloaded. +- Audio URLs other than data URLs, and formats other than WAV. +- The DFlash2 draft model, and the FP8 and NVFP4 variants. +- More than one GPU: the model fits one GB10. From 4302fe2564a27a5762f0d9134c7c64a7e63affa3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:05:44 +0000 Subject: [PATCH 284/361] server, lanes: room under 600 lines after the rebase onto main The video decoder check and the audio locator's binding run from input_types.start, beside the media they decide, so server.zig stays at 600 lines; stream.zig's two loop-guard tests join long_loop_test.zig. No behaviour changes. --- zig/src/core/lanes/long_loop_test.zig | 29 ++++++++++++++++++++++++++- zig/src/core/lanes/stream.zig | 27 ------------------------- zig/src/server/input_types.zig | 6 ++++++ zig/src/server/server.zig | 3 +-- 4 files changed, 35 insertions(+), 30 deletions(-) diff --git a/zig/src/core/lanes/long_loop_test.zig b/zig/src/core/lanes/long_loop_test.zig index 585ae6ad372..c2876148aa0 100644 --- a/zig/src/core/lanes/long_loop_test.zig +++ b/zig/src/core/lanes/long_loop_test.zig @@ -1,4 +1,4 @@ -//! The loop guard on a long repeated passage: the reasoning closes at one token, a token at a time or in windows. +//! The loop guard on a stream: its cap, a short cycle's latch, and a long repeated passage's close at one token. const std = @import("std"); const stream = @import("stream.zig"); const long_loop = @import("long_loop.zig"); @@ -34,3 +34,30 @@ test "the loop guard closes a long repeated passage's reasoning at one token, a try std.testing.expectEqual(want, try closesAt(1)); try std.testing.expectEqual(want, try closesAt(6)); } + +test "loop guard stops at the cap even when no cycle fires" { + const gpa = std.testing.allocator; + var tokens: [20]u32 = undefined; + for (&tokens, 0..) |*token, i| token.* = @intCast(100 + i); + var guarded = try stream.Stream.init(gpa, .{ .id = "guarded", .prompt = &.{1}, .max_new = 10, .think_close = &.{ 90, 91, 92 }, .think_end = 91, .loop_guard = true }); + defer guarded.deinit(gpa); + try std.testing.expectEqual(@as(usize, 10), try guarded.commit(gpa, &tokens, &.{})); + try std.testing.expect(guarded.finished and guarded.reason == .length); +} + +test "loop guard fires, closes thinking, and latches once" { + const gpa = std.testing.allocator; + var tokens: std.ArrayList(u32) = .empty; + defer tokens.deinit(gpa); + for (0..stream.loop_warm_in) |i| try tokens.append(gpa, @intCast(1000 + i)); + for (0..257) |_| try tokens.append(gpa, 7); + var s = try stream.Stream.init(gpa, .{ .id = "loop", .prompt = &.{1}, .max_new = 400, .think_close = &.{ 90, 91, 92 }, .think_end = 91, .loop_guard = true }); + defer s.deinit(gpa); + try std.testing.expectEqual(@as(usize, 321), try s.commit(gpa, tokens.items, &.{})); + try std.testing.expectEqual(@as(u32, 1), s.loop_period.?); + try std.testing.expect(!s.finished and !s.think_open and s.force.items.len == 3); + while (s.popForce()) |token| _ = try s.commit(gpa, &.{token}, &.{}); + try std.testing.expect(!s.finished and s.force.items.len == 0); + _ = try s.commit(gpa, &.{8}, &.{}); + try std.testing.expect(!s.finished and s.loop_period.? == 1); +} diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index 6413e7fb6ae..e5ef3fb606e 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -563,33 +563,6 @@ test "a logprob stream lands a row with each token it lands, and refuses tokens try std.testing.expectEqual(@as(u32, 9), s.rows.items[1].token); } -test "loop guard stops at the cap even when no cycle fires" { - const gpa = std.testing.allocator; - var tokens: [20]u32 = undefined; - for (&tokens, 0..) |*token, i| token.* = @intCast(100 + i); - var guarded = try Stream.init(gpa, .{ .id = "guarded", .prompt = &.{1}, .max_new = 10, .think_close = &.{ 90, 91, 92 }, .think_end = 91, .loop_guard = true }); - defer guarded.deinit(gpa); - try std.testing.expectEqual(@as(usize, 10), try guarded.commit(gpa, &tokens, &.{})); - try std.testing.expect(guarded.finished and guarded.reason == .length); -} - -test "loop guard fires, closes thinking, and latches once" { - const gpa = std.testing.allocator; - var tokens: std.ArrayList(u32) = .empty; - defer tokens.deinit(gpa); - for (0..loop_warm_in) |i| try tokens.append(gpa, @intCast(1000 + i)); - for (0..257) |_| try tokens.append(gpa, 7); - var s = try Stream.init(gpa, .{ .id = "loop", .prompt = &.{1}, .max_new = 400, .think_close = &.{ 90, 91, 92 }, .think_end = 91, .loop_guard = true }); - defer s.deinit(gpa); - try std.testing.expectEqual(@as(usize, 321), try s.commit(gpa, tokens.items, &.{})); - try std.testing.expectEqual(@as(u32, 1), s.loop_period.?); - try std.testing.expect(!s.finished and !s.think_open and s.force.items.len == 3); - while (s.popForce()) |token| _ = try s.commit(gpa, &.{token}, &.{}); - try std.testing.expect(!s.finished and s.force.items.len == 0); - _ = try s.commit(gpa, &.{8}, &.{}); - try std.testing.expect(!s.finished and s.loop_period.? == 1); -} - test "answer_max limits the reply after the think block, not the reasoning" { const gpa = std.testing.allocator; var s = try Stream.init(gpa, .{ .id = "answer", .prompt = &.{1}, .max_new = 12, .think_end = 91, .answer_max = 2 }); diff --git a/zig/src/server/input_types.zig b/zig/src/server/input_types.zig index c159a9cd900..88483a83a84 100644 --- a/zig/src/server/input_types.zig +++ b/zig/src/server/input_types.zig @@ -35,6 +35,12 @@ pub fn decodes(vision: ?api.Vision) bool { return false; } +/// At startup: the video decoder (none: video parts are a 400, never a 500) and the audio locator's token (audio.zig). +pub fn start(srv: anytype) !void { + srv.video_decoder = decodes(srv.info.vision); + try @import("audio.zig").bindLocator(&srv.info, srv.text); +} + /// The media a request may carry: the template's vision and PDF, and the image and video inputs /v1/models publishes. pub fn media(srv: anytype) @import("messages.zig").Media { var result = @import("messages.zig").Media.ofVision(srv.info.vision, srv.config.vision_pdf); diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 71d4a1ae04d..41e7e520615 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -135,8 +135,7 @@ pub const Server = struct { log.line("--vision: marker token {d} is not an added token in this tokenizer; image and video input cannot be served safely", .{id}); return error.InvalidVisionMarkers; }; - srv.video_decoder = @import("input_types.zig").decodes(srv.info.vision); // no decoder: video parts are a 400, never a 500 - try @import("audio.zig").bindLocator(&srv.info, text); + try @import("input_types.zig").start(srv); // the video decoder and the audio locator's token srv.voices = .{ .gpa = gpa, .io = io, .dir = config.voice.dir }; if (srv.info.speech == null and (config.voice.dir != null or config.voice.inline_voices or config.voice.manage)) return error.VoicesRequireSpeech; if (config.voice.dir) |dir| try srv.voices.load(dir); From 25480da01859875cf7591081dc2a7fc5cc7e041a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:05:44 +0000 Subject: [PATCH 285/361] server: /v1/models lists audio in input_types when the engine takes it Main's input_types (#3004) publishes text, image and video; a Transcribe server now adds "audio" after them, and the request media reads the same answer. Other models' lists are unchanged. --- docs/api.md | 3 ++- zig/src/server/input_types.zig | 26 +++++++++++++--------- zig/src/server/models_input_types_test.zig | 8 +++++++ zig/src/server/status_routes.zig | 2 +- 4 files changed, 26 insertions(+), 13 deletions(-) diff --git a/docs/api.md b/docs/api.md index a55547da186..05052ba9212 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1704,7 +1704,8 @@ adds `reasoning`: `default_enabled`, `default_effort` when the template consumes Every native entry ends with `input_types`, the content part types the model takes: `["text"]`, plus `"image"` when it was started with `--vision` (`image_url` parts), plus `"video"` when its checkpoint reads video and this server -loads the `libtfvideo` runtime (`video_url` parts), for example `["text", "image", "video"]`. The server decides it +loads the `libtfvideo` runtime (`video_url` parts), plus `"audio"` when the engine has an audio encoder +(`input_audio` and `audio_url` parts), for example `["text", "image", "video"]`. The server decides it once at startup, and requests are refused by the same fact: a `video_url` part to an entry without `"video"` gets HTTP 400 (`invalid_request_error`), never a 500. Without `libtfvideo` the startup log says so once. diff --git a/zig/src/server/input_types.zig b/zig/src/server/input_types.zig index 88483a83a84..b60cf17a10a 100644 --- a/zig/src/server/input_types.zig +++ b/zig/src/server/input_types.zig @@ -3,22 +3,26 @@ const std = @import("std"); const api = @import("engine_api"); const json = @import("json"); -/// Images with --vision; videos when the model offers them and this server can decode them (libtfvideo loads). +/// Images with --vision; videos when the model offers them and this server can decode them; audio with an encoder. pub const Inputs = struct { image: bool = false, video: bool = false, + audio: bool = false, - pub fn of(vision: ?api.Vision, video_decoder: bool) Inputs { - const v = vision orelse return .{}; - return .{ .image = true, .video = v.video != null and video_decoder }; + pub fn of(vision: ?api.Vision, video_decoder: bool, audio: bool) Inputs { + const v = vision orelse return .{ .audio = audio }; + return .{ .image = true, .video = v.video != null and video_decoder, .audio = audio }; } - /// `["text"]`, then "image" and "video" when taken, in that order. + /// `["text"]`, then "image", "video" and "audio" when taken, in that order. pub fn value(i: Inputs, a: std.mem.Allocator) std.mem.Allocator.Error!json.Value { - const out = try a.alloc(json.Value, 1 + @as(usize, @intFromBool(i.image)) + @intFromBool(i.video)); + const out = try a.alloc(json.Value, 1 + @as(usize, @intFromBool(i.image)) + @intFromBool(i.video) + @intFromBool(i.audio)); out[0] = .{ .string = "text" }; - if (i.image) out[1] = .{ .string = "image" }; - if (i.video) out[out.len - 1] = .{ .string = "video" }; + var n: usize = 1; + inline for (.{ "image", "video", "audio" }) |name| if (@field(i, name)) { + out[n] = .{ .string = name }; + n += 1; + }; return .{ .array = out }; } }; @@ -41,13 +45,13 @@ pub fn start(srv: anytype) !void { try @import("audio.zig").bindLocator(&srv.info, srv.text); } -/// The media a request may carry: the template's vision and PDF, and the image and video inputs /v1/models publishes. +/// The media a request may carry: the template's vision and PDF, and the inputs /v1/models publishes. pub fn media(srv: anytype) @import("messages.zig").Media { var result = @import("messages.zig").Media.ofVision(srv.info.vision, srv.config.vision_pdf); - const taken = Inputs.of(srv.info.vision, srv.video_decoder); + const taken = Inputs.of(srv.info.vision, srv.video_decoder, srv.info.audio != null); result.images = taken.image; result.videos = taken.video; + result.audio = taken.audio; result.native_deepseek = srv.text.native_deepseek; - result.audio = srv.info.audio != null; return result; } diff --git a/zig/src/server/models_input_types_test.zig b/zig/src/server/models_input_types_test.zig index 8f0743b99c5..8261e6c8faa 100644 --- a/zig/src/server/models_input_types_test.zig +++ b/zig/src/server/models_input_types_test.zig @@ -133,3 +133,11 @@ test "model discovery input types: a video the decoder library cannot open is a try t.expect(std.mem.startsWith(u8, cx.message, "video 1: this server takes no video input: ")); try t.expect(std.mem.indexOf(u8, cx.message, sys.optional_libraries.spec(.video).names[0]) != null); } + +test "input_types lists audio after text and image when the engine has an audio encoder" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const types = (try @import("input_types.zig").Inputs.value(.{ .image = true, .audio = true }, arena.allocator())).array; + try t.expectEqual(@as(usize, 3), types.len); + for ([_][]const u8{ "text", "image", "audio" }, types) |want, got| try t.expectEqualStrings(want, got.string); +} diff --git a/zig/src/server/status_routes.zig b/zig/src/server/status_routes.zig index 0d6ba8bc02d..022abfddbf1 100644 --- a/zig/src/server/status_routes.zig +++ b/zig/src/server/status_routes.zig @@ -109,7 +109,7 @@ fn entries(srv: *Server, a: Allocator, ids: []const []const u8) ![]Value { const data = try a.alloc(Value, ids.len); const reasoning = try modelReasoning(a, srv); for (ids, data) |id, *slot| { - slot.* = try modelValue(a, id, info, created, reasoning, .of(info.vision, srv.video_decoder)); + slot.* = try modelValue(a, id, info, created, reasoning, .of(info.vision, srv.video_decoder, info.audio != null)); } return data; } From bd8d90441d7bb1ff80e6ec4394aa4114f93a7fe6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:57:31 +0000 Subject: [PATCH 286/361] =?UTF-8?q?nemotron=20cuda:=20merge=20repairs=20?= =?UTF-8?q?=E2=80=94=20drop=20the=20doubled=20record/recordBody=20in=20cud?= =?UTF-8?q?a=5Fseq=5Fgraphs=20and=20fmt=20the=20resolved=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zig/src/core/engine_api.zig | 1 - zig/src/core/engine_request.zig | 3 ++ zig/src/families/nemotron/cuda_seq_graphs.zig | 33 ------------------- 3 files changed, 3 insertions(+), 34 deletions(-) diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 13f0cab8a80..a26c23258cf 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -35,7 +35,6 @@ pub const grammar = lanes.grammar; pub const Request = @import("engine_request.zig").Request; pub const Stop = @import("engine_request.zig").Stop; - /// Image and video input an engine serves, and --vision's limits (engine_vision.zig). const vision_types = @import("engine_vision.zig"); pub const PreparedImage = vision_types.PreparedImage; diff --git a/zig/src/core/engine_request.zig b/zig/src/core/engine_request.zig index c6b9d4d1c9a..5c8f0c07b3e 100644 --- a/zig/src/core/engine_request.zig +++ b/zig/src/core/engine_request.zig @@ -4,6 +4,7 @@ const lanes = @import("lanes"); const CallGate = @import("engine_request_controls.zig").CallGate; const Structure = @import("engine_request_controls.zig").Structure; const Image = lanes.stream.Image; +const Audio = lanes.stream.Audio; const Sampling = lanes.Sampling; const Penalties = lanes.Penalties; @@ -68,6 +69,8 @@ pub const Request = struct { prompt_logprobs: ?u8 = null, /// Images whose rows replace placeholder tokens of ``prompt``, in order; only when ``Info.vision`` is set. images: []const Image = &.{}, + /// Audio clips whose rows replace placeholder tokens of ``prompt``, in order; only when ``Info.audio`` is set. + audios: []const Audio = &.{}, /// The prompt as the prompt cache matches it (each image's placeholders by its content); empty: ``prompt``. cache_key: []const u32 = &.{}, /// A streamed reply's tokens its client has not read yet (the server's mailbox counts them); null: not watched. diff --git a/zig/src/families/nemotron/cuda_seq_graphs.zig b/zig/src/families/nemotron/cuda_seq_graphs.zig index feb53aa5486..275bbfc400a 100644 --- a/zig/src/families/nemotron/cuda_seq_graphs.zig +++ b/zig/src/families/nemotron/cuda_seq_graphs.zig @@ -66,36 +66,3 @@ fn recordBody(e: *Engine, body: Engine.Body) !void { .head => |x| try x.h.level(x.rows, x.j, x.vocab), } } - -/// One graph of `body` on the bound sequence's buffers, instantiated and uploaded. -pub fn record(e: *Engine, body: Engine.Body) !cuda.graph.Exec { - const t0 = std.Io.Clock.awake.now(e.io); - try cuda.graph.beginCapture(e.stream, .thread_local); - recordBody(e, body) catch |err| { - if (cuda.graph.endCapture(e.stream)) |g| { - var x = g; - x.deinit(); - } else |_| {} - return err; - }; - var g = try cuda.graph.endCapture(e.stream); - defer g.deinit(); - const exec = try g.instantiate(); - try exec.upload(e.stream); - try e.stream.synchronize(); - e.stats.captures += 1; - e.stats.capture_ns += @intCast(std.Io.Clock.awake.now(e.io).toNanoseconds() - t0.toNanoseconds()); - return exec; -} - -fn recordBody(e: *Engine, body: Engine.Body) !void { - switch (body) { - .window => |w| { - const f = e.forward(null); - try f.windowSegs(&.{.{ .b = f.b, .row0 = 0, .rows = w.rows, .sampled = f.sampled, .mask = w.mask, .slot = f.slot, .untaught = f.untaught }}); - if (w.feed) return e.ops().serialFeed(e.b.sampled, e.b.ids, e.b.meta, e.history_dev); - try e.ops().download(std.mem.sliceAsBytes(e.pinned.slice(u32)[engine.pin_sampled..][0..w.rows]), e.b.sampled); - }, - .head => |x| try x.h.level(x.rows, x.j, x.vocab), - } -} From 83dea9a4bdc61d338d6ce4436e692c03dfb53b7e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:25:20 +0000 Subject: [PATCH 287/361] nemotron cuda: carry audio through split lane prefill --- zig/src/core/lane_host_lone.zig | 26 ------------------- zig/src/families/nemotron/cuda_lanes_fill.zig | 4 ++- 2 files changed, 3 insertions(+), 27 deletions(-) diff --git a/zig/src/core/lane_host_lone.zig b/zig/src/core/lane_host_lone.zig index 3338efbdad3..278476a3dbb 100644 --- a/zig/src/core/lane_host_lone.zig +++ b/zig/src/core/lane_host_lone.zig @@ -1,35 +1,9 @@ //! A lane host's lone driver: the backend's own loop runs a lone stream until a foreground request or a cancel waits. -const lanes = @import("lanes"); const LaneHost = @import("lane_host.zig").LaneHost; const status = @import("lane_host_status.zig"); const backlog = @import("lane_host_backlog.zig"); const Job = LaneHost.Job; -/// A backend's own driver for a lone greedy stream (the GPU round), which LaneHost runs while the stream is alone. -pub const Lone = struct { - ctx: *anyopaque, - sampled: bool = false, // it drives sampled streams too - plain: bool = false, // it drives streams with drafts off too - logprobs: bool = false, // it gives each token its logprob row too - structures: bool = false, // it masks each window's rows by the stream's grammar too - images: bool = true, // it takes image requests too (false: they stay in the lane core) - // thinking budgets above this and loop guards: it hands the stream over before a forced close (0: never) - min_budget: u32 = 0, - resumes: bool = false, // it takes the lane core's stream back between rounds (LoneHooks.resumed); else only opens - /// Prefills (or resumes) `s` and decodes it until it finishes (false) or `hooks.yield` hands it to the lane core. - run: *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: LoneHooks) anyerror!bool, -}; - -/// What a lone driver tells the host between rounds: tokens landed; and asks: hand the stream over now? -pub const LoneHooks = struct { - ctx: *anyopaque, - committed: *const fn (ctx: *anyopaque) void, - yield: *const fn (ctx: *anyopaque) bool, - resumed: bool = false, // the stream comes from the lane core between rounds: no prompt pass, its drafts the core's - // After a completed nonfinal prompt call, true transfers the unfinished pass to the shared fill queue. - prefill_yield: ?*const fn (ctx: *anyopaque) bool = null, -}; - /// An idle driver takes a lone drafted request; plain, sampled, with logprobs, a budget or a grammar when supported. pub fn fits(h: *LaneHost, job: *Job) bool { if (!takes(h, job)) return false; diff --git a/zig/src/families/nemotron/cuda_lanes_fill.zig b/zig/src/families/nemotron/cuda_lanes_fill.zig index 2ed73770243..63ce9b88bcc 100644 --- a/zig/src/families/nemotron/cuda_lanes_fill.zig +++ b/zig/src/families/nemotron/cuda_lanes_fill.zig @@ -91,6 +91,8 @@ fn run(self: *Cuda, s: *lanes.Stream, from: usize) !void { const e = self.e; if (s.images.len > 0) try (e.vision orelse return error.NoVision).begin(e.stream, s.images, from); defer if (e.vision) |v| v.end(); + if (s.audios.len > 0) try (e.audio orelse return error.NoAudio).begin(e.stream, s.audios, from); + defer if (e.audio) |a| a.end(); reset(self, s, from); var sink: Cuda.PromptSink = .{ .gpa = self.gpa, .s = s }; var tap: Cuda.TapSink = .{ .self = self, .taps = &self.lanes.getPtr(s).?.taps }; @@ -137,7 +139,7 @@ fn stepOnce(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool { const cancel: engine.Cancel = .{ .ptr = s, .check = Cuda.cancelled, .yields = s.yield_check != null }; tap = .{ .self = self, .taps = &self.lanes.getPtr(s).?.taps }; hooks(self, s, &sink, &tap); - const alone = s.images.len > 0 or pass.segmented(e, s.prompt(), from, null, cancel, keepOf(s), lanes.cutPoints(s)); + const alone = s.images.len > 0 or s.audios.len > 0 or pass.segmented(e, s.prompt(), from, null, cancel, keepOf(s), lanes.cutPoints(s)); clear(self); if (alone) { try run(self, s, from); From b3f9691dea9b9f103eb14bc1fa309b16767c8e2a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:33:56 +0000 Subject: [PATCH 288/361] server: preserve speech voice startup with audio input --- zig/src/server/server.zig | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 41e7e520615..57125866f36 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -136,10 +136,7 @@ pub const Server = struct { return error.InvalidVisionMarkers; }; try @import("input_types.zig").start(srv); // the video decoder and the audio locator's token - srv.voices = .{ .gpa = gpa, .io = io, .dir = config.voice.dir }; - if (srv.info.speech == null and (config.voice.dir != null or config.voice.inline_voices or config.voice.manage)) return error.VoicesRequireSpeech; - if (config.voice.dir) |dir| try srv.voices.load(dir); - _ = try srv.voices.select(srv.arena.allocator(), config.voice.default, "default"); + try @import("speech_voices.zig").start(srv, gpa, io, config); if (!srv.info.capability(.text_generation)) { if (config.cortheon) return error.CortheonRequiresTextGeneration; return srv; From 968701910e464611dfb78c71b85493f30e5ef3e0 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:20:33 -0600 Subject: [PATCH 289/361] cuda: Nemotron 3.5 Transcribe takes --mtp-drafts and --mtp-confidence, as the other Nemotron checkpoints do --- zig/src/native/cuda_refusal.zig | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index f3061e54e35..250789550a1 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -52,7 +52,7 @@ pub fn backend(o: api.Open) ?[]const u8 { } else if (o.mtp_drafts != null or o.mtp_confidence != null) { if (qwen_mtp and o.mtp_confidence != null) return "--mtp-confidence is not supported by the Qwen CUDA MTP head"; if (!qwen_mtp and !std.mem.eql(u8, o.model_type, nemotron.native.model_type) and - !std.mem.eql(u8, o.model_type, nemotron.omni.model_type)) + !std.mem.eql(u8, o.model_type, nemotron.omni.model_type) and !std.mem.eql(u8, o.model_type, nemotron.transcribe.model_type)) return "--mtp-drafts: this CUDA family's drafts are not tunable; serve it without --mtp-drafts or --mtp-confidence"; } if (o.policy.len > 0) return "--policy is not supported by this CUDA build"; @@ -68,6 +68,18 @@ pub fn backend(o: api.Open) ?[]const u8 { return null; } +test "Nemotron 3.5 Transcribe takes --mtp-drafts and --mtp-confidence as the other Nemotron checkpoints do" { + const types = [_][]const u8{ nemotron.native.model_type, nemotron.omni.model_type, nemotron.transcribe.model_type }; + for (types) |t| { + try std.testing.expect(backend(.{ .dir = "d", .model_type = t, .mtp_drafts = 2 }) == null); + try std.testing.expect(backend(.{ .dir = "d", .model_type = t, .mtp_confidence = 0.5 }) == null); + } + // a family whose drafts are not tunable still refuses each flag by name + const fixed = "--mtp-drafts: this CUDA family's drafts are not tunable; serve it without --mtp-drafts or --mtp-confidence"; + try std.testing.expectEqualStrings(fixed, backend(.{ .dir = "d", .model_type = "lfm2", .mtp_drafts = 2 }).?); + try std.testing.expectEqualStrings(fixed, backend(.{ .dir = "d", .model_type = "lfm2", .mtp_confidence = 0.5 }).?); +} + /// LFM2 opens outside `family()`: its ranks are refused here, and --vision goes on to core's gate in its open. pub fn lfm2(o: api.Open) ?[]const u8 { return unranked(o); From b344443b4e315e85d4f4b7f6c3b69fbff50b8160 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:39:52 +0000 Subject: [PATCH 290/361] changelog: #1632 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20e4fc5c599..fc4da628c78 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 +- Nemotron 3.5 Transcribe on CUDA: chat requests take speech as 16 kHz mono WAV in OpenAI `input_audio` and vLLM `audio_url` parts, up to an hour of audio a request in the model's trained 65,536-token window, with each clip's rows keyed in the prompt cache and MTP drafts running over them; `/v1/models` lists `audio` among its input types (#1632, closes #1549). Thanks to @BobClawblaw. + - Inkling 2 Mini on Metal: the startup line breaks the serve's demand into weights, dense layers and scratch, the state of each stream at the window and what the streams share, beside the room the load limit leaves; which streams and windows start is unchanged (#4705, refs #4274 and #4387). - Inkling 2 Mini on Metal: the router's and loop gates' dots run a thread per output with main's serial arithmetic (one row keeps main's kernels), so prompts reach the first token about 42% sooner and four streams decode about 64% faster on an M5 Ultra, with identical tokens (#4912). From 95591a94f8833bfb150986e3454d250dc52ef224 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:41:18 +0000 Subject: [PATCH 291/361] app changelog: #4072 (titles wait for the reply) under Unreleased --- app/CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/CHANGELOG.md b/app/CHANGELOG.md index 29a8ec779e2..387889a9a4c 100644 --- a/app/CHANGELOG.md +++ b/app/CHANGELOG.md @@ -8,6 +8,8 @@ See the [engine changelog](../CHANGELOG.md) for engine releases. These are highlights from changes merged after Desktop 1.0.0. They are available in builds from current source and are awaiting a packaged Desktop release. +- With the built-in engine, a conversation's title is generated after the reply finishes, so the title request no longer + shares the engine with your reply and slows it. [#4072](https://github.com/ashhart/TensorFold/pull/4072) Thanks @AIFlowML. - Search in **Current conversation** ignores the project filter from **All saved conversations**. Switching back restores the selected project. [#3900](https://github.com/ashhart/TensorFold/pull/3900) - **Planning only** opens the model picker on **Local**. The regular model button opens **All**. From 9852a756ad2fbbd7e73754d6dcc4512e15f26865 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:07:16 +0000 Subject: [PATCH 292/361] CONTRIBUTING: a changed reduction order or rounding point keeps every output bit The FP64-reference, per-column error and tie-policy lines allowed results that differ from main's. Exactness is now bit for bit, by default and with any switch on; the one exception is a checkpoint's own trained format. --- CONTRIBUTING.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b53c5a885d8..5dd23d8c0be 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -128,11 +128,10 @@ Verify these contracts at the same checkpoint, backend, runtime and settings: A new or changed GPU kernel registers with the [kernel contract](docs/kernel-contract.md), and its pull request posts each backend's `SUMMARY` line. How to bound, profile and measure a speed change is in [docs/optimizing.md](docs/optimizing.md). Keep the checkpoint's activation precision and the required accumulation precision. -A changed reduction order needs an independent FP64 reference for each affected projection class, with native error no worse than the current reference. -Compare prompt and decode references separately on identical input rows. -Report worst per-column differences as well as aggregate error; an average must not hide a worse column. -For model fidelity, use teacher-forced histories and record all top-token differences and margins. -A documented one-step tie policy applies only to the same two contenders with both margins within that policy. +A change to reduction order, accumulation order or rounding point must keep every output bit equal to main's: the same token ids and the same logits bits, by default and with any switch on. +An FP64 reference or an error bound does not make a different result acceptable, and lower-precision formats are not accepted, even opt-in. +The one exception is a checkpoint's own trained format (for example a KV cache format the checkpoint was trained and published in), checked bit for bit against the serial reference. +Compare prompt and decode separately on identical input rows. ## Performance receipts From 549b55a129a45656a5eeef6c320ead37f833a73a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:07:26 +0000 Subject: [PATCH 293/361] changelog: CONTRIBUTING: a changed reduction order or rounding point keeps every output bit --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc4da628c78..f0a1c8c6746 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,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. - 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). +- CONTRIBUTING: exactness is bit for bit. A changed reduction order or rounding point must keep every output bit, by default and with any switch on; an FP64 reference no longer makes a different result acceptable (#4888). - 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. From 373f828ca9e4b8d21da4eae1e864bdb11d9cb9d5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:56:13 +0000 Subject: [PATCH 294/361] qwen27 metal: 5-bit and 6-bit g64 keep v1.3.4's K splits on M5 their prompt rows keyed on promptSplit, where v1.3.4 split K with `split` on both (5120 x 17408: 8, then 4 on decode and 2 on prompt). A different split changes the K-slice FP32 reduction order, so their output bits moved. projection.laneSplit and promptSlices keep `split` for 5/6-bit g64 and leave 4-bit and every other width as main has them. (groups ascending in a slice, C = fma(s, P, fma(b, xsum, C)), slices added into slice 0 in index order) on the same code values, and its kernel contract gates the 5/6-bit reg variants bit for bit against the lane kernel. Gemma 4 is unchanged. --- CHANGELOG.md | 2 ++ zig/qwen27_quant_test.zig | 30 ++++++++++++++++++++++++++ zig/src/families/qwen27/projection.zig | 15 +++++++++++-- zig/src/families/qwen27/quant_gpu.zig | 2 +- 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0a1c8c6746..ef9ebe9498a 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 Metal M5: 5-bit and 6-bit group-64 checkpoints split K for decode and prompt rows as v1.3.4 did again, so their sums run in v1.3.4's order; #4419 had moved them onto the 4-bit M5 split tables, and its register-direct kernels stay, at the restored splits. Gemma 4 and 4-bit are unchanged. + - Nemotron 3.5 Transcribe on CUDA: chat requests take speech as 16 kHz mono WAV in OpenAI `input_audio` and vLLM `audio_url` parts, up to an hour of audio a request in the model's trained 65,536-token window, with each clip's rows keyed in the prompt cache and MTP drafts running over them; `/v1/models` lists `audio` among its input types (#1632, closes #1549). Thanks to @BobClawblaw. - Inkling 2 Mini on Metal: the startup line breaks the serve's demand into weights, dense layers and scratch, the state of each stream at the window and what the streams share, beside the room the load limit leaves; which streams and windows start is unchanged (#4705, refs #4274 and #4387). diff --git a/zig/qwen27_quant_test.zig b/zig/qwen27_quant_test.zig index ede401d1407..0c282fbaddf 100644 --- a/zig/qwen27_quant_test.zig +++ b/zig/qwen27_quant_test.zig @@ -383,3 +383,33 @@ test "qwen27 quant: 5-bit and 6-bit g64 use reg lane keys with 128/2048 row capa try t.expectEqual(@as(u32, 2), k.lanes.count()); } } + +test "qwen27 quant: 5-bit and 6-bit g64 keep v1.3.4's K split on decode and prompt; 4-bit keeps the M5 tables" { + // the 27B's projection shapes (n, k): every row of the M5 and prompt tables + const shapes = [_][2]u32{ .{ 5120, 17408 }, .{ 12288, 5120 }, .{ 10240, 5120 }, .{ 5120, 6144 }, .{ 34816, 5120 }, .{ 2048, 5120 }, .{ 6240, 5120 } }; + for ([_]u8{ 4, 5, 6 }) |bits| for (shapes) |s| { + const v134 = try projection.split(s[0], s[1]); // prepare's split before #4419 moved 5/6-bit onto the M5 table + try t.expectEqual(if (bits == 4) @as(u32, 4) else v134, projection.laneSplit(bits, 64, .{ .slices = v134, .m5 = 4 })); + try t.expectEqual(v134, projection.laneSplit(bits, 64, .{ .slices = v134, .m5 = null })); + var r: mtl.Record = .{}; + var k = quant.Kernels{ .allocator = a, .device = r.device(), .long_prompt = true }; + defer k.deinit(); + var p = matrix(&r, s[0]); + p.k = s[1]; + p.bits = bits; + p.slices = if (bits == 4) projection.laneSplit(4, 64, .{ .slices = v134, .m5 = null }) else v134; + const ref = quant.Ref{ .buffer = r.virtual() }; + const sums: quant.Sums = .{ .ref = ref, .stride = 2080 }; + try k.prepareDecode(p); + try k.quant(r.encoder(), p, ref, sums, ref, ref, 1); + k.prompt = true; + try k.quant(r.encoder(), p, ref, sums, ref, ref, 128); + try k.quant(r.encoder(), p, ref, sums, ref, ref, 2048); + // every entry built for these rows: 5/6-bit at v1.3.4's split; 4-bit at main's decode or prompt-table split + const prompt4 = projection.promptSplit(s[0], s[1]) orelse p.slices; + var it = k.lanes.keyIterator(); + while (it.next()) |key| { + if (bits == 4) try t.expect(key.slices == p.slices or key.slices == prompt4) else try t.expectEqual(v134, key.slices); + } + }; +} diff --git a/zig/src/families/qwen27/projection.zig b/zig/src/families/qwen27/projection.zig index 2603403df60..6612a4435ee 100644 --- a/zig/src/families/qwen27/projection.zig +++ b/zig/src/families/qwen27/projection.zig @@ -34,6 +34,17 @@ pub fn promptSplit(n: usize, k: usize) ?u32 { return null; } +/// A tensor-unit lane matrix's split: 4-bit g64 its M5 table; 5/6-bit g64 keep v1.3.4's `split` (its fp32 K order). +pub fn laneSplit(bits: u8, group: u32, key: Split) u32 { + return if (bits == 4 and group == 64) key.m5 orelse key.slices else key.slices; +} + +/// A prompt pass's split: 5/6-bit g64 keep the decode split (v1.3.4's prompt bits); other widths as before. +pub fn promptSlices(bits: u8, group: u32, gn: usize, k: usize, slices: u32) u32 { + if (group == 64 and (bits == 5 or bits == 6)) return slices; + return promptSplit(gn, k) orelse slices; +} + /// A part's rows in the checkpoint, which are the staged rows on one Mac. fn globalRows(p: Triple) usize { return if (p.gn != 0) p.gn else p.weight.shape[0]; @@ -52,7 +63,7 @@ fn splitRows(parts: []const Triple) usize { } /// The K split a staged matrix takes: the tensor's rows key the fp32 order, the fused checkpoint rows the M5 table. -const Split = struct { slices: u32, m5: ?u32 }; +pub const Split = struct { slices: u32, m5: ?u32 }; fn splitFor(parts: []const Triple, k: usize) !Split { return .{ .slices = try split(tensorRows(parts[0]), k), .m5 = m5Split(splitRows(parts), k) }; @@ -79,7 +90,7 @@ pub fn prepare(device: mtl.Device, allocator: std.mem.Allocator, owned: *std.Arr n = try std.math.add(usize, n, rows); } if (!device.tensorUnits() or n % tile != 0) return prepareRows(device, allocator, owned, parts, n, k, tile, slices, gn); - if (group == 64 and (bits == 4 or bits == 5 or bits == 6)) slices = key.m5 orelse slices; + slices = laneSplit(bits, group, key); if (bits != 4 or group != 64) return prepareLanes(device, allocator, owned, parts, n, k, tile, slices, gn); const w = try device.buffer(n * k / 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); owned.append(allocator, w) catch |err| { diff --git a/zig/src/families/qwen27/quant_gpu.zig b/zig/src/families/qwen27/quant_gpu.zig index ed16663ae37..d8b583eb491 100644 --- a/zig/src/families/qwen27/quant_gpu.zig +++ b/zig/src/families/qwen27/quant_gpu.zig @@ -230,7 +230,7 @@ pub const Kernels = struct { var span = profile.begin(k.profiler, input_encoder, .dense); // Prompt rows take the checkpoint matrix's split, as decoded rows already do through `p.slices`. const gn = if (p.gn != 0) p.gn else p.n; - const sk = if (k.prompt) projection.promptSplit(gn, p.k) orelse p.slices else p.slices; + const sk = if (k.prompt) projection.promptSlices(p.bits, p.group, gn, p.k, p.slices) else p.slices; span.shape = .{ .n = p.n, .k = p.k, .sk = sk, .bits = p.bits }; errdefer span.cancel(); const e = span.encoder; From ac79d6db66ef81a445715171f5e89c635c9ce397 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:20:15 +0000 Subject: [PATCH 295/361] changelog: #4962's line from lines/4962.txt in place of its own --- CHANGELOG.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef9ebe9498a..938a883d529 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased -- Qwen 3.8-27B on Metal M5: 5-bit and 6-bit group-64 checkpoints split K for decode and prompt rows as v1.3.4 did again, so their sums run in v1.3.4's order; #4419 had moved them onto the 4-bit M5 split tables, and its register-direct kernels stay, at the restored splits. Gemma 4 and 4-bit are unchanged. +- Qwen 3.8-27B on Metal M5: 5-bit and 6-bit group-64 checkpoints split K for decode and prompt rows as v1.3.4 did again, so their sums run in v1.3.4's order; #4419 had moved them onto the 4-bit M5 split tables, and its register-direct kernels stay, at the restored splits. Gemma 4 and 4-bit are unchanged (#4962). - Nemotron 3.5 Transcribe on CUDA: chat requests take speech as 16 kHz mono WAV in OpenAI `input_audio` and vLLM `audio_url` parts, up to an hour of audio a request in the model's trained 65,536-token window, with each clip's rows keyed in the prompt cache and MTP drafts running over them; `/v1/models` lists `audio` among its input types (#1632, closes #1549). Thanks to @BobClawblaw. @@ -18,8 +18,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Inkling 2 Mini on CUDA: decode experts run a warp over 8 columns with gate and up in one launch, about 3% faster one-stream decode on GB10 on top of #4728, with identical tokens (#4729). Thanks @jschmied. - - - Inkling 2: required and named tool calls use the model's own message format, so a request that needs several calls ends after them instead of repeating until max_tokens; a required single call keeps its parsed tool_calls but its token ids change (#4898). - OCR: `POST /ocr` takes PaddleX's request contract (step 6 of #2440): page results with reading-order blocks, lines and optional word boxes, the whole document's page count kept when processing stops early, and a repeated query refused (#2575). From a1da8553906c86af4364934c58dbf7f9bfbc7eb8 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:13:52 +0000 Subject: [PATCH 296/361] environment: register TF_Q27_KV_GROW and TF_QWEN_KV_SNAPSHOT_GPU Both were read but had no row, so a malformed value was never refused at startup. - TF_Q27_KV_GROW (Metal): 0 or a multiple of 16 that fits u32, blank refused, as kv_grow.step accepts; a new `multiple` field carries the 16. A host test checks the row and the reader accept the same texts. Malformed text is now refused at every Metal start, where before it was read only by the Qwen27 server with unpaged K/V. - TF_QWEN_KV_SNAPSHOT_GPU (CUDA): exactly 0 or 1, blank as unset. Its reader turns it on only for exact 1; other text it read as off ("true", "on", " 1", "2") is now refused at a CUDA start. - Flags (the scopes a start checks) moves to environment_flags.zig unchanged, so environment.zig keeps room under 600 lines. --- zig/src/platform/environment.zig | 48 ++++-------------------- zig/src/platform/environment_flags.zig | 44 ++++++++++++++++++++++ zig/src/platform/environment_kv_test.zig | 37 ++++++++++++++++++ zig/src/platform/environment_test.zig | 4 ++ zig/src/qwen27_memory_test.zig | 10 +++++ 5 files changed, 102 insertions(+), 41 deletions(-) create mode 100644 zig/src/platform/environment_flags.zig create mode 100644 zig/src/platform/environment_kv_test.zig diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 23f6649c726..f8ad555e12a 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -21,6 +21,8 @@ pub const Rule = struct { base: u8 = 10, /// When nonempty, the only whole numbers accepted. only: []const u64 = &.{}, + /// A whole number must be a multiple of this (0 included). + multiple: u64 = 1, /// A `.word` setting matches its texts in any case. ignore_case: bool = false, /// A `.word` setting's accepted texts; the parsed value is the matching index. @@ -78,6 +80,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_QWEN_KEEP_LATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_Q35_GROUP_PROJ", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (1 groups same-input ModelOpt decode projections in one launch; default 0)" }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .scope = .cuda, .kind = .size, .min = 1, .max = 2147483647, .forms = "a whole page size from 1 to 2147483647 (unset: off)" }, + .{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps shared-prefix snapshots on the device)" }, .{ .name = "TF_COST_KEY_TRACE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_TIMING", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TF_NO_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps the CUDA drafter's chains only)" }, @@ -102,6 +105,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_DRAMA_PREFILL_ROWS", .scope = .drama3, .kind = .u32, .trim = " ", .forms = "whole prompt rows a chunk, 1 through 1024 (checked when a Drama 3 checkpoint opens)" }, .{ .name = "TF_DRAMA_REFERENCE_CACHE", .scope = .drama3, .kind = .u32, .trim = " ", .forms = "kept reference states, 0 (off) through 16 (checked when a Drama 3 checkpoint opens)" }, .{ .name = "TF_Q27_COPY_ROWS", .scope = .metal, .kind = .u32, .forms = "a whole number from 0 to 4294967295 (0 disables copied rows)" }, + .{ .name = "TF_Q27_KV_GROW", .scope = .metal, .kind = .u32, .multiple = 16, .blank_default = false, .forms = "0 (off, the default) or a row count that is a multiple of 16, at most 4294967280" }, .{ .name = "TF_Q27_DRAFT_SLOTS", .scope = .metal, .kind = .u32, .forms = "a whole number from 0 to 4294967295 (clamped to the current stream bounds)" }, .{ .name = "TF_Q27_DFLASH_ADAPTIVE_BLOCK", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 lets a lone Qwen3.8-27B stream's DFlash2 block take 8 or 16 rows from its landed depth; default 0)" }, .{ .name = "TF_Q27_DFLASH_ABSORB_BATCH", .scope = .metal, .kind = .flag, .forms = "0 or 1 (default 0; 1 absorbs a shared round's DFlash2 taps for all streams in one pass)" }, @@ -395,6 +399,7 @@ pub fn parse(name: []const u8, raw: ?[]const u8) Error!?u64 { }; if (n > max or n < r.min or n > r.max) return error.InvalidEnvironment; if (r.only.len > 0 and std.mem.indexOfScalar(u64, r.only, n) == null) return error.InvalidEnvironment; + if (n % r.multiple != 0) return error.InvalidEnvironment; if ((r.kind == .positive or r.kind == .segments or r.kind == .mib) and n == 0) return error.InvalidEnvironment; if (r.kind == .mib and n > std.math.maxInt(usize) / (1 << 20)) return error.InvalidEnvironment; if (r.kind == .prompt and (n < 128 or n > 2048 or n % 16 != 0)) return error.InvalidEnvironment; @@ -524,47 +529,7 @@ pub fn parallel(flag: ?[]const u8, raw: ?[]const u8) Error!?[]const u8 { return if (text.len == 0) null else text; } -pub const Flags = struct { - cuda: bool = false, - metal: bool = false, - xpu: bool = false, - slide: bool = false, - hooks: bool = false, - dsv41: bool = false, - gemma4: bool = false, - drama3: bool = false, - glm: bool = false, - flashnext: bool = false, - nemotron: bool = false, - minimax_m3: bool = false, - chat: bool = false, - hub: bool = false, - device: ?u32 = null, - segments: ?u32 = null, - carveout: bool = false, - /// --parallel named: TENSORFOLD_PARALLEL then stays out of the way, as a flag-named device does. - parallel_named: bool = false, - - fn includes(f: Flags, scope: Scope) bool { - return switch (scope) { - .common => true, - .cuda => f.cuda, - .metal => f.metal, - .xpu => f.xpu, - .slide => f.slide, - .hooks => f.hooks, - .dsv41 => f.dsv41, - .gemma4 => f.gemma4, - .drama3 => f.drama3, - .glm => f.glm, - .flashnext => f.flashnext, - .nemotron => f.nemotron, - .minimax_m3 => f.minimax_m3, - .chat => f.chat, - .hub => f.hub, - }; - } -}; +pub const Flags = @import("environment_flags.zig").Flags; /// The environment is injectable so the actual startup validator runs against host fixtures without a GPU. pub fn refusal(a: std.mem.Allocator, environment: anytype, flags: Flags) !?[]const u8 { @@ -592,4 +557,5 @@ pub const Process = struct { test { _ = @import("environment_test.zig"); _ = @import("environment_flashnext_test.zig"); + _ = @import("environment_kv_test.zig"); } diff --git a/zig/src/platform/environment_flags.zig b/zig/src/platform/environment_flags.zig new file mode 100644 index 00000000000..82009b0c3b8 --- /dev/null +++ b/zig/src/platform/environment_flags.zig @@ -0,0 +1,44 @@ +//! Which scopes a startup checks: each backend or feature switch the server or a family entry point turns on. +const Scope = @import("environment.zig").Scope; + +pub const Flags = struct { + cuda: bool = false, + metal: bool = false, + xpu: bool = false, + slide: bool = false, + hooks: bool = false, + dsv41: bool = false, + gemma4: bool = false, + drama3: bool = false, + glm: bool = false, + flashnext: bool = false, + nemotron: bool = false, + minimax_m3: bool = false, + chat: bool = false, + hub: bool = false, + device: ?u32 = null, + segments: ?u32 = null, + carveout: bool = false, + /// --parallel named: TENSORFOLD_PARALLEL then stays out of the way, as a flag-named device does. + parallel_named: bool = false, + + pub fn includes(f: Flags, scope: Scope) bool { + return switch (scope) { + .common => true, + .cuda => f.cuda, + .metal => f.metal, + .xpu => f.xpu, + .slide => f.slide, + .hooks => f.hooks, + .dsv41 => f.dsv41, + .gemma4 => f.gemma4, + .drama3 => f.drama3, + .glm => f.glm, + .flashnext => f.flashnext, + .nemotron => f.nemotron, + .minimax_m3 => f.minimax_m3, + .chat => f.chat, + .hub => f.hub, + }; + } +}; diff --git a/zig/src/platform/environment_kv_test.zig b/zig/src/platform/environment_kv_test.zig new file mode 100644 index 00000000000..176b3eaeea2 --- /dev/null +++ b/zig/src/platform/environment_kv_test.zig @@ -0,0 +1,37 @@ +//! The Qwen K/V rows: grow-as-used steps on Metal and device prefix snapshots on CUDA, refused by name at startup. +const std = @import("std"); +const e = @import("environment.zig"); +const t = std.testing; + +const One = struct { + name: []const u8, + raw: ?[]const u8, + pub fn get(v: One, name: []const u8) ?[]const u8 { + return if (std.mem.eql(u8, name, v.name)) v.raw else null; + } +}; + +test "environment: TF_Q27_KV_GROW takes 0 or a multiple of 16 that fits u32, and refuses blank, others and padding" { + for ([_][]const u8{ "0", "16", "4096", "4294967280", "+32", "1_6" }) |raw| _ = try e.parse("TF_Q27_KV_GROW", raw); + try t.expectEqual(@as(?u64, 4096), try e.parse("TF_Q27_KV_GROW", "4096")); + try t.expectEqual(@as(?u64, null), try e.parse("TF_Q27_KV_GROW", null)); + for ([_][]const u8{ "", " ", "8", "24", "15", " 16", "16 ", "4294967296", "0x10", "-16", "off" }) |raw| + try t.expectError(error.InvalidEnvironment, e.parse("TF_Q27_KV_GROW", raw)); + const why = (try e.refusal(t.allocator, One{ .name = "TF_Q27_KV_GROW", .raw = "24" }, .{ .metal = true })).?; + defer t.allocator.free(why); + try t.expect(std.mem.indexOf(u8, why, "TF_Q27_KV_GROW=\"24\"") != null); + try t.expect(try e.refusal(t.allocator, One{ .name = "TF_Q27_KV_GROW", .raw = "24" }, .{ .cuda = true }) == null); +} + +test "environment: TF_QWEN_KV_SNAPSHOT_GPU is exact 0 or 1 on CUDA, blank as unset" { + try t.expectEqual(@as(?u64, 1), try e.parse("TF_QWEN_KV_SNAPSHOT_GPU", "1")); + try t.expectEqual(@as(?u64, 0), try e.parse("TF_QWEN_KV_SNAPSHOT_GPU", "0")); + for ([_]?[]const u8{ null, "", " \t" }) |raw| try t.expectEqual(@as(?u64, null), try e.parse("TF_QWEN_KV_SNAPSHOT_GPU", raw)); + // texts the reader took as off (only exact 1 is on) are refused at a CUDA start now + for ([_][]const u8{ "true", "on", "2", " 1", "1 ", "yes" }) |raw| + try t.expectError(error.InvalidEnvironment, e.parse("TF_QWEN_KV_SNAPSHOT_GPU", raw)); + const why = (try e.refusal(t.allocator, One{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .raw = "true" }, .{ .cuda = true })).?; + defer t.allocator.free(why); + try t.expect(std.mem.indexOf(u8, why, e.rule("TF_QWEN_KV_SNAPSHOT_GPU").forms) != null); + try t.expect(try e.refusal(t.allocator, One{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .raw = "true" }, .{ .metal = true }) == null); +} diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index cb5aefc174d..85a3af31b3e 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -43,6 +43,10 @@ const valid = [_]Case{ .{ .name = "TF_FLASHNEXT_BATCH_DRAWS", .raw = "1", .n = 1 }, .{ .name = "TF_CUDA_POOL_AFTER_WARMUP", .raw = "0", .n = 0 }, .{ .name = "TF_CUDA_POOL_AFTER_WARMUP", .raw = "1", .n = 1 }, + .{ .name = "TF_Q27_KV_GROW", .raw = "0", .n = 0 }, + .{ .name = "TF_Q27_KV_GROW", .raw = "4096", .n = 4096 }, + .{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .raw = "1", .n = 1 }, .{ .name = "TF_LFM3_METAL_WARM_TURNS", .raw = "0", .n = 0 }, .{ .name = "TF_LFM3_METAL_WARM_TURNS", .raw = "1", .n = 1 }, .{ .name = "TF_FLASHNEXT_READOUT_FUSED", .raw = "0", .n = 0 }, diff --git a/zig/src/qwen27_memory_test.zig b/zig/src/qwen27_memory_test.zig index c0e0b605cfc..23246f0e59d 100644 --- a/zig/src/qwen27_memory_test.zig +++ b/zig/src/qwen27_memory_test.zig @@ -156,6 +156,16 @@ test "qwen27 memory: grow-as-used K/V is off unless TF_Q27_KV_GROW names a 16-ro for ([_][]const u8{ "", "-1", "15", "4097", "x", "99999999999" }) |text| try std.testing.expectError(error.BadKvGrowStep, kv_grow.step(text)); } +test "qwen27 memory: the TF_Q27_KV_GROW row accepts exactly the texts kv_grow.step accepts" { + const settings = @import("sys").environment; + const texts = [_][]const u8{ "0", "16", "4096", "4294967280", "+32", "1_6", "", " ", "8", "24", "15", " 16", "16 ", "-16", "x", "4294967296", "0x10" }; + for (texts) |text| { + const reader = if (kv_grow.step(text)) |_| true else |_| false; + const row = if (settings.parse("TF_Q27_KV_GROW", text)) |_| true else |_| false; + try std.testing.expectEqual(reader, row); + } +} + test "qwen27 memory: a slot starts at one step and grows to the need, a quarter more, or the context" { // first rows: one step, never past the context try std.testing.expectEqual(@as(u32, 4096), kv_grow.first(4096, 32784)); From c4af6966b770f29ff0d2c9ec7dace6ce938c72c6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:13:52 +0000 Subject: [PATCH 297/361] docs: the settings and start flag missing before 1.3.5 docs/environment.md gains rows for TF_CUDA_POOL_AFTER_WARMUP, TF_GLM_WIDE_EXPERT_TILE, TF_Q27_KV_GROW and TF_QWEN35_CHUNK, each as its reader takes it, and TF_QWEN_KV_SNAPSHOT_GPU moves from the lenient list to the table now that it is checked. docs/run-guide.md describes tensorfold start --startup-timeout: above 0 and at most 3600 seconds; unset, 600 plus 6 for every GB of weights past 20 GB, at most 3600. --- CHANGELOG.md | 2 ++ docs/environment.md | 7 +++++-- docs/run-guide.md | 2 ++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 938a883d529..b5caa7d76e5 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 +- Settings: `TF_Q27_KV_GROW` (Metal) and `TF_QWEN_KV_SNAPSHOT_GPU` (CUDA) are checked at startup and refused by name like every registered setting; their accepted values are unchanged, except that `TF_QWEN_KV_SNAPSHOT_GPU` text other than `0` or `1`, which was read as off, is now refused. `docs/environment.md` now covers `TF_CUDA_POOL_AFTER_WARMUP`, `TF_GLM_WIDE_EXPERT_TILE`, `TF_Q27_KV_GROW`, `TF_QWEN35_CHUNK` and `TF_QWEN_KV_SNAPSHOT_GPU`, and `docs/run-guide.md` covers `tensorfold start --startup-timeout`. + - Qwen 3.8-27B on Metal M5: 5-bit and 6-bit group-64 checkpoints split K for decode and prompt rows as v1.3.4 did again, so their sums run in v1.3.4's order; #4419 had moved them onto the 4-bit M5 split tables, and its register-direct kernels stay, at the restored splits. Gemma 4 and 4-bit are unchanged (#4962). - Nemotron 3.5 Transcribe on CUDA: chat requests take speech as 16 kHz mono WAV in OpenAI `input_audio` and vLLM `audio_url` parts, up to an hour of audio a request in the model's trained 65,536-token window, with each clip's rows keyed in the prompt cache and MTP drafts running over them; `/v1/models` lists `audio` among its input types (#1632, closes #1549). Thanks to @BobClawblaw. diff --git a/docs/environment.md b/docs/environment.md index b7dc68b1445..f0962686dce 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -28,10 +28,12 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TENSORFOLD_CUDA_KERNELS` | A path without control characters, used as given: a captured kernel set's folder, or `native` for the engine's own kernels. Unset uses the binary's bundled set for the GPU when it has one, else the engine's own kernels. A family that runs only on the engine's own kernels (Qwen3 among them) refuses any other value; Qwen3 reads a blank value as unset | | `TF_CUDA_CARVEOUT` | Exactly `0` or `1`; default off | | `TF_CUDA_CARVEOUT_MIB` | Positive whole MiB count whose byte size fits the platform, or empty for 1792 MiB | +| `TF_CUDA_POOL_AFTER_WARMUP` | Dense Qwen 3.5/3.8 on CUDA: exactly `0` or `1`; default `0` (blank is refused). `1` sizes the still-empty KV page pool again after warm-up from the free memory then measured, under the same reserve and cap; it applies only to a one-rank paged serve with `--prompt-cache-gib 0` and without `--slide` or vision, and other modes keep their startup pool. A pool that cannot keep its pages and the reserve is refused by name; `/memory` reports the decision | | `TF_Q27_COPY_ROWS` | Whole u32 count; zero disables copied rows; default 48 | | `TF_Q27_DRAFT_SLOTS` | Whole u32 count, clamped to 1 through the lane stream limit; default 8. DFlash2 can draft for at most the smaller of this count and the admitted streams, and none without a drafter. Under `--mtp-drafts` the MTP head drafts every stream and this does nothing. | | `TF_Q27_DFLASH_ADAPTIVE_BLOCK` | Qwen3.8-27B on Metal: exactly `0` or `1`; default 0. `1` lets a lone stream's DFlash2 block narrow from 16 to 8 rows after 8 consecutive rounds landing at most 4 tree drafts, and return to 16 after a round landing 6 or more. Only the drafter's proposal changes. | | `TF_Q27_DFLASH_ABSORB_BATCH` | Qwen3.8-27B on Metal: exactly `0` or `1`; default `0`. `1` absorbs a shared round's new DFlash2 taps for up to 128 rows across streams in one pass, each stream's results in its own caches. | +| `TF_Q27_KV_GROW` | Qwen3.8-27B on Metal: `0` (the default: every slot holds the whole context) or a row count that is a multiple of 16, at most 4294967280; blank and other text are refused. A slot starts at that many rows, grows to a need rounded up to the step or a quarter more, at most the context, and gives the rows back when its stream ends; drafter tap rings grow the same way. Read when the K/V is not paged; checked at every Metal start | | `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one; existing depth when unset | | `TF_TIMING` | Exactly `0` or `1`; default off (each call's wall time on stderr while set) | | `TF_NO_TREES` | Exactly `0` or `1`; default off. `1` keeps the CUDA drafter's chains only, and retains precedence over `TF_DRAFT_NODES` | @@ -42,6 +44,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_QWEN_KEEP_LATE` | Exactly `0` or `1`; default off | | `TF_Q35_GROUP_PROJ` | Exactly `0` or `1`, read when a ModelOpt checkpoint loads on CUDA (sm_90 or newer); default off. `1` runs Qwen 3.5 same-input decode projections (MLP gate and up, GDN `in_proj_qkv` and `in_proj_z`, `in_proj_a` and `in_proj_b`, attention q, k and v) as one launch per group, each projection with its own tile and K slices, so outputs keep their bits | | `TF_QWEN_KV_PAGE_TEST` | Whole page size from 1 to 2147483647; unset off. Each cache's own buffer reads through a table of n-position pages in reverse order (checks) | +| `TF_QWEN_KV_SNAPSHOT_GPU` | Qwen on CUDA: exactly `0` or `1`; unset, blank or `0` keeps shared-prefix snapshots in pinned host memory. `1` keeps up to `n` of them on the device under `TF_QWEN_KV_SHARE=n`, a failed device allocation falling back to the host. Other text, which older builds read as off, is refused at a CUDA start | | `TF_QWEN_POOL_LOG` | Exactly `0` or `1`; default off (the pool's census after a prompt pass) | | `TF_COST_KEY_TRACE` | Exactly `0` or `1`; default off (each cost key's parts on stderr) | | `TF_Q27_POCKET_OFF` | `all`, or a list of `layer:neuron` pairs; default off (pocket diagnostics) | @@ -85,6 +88,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_GLM_DRAFT_CONFIDENCE` | Finite number 0 through 1 where a DFlash2 chain's chance product stops it; default 0.7 on CUDA, 0.5 on Metal | | `TF_GLM_CONTEXT_CEILING` | GLM-5.3-Flash on CUDA: whole token count 1 through 2147483616, the window `--context` may ask for and `--context 0` serves, in place of config.json's 1048576; read at GLM's open. Past that length the model's quality is the operator's to check. Unset keeps config.json's window | | `TF_GLM_EXPERT_FORM` | `classic` or `factored`: the expert form GLM's CUDA decode windows use at every width (the same bits either way), also at a load that times nothing; unset or blank races the two at each timed width when a build first loads with drafts and scratch context and keeps each width's winner, else classic; read on rank 0, which chooses every rank's forms | +| `TF_GLM_WIDE_EXPERT_TILE` | GLM on CUDA: exactly `0` or `1`; default off. `1` runs a factored decode window's NVFP4 routed down projection (f32 out) wider than the decode tile on the factored 64-pair tile instead of the original waves. Read once before the expert modules load | | `TF_GLM_INDEX_CUDA` | GLM on CUDA: exactly `1` (both DSA indexer kernels), `0` (neither) or `scores` (scores only); unset or blank is `both` | | `TF_GLM_KV_HOST_GIB` | GLM on CUDA: a finite GiB amount of at least 0 for the DSA layers' pinned host pages; unset or blank uses one full window and 16 rows a page | | `TF_GLM_RANK` | GLM-5.3-Flash on CUDA: a whole rank index from 0 through 4294967295, set with `TF_GLM_WORLD`; unset with it gives one rank | @@ -112,6 +116,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_QWEN27_JOIN` | Qwen3.8-27B on Metal before M5: exactly `0` or `1`; `1` runs a window's rows in pairs over the keys below it in the decode tail attention (same replies); unset or blank is `1` | | `TF_QWEN27_TIED_HEAD` | Dense Qwen on Metal: exactly `0` or `1`; `1` lets a checkpoint with a tied head load on the 27B engine, its head read from the embedding (one Mac, no draft head, qualified shapes only); unset or blank is `0` | | `TF_QWEN35_METAL_KV_PAGES` | Qwen 3.5 on Metal: exactly `0` or `1`; `1` puts the streams' keys and values in core-pool pages; unset or blank is `0` | +| `TF_QWEN35_CHUNK` | Qwen 3.5 on Metal: whole prompt rows a prefill pass, 1 through the served context window; default 128. Checked before the checkpoint loads, naming the setting | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | | `GLM_ROUND_PROF` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `1` has the server log a summary of its verify windows when streams end (window GPU time, idle gap, drafts span and host phases by rows, streams and drafted or plain; partial accepts); default off | | `GLM_POOL_TOKENS` | GLM-5.3-Flash on Metal, one Mac: a whole number of tokens from 1024 through 4294967231 for the shared latent pool; `--context` stays the most one stream may use, so `--parallel 3 --context 1048576 GLM_POOL_TOKENS=2000000` shares a 2M-token pool and a stream is cut to the pool when it is smaller; refused with the pair or `GLM_POOL=0`, and when the pool does not fit the load limit; unset or blank: the pool is the window, as before | @@ -249,8 +254,6 @@ These settings retain their existing boolean policies rather than gaining new al and `TF_SLIDE_FIT_REDUCE` its exact `tree` reduction selection. These developer switches keep their existing semantics. - GLM: `GLM_EHPROJ_NAX` retains its first-character `0` disabling rule, `TF_GLM_DFLASH2_PROF` enables by presence, even empty or `0`, and `TF_KV_POISON` (also read by Nemotron) is on only for exact `1`. -- Qwen shared-prefix snapshots: `TF_QWEN_KV_SNAPSHOT_GPU` opts in only for exact `1`. With `TF_QWEN_KV_SHARE=n`, - at most `n` states occupy device memory; a failed device allocation retains the pinned-host fallback. Unset keeps host snapshots. - The existing tool-grammar, rows-sync, log-time, memory-pressure and XPU-MTP boolean policies are unchanged. - Flash Next keeps its lenient readers where they are: `TF_FLASHNEXT_TP` and `TF_FLASHNEXT_LOGITS` take a path, `TF_FLASHNEXT_OWNED` a list, `TF_FLASHNEXT_DEPTH_LOG` and `TF_TP_TRACE`/`TF_TP_LOCAL`/`TF_TP_STATS` select by presence, diff --git a/docs/run-guide.md b/docs/run-guide.md index 0f610805242..47d0c790958 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -34,6 +34,8 @@ comma-separated list to the child unchanged, and uses its first nonempty trimmed must be UTF-8, at most 256 bytes, and contain no whitespace or control characters. The server accepts each registered entry. Send external requests with `Authorization: Bearer KEY`, replacing `KEY` with one accepted entry. Keys are never printed or placed in the child arguments. A failed first reply is fatal and the started server is stopped. +`--startup-timeout SECONDS` sets how long `start` waits for the server to load, above 0 and at most 3600; unset, it +waits 600 seconds plus 6 for every GB of weights past 20 GB, at most 3600. No existing `serve` default or flag changes. ## Send a request From f196d625d0aa2c249f03b49f4a057fa2ff9759bc Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:35:56 +0000 Subject: [PATCH 298/361] changelog: #4963's line from lines/4963.txt in place of its own --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5caa7d76e5..603cb0d944a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased -- Settings: `TF_Q27_KV_GROW` (Metal) and `TF_QWEN_KV_SNAPSHOT_GPU` (CUDA) are checked at startup and refused by name like every registered setting; their accepted values are unchanged, except that `TF_QWEN_KV_SNAPSHOT_GPU` text other than `0` or `1`, which was read as off, is now refused. `docs/environment.md` now covers `TF_CUDA_POOL_AFTER_WARMUP`, `TF_GLM_WIDE_EXPERT_TILE`, `TF_Q27_KV_GROW`, `TF_QWEN35_CHUNK` and `TF_QWEN_KV_SNAPSHOT_GPU`, and `docs/run-guide.md` covers `tensorfold start --startup-timeout`. +- Settings: `TF_Q27_KV_GROW` (Metal) and `TF_QWEN_KV_SNAPSHOT_GPU` (CUDA) are checked at startup and refused by name like every registered setting; their accepted values are unchanged, except that `TF_QWEN_KV_SNAPSHOT_GPU` text other than `0` or `1`, which was read as off, is now refused. `docs/environment.md` now covers `TF_CUDA_POOL_AFTER_WARMUP`, `TF_GLM_WIDE_EXPERT_TILE`, `TF_Q27_KV_GROW`, `TF_QWEN35_CHUNK` and `TF_QWEN_KV_SNAPSHOT_GPU`, and `docs/run-guide.md` covers `tensorfold start --startup-timeout` (#4963). - Qwen 3.8-27B on Metal M5: 5-bit and 6-bit group-64 checkpoints split K for decode and prompt rows as v1.3.4 did again, so their sums run in v1.3.4's order; #4419 had moved them onto the 4-bit M5 split tables, and its register-direct kernels stay, at the restored splits. Gemma 4 and 4-bit are unchanged (#4962). From 9d249389a5ff76eeb3d18cb535ee73a3a069abd1 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:40:08 +0100 Subject: [PATCH 299/361] inkling2 metal: serve images under --vision with the image tower, patch decode and prefill row splice - Add the 23-layer vision tower (vision.metal, vision_gemm.metal) as the `vision` source of inkling2_metal, with host code in metal/vision*.zig. - Decode PNG/JPEG/WebP through the family's image decoder and patchify in the processor's merge-block order with the HF two-step normalisation. - Splice the tower's BF16 rows over the image placeholders in forward prefill, across chunks and cache restores (metal/images.zig); native opener loads the tower under --vision. - Let inkling2_loop past the Metal dispatcher's --vision gate (native/metal.zig) so the opener is reached, and name Inkling 2 Mini in the refusal text and docs/vision.md. - Add contract records, probes and host-checked planted controls for the tower kernels; test-inkling2-media-metal runs the device and checkpoint checks. - Build the Mini contract suites in place: their probes point into the suites, and the returned copy left them dangling once a seventh suite was added. - Add the vision CHANGELOG bullet under Unreleased. Co-authored-by: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> --- CHANGELOG.md | 2 + docs/vision.md | 2 +- zig/build/inkling2_host.zig | 5 +- zig/kernels/metal/inkling2/vision.metal | 153 ++++++ zig/kernels/metal/inkling2/vision_gemm.metal | 120 +++++ zig/kernels/metal/inkling2/vision_sources.zig | 4 + zig/kernels/metal/inkling2_sources.zig | 1 + .../inkling2_vision_metal_records.zig | 41 ++ zig/src/core/contract/registry_joins.zig | 2 + zig/src/families/inkling2/config.zig | 2 + zig/src/families/inkling2/config_test.zig | 1 + .../inkling2/fixtures/media_photo.jpg | Bin 0 -> 1835 bytes .../inkling2/fixtures/media_photo.raw | Bin 0 -> 4500 bytes .../families/inkling2/fixtures/media_rgb.png | Bin 0 -> 2128 bytes .../families/inkling2/fixtures/media_rgb.raw | Bin 0 -> 5289 bytes .../families/inkling2/fixtures/media_rgba.png | Bin 0 -> 2312 bytes .../families/inkling2/fixtures/media_rgba.raw | Bin 0 -> 6660 bytes zig/src/families/inkling2/metal/backend.zig | 15 +- zig/src/families/inkling2/metal/forward.zig | 16 + zig/src/families/inkling2/metal/host_test.zig | 2 + zig/src/families/inkling2/metal/images.zig | 61 +++ zig/src/families/inkling2/metal/metal.zig | 1 + zig/src/families/inkling2/metal/vision.zig | 430 ++++++++++++++++ .../inkling2/metal/vision_checkpoint_test.zig | 34 ++ .../families/inkling2/metal/vision_gemm.zig | 103 ++++ .../families/inkling2/metal/vision_image.zig | 109 +++++ .../inkling2/metal/vision_image_test.zig | 234 +++++++++ .../inkling2/metal/vision_real_test.zig | 85 ++++ .../families/inkling2/metal/vision_tables.zig | 38 ++ .../families/inkling2/metal/vision_test.zig | 463 ++++++++++++++++++ zig/src/inkling2_media_checks.zig | 5 + zig/src/native/inkling2.zig | 45 +- zig/src/native/metal.zig | 4 +- .../contract/metal_inkling2_controls_host.zig | 1 + zig/tests/contract/metal_inkling2_main.zig | 10 +- zig/tests/contract/metal_inkling2_vision.zig | 116 +++++ .../metal_inkling2_vision_controls.zig | 110 +++++ .../contract/metal_inkling2_vision_gemm.zig | 191 ++++++++ .../contract/metal_inkling2_vision_glue.zig | 279 +++++++++++ .../contract/metal_inkling2_vision_rows.zig | 192 ++++++++ .../contract/metal_inkling2_vision_stress.zig | 22 + .../contract/metal_inkling2_vision_util.zig | 50 ++ zig/tests/contract/metal_limits.zig | 6 + zig/tests/contract/metal_main.zig | 3 +- 44 files changed, 2940 insertions(+), 18 deletions(-) create mode 100644 zig/kernels/metal/inkling2/vision.metal create mode 100644 zig/kernels/metal/inkling2/vision_gemm.metal create mode 100644 zig/kernels/metal/inkling2/vision_sources.zig create mode 100644 zig/src/core/contract/inkling2_vision_metal_records.zig create mode 100644 zig/src/families/inkling2/fixtures/media_photo.jpg create mode 100644 zig/src/families/inkling2/fixtures/media_photo.raw create mode 100644 zig/src/families/inkling2/fixtures/media_rgb.png create mode 100644 zig/src/families/inkling2/fixtures/media_rgb.raw create mode 100644 zig/src/families/inkling2/fixtures/media_rgba.png create mode 100644 zig/src/families/inkling2/fixtures/media_rgba.raw create mode 100644 zig/src/families/inkling2/metal/images.zig create mode 100644 zig/src/families/inkling2/metal/vision.zig create mode 100644 zig/src/families/inkling2/metal/vision_checkpoint_test.zig create mode 100644 zig/src/families/inkling2/metal/vision_gemm.zig create mode 100644 zig/src/families/inkling2/metal/vision_image.zig create mode 100644 zig/src/families/inkling2/metal/vision_image_test.zig create mode 100644 zig/src/families/inkling2/metal/vision_real_test.zig create mode 100644 zig/src/families/inkling2/metal/vision_tables.zig create mode 100644 zig/src/families/inkling2/metal/vision_test.zig create mode 100644 zig/src/inkling2_media_checks.zig create mode 100644 zig/tests/contract/metal_inkling2_vision.zig create mode 100644 zig/tests/contract/metal_inkling2_vision_controls.zig create mode 100644 zig/tests/contract/metal_inkling2_vision_gemm.zig create mode 100644 zig/tests/contract/metal_inkling2_vision_glue.zig create mode 100644 zig/tests/contract/metal_inkling2_vision_rows.zig create mode 100644 zig/tests/contract/metal_inkling2_vision_stress.zig create mode 100644 zig/tests/contract/metal_inkling2_vision_util.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 603cb0d944a..a678b4d3d20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -215,6 +215,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: a plan for Inkling 2 Mini on CUDA and Metal in slices a contributor can claim (#4274). Thanks @akol1. +- Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. + - Docs: the Flash Next HIP recipe adds the measured four-rank serve path and fixes its receipt link (#4669). Thanks @timmyit. - Desktop: the app changelog lists the Room, Kanban and saved-bot changes (#4376). Thanks @garvrao80. diff --git a/docs/vision.md b/docs/vision.md index a0d1f9c2e6f..f42700d2502 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -156,7 +156,7 @@ For Qwen, each image request carries its own multimodal rotary positions and con `tensorfold-native serve` takes `--vision`, `--vision-max-images` (default 4), `--vision-image-tokens` (default 4,096; 13,312 for Nemotron 3.5 Super VL) and `--vision-image-share` (`request`, the default, or `fixed`) for engines that read images: GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4 -[31B](recipes/gemma-4-native.md#images) and [12B](recipes/gemma-4-12b-native.md#images) and Step-5-Preview on one +[31B](recipes/gemma-4-native.md#images) and [12B](recipes/gemma-4-12b-native.md#images), Step-5-Preview and Inkling 2 Mini on one Mac, GLM-5.3-Flash on [CUDA ranks](recipes/glm-5.3-flash-cuda.md#requests) and Nemotron 3.5 Super VL on CUDA. Other native engines refuse the flag at startup. On CUDA and HIP a tower loads only with `--vision`, d1-3B's pictures included; a checkpoint with a tower starts diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 21e7aa23356..e3baaa39b4f 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -37,11 +37,14 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu b.step("test-inkling2-host", "Inkling 2 family package: config, weight map, layer plan, chat template and tokenizer").dependOn(&run.step); test_step.dependOn(&run.step); - // The metal module reaches Darwin-only std.c, so this test runs on macOS only, like main's Metal steps. + // The metal module reaches Darwin-only std.c, so these tests run on macOS only, like main's Metal steps. if (target.result.os.tag == .macos) { const metal_run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/inkling2_metal_host_test.zig") })); b.step("test-inkling2-metal-host", "Inkling 2 Mini Metal launch plans and arithmetic references").dependOn(&metal_run.step); test_step.dependOn(&metal_run.step); + const media_run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/inkling2_media_checks.zig") })); + media_run.has_side_effects = true; + b.step("test-inkling2-media-metal", "Inkling 2 Mini image tower on this GPU: kernels, tower fixtures and the original checkpoint").dependOn(&media_run.step); } const native = b.addObject(.{ .name = "inkling2-native", .root_module = module(b, target, .Debug, "zig/inkling2_native_compile.zig") }); _ = native.getEmittedBin(); diff --git a/zig/kernels/metal/inkling2/vision.metal b/zig/kernels/metal/inkling2/vision.metal new file mode 100644 index 00000000000..a188fb6f553 --- /dev/null +++ b/zig/kernels/metal/inkling2/vision.metal @@ -0,0 +1,153 @@ +// Inkling 2 image tower glue (HF Inkling2VisionModel): each torch op's output rounded once to bf16, sums in fp32. + +// The patches as bf16, the dtype the reference casts pixel_values to before the patch projection. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_pack( + const device float* x [[buffer(0)]], device bfloat* y [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) y[i] = bfloat(x[i]); +} + +struct Ik2vEmbed { + uint patches; // patch rows of the image; the sequence is one class row and then these + uint width; +}; + +// Row 0: bf16(class + class position). Row 1 + i: bf16(patch_i + bf16(sum of the 4 bilinear taps of table * w)). +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_embed( + const device bfloat* pe [[buffer(0)]], const device bfloat* table [[buffer(1)]], + const device uint* taps [[buffer(2)]], const device float* weights [[buffer(3)]], + const device bfloat* cls [[buffer(4)]], const device bfloat* cls_pos [[buffer(5)]], device bfloat* x [[buffer(6)]], + constant Ik2vEmbed& p [[buffer(7)]], uint2 at [[thread_position_in_grid]]) { + if (at.x >= p.width || at.y > p.patches) return; + if (at.y == 0) { + x[at.x] = bfloat(float(cls[at.x]) + float(cls_pos[at.x])); + return; + } + const ulong i = ulong(at.y - 1); + float pos = 0.0f; + for (uint k = 0; k < 4; k++) pos += float(table[ulong(taps[i * 4 + k]) * p.width + at.x]) * weights[i * 4 + k]; + x[ulong(at.y) * p.width + at.x] = bfloat(float(pe[i * p.width + at.x]) + tf_vis_bf(pos)); +} + +struct Ik2vRows { + uint rows; + uint width; + float eps; +}; + +#define IK2V_ROW(i) float(xr[i]) + +// nn.LayerNorm on bf16 rows: fp32 statistics, one rounding of (x - mean) * inv * w + b. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_layer_norm( + const device bfloat* x [[buffer(0)]], const device bfloat* w [[buffer(1)]], const device bfloat* b [[buffer(2)]], + device bfloat* y [[buffer(3)]], constant Ik2vRows& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + const device bfloat* xr = x + ulong(row) * p.width; + device bfloat* yr = y + ulong(row) * p.width; + TF_VIS_LAYER_NORM_STATS(IK2V_ROW) + TF_VIS_LAYER_NORM_OUT(IK2V_ROW) +} + +struct Ik2vQkv { + uint rows; // sequence rows in all + uint heads; + uint dim; + uint r0; // the first sequence row of acc's rows +}; + +// acc [n, 3, heads * dim] fp32 q, k, v sums to head-major fp32 Q, K, V [heads, rows, dim]: bias, bf16, q k rotated. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_qkv( + const device float* acc [[buffer(0)]], const device bfloat* bq [[buffer(1)]], const device bfloat* bk [[buffer(2)]], + const device bfloat* bv [[buffer(3)]], const device float* cs [[buffer(4)]], const device float* sn [[buffer(5)]], + device float* Q [[buffer(6)]], device float* K [[buffer(7)]], device float* V [[buffer(8)]], + constant Ik2vQkv& p [[buffer(9)]], uint3 at [[thread_position_in_grid]]) { + const uint d = at.x, which = at.y / p.heads, h = at.y % p.heads, r = at.z, g = p.r0 + at.z; + const uint width = p.heads * p.dim; + const ulong base = ulong(r) * 3 * width + ulong(which) * width + h * p.dim; + const device bfloat* bias = which == 0 ? bq : (which == 1 ? bk : bv); + const float v = tf_vis_bf(acc[base + d] + float(bias[h * p.dim + d])); + const ulong out = (ulong(h) * p.rows + g) * p.dim + d; + if (which == 2) { + V[out] = v; + return; + } + const uint e = d ^ 1u; + const float partner = tf_vis_bf(acc[base + e] + float(bias[h * p.dim + e])); + const float c = cs[ulong(g) * p.dim + d], s = sn[ulong(g) * p.dim + d]; + const float turned = (d & 1u) == 0 ? v * c - partner * s : v * c + partner * s; + (which == 0 ? Q : K)[out] = tf_vis_bf(turned); +} + +// Transformers eager rounds QK and QK * scale to BF16 before the FP32 softmax. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_softmax( + device float* S [[buffer(0)]], constant uint& n [[buffer(1)]], constant float& scale [[buffer(2)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]], + uint tn [[threads_per_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + device float* s = S + ulong(row) * n; + float m = -INFINITY; + for (uint i = t; i < n; i += tn) { + s[i] = tf_vis_bf(tf_vis_bf(s[i]) * scale); + m = max(m, s[i]); + } + m = tf_vis_max(m, part, tn, lane, sg); + float z = 0.0f; + for (uint i = t; i < n; i += tn) { + const float e = metal::precise::exp(s[i] - m); + s[i] = e; + z += e; + } + const float inv = 1.0f / tf_vis_sum(z, part, tn, lane, sg); + for (uint i = t; i < n; i += tn) s[i] = tf_vis_bf(s[i] * inv); +} + +struct Ik2vHeads { + uint rows; + uint r0; + uint heads; + uint dim; +}; + +// O [heads, rows, dim] (one chunk of queries, fp32) to rows [r0, r0 + rows) of out [S, heads * dim], bf16. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_heads( + const device float* O [[buffer(0)]], device bfloat* out [[buffer(1)]], constant Ik2vHeads& p [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + const uint h = at.x / p.dim, d = at.x % p.dim; + out[ulong(p.r0 + at.y) * (p.heads * p.dim) + at.x] = bfloat(O[(ulong(h) * p.rows + at.y) * p.dim + d]); +} + +// The exact GELU (nn.GELU's erf form); erf by Abramowitz and Stegun 7.1.26, |error| < 1.5e-7, far under bf16's step. +inline float ik2v_erf(float x) { + const float a = fabs(x), t = 1.0f / (1.0f + 0.3275911f * a); + const float poly = t * (0.254829592f + t * (-0.284496736f + t * (1.421413741f + t * (-1.453152027f + t * 1.061405429f)))); + const float e = 1.0f - poly * metal::precise::exp(-a * a); + return x < 0.0f ? -e : e; +} + +inline float ik2v_gelu(float v) { return 0.5f * v * (1.0f + ik2v_erf(v * 0.70710678118654752f)); } + +// y = bf16(gelu(bf16(acc + b))) over acc [rows, width] fp32 sums: the MLP's first linear and its activation. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_bias_gelu( + const device float* acc [[buffer(0)]], const device bfloat* b [[buffer(1)]], device bfloat* y [[buffer(2)]], + constant uint& width [[buffer(3)]], uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + y[i] = bfloat(ik2v_gelu(tf_vis_bf(acc[i] + float(b[at.x])))); +} + +// y = bf16(gelu(y)): the merger's activation between its two bias-free linears. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_gelu_rows( + device bfloat* y [[buffer(0)]], constant uint& width [[buffer(1)]], uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + y[i] = bfloat(ik2v_gelu(float(y[i]))); +} + +// x = bf16(x + bf16(lambda * bf16(acc + b))): a layer-scaled branch joins the bf16 residual stream. +[[max_total_threads_per_threadgroup(256)]] [[kernel]] void ik2v_residual( + const device float* acc [[buffer(0)]], const device bfloat* b [[buffer(1)]], const device bfloat* lambda [[buffer(2)]], + device bfloat* x [[buffer(3)]], constant uint& width [[buffer(4)]], uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + const float branch = tf_vis_bf(acc[i] + float(b[at.x])); + x[i] = bfloat(float(x[i]) + tf_vis_bf(float(lambda[at.x]) * branch)); +} diff --git a/zig/kernels/metal/inkling2/vision_gemm.metal b/zig/kernels/metal/inkling2/vision_gemm.metal new file mode 100644 index 00000000000..3840114b659 --- /dev/null +++ b/zig/kernels/metal/inkling2/vision_gemm.metal @@ -0,0 +1,120 @@ +// Inkling 2 tower GEMMs after gemm_nax.metal: y = x w^T, fp32 sums; P is gemm_nax's parameter array. + +namespace tfp { + +// gemm_nax with output type O apart from operand type T: an fp32 block stays fp32 for an epilogue's one rounding. +template +inline void gemm_out(const device T* A, const device T* B, device O* D, const device int* P, uint3 tg, uint sg, + uint lane) { + const int swz = P[8]; + const int ty = (int(tg.y) << swz) + (int(tg.x) & ((1 << swz) - 1)), tx = int(tg.x) >> swz; + if (tx >= P[6] || ty >= P[7]) { + return; + } + const int lda = P[3], ldb = P[4], ldd = P[5]; + const int row = ty * 64 + 32 * int(sg / 4), col = tx * 128 + 32 * int(sg % 4); + A += long(P[13]) + long(P[10]) * tg.z + (TA ? long(row) : long(row) * lda); + B += long(P[14]) + long(P[11]) * tg.z + (TB ? long(col) * ldb : long(col)); + D += long(P[12]) * tg.z + long(row) * ldd + col; + const int rows = AM ? 32 : min(32, P[0] - row), cols = AN ? 32 : min(32, P[1] - col); + const bool full = (AM || rows == 32) && (AN || cols == 32); + const short2 home = frag_home(ushort(lane)); + frag acc[2][2]; + if (full) { + gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + gemm_store(acc, D, ldd, rows, cols, home); + } else { + gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + if (rows > 0 && cols > 0) { + gemm_store(acc, D, ldd, rows, cols, home); + } + } +} + +} // namespace tfp + +// Score products stay a full fp32 dot so an M5 does not cut an fp32 operand to 10 mantissa bits. +template +inline void ik2_f32_dot(const device float* A, const device float* B, const device int* P, device float* D, uint3 tid) { + const int col = int(tid.x), row = int(tid.y), b = int(tid.z); + const int m = P[0], n = P[1], K = P[2]; + if (col >= n || row >= m) return; + const int lda = P[3], ldb = P[4], ldd = P[5], sa = P[10], sb = P[11], sd = P[12]; + const device float* a = A + long(b) * sa + long(row) * lda; + const device float* brow = B + long(b) * sb; + float s = 0; + for (int k = 0; k < K; ++k) { + s = fma(a[k], NT ? brow[long(col) * ldb + k] : brow[long(k) * ldb + col], s); + } + D[long(b) * sd + long(row) * ldd + col] = s; +} + +#define IK2_F32_DOT(NAME, NT) \ + [[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \ + const device float* A [[buffer(0)]], const device float* B [[buffer(1)]], \ + const device int* P [[buffer(2)]], device float* D [[buffer(3)]], uint3 tid [[thread_position_in_grid]]) { \ + ik2_f32_dot(A, B, P, D, tid); \ + } + + +#define IK2_GEMM_OUT(NAME, T, O, TB, AM, AN) \ + [[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \ + const device T* A [[buffer(0)]], const device T* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \ + device O* D [[buffer(3)]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + tfp::gemm_out(A, B, D, P, tg, sg, lane); \ + } + +// bf16 x w^T, bf16 out: the projections without a bias (one rounding of the fp32 sums) +TF_GEMM_NAX_KERNEL(ik2_gemm_bf16_nt_00, bfloat16_t, false, true, false, false) +TF_GEMM_NAX_KERNEL(ik2_gemm_bf16_nt_01, bfloat16_t, false, true, false, true) +TF_GEMM_NAX_KERNEL(ik2_gemm_bf16_nt_10, bfloat16_t, false, true, true, false) +TF_GEMM_NAX_KERNEL(ik2_gemm_bf16_nt_11, bfloat16_t, false, true, true, true) +// bf16 x w^T, fp32 out: the tower's projections with a bias, which an epilogue adds before its one rounding +IK2_GEMM_OUT(ik2_gemm_bf16f_nt_00, bfloat16_t, float, true, false, false) +IK2_GEMM_OUT(ik2_gemm_bf16f_nt_01, bfloat16_t, float, true, false, true) +IK2_GEMM_OUT(ik2_gemm_bf16f_nt_10, bfloat16_t, float, true, true, false) +IK2_GEMM_OUT(ik2_gemm_bf16f_nt_11, bfloat16_t, float, true, true, true) +// q k^T and p v, full fp32. The four edge names stay so the existing pipeline table still resolves. +IK2_F32_DOT(ik2_gemm_f32_nt_00, true) +IK2_F32_DOT(ik2_gemm_f32_nt_01, true) +IK2_F32_DOT(ik2_gemm_f32_nt_10, true) +IK2_F32_DOT(ik2_gemm_f32_nt_11, true) +IK2_F32_DOT(ik2_gemm_f32_nn_00, false) +IK2_F32_DOT(ik2_gemm_f32_nn_01, false) +IK2_F32_DOT(ik2_gemm_f32_nn_10, false) +IK2_F32_DOT(ik2_gemm_f32_nn_11, false) + +#ifdef TF_SIMD_FRAGS +// y = x w^T for at most 8 rows without tensor units: one 8x8x8 MMA per K octet in order, the tile GEMM's bits. +[[max_total_threads_per_threadgroup(32)]] [[kernel]] void ik2_gemm_bf16_nt_rows( + const device bfloat* A [[buffer(0)]], const device bfloat* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], + device bfloat* D [[buffer(3)]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + const int m = P[0], K = P[2], lda = P[3], ldb = P[4], ldd = P[5]; + const int col = int(tg.x) * 16; + const uint qid = lane >> 2u; + const uint fm = (qid & 4u) + ((lane >> 1u) & 3u); + const uint fn = (qid & 2u) * 2u + (lane & 1u) * 2u; + const bool live = int(fm) < m; + const device bfloat* a = A + long(fm) * lda + fn; + const device bfloat* b0 = B + long(col) * ldb; + const device bfloat* b1 = b0 + 8 * long(ldb); + simdgroup_matrix acc0(0.0f), acc1(0.0f); +#pragma clang loop unroll_count(8) + for (int k = 0; k < K; k += 8) { + simdgroup_matrix fa, fb0, fb1; + fa.thread_elements()[0] = live ? a[k] : bfloat(0.0f); + fa.thread_elements()[1] = live ? a[k + 1] : bfloat(0.0f); + simdgroup_load(fb0, b0 + k, ldb, ulong2(0, 0), true); + simdgroup_load(fb1, b1 + k, ldb, ulong2(0, 0), true); + simdgroup_multiply_accumulate(acc0, fa, fb0, acc0); + simdgroup_multiply_accumulate(acc1, fa, fb1, acc1); + } + if (!live) return; + device bfloat* d = D + long(fm) * ldd + col + fn; + d[0] = bfloat(acc0.thread_elements()[0]); + d[1] = bfloat(acc0.thread_elements()[1]); + d[8] = bfloat(acc1.thread_elements()[0]); + d[9] = bfloat(acc1.thread_elements()[1]); +} +#endif diff --git a/zig/kernels/metal/inkling2/vision_sources.zig b/zig/kernels/metal/inkling2/vision_sources.zig new file mode 100644 index 00000000000..66b3903c5d1 --- /dev/null +++ b/zig/kernels/metal/inkling2/vision_sources.zig @@ -0,0 +1,4 @@ +//! Inkling 2's image tower: the prefill GEMM template, the towers' shared glue, the tower's GEMMs and its glue kernels. + +pub const vision = @embedFile("../prefill/gemm_nax.metal") ++ @embedFile("../prefill/gemm_nax_kernel.metal") ++ + @embedFile("../prefill/vision_glue.metal") ++ @embedFile("vision_gemm.metal") ++ @embedFile("vision.metal"); diff --git a/zig/kernels/metal/inkling2_sources.zig b/zig/kernels/metal/inkling2_sources.zig index f105ac0f3a2..bacce257281 100644 --- a/zig/kernels/metal/inkling2_sources.zig +++ b/zig/kernels/metal/inkling2_sources.zig @@ -8,3 +8,4 @@ pub const experts = @import("inkling2/experts_sources.zig").experts; pub const loop = @import("inkling2/loop_sources.zig").loop; pub const runtime = @import("inkling2/runtime_sources.zig").runtime; pub const inkling2_dspark = @import("inkling2/dspark_sources.zig").dspark; +pub const vision = @import("inkling2/vision_sources.zig").vision; diff --git a/zig/src/core/contract/inkling2_vision_metal_records.zig b/zig/src/core/contract/inkling2_vision_metal_records.zig new file mode 100644 index 00000000000..e138ef675b3 --- /dev/null +++ b/zig/src/core/contract/inkling2_vision_metal_records.zig @@ -0,0 +1,41 @@ +//! Inkling 2 Mini image-tower launches (zig/kernels/metal/inkling2/vision*.metal). +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +const reduce = std.mem.alignForward(u32, 4 * 33, 16); +const gemm_kinds = [_][]const u8{ "bf16_nt", "bf16f_nt", "f32_nt", "f32_nn" }; + +const kernels = [_]M{ + .{ .name = "metal inkling2 vision ik2v_pack", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_embed", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_layer_norm", .threads = 256, .tg_memory = reduce, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_qkv", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_softmax", .threads = 256, .tg_memory = reduce, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_heads", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_bias_gelu", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_gelu_rows", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 vision ik2v_residual", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; + +pub const records = blk: { + var out: [kernels.len + gemm_kinds.len * 4 + 1]M = undefined; + for (kernels, 0..) |k, i| out[i] = k; + var at: usize = kernels.len; + for (gemm_kinds) |kind| for (0..2) |m| for (0..2) |n| { + out[at] = .{ + .name = std.fmt.comptimePrint("metal inkling2 vision ik2_gemm_{s}_{d}{d}", .{ kind, m, n }), + .threads = 256, + .tg_memory = 0, + .reserved = 256, + .offline = false, + }; + at += 1; + }; + // Without tensor units the small-row GEMM runs on 8x8 matrices, one simdgroup a threadgroup. + out[at] = .{ .name = "metal inkling2 vision ik2_gemm_bf16_nt_rows", .threads = 32, .tg_memory = 0, .reserved = 32, .offline = false }; + break :blk out; +}; + +test "Inkling 2 Mini image-tower launch declarations fit all Apple families" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 8389f3ec6ec..1ebc696fe43 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -112,6 +112,7 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("inkling2_loop_metal_records.zig").records ++ @import("inkling2_runtime_metal_records.zig").records ++ @import("inkling2_dspark_metal_records.zig").records ++ + @import("inkling2_vision_metal_records.zig").records ++ @import("flint_records.zig").records ++ @import("hy4_records.zig").metal ++ @import("uocr_records.zig").records ++ @@ -163,4 +164,5 @@ test { _ = @import("inkling2_runtime_metal_records.zig"); _ = @import("inkling2_dspark_metal_records.zig"); _ = @import("h3_image_cuda_records.zig"); + _ = @import("inkling2_vision_metal_records.zig"); } diff --git a/zig/src/families/inkling2/config.zig b/zig/src/families/inkling2/config.zig index 9d30527e4d8..07f3330fc2e 100644 --- a/zig/src/families/inkling2/config.zig +++ b/zig/src/families/inkling2/config.zig @@ -116,6 +116,7 @@ pub const Vision = struct { mlp_ratio: u32, proj_hidden: u32, text_hidden: u32, + eps: f32, // layer_norm_eps }; pub const Config = struct { @@ -333,6 +334,7 @@ fn parseVision(o: std.json.ObjectMap, text_hidden: u32, why: *Why) !Vision { return error.Layout; } v.mlp_ratio = @intFromFloat(ratio); + v.eps = if (o.contains("layer_norm_eps")) try float(o, "layer_norm_eps", why) else 1e-5; try fixed(o, "projector_bias", false, why); return v; } diff --git a/zig/src/families/inkling2/config_test.zig b/zig/src/families/inkling2/config_test.zig index a8ad85ab3c7..35183588702 100644 --- a/zig/src/families/inkling2/config_test.zig +++ b/zig/src/families/inkling2/config_test.zig @@ -64,6 +64,7 @@ test "Inkling 2 Mini's config.json parses: 24 weight layers, 48 visits and four try t.expectEqual(@as(u32, 3), loop.passes); try t.expectEqual(@as(u32, 64), loop.gate_rank); try t.expectEqual(@as(u32, 2304), c.vision.text_hidden); + try t.expectEqual(@as(f32, 1e-5), c.vision.eps); const m = c.mtp.?; try t.expectEqual(@as(u32, 3), m.layers); try t.expectEqual(@as(u32, 9216), m.inter); diff --git a/zig/src/families/inkling2/fixtures/media_photo.jpg b/zig/src/families/inkling2/fixtures/media_photo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7c44db9f3239dba245948fc282f94cf3f9512228 GIT binary patch literal 1835 zcmbW1c~sI_8^?bLh=>~sX4+_@m^!{$E@3Xcjx8E=)B`Sz<}z(6HAAkTB$CyXxlS16 zQpYAC%{3j%ObpXeLsP>IK{G9v%u>wMz=ao^IrEWiyn5CVKA^2|%g=#(*6dgalNO zATSc7_yaIe`hOIip-gzF1E_$&U=;{>)3q|2q1*=`NT}|&w(hEW zgkvz%Xp~*bwcpgt_E$ec6NOTY{qdL!aCQAH23rlycUV|jedn+T>$um+`M|+L9-fDB zcwayN0MZYEK_^b03Xg~+pN@@-r_vG<=@&2ka`{T?)ihSlb@q*$xq10_i#XhS#U=Mk zYkseN_^9r2{gdXFKU&+`p9?yA`}zk4MMGlA_?x#AlT*|0X5KG+TKv4Uyz)gR-{b-T z;6JgH>z`o%!KG{hNCg4`LtvX+AQhT&f{_sDx3;Rf?gZGeXgyQA6gAZTYrj=LgPYkC zrRd`^LUnzN!?^jvCfZlB{|@ZJ|3&sU*uS|XfCd<(ygV=xa09+*qL`85up^bsP4~6g9}_d`i2ZCrKn3`!v)U+DQ4hes<|6Fg8i(yJv+~14 zXwbEN-?@Z0ic&jkI!bTY@qUyvay~{jR7R{-#{`!WR}%9xN4Ths7I<#=>4pB6Ax^w` zn_djd^s&wRrU`kBX0m%>!foGK-j3oN#{WQ|$SU{&5Ve#=8So)?VaxuyfYh z%Ad+K!}mO6jq>yM+SSj!ddil0nBH@7Eni5?^b9DPwK%skgeAs|UJcyopZ)Sd;&rmQ zL1b0~UTTcZ-euN@{+t^Ot@p2dQne`C@Dz>5hS}c@18Ekm9N;qccd}Nk=l2a1kn5+h zp&Drev?JAMQgl!7$z;a&RsGg}O{W|t!?p(O&Nx0XH}E0fi_3dz*(PwL8O&n}zr4Qq zf=l4)9a-I8{xkZC<#9Dk($MozcNn-VuE#oz9c_{7%{I*4R>j7(;c8|1Q<*z%MZim1 zE9up|5WiwCazwmbKP0t*Sg`SMuF-`O+{Z&=RvqUUcfOl*YWfCPu4*ar(aV}hNUJF{ zC1l%Egjqro{m?!ZJmE+-f>S7Vl!~Cpw5qVPW%(2^tOw&V8di0@vyX3!fkfF_7MO|{`qdH{cRU@ zL6w#p9qw#!D>Ti@vNg$8Xys6`%$;|6B@t4BOB8@{&03PBhcLp2lc3F3-9=$1CWp$3 zRQa8KYpW*YO^i;w6mGU?U>}CEW-!_@9Im&fxF^4t>@eAB?2$v1P;e4m!lgd9 z15E+JWs)PLVL9{48}iJkI*Y0?J~HiQYw?ol9(HqA#gyLiz2j++%-UlQfj(GnYE z4c$J2L?-$5=YQBZwRM?2=w16p&5Yf4W;Uvxp6=CX!|##z%SUWZ+1KZIg#y}z0nv~F=br`Fp#a^Z z2mh=9|Fi($xd|4!01>_b0K@@d8Eo0AKt8 zVgUs!0|qk*3m^{(FBAb=8U{-q4KE`KODP9lE(lXJ2v<4@SUm@MLkwq03vf;eep3dD zSO||>36fp{p=Jo0atp9^2E=p*wSfT9ga)#W2F;TP zH3||y4-!cg4_6xyUmy};BobyQ5?d`2VKonaIudm~6L~@sib)QnPZE<;5vfrRlU^E; zU=gTi5vFns*>MNkeiqAn5%+)=(ufZ4ixJC^3iY26|ECo8qzd+^79gq=1Fj1kwG1o0 z6E4ISH^&i9#t|^k5<=4vPT3D(-V;;g5?$*RQSuOg^$w2v4~zW~j{zGp1RO#N8dVS* zQ579a8yjUH7lI@if+-wsFBye48IL>~l06roK^v7w9G6ZPvs56QQxwBq9k*c~tY#L` zZXmR78pw7T?syp7gBjn96VQq(0*D&~j~fn^8w{2g1gI7nt`;J+8y&bBF}V_Iy&x;Z z8$`+-InWwY(-~se8erZVVdNQW>K$V77>)E9kNO#t{2G@69bg0@TM8vo5F=X^A!`~V zXdoqLBO`q&A&4&{g*PIbJRhq)CXzxYl1L<=PbHyJ9miZG!&@P=UmVM3AKh*%#&jp~ zY9h>eC)9@?|Bn~hjVTe1Apn>j8>1o|s3r`jARVqEEwm&*wkj>RBSpL>F~lKG&LLLP zC0*4bcG@Lu;30wMBy;N}bnzpI^(2h=B9Z+ilmRMM1uI$$Dr*lZb`&ae8Y^=jEPEm? zeJCz?E-9ZiE1o+np+79DLn^~cExS-F##AWBTPo9BC(Uav<7_M8Wgy>kD*t#e{(mj} zg(m!iI5L7R0*fRllq?UNFA}3CL8UJxsw_IMEjP0&Shy`$zAaeCDqYMfT+%LK)+vJA zD}~@Fn&vHg>MeoqEr#rZ7gPI60{=Vy`qtwlZY8Hf6v#YQ;2p$~1G(HFwiBg4r~a-!qlt zHIC^tmG3o}^E0aXGQ<2e#sD~R13YO6J#!B{fD}A|89j#|Jenjts3|?JE;_U`J)bu` zu{=MrLOjq(Kf+8u!cslrTRrt+HUCvb31316c`WR9N*ioD9e+O)h&~~SKM;#O8ILp8LV zJ+k&cwfQ`~`#!$_NPz}Pj|NC+4n>#|MwS{)j~+$5AxE4nMx`f1r#(i`IZ@R&M8-Qz z*h)g}O-0X1NeOK||8G6^TuT*WN(ya8DQ`*ubww|JMm2*)IEh9xi$p+=NH&s2Mwv)N zpGHWhM^maocd<%cwnB-#Ms~qQf5u36$wQpfMVHh?d*4N++d!P^P^RNXq3=n#@<_Ay zO1=I^;Q&mB1W$<)QL+?JrV>t<8BVqwOt2?T%`Z^VD^#!~M#M8r-9}98PD;~XOyovY z083B+SXl{LQ5IZH3~5voZciC+N)>uiA$(9Rfle=oO+AcIIFLb%pLS`ULU;s;8Fjr&<%XmONid7Nx$plE}pXOgRHkg#f;wP>unX{o?#q{U{! z$ZN97X28~H;n!}%*=6MDbm8e~{_kk%{%`I3Ya;t(F92@I33|#1Z`2cX8J$WHaXCzB}BUN-RQ*ba@aW!IbQfF~lZFEavPa!^w5Z z({<(9ZS>x1>F;pk>3tjLZvgaa5%+ii`E~#RebNbh^9Fa<5q{7SZT>2K{~>7fAc+Vr zeE&9i`zL$=G=Dledm%l0N>6z?Qg$v@e?wG&DOh|yV}4UBjeUKRcdVCtq@R1KqjU{s~dHC&W?C*Xc_<{iXd?^2Y9{_^Y2#44VgVzpx+XR#VCVcZ4hzcKr6C;EjFMuI2 zi8VTX3_FY_On^W{hCED#Hcx*=SB5@bgJNQVVrPR}Zh>obglc+*czlI)frE93gn5jC zk&uRkmV=+2gQlW{s;GpptANn4g~GRn$hv{w!hz?-g6qhH=iPGj(2NDriUjI+?%aqN z<%<*Sh5++^75ae||9nRPj^qG~;Te?t6n*FslK>r)2^xeICXW~?jtVZ0BQ%USIEy(w zia11zM@o!NON~WSiB(sQOI(d!VvA{Kigas@YH^Hxc8rO9i-v-Tgp`Z6kc*OzhqIB6 zm!FKzp^LAnjmo8sv8#-@xQpn+nBcvM)5wS6%ZlXDgYepk=+T-A>U;j;j3w}pD)EsC z`i(pHjXC>{JOr2i2#)^>i0%rX5D$|a8JGhgl@lY4LM)RgFqbSgmpD6=KtPp1MV3iR zm0C`dW>u9~S(0yEmuF;@dTEw-Zj+33mW6ken0}juev*lblBtT3qmY)kk(Ilim(8M) z->s6@tdZ8Vr_!yF<-dmKw4DOTk^jn>^~swQ(w`2>kpkkJBj1w=>X#Spkumj>PWzKo z{+3q=o9Pjr?g6J62A>lXpBNUK4kVv7BB2y1oHQ?=JvE^`IiE>BomoYoQ%j&+O`CyK zo@-d2b6%Z@W1od-pn-0kmvoz~cc7Ydo1lWCuY{wNlA_j&ps|*t+LoTepr7TYoyx18 z*1C`Dv!)!ur1rg^>CmG3$({bxm^Rs)G}f9GjI-2*sJw`z%!#ACnX1^Fr0=7t<&>}XtE}v^to*p9 z*uA40zMd7wts=~%5!t3Q+NUSosUhT}Q|F{f>7iBas6g3b4sm{PqTkiu8LT(gI%(VVyvrY zvXpJErgE^ab+ER0sg&SvP9~!K=7_u^Rq?%t$6>hdI7aK1-K{)wLJ^7EEl*p z9=TK-x-2ENcPqJ7EwyVfw`e)MTs^yIM7MrOwvkP@pi{P&Sh$^Bxtd|Os%EygY`Cs* zyQ*}z%7VGgh{4Q-xXqlu^_QybioF1gw+5HR0;jV7uD&0(wI{c@6~DJAx3wh7z&hBk zG0(S6(6&d~yHDJ>SmeA)?Ydv_u95e+bNjb${kd=h$2S7NLJGt^3%*Gb!Z{qoQyjxl zB*kYc!)YwNgfPK!H^*i@!h=D;iAchcO}@HQzp_`usa(LqVZys-z{YIDyK=zPb;Hkm zyzGO@(0aPnmBIdp$P$Xe0h-JUthV#7y&|l}4X?oowzfXK&=$GF6~n$r!O1_-zE{x1 zG}yvj+rw4hzhLabcI>`s^2K2Iz;*k>tIQ>@$O^m5M6%5wxyVt-#9-LNPS?#k*TiVt%~s#Y zdg01o@6CM5TM&Nn$Z-d(lx2nFR#)-x7902(+g}jdW)t0K7u$6o+<+z9kSW@XGTWp#*ta^>!#~)@ zMA^ki+rdrR(N*BdSKQ-U+~Hc>(qrD^Y2M{`;qQFf{CD09dD;HeZ`0gm*4cvG-GAcTj^)~z?A(v=+nn{= zqWasV{M)Vo0r;i)g>m^SE~I^?rF@e<*@wZ zv;ggO1nqYU>wypKjT7&W7woDZ?xrQ{xG3$WEbW{$@1QyE!8+;WK<~~=?%7f6-&gME zWAE-#_6cg>(qr--arG~8^bl|A6@2R>f$kTI=|hh1BarPqkn1j)?KPq9Jf`qbsP0#+ z?OU_#XSwQizU*+s?rzELi_z_d)#|6&@Ri)~o8juS=Ig2L?XmOh!20dL{O-X3`GE!a zgbVnF5BQ4{_nsO1nIHGACHSc+{iZJT!8Y^NI{D2x`prT9$W8J4QS0ek^5$ml{8I7^ zY5N{w?gDZ0BzW~5eEa}?^)r6-CW-V!it;;?_*9ViFP!>LpY>d(_H(H9bFKJiwE1hg z_I$qfdBygL$@8hv_mtK2vDx~c-ubBF^u*})yYKkF^!LpB_0jzI&jSCI1^${1{+AH{ znH2o88vmXk{kkRps4M^IFZtg(`sF+S%s2kmLI34U`_fGR2}u75Q~w@U{S#*Y7i<3{ zZ2t;%{~vVsFMj_*g8nv${W6aINt69sm;Yj%{%NBBa;g7utNnkk|9ZFlkGuPu!TpQI m{*TN4q0{@K)%~T}|ES;n!R7wN?ElE}{Mz>a$^HD^{r%a|8MOrf literal 0 HcmV?d00001 diff --git a/zig/src/families/inkling2/fixtures/media_rgb.png b/zig/src/families/inkling2/fixtures/media_rgb.png new file mode 100644 index 0000000000000000000000000000000000000000..bd9c15dceb6112ff78dd47a96dd1def64af447b0 GIT binary patch literal 2128 zcmV-W2(R~vP)a!{{LT@>MFZ1n*f0pw9p@NPQ*092SPzAGtYU~ zTjD5bCNH^GvP^opVUlvaL^8|eNjKTey(EiVKRHUqxnZ)Ke9v7at6U{nB$v78M6$|V zCy%+k|DP8Iu@LVnl-)D-vz)xu!{%Dhs;Qs57C)jB`F%FsI3Y z0f`&7c;Y;hdX!l5J3slI@6Mn6D!)Jq``zPWjZ8EtOH^@cSvWV<9$C&i|&8Sp}#XTEUHaX=^0E8csX9UA;#pAu(0(&e2Y zEij}@&XjjL9MU1D#T{>a;SWADVa6dp7&507j9Ag4ok?w0EIFdgg8ydBkPkkwWWgzA z5>Jdc=bRh*^hrF%ABR*pBqHonlyOek}fyYnNwmIAYD;nLy1}@{Yr;dFlR`OEt<@E=9&c)F1ZcL9rGGbw&9&? z##~X3$L-Jxgx45w&jIf&dCw%w$m#gMp9$BLV+CW*_{I*2ISrm-28H6DFyV+bOJACc4Mdr19?EyiSQbIUvXO!(l6XSV1t=ZF{f ziXF4XimZ6=CC^;Z3l9*R$OG# z6*FE#99qmd;FTRZJjE~zSJ*IQho^9tIf)JfmLyI|ECYaTaKH{P^vH|%-sL`|^eOzH z#UAZgXMww7yIZ``R;;P;$Qc{nC~?4sO~J7R+m!exhis8}q0bwi zXwcw@Du42o2l^qdN8IoW^Z%sZJ1r($@k+)iQ>v6X&7=Wys$B6wgCPq}*wCj&;yq^j zOMqZPg`5d}I!yV@k|96XWzOdaDklM#B0Ee9tXHfUNSyPrB?=q0EpC*UWh(=ao8HB$k3*YkuRE zCI6(xEgJ^Ky$k;@#&rz7kW=K>Pcey6TvOqOGybN_m|vK&pu|2u*=EKu8~$cHIPw?~ zs6{uE7Hq{^4iVp2Xx54;J&q|{XHAQDe&>U|xLGk+yoELt%6Q681OH)IcHYb zJM#cYJ+$d(2*4gC-Z-Wd2r4pX5d|)JrOaK>{ScJMio8~*%>{q4&432NbH4E&L9qy< zMO3ZR={&KKu#WE<#sxi|sL+U9yog-8;Uwl%sP~W)7SY+JfsAJK%U#yIFvz5WS2y$m@T1^& zQM!tk%jidj!C_?hXIg9rHp}Fpj3xFs<}TX8PPoGf+nH2EgF{8yvI6c)TxKEc34toMw63Z)Nbtfo>EBqhAu<; z;4v(55W4ihuax6#VN+;JnH?%2GId@!k1({1^s^Vmq8e;I2yxAM5AY9IP-94&2U=94 zq3!cO{K0OKTec}vjXGZtsT4Sv#O_O6gtHxoEfxXc2la5R28Ya~Arr?lc&W)>nphzgf;N{2r)`I_@MOxlm*l!EKK zOldNT{XI~j%@J8R=9oHX-13<}qP!i3a}->-U=l=Fa`|uWjE2-=XT@~@0000$|ID=ZJr4kk1cAFD;C4BHz`!UKFcASB zMuC|a;LrmO17I})b^=&n1>Ud&ekZWV4J`KpQ9rPT1m2^7y)+OF0bhiHLKI-*Kt2ha zOan)z%A#{w5i!08HbjRSt>f%6SO(E{KOaGL=9Nd&YKFbV+GAUFa7m2%JwgHu(Y z1pyyH!RIj0r3YOGkTikI32>Pe^xMHTPLOefyc* znFLRzK|Tw9lL!A`!T*)OZUq!L@J1fIr2*d50!Ma0L;ztCoG5{h0njKAGD6UJIrLW; znxcXX2=qJ(EyAFe^^n^DEjK~05zwnvXuTa;>x5EnXuB8smmhkMgubAlf6)*df<6gD z%_wv{4joQHXVcJ6SxC%79TvJ=f(BQhyEy1h9=fRksaw$K4ulDiMuf}~WCCR4LD^%F zY=&Ic1IwH$*<*<8RaEB2WQ+AO(jZ%5k}-trU8^i%m&Kj3j9a$PD@*ugB~o^jk{zLC zwUF#^Sau;QI~$k%nw0&RmUXkT3whZvR(4ZK*1saVos*5>W%o8@#+J<7k!b}PF3KK| zWDY>_AgHiFis^EN4_3@kDV8G&7piyxQ!LgiXoF&#NwI-YY_Td*cEtxyMcl1my^6A5 zagbCTpcKbx#o3VJd{}Wcs<;$a07=EoX~nRt;0S`Y@*_6NwEY_nnC3}NV!0+^utP@O6f(EOHk!TOu0#~++W z@_<`e@+!-IWgn^hnNog3D=&nU{lm%uQ6(5xUP&qkrT_ZB<*2%UTsXEG4 zTvAV{sGsE2GkNtB4fT^P_56<7A*f#v)qY965YQ|EH9knQRIXVEYhG1p7(|mmHCr&v zCcWk}gJ!o$^97+fX4Mqznj=ol4{pt2ujaI0^DU|Qoznb5Yc7Q}zlAkJqng{|no&v3 zpVJycR@0N$AgpG5Nn@{QW^tP5dChYTjk~2;)X}^oXx54vQqpV&w6B5MAf%<_+7+<& zBb7FTXx~S*J1}jpUfXBT?l);aCA42#wVYl1U#IpbxAu3hw(Hl5r1lb}?MG_|hO~pj z+Iyqg`{UZ4q;`5*J3XtNoY&4`wa=Bbvn$%CIPGj+yS$-Y(9*u$(XJ7+8$~T8X+H#X zK~UEV>9)#sJ7FE8((Ocaaa4B*)9usi>IPlOq&rUNPFZ!Q?7B-%-3@NtP_M3^Uw4hv zfs}3}t-B|ryDzNkiR#A1b(*Bkn$}@i-BWqpOjc(v>0Ykr=5V?NylzQDx1^<8+0ikA zZoQ}rO1ggm_+}7)55gmI{Bs!JrNXx(IEUibuUqkJcKmlIKE#b* z^Wri;t|aks6n-;}PYB@;h4C3t9F5}-Ch@1z_^d4M$m2d1cb0H}1z*A8>v=rVz~5}) zn>zRg0ndo|rxLy&For?nhmdin-1s?c{90u^iWuvtu@5u;s5f>E#)~GSNEnA&jl=9l zz-b)hHp;!m5q{&Xq!Ff!chSb4kkJ%2TBF9l#Ep+6jSr`di?YVo^2X;_ni3DXI{^nw>He_mU(l>{IOu(C7N@R`2b+~473y>%a?LX4Yt%&mXnC(Th!7Y zv)rJ!fCh_Xviwe1R94Fvy9IMvM!PL{crD}nmhq%z5@mUUw#*7yh_J;QwK(GzZ_*M- zTNY<6FXb)kSj(o8WlP2KHfM?OmK_ZX+p>J#vHVl8d?H#tl`O{r+ab`_glwnewqvmE zHqfTddF~sW2DJ(FX0$#b=+fjU{1$Ox8n(~<59okVbWoz z9J6W1ijZSv*s(h5SP^%uO*)pP9kHzAA9+WVb!;v3CX#=TD;NCdo4t@cj<@EV1zG ze7MQ?IN^KR>YHQt1)RR6ZlA;JTkZEPA$_kS=_sqSOM6TA-(%Fi=ht^?w9KS*eY7>MbX=(oL=MQoVkPA*l>S?VzboL)6hQ zbtFptH%>K@)TuOeB1`?0rv#SjSE2@1D3PPC^3l-dl%9jpPwQ!yfnH#ug9N?IO0TffAt$}vO@HL2clznQB%P(`qcmL( z(FenHUzF~P)6FE^O4HwG>FarV7)#$+q6b#!F&qu^^oR!iK#QK*p)~@1w@6QsXe$tW z5)Af0L0lf33J2$^f^(7J5;V9B3$D}$Uo-^Qnu6~V!By7a7JG2BGx&)+Snviv@COf* z!M#+lK?m7T@TYLF84Z3L51vW}rF8IYHh6PBIFJpFE(J$bf)E!R#Rn%gg1T04LMNyd zg18toOFMGidl*u%~0%I4MMH1ryB9DU+4-|P;9wFh#%c{r_HQ~ zSfZd$>@g$`n-X6UiBGKw&Yn2tOq_BjI^M*u{zR8dKvd!vI`La50frOmXhIoJ+?h<= zpHAG9O-#xsjBH{`DPgN5Y+PaFMxDbAYW?5QKp)D?H?nm0ATpSnz@1S&OxPANmFA>q_r z(bTwjYD_XUF`arMnnHZe;OqJP*WOk#OkFiWapD7zMbyKEAWG-1Vzt}V9oSC29nE~F+&Hl_)GBb$E z45u@rLzxG{86=t+70*mgX7F@oRyH#~pIOLe{H2Vwl5ugFHGF1OBlCJI^Li)qrjY3s zGjS>NE|B{NnA-#8w#sw+;M{Ii?mtNGOEmWlmitbhJ7mcHYRa7;avf`~WzYTU%w2Tn zu6uL+{kaij4xw`Q(z&sr+=OuM;b?9~JU2U;o0`r&lg)YZx%q6)Tgtsy$-Twpe0*+s zBe%Sj+tA6yg?!s_y;TC^kELlLQ!b5anQmCL07oLn3o{1Ms$-=Yg!qRMk%oj+uu)0)u zy;4}t72e|uOr!9As}S!Lb_s=pVxcS*ia;?97E@61OL_4#xL8va&mhI`(c*Vlk=GY5 z8j8P}ikFDub!&0By?CdysBjm@c#B$paXeX^L=_*Wi>6S~9xl#^7GH=LpGg*9N*Cv6 zi@to3VT<8XF;pqO%N5_|iyIon?XBYePBAYOKNgD>saOKayTLLCm5<8HeQ^1ls(c11 z|ALmASowm!{D+|on##8lWzbq4Y%kyLEKhNlM|;cT{AH9ZPol~ey6g^>p9_~4M$50p z%f4iJRl2+`TV9hdGi*6pDzB-O-{;C(_;RvQ-rXwi@05=U<-=l`mC77YJpfi)Q1!69 z`W;+ttEw%eItZ=)fmMg-t3wUd0jBC`q6%B9Bkk1*&gwnx>Qrxas=xXSS)EB$pQEdP z4OO2HSE*=qO}x4`SzVW|Zpv2Q&sW#7)h(s!)=HJ-swuvDq){!ls(h#Vy-?-EYD21C z1ZtWM^%byY{HJHqBpq zn5;cP)m(JV9jf`lwbjwu8}ZtzWNmf27S7fp`PvS)_CcxkNu_p>tL@=yeT~{zt=iX} zT1}{36>I0E+CZTGGgxmy_3QGw2-g*=`W;AJh1SPmbx2>=8tV6$>RO_1wAL|ueX_G| za@QAn>o5B2PO|Qz>TBrw%20h-xc*MG9*Ng`ll2Yh`g_^>-h92p*8g3q@2b>GT)o2A zk2mVwR=v}yUl-~>iuJQneHhTZ0c`#OHT%h%L*ZtBRdXoP9Dz0`Va%^pKjZ)#2< zntE%q$KIUlY|e2v=Xsk;{mq4Ba~aiKLN{LtHJ68*tE0_OytzHu+>vhPv(0?I`7zu4 zxYRseX`bbpXZhxjjpnzl<_(=DC^S1_^M6tk0@?$?HUPD6mA7HIJyF#jgS020Z3Ju2 z(6@0z`%zQ-VWR!4wQaMvUv;*hceh{nwpaPv%gOd?s=bMB$3yKs;dUqySqZ&bh!Io zw401~v&n8T-94V|p2>F`Z1-5Hd$rO%&vno9-Cr8rtF5lo>B2&Hyx3Jp-LZghCn($o z37A~a!NNq9Fc}eMpn?+<7U+c;24S&Dc#ROAwF+<9g|$v$gIn0_6*l{YUQ*ab37cqv z4GCX_g;Z21#DzvuIFS|(Wrd4*;T$VmC<%ir!evgl#0!dsa7RlR))7!aP>RB2N$3H@ z2SHHz;%vP*#~^x4;(S63SjBhj;&P`Laf@5M;s(F?At`=N zi5Xhl8xm__@yn=Kj*CZ=Vm&RM%Zfl=?9Yn*OXAgvDC5Ktyg0TY-qsRt>4=yh8bt9i zNz?+;WKc3f(*1JjAy|4=B`rdvxv2CaCN0!UD-F_8leCJEwpgWYc4?baTIZIwc%@#y zR3fEAlvJaouS3#-uvCdk=i?Hel%%xO%t|-qC4rTOm89zx=@w4<6EFR_Ax&vX6FL$i MNVq7OC27w811+*Wi~s-t literal 0 HcmV?d00001 diff --git a/zig/src/families/inkling2/fixtures/media_rgba.png b/zig/src/families/inkling2/fixtures/media_rgba.png new file mode 100644 index 0000000000000000000000000000000000000000..375ff1709c03d490722409afb6c02148d8470d44 GIT binary patch literal 2312 zcmV+j3HSDiP) zi2UMO-YZEHA=qG;)s$FC1XmKC@KDEvDGbEs!N7-$x63mwQh0IEjg)6 zZtId^x1?XU=yyw|bxETx=~FVIMT3$qC2uIHD4EdW&hImyeOgqM6#ibOWRVs#O7_L~ zost#>)h)0AG=WRt2mH7-Dh-m=qsMn;RT5%Gb;Mv~;m9I5A65O8xTocGL@KWanunN?`0??qK+I5nF0Dl2K$>{SO@FU;?_+4N#nOfJ_ z52JJ7*i_bj75EF~7J-RCHU!ht`A49oe$RP-*VaUb8WdE^f;gTF?`z=JkZb~9RN52B zGw{Z673#H()MwyCF!wUm7i_TjEVxR!MI9=QPLuR^1Y8-7Yf_4?QBc(?-_C{jSfdLn z9{{`lt~L6@u(p7G*;sbcXW&8bpVXf!d##PB`cqkd(CJe_cAR_9Xg*5R4+^SKzSiRq zs7QHsL@LBH;GN#i=47`7GnpIfl2hnJxsd5;w=KAl<9&gzlOlX70XK7mOn_qwsuQ5u zg|dcj7j|n{=)$;$jT&0rH2L2Qb*v7R6R!IGM(19T(q@~K9xt41S^W_y{mu>jTgRV* zuttjFq2qs-gtkr%DX0okf%Ro=AVVtxTqUJV6kaXs&%S>$j4%DZBfw2rJ#xII1Lrze zE3-%{;A>Kvh4Wz}Qn2g01_f1AZcM(Thf6ZGNG__5a?5(YOJ0f))Ri`3bvRSDmgNqq z;38s?=dT=l(Ei8>E&<<+-YT$4K{XWEI~k9SWeWU@w78!;elDOpBNN42IaV0XGe58A z7~9dYio6`&Ny099f7mBQbwoaEJLne^wFe%45Hj)4JbHFyL*&N1%bm65pB*&S`hT7Br80lwu23fdEL#SS#EuW~GJ`!cd%h|cuBH)n8z zl#d}-$?QbHv9^~wb>TA#bw@c!^;G%0M=H#4`~?No`rN=FDR(C_f@Al7`cAe>-eeZ$ zoY|4Nma;8U$fE_gR&E0PLnrUaZ9;4^WA&HR8yT5) z^j*jI11F2M`%)*q`)&*zHB!CY_`a_bO>OQ0pJxe6VA>_6P7C1(uQ-iNq<|wHU(8*R;HxRYKOd1ER$Qr=r!6-ek0J1PFyPAG$Lr{f|RR~ z68lcRCJ9l@SEL1CK|8T)_I*YR{3Xta4cQ*)Sx1m>oviD#A&Z3$bo{&r>fdss-g43r zDc1+u+nZ(QVx`y-d`FvCq=FtQw_{{hNi|bbP`xHiR{Go$*tQ@aeK#c^sUl5AzVE8L zq3kKC>Sv_9Tp%r#i-P;A{lQ#>rh<;0@xb{8q~cvMicJctsLnMF4h`+H&q5Dh8>WHJ zI14_L@;-Ejq

fd2Wace%`cJ)!8ED|3s&rNckMM0f&MuB=CTO_K9A87f3?}?-X9q z(;wtr>xFVLenD;>Bh(MdzjeG&cSi2XqsVLWmc8n`wmM%V^idqG*jx%hjmf8yRhix- zpT?hMrO>hHv)?Ei-C!J-qMxW8pOFf9g_KGi84jkmCGbiIA4w74^79FI#JDDCs2p2* z9OcLUj#I{;G89bjkq^OL*=Umrd#a5Ovb{`R%D$4@(Pu$LPhRZi5 zZ4t+ql-I*K)@L%<{&$*q{@N;9&=qyg{sa3SgqLd=)oE<1y|^)o?fF3vr=%L`8I3zq zp?)WAb~7UoS9B8!s!Cu>!$qjo&MQeh@%gr*28< zb|;X&`uF6&Sl0vC8o9q-A$NaYi2IL%>PbdsvT|d%E`9fgyoE=fF(MzIn(Ft}i5u9s zGPn}JCO_ZR%}BL?WJM1Wonz@-Yjd{7z+qgAZ7R?-L|3HbuVpJjcp=!hU5&nYTV{`q zRBI0Gd-4@ptPpJ(T=MraDMbf!BrO}IHu>i25tva>Es(d&o;HUJCA7Vp z1+z2R8IvzABgG>9qSt;&D#Rb8Vr)yumQ3%G>m(vEC2m;@stpY{WG${@Lt#d~SR4xI zd5+P2qp>o_2y>3lNCg}Y9RvR*rNBoWJ~JY5bK1~}bshLhs;g_@F4pOr2iSi|;aQcT zLI=h`@dpgL(63>!hW##_)^OB?X$=Q;zWI#PbM(})8en(_f;}Z)C$C7-xjL~U#})E> zv7~E-g7z`_GVlX=H`?=isp2L1f-zF)hM%|IBct>nThZpme*;cPDKQi5y0#W{=)^hV iP`pjPii`8-7XJr7$b^>n)qj=%0000}j&I-=vPucMopDw01#v|QO*mF#o8T!V z(M2*Lt??xyQCV~s)|c_+fQe$bBBhMEPP-B+${sT0xbA)C!#(%&=i$VR8BPfx@}7bG~kQgBl^>!n1|PdAA{y1K?wp%tP` zJ3>G0$LMxBK@W^mbl+T{`;n#=va}g_YM@9@p-ej=(tD`T7&UqW4SE|b+5t&Dx9Jmf zX&>}yUkqt~$izaS)fm&!n9`}3(^@R)M1VMub`@!~$C6HKBZJmVjP?{_wcjO^_EfTH z&m@~RKo0FW5tlZS;Ivl>ZtcxkuQpfoYp)iA+H#H8-rfpn|GOR0-rbLBD{?~n;5emy zYA$FWM_Q{gYhOiP`v!{Imr>UCAZp)6Mf*Bx+K6C{%m6OXA!GkPbU4jWYI^+razw? z`kzKz`s)*%J|(#I*JQo=e9^D}nHbdPYrOuRR!CoONAyxZrr#nb^be0y`e)~YzKyj0 zO=R`YBd?cH)bB)D|1L!R1QoSw`ju$t_n@WUACmq*(AFP>uA097a18aQL)Lqs=+D4d z@4!^Q26O#oSn4kT^y@*!Ge~1xLpr0%Y~+YBUP-L+EHW9dA&c=UvKcp!!x)RWjJG8? zc@-^%L!v|oHD*N7mQt`jk}OF{u_DY z4it@hQ8s=CqH#Y|jQgTyWY91g&@!%qWIPsaqYYi-YV?g(42`EjHhv$9@pO!hmt$(Y z6mw$;OXG!r@gflWebTUJk&X?Kf!#n1dkwK{j7;j;!rnkO_BL{`*F{`xF2S*P3U2mK zSugv$qMv1IV$7ElYtE9%oF|KU6WP=_%$p)E^Fs;FTo>HtC$nC2t>`!3CkD-1 zYP|XJR>=HjJ7OO7W9F%xF#m0wGAnbz{0`FQ{g5@khrC&jqFIBoc?Co@74u5e%!i?2 zwxMM{7LwV6w)rG<&Fj!Na~PV}LpDdCs2Q8%n3`|K+!ldLUWX zp>6#Ey4JJNw|);p>-CVW7eKLIhq3iCOs#3mt^b9k^;W?80LZ?PH1?ZxI{Ob9gZ(BG zW5377+C`Vi{#&=j{s+I!{t)l5S0XO^(+SSLO>ou6}djAZ*yNwIIBvHdoh+RHSz-$zUPZwU6giJTeIIO95;CCSblDb50ooe$8|`6rq?x6snrAUGc-;x>_nyF;hrZe*ZcA`nk8oAh)N+b1PaQPS=ibDl^B*32wh} ziZjmz&Ve-NM3y@edCr0&=R%n~9U^x!DxA7!ZVeh-7%lD^NZdteb3aCx`vv;kwKU`e zlDP~ioXX5SN>i>xbM9VRsx!DYkta(UPeG^iY-J1{(ZqO~HrDg7%j9{)ZSlO}w|SoD z9iHbRF3)=j&hwh!_I!}_dfqPjJs*id&j&T$b4V-XIiel$X!|kGk#fRw+&JYqVlH@C zq&+7i>-ie;9yf}f^(dM zPQ>Ngk>Gqg1-EZ!*6Tyj@B6nH^szPG_nB76r|#LevLEv~U^pQGWs5iQ>jA^8NfeRrbkyB&Ss?KJfLnq*&-6km{UhbX)kHej7jM9sDBV;&&%F zex=~%k@fP275%(P4Dw&9@jTlK@kg~I{2Bcif0mr!PadcE)8_(z9@4z}Wj=;He>sZ$ z6)5u&hQ&?pVcXhgOhcSeAo0#y_#)jW@nZi5Vmhk8Nw(xG=5jI3z;X@K!cz?ki{zBFp zKDg))pCksur_}iHcUz(G>Fr4P#C|Ny$%(LkoC-(gLO6hQ_&Q|67b73O7RB(@D2Hz+ zF}#T?;hU%y&Qc?M54FONkQ8oFJG_;;;a902ehkC#PGQ1lhjME|1GMRzfV=-*9Dbf=Atu5g*63%4bDnBNu!?}#1{aYetL;Gzb>9sOq3 z8$G4ykE+a3Z;g+xZH1!i+mYzHek^*0oQPgOPDR(xh3ExHN3TaVdNcCT8&QmwQI6hB zV)Rz3M1N1UXoDJRx73!R&rv(trf&3U>PMf)F#1o((d|&8|BG?-T}-26%%h*fGP)9o z?hA^)O`7-{I$iuz#t{FPiHUz`W8-j{;$LuE;)nWeaXs&d9~^PTRpz)|aL2!u^~Tp0 z{qb*z!MMsCU(*W3uWU!+XZK_AxSWVzI!?tenG5l&kdEJiZ2T9<$I~dr??yTP2#N7B zRpJj*E&c#C;!jX3zKx`~MD6&?)Q#_?etZXp@m-MPG8DDP@%=E3AB1^)fn|Iz5Z8f{ zJ4lm!U#ClchA|}fH!;c2+t}nWE>m)a+mdAcw&d}=BY8r^mHbMAOP(sYli$vIlfI%q z84!a>PmNEW*9s+5?MQNCKbG7eCz4l>Q^}vrh2)(`C+|Zxc`NeCM^Q|wdrod4G5G{l zlFw01og2v)sg-<%B$c6^e4V<<52>F7hRIJLCwD_h?uT*mV@#9#VxC-$Wzqs9zYY=( zB#p3JrxW%v20?3Lgd=UNaG=X19ObqMhx={9(Y!9a8JF9VvG{G7<9J6V7;$C72`+Pm;LiLo>&;wH^k?E?FmrK@&)m=o zWv*^VGUa|ObE}-l+&fNX#JP~EBc0iTY~~r{GZKoK7f{Z;PGaWoRLQidmU)jF>baHK zO;Y9~YG?MNZe~jT%t{P1TF9A$p=1ujSnX+s!91ffXH>V!d=HdUJtenVr^~Ho47pV% zCTF*?x#L}?+&A2o+zEbL?o{59Q<-xYCAi%6f;%TgbJ-f7yQ3A#-Pn%g ze$kKR?vxX``^TwVYcAwkNavnHHuoU%xffB)ZAUrx5{bD9RdO=ba-UKox0_nIJtXBo z?cB%I&9T(aF&O3!ft*_jC1=7oXTvmiJm$HRu*{tgVKur1 zEBb{)F)Vxya^V;#h2t?UoQC%X@r8g*F`WqEX3o4fgVo7zY(ub&(v}lw*MXR(Aq>=&c(kgUI$Dm)b zV^}&Ca>)&)@XQ1jiq^Yje>8f7FP`$#$RHHVw8g`kgm%A<1EBv-(M7 zyHU*u?rJ&ft!^p$t6RljwN>M*FSJ6{N86EVi(=I-C8~W&RmUV$w^O>hpltOsl&`AH zRZzKlIK=8~@u6od|u0g-L4#R2)ay1I28pF8yJxr^YU|zit z%c=lWGoboKq^Vz`)78Jv80wdpnEH=wY(4HW)i=5=^^Ja8{Z8Id|L=&aE+)A8J%YQw zIqR)&EBfmVF<6&seErE*sQyMfQh$SDb(s=%^={OOg!(&_uB&^l???Ii$5gDV%=N<{ z)^(`Vt*F(HL__UX{Y#MQUbO3HqFcWR{rY+g>*qkOZ-7$26yy5EnAUH=ynZ{D^#o8) zftsohHm}v`nwK($X41qoRp#a`E>rV1x22i)+nSqrNAuo@tJz9$&1VI7Q}ynqRP;9= z7lX}bYJ79l3N?4MBh7zMtoZ>YntLeKTtPz9KV^3By$Y#vDE=6^tJGN?2; z)S5@5(L5ck=82G+YtU}4N4NQ1^qXrjYz81VuYl703C7JNrp?6M~i+9d|1 zNsX6Ohm}5QN2JeEOxi;UwNsLY1hv!BYRXDF%1c%%N{3Qe`Z7f63{)gPYSMSmkWNNR zx)742I;?aJy3&>COV?p2MIlQWC~C&i4VX&5#av2bDLn#6TS1)^X*$2w={mn=44t2w zm`>Klc2pnis1DoN?6-Alyrc6hxjN4i*Li{5oma@)*+u@&Un$s;iSN8mq0XElo%i~& z&MG<4Susv^n7Pn75b4fw$ac)gcfNvR=S-A4ZitA-^UfwLJ5K?fZJ^$br0LzI)AcHhq4$`H>D6s)?>U#L z_q^NEYx-@yS9wQIB3JJ@;(G6qySJUZy&?H~Z&9!Z;(L22)H6_|x2hlOsSevaWSr_9 zJQsS$BHjBcvOPQUJ=Lvxr=i^Y4#eKKQR$tJT5kgyy*OIEA3^FR(e9~x?%jZXFO6X@ z54l%`()%^Wy@xREseA5KuLq(K7h!Hwt+vgi+fi{aoN$b&kR!5=Ul zJc;R`hq-!Q4z>Y4M|;RS+Drb?ClnkVLj34Z3XKk=$mr;PY@~YkNM#6`>_-)EtyhGWST*?aK6m`$alDx_h z9gz}wnN?AJ>ly4!esLVC5Ez+hNxVPigG<_ zN(K$(F0_=JASt(^t^6Kcww`HRG;6&Z?|Ktb?PQFO|AG-ee3jb}{zkgRM`T#MN6camv5Og*7M~}} z;vlju_9w@JiMST~C%DB?f_q`jdKYIF{fn=P!NoZ>exdr{VqH73i1uTP3+2S(;&Ezm z(Og(0kzQnxUEG2E;x{O&DKBn@xG15rXrQK^8;d`pwRjfNqK@`rJGzS}&|mxo!^IHt z;;&E^>Yf*SFkS3}`9g=~;vitLKL{U@25*rL{~!YnBnFK7PsU0zVKrHBEZOi4a^S>> z3&$ilm;^V@$a-;h(T~%_AWp6ESl0^SymkcV_hYz0PC#{7Y?upB_l%z-3zb>zB5pw$ y4?={>jLoR2X`qc3dXUs^;{|l_Hu{h;#7_134ixOg7%MQv9?Y>4OY8$+75*PIy`C`u literal 0 HcmV?d00001 diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index b7faf6dab82..5176d144ae4 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -6,10 +6,11 @@ const st = @import("state.zig"); const fwd = @import("forward.zig"); const Model = @import("model.zig").Model; const snapshot = @import("snapshot.zig"); +const img = @import("images.zig"); const cfg = @import("../config.zig"); const be = lanes.backend; -pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64 }; +pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64, images: ?img.Encoder = null }; const ring = 4096; /// The prompt cache gets the bytes left by live streams and never evicts the state being restored. @@ -169,7 +170,7 @@ pub const Metal = struct { return h; } - fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream) !void { + fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, stream: ?*lanes.Stream, pictures: ?*img.Rows) !void { const base = cache.len; var at: usize = 0; while (at < ids.len) { @@ -187,7 +188,8 @@ pub const Metal = struct { const capture = self.prepared and stream != null; if (capture) _ = self.nextTapGeneration(); const taps: ?st.Ref = if (capture) .{ .buf = s.taps.? } else null; - try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = taps }); + const rows_of: []const fwd.ImageRows = if (pictures) |p| p.chunk(base + at, base + end) else &.{}; + try fwd.run(self.model, s, cache, ids[at..end], .{ .taps = taps, .images = rows_of }); if (capture) { const rows = end - at; if (self.sink) |k| try k.take(k.ptr, stream.?, .{ @@ -219,7 +221,6 @@ pub const Metal = struct { const self = cast(ptr); const ids = stream.prompt(); if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidInklingPrompt; - if (stream.images.len > 0) return error.InklingHasNoImageTower; const need = st.cacheBytes(ids.len + stream.max_new); if (self.held + need > self.options.budget) { std.log.warn("inkling2_loop: a stream needs {d:.1} GiB of state; {d:.1} of {d:.1} GiB are held", .{ gib(need), gib(self.held), gib(self.options.budget) }); @@ -240,7 +241,9 @@ pub const Metal = struct { if (snapshot.restore(cache, self.model.queue, snap)) stream.cached = @intCast(snap.at) else |_| stream.reuse_failed = true; } else stream.reuse_failed = true; } - try self.feed(cache, ids[cache.len..], stream); + var pictures = try img.Rows.init(self.gpa, self.options.images, stream, cache.len); + defer pictures.deinit(); + try self.feed(cache, ids[cache.len..], stream, &pictures); } pub fn warm(self: *Metal) !void { @@ -248,7 +251,7 @@ pub const Metal = struct { defer cache.deinit(); var ids: [st.prompt_rows]u32 = undefined; for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000); - try self.feed(&cache, &ids, null); + try self.feed(&cache, &ids, null, null); try fwd.run(self.model, &self.scratch, &cache, ids[0..st.window_rows], .{ .all = true }); } diff --git a/zig/src/families/inkling2/metal/forward.zig b/zig/src/families/inkling2/metal/forward.zig index 94238d8c354..c772f5bcbbc 100644 --- a/zig/src/families/inkling2/metal/forward.zig +++ b/zig/src/families/inkling2/metal/forward.zig @@ -14,11 +14,14 @@ const Model = model_file.Model; pub const Ref = state.Ref; pub const Segment = struct { cache: *state.Cache, rows: usize }; +/// The BF16 rows [off, off + rows * hidden * 2) of `buf` replace the normed embeddings of chunk rows [row, row + rows). +pub const ImageRows = struct { row: u32, rows: u32, buf: mtl.Buffer, off: usize = 0 }; pub const Options = struct { all: bool = false, ids: ?Ref = null, flight: ?*mtl.CommandBuffer = null, taps: ?state.Ref = null, + images: []const ImageRows = &.{}, }; pub const FinalPlan = struct { work_rows: usize, logits_rows: usize, logits_row: usize, capture_rows: usize }; @@ -309,6 +312,17 @@ pub fn run(m: *const Model, s: *state.Scratch, cache: *state.Cache, ids: []const return runShared(m, s, &.{.{ .cache = cache, .rows = ids.len }}, ids, options); } +/// Image rows ride one segment's chunk, fit their buffer, and replace only placeholder tokens. +fn checkImages(m: *const Model, ids: []const u32, segments: usize, options: Options) !void { + if (options.images.len == 0) return; + if (segments != 1 or options.ids != null) return error.Inkling2ImageRows; + for (options.images) |im| { + const end = @as(usize, im.row) + im.rows; + if (im.rows == 0 or end > ids.len or im.off + @as(usize, im.rows) * state.hidden * 2 > im.buf.length()) return error.Inkling2ImageRows; + for (ids[im.row..end]) |id| if (id != m.config.image_token) return error.Inkling2ImageRows; + } +} + pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, ids: []const u32, options: Options) !void { const rows = ids.len; if (rows == 0 or rows > s.rows or segments.len == 0 or segments.len > state.max_segments or (!options.all and segments.len != 1)) return error.Inkling2RowsExceeded; @@ -331,11 +345,13 @@ pub fn runShared(m: *const Model, s: *state.Scratch, segments: []const Segment, for (ids) |id| if (id >= m.config.text.vocab) return error.Inkling2Token; @memcpy(s.ids.slice(u32, rows), ids); } + try checkImages(m, ids, segments.len, options); const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = m.queue.commandBuffer(); const e = cb.compute(.serial); glue.embedNorm(&m.glue, e, options.ids orelse at(s.ids, 0), r(m.weights.embed), r(m.weights.embed_norm), at(s.p, 0), @intCast(rows)); + for (options.images) |im| copyBf16(m, e, at(im.buf, im.off), at(s.p, im.row * state.hidden * 2), im.rows * state.hidden); for (m.weight_plan.visits[0..m.weight_plan.n_visits]) |*v| try visit(m, e, s, v, segments, rows, options.taps); widen(m, e, at(s.p, 0), at(s.partial, 0), rows * state.hidden); const final = finalPlan(rows, options.all, options.taps != null); diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index e9e1998f151..2de5c31ff26 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -13,4 +13,6 @@ test { _ = @import("dspark_state.zig"); _ = @import("dspark.zig"); _ = @import("backend.zig"); + _ = @import("images.zig"); + _ = @import("vision_image_test.zig"); } diff --git a/zig/src/families/inkling2/metal/images.zig b/zig/src/families/inkling2/metal/images.zig new file mode 100644 index 00000000000..6147760f053 --- /dev/null +++ b/zig/src/families/inkling2/metal/images.zig @@ -0,0 +1,61 @@ +//! A prompt's picture rows: the tower's BF16 output for each image, and the part of it a prefill chunk takes. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const fwd = @import("forward.zig"); +const state = @import("state.zig"); + +/// The tower behind the backend: one image's rows as a new BF16 buffer [tokens, hidden], the caller's to free. +pub const Encoder = struct { + ctx: *anyopaque, + encode: *const fn (ctx: *anyopaque, image: lanes.stream.Image) anyerror!mtl.Buffer, +}; + +pub const Rows = struct { + gpa: std.mem.Allocator, + whole: []fwd.ImageRows, + made: usize = 0, + part: []fwd.ImageRows, + + /// Encodes each picture of `stream` at or after row `first` (a restored prefix already holds the earlier ones). + pub fn init(gpa: std.mem.Allocator, encoder: ?Encoder, stream: *const lanes.Stream, first: usize) !Rows { + const prompt_len = stream.prompt().len; + const whole = try gpa.alloc(fwd.ImageRows, stream.images.len); + const part = gpa.alloc(fwd.ImageRows, stream.images.len) catch |err| { + gpa.free(whole); + return err; + }; + var self: Rows = .{ .gpa = gpa, .whole = whole, .part = part }; + errdefer self.deinit(); + for (stream.images) |im| { + if (im.at > prompt_len or im.tokens > prompt_len - im.at) return error.BadInklingImageRows; + if (im.at + im.tokens <= first) continue; + const e = encoder orelse return error.InklingVisionDisabled; + if (im.tokens != @as(u64, im.gh) * im.gw) return error.BadInklingImageGrid; + const buffer = try e.encode(e.ctx, im); + self.whole[self.made] = .{ .row = im.at, .rows = im.tokens, .buf = buffer }; + self.made += 1; + if (buffer.length() < @as(usize, im.tokens) * state.hidden * 2) return error.BadInklingImageRows; + } + return self; + } + + /// The pictures' rows inside prompt positions [start, end), as rows of that chunk. + pub fn chunk(self: *Rows, start: usize, end: usize) []const fwd.ImageRows { + var count: usize = 0; + for (self.whole[0..self.made]) |im| { + const from = @max(start, im.row); + const to = @min(end, im.row + im.rows); + if (from >= to) continue; + self.part[count] = .{ .row = @intCast(from - start), .rows = @intCast(to - from), .buf = im.buf, .off = im.off + (from - im.row) * state.hidden * 2 }; + count += 1; + } + return self.part[0..count]; + } + + pub fn deinit(self: *Rows) void { + for (self.whole[0..self.made]) |im| im.buf.deinit(); + self.gpa.free(self.whole); + self.gpa.free(self.part); + } +}; diff --git a/zig/src/families/inkling2/metal/metal.zig b/zig/src/families/inkling2/metal/metal.zig index bef58022713..c79c36dff00 100644 --- a/zig/src/families/inkling2/metal/metal.zig +++ b/zig/src/families/inkling2/metal/metal.zig @@ -5,3 +5,4 @@ pub const glue = @import("glue.zig"); pub const experts = @import("experts.zig"); pub const experts_plan = @import("experts_plan.zig"); pub const loop = @import("loop.zig"); +pub const vision = @import("vision.zig"); diff --git a/zig/src/families/inkling2/metal/vision.zig b/zig/src/families/inkling2/metal/vision.zig new file mode 100644 index 00000000000..2f652ff1542 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision.zig @@ -0,0 +1,430 @@ +//! Inkling 2 Mini's image tower on Metal: BF16 activations and weights, FP32 accumulators, BF16 text-width output. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +const frags = @import("../../../core/frags.zig"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const config = @import("../config.zig"); +const gm = @import("vision_gemm.zig"); +const tables = @import("vision_tables.zig"); +const image = @import("vision_image.zig"); + +pub const Prepared = image.Prepared; +pub const prepare = image.prepare; +pub const problem = image.problem; +/// The tensor-unit GEMMs, for the kernel contract's probes (tests/contract/metal_inkling2_vision_*.zig). +pub const gemm = gm; + +const Ref = gm.Ref; +const chunk_rows: u32 = 1024; // sequence rows a projection pass multiplies at once (the fp32 sums' scratch) +const score_bytes: usize = 256 << 20; // the attention scores' fp32 scratch + +pub const Options = struct { + /// The most image tokens one encode takes (--vision's image budget): the scratch is sized for it. + max_tokens: u32 = 4096, +}; + +const Layer = struct { + ln1_w: Ref, + ln1_b: Ref, + ln2_w: Ref, + ln2_b: Ref, + ls1: Ref, + ls2: Ref, + w: [4]Ref, // q, k, v, out + b: [4]Ref, + fc1_w: Ref, + fc1_b: Ref, + fc2_w: Ref, + fc2_b: Ref, +}; + +const glue_names = [_][]const u8{ "pack", "embed", "layer_norm", "qkv", "softmax", "heads", "bias_gelu", "gelu_rows", "residual" }; +const Glue = enum { pack, embed, layer_norm, qkv, softmax, heads, bias_gelu, gelu_rows, residual }; + +/// Kernel constants (the structs of kernels/metal/inkling2/vision.metal). +const Rows = extern struct { rows: u32, width: u32, eps: f32 }; +const Qkv = extern struct { rows: u32, heads: u32, dim: u32, r0: u32 }; +const Heads = extern struct { rows: u32, r0: u32, heads: u32, dim: u32 }; +const Embed = extern struct { patches: u32, width: u32 }; + +const scratch_names = [_][]const u8{ "pix", "pixb", "pe", "taps", "weights", "cs", "sn", "x", "xn", "att", "acc", "q", "k", "v", "s", "o", "mid", "p1" }; + +pub const Tower = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + cfg: config.Vision, + max_tokens: u32, + owned: ?ck.Checkpoint = null, + lib: mtl.Library, + gemm: gm.Gemm, + glue: [glue_names.len]mtl.Pipeline, + layers: []Layer, + patch_w: Ref, + pos_table: Ref, + cls: Ref, + cls_pos: Ref, + pre_w: Ref, + pre_b: Ref, + proj_in: Ref, + proj_out: Ref, + scratch: [scratch_names.len]mtl.Buffer, + qchunk: u32, + follow: ?mtl.ResidencySet.Follow = null, + + /// The tower from `dir`'s checkpoint (the shards holding model.visual.*), sized for `opts.max_tokens` image tokens. + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, device: mtl.Device, queue: mtl.Queue, cfg: *const config.Config, opts: Options) !*Tower { + var checkpoint = ck.Checkpoint.init(gpa); + errdefer checkpoint.deinit(); + try geometry(cfg.vision, opts); + try readShards(&checkpoint, io, dir, device); + const t = try loadFromCheckpoint(gpa, device, queue, cfg, opts, &checkpoint); + t.owned = checkpoint; + return t; + } + + /// The caller keeps the checkpoint and its residency alive through tower deinit. + pub fn loadFromCheckpoint(gpa: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, cfg: *const config.Config, opts: Options, checkpoint: *const ck.Checkpoint) !*Tower { + const v = cfg.vision; + try geometry(v, opts); + const t = try gpa.create(Tower); + errdefer gpa.destroy(t); + t.* = .{ .gpa = gpa, .device = device, .queue = queue, .cfg = v, .max_tokens = opts.max_tokens, .lib = undefined, .gemm = .{}, .glue = undefined, .layers = &.{}, .patch_w = undefined, .pos_table = undefined, .cls = undefined, .cls_pos = undefined, .pre_w = undefined, .pre_b = undefined, .proj_in = undefined, .proj_out = undefined, .scratch = undefined, .qchunk = 0 }; + t.layers = try gpa.alloc(Layer, v.layers); + errdefer gpa.free(t.layers); + try t.bind(checkpoint); + const src = try frags.source(device, gpa, sources.vision); + defer gpa.free(src); + t.lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + errdefer t.lib.deinit(); + t.gemm = try gm.Gemm.init(device, t.lib, &.{ .bf16_nt, .bf16f_nt, .f32_nt, .f32_nn }); + errdefer t.gemm.deinit(); + var made: usize = 0; + errdefer for (t.glue[0..made]) |p| p.deinit(); + inline for (glue_names, 0..) |name, i| { + t.glue[i] = try mtl.Pipeline.init(device, t.lib, "ik2v_" ++ name, false); + made += 1; + } + try t.allocate(); + return t; + } + + fn geometry(v: config.Vision, opts: Options) !void { + if (v.heads == 0 or v.hidden % v.heads != 0 or (v.hidden / v.heads) % 4 != 0 or v.hidden / v.heads > 128) + return error.UnsupportedVisionGeometry; + if (v.patch != image.patch or v.merge != image.merge or v.grid != image.grid or opts.max_tokens == 0) return error.UnsupportedVisionGeometry; + } + + pub fn deinit(t: *Tower) void { + t.setResident(null); + for (t.scratch) |b| b.deinit(); + for (t.glue) |p| p.deinit(); + t.gemm.deinit(); + t.lib.deinit(); + t.gpa.free(t.layers); + if (t.owned) |*weights| weights.deinit(); + t.gpa.destroy(t); + } + + /// Reads the shards that hold the tower's tensors into the tower's own checkpoint. + fn readShards(checkpoint: *ck.Checkpoint, io: std.Io, dir: []const u8, device: mtl.Device) !void { + const gpa = checkpoint.allocator; + const index_path = try std.fs.path.join(gpa, &.{ dir, "model.safetensors.index.json" }); + defer gpa.free(index_path); + const index = std.Io.Dir.cwd().readFileAlloc(io, index_path, gpa, .limited(256 << 20)) catch |err| switch (err) { + error.FileNotFound => null, + else => return err, + }; + var files: std.ArrayList([]const u8) = .empty; + defer files.deinit(gpa); + var doc: ?std.json.Parsed(std.json.Value) = null; + defer if (doc) |d| d.deinit(); + defer if (index) |b| gpa.free(b); + if (index) |json| { + doc = try std.json.parseFromSlice(std.json.Value, gpa, json, .{}); + const map = doc.?.value.object.get("weight_map") orelse return error.BadCheckpointIndex; + if (map != .object) return error.BadCheckpointIndex; + var it = map.object.iterator(); + while (it.next()) |e| { + if (!std.mem.startsWith(u8, e.key_ptr.*, "model.visual.") or e.value_ptr.* != .string) continue; + const name = e.value_ptr.string; + const seen = for (files.items) |f| { + if (std.mem.eql(u8, f, name)) break true; + } else false; + if (!seen) try files.append(gpa, name); + } + } else try files.append(gpa, "model.safetensors"); + if (files.items.len == 0) return error.NoVisionTensors; + for (files.items) |name| { + const joined = try std.fs.path.join(gpa, &.{ dir, name }); + defer gpa.free(joined); + const path = try gpa.dupeSentinel(u8, joined, 0); + defer gpa.free(path); + try checkpoint.addFileSelected(device, path, "", "model.visual."); + } + } + + fn tensor(checkpoint: *const ck.Checkpoint, name: []const u8, dims: []const usize) !Ref { + const x = try checkpoint.get(name); + if (x.dtype != .bf16 or x.rank != dims.len or !std.mem.eql(usize, x.shape[0..x.rank], dims)) { + std.log.err("inkling2 vision: {s} is not bf16 {any}", .{ name, dims }); + return error.UnexpectedVisionTensor; + } + return .{ .buf = x.buffer, .off = x.offset }; + } + + fn layerTensor(checkpoint: *const ck.Checkpoint, i: usize, comptime tail: []const u8, dims: []const usize) !Ref { + var name_buf: [128]u8 = undefined; + return tensor(checkpoint, try std.fmt.bufPrint(&name_buf, "model.visual.backbone.layers.{d}." ++ tail, .{i}), dims); + } + + fn bind(t: *Tower, checkpoint: *const ck.Checkpoint) !void { + const v = t.cfg; + const h: usize = v.hidden; + const ff: usize = h * v.mlp_ratio; + const pre = "model.visual.backbone."; + t.patch_w = try tensor(checkpoint, pre ++ "embeddings.patch_embedding.weight", &.{ h, image.patch_width }); + t.pos_table = try tensor(checkpoint, pre ++ "embeddings.position_embedding", &.{ @as(usize, v.grid) * v.grid, h }); + t.cls = try tensor(checkpoint, pre ++ "embeddings.class_embedding", &.{h}); + t.cls_pos = try tensor(checkpoint, pre ++ "embeddings.cls_position_embedding", &.{h}); + t.pre_w = try tensor(checkpoint, pre ++ "ln_pre.weight", &.{h}); + t.pre_b = try tensor(checkpoint, pre ++ "ln_pre.bias", &.{h}); + t.proj_in = try tensor(checkpoint, "model.visual.proj_in.weight", &.{ v.proj_hidden, h * v.merge * v.merge }); + t.proj_out = try tensor(checkpoint, "model.visual.proj_out.weight", &.{ v.text_hidden, v.proj_hidden }); + for (t.layers, 0..) |*l, i| { + l.ln1_w = try layerTensor(checkpoint, i, "ln_1.weight", &.{h}); + l.ln1_b = try layerTensor(checkpoint, i, "ln_1.bias", &.{h}); + l.ln2_w = try layerTensor(checkpoint, i, "ln_2.weight", &.{h}); + l.ln2_b = try layerTensor(checkpoint, i, "ln_2.bias", &.{h}); + l.ls1 = try layerTensor(checkpoint, i, "ls_1.gamma", &.{h}); + l.ls2 = try layerTensor(checkpoint, i, "ls_2.gamma", &.{h}); + l.w[0] = try layerTensor(checkpoint, i, "self_attn.q_proj.weight", &.{ h, h }); + l.w[1] = try layerTensor(checkpoint, i, "self_attn.k_proj.weight", &.{ h, h }); + l.w[2] = try layerTensor(checkpoint, i, "self_attn.v_proj.weight", &.{ h, h }); + l.w[3] = try layerTensor(checkpoint, i, "self_attn.out_proj.weight", &.{ h, h }); + l.b[0] = try layerTensor(checkpoint, i, "self_attn.q_proj.bias", &.{h}); + l.b[1] = try layerTensor(checkpoint, i, "self_attn.k_proj.bias", &.{h}); + l.b[2] = try layerTensor(checkpoint, i, "self_attn.v_proj.bias", &.{h}); + l.b[3] = try layerTensor(checkpoint, i, "self_attn.out_proj.bias", &.{h}); + l.fc1_w = try layerTensor(checkpoint, i, "mlp.c_fc.weight", &.{ ff, h }); + l.fc1_b = try layerTensor(checkpoint, i, "mlp.c_fc.bias", &.{ff}); + l.fc2_w = try layerTensor(checkpoint, i, "mlp.c_proj.weight", &.{ h, ff }); + l.fc2_b = try layerTensor(checkpoint, i, "mlp.c_proj.bias", &.{h}); + } + } + + fn sizes(t: *const Tower) [scratch_names.len]usize { + const v = t.cfg; + const tokens: usize = t.max_tokens; + const P = tokens * v.merge * v.merge; + const S = P + 1; + const h: usize = v.hidden; + const hd = h / v.heads; + const ff = h * v.mlp_ratio; + const q: usize = t.qchunk; + const rows = @min(S, chunk_rows); + return .{ P * image.patch_width * 4, P * image.patch_width * 2, P * h * 2, P * 4 * 4, P * 4 * 4, S * hd * 4, S * hd * 4, S * h * 2, S * h * 2, S * h * 2, rows * @max(3 * h, ff) * 4, @as(usize, v.heads) * S * hd * 4, @as(usize, v.heads) * S * hd * 4, @as(usize, v.heads) * S * hd * 4, @as(usize, v.heads) * q * S * 4, @as(usize, v.heads) * q * hd * 4, rows * ff * 2, tokens * v.proj_hidden * 2 }; + } + + fn allocate(t: *Tower) !void { + const v = t.cfg; + const S: usize = @as(usize, t.max_tokens) * v.merge * v.merge + 1; + const per_query = @as(usize, v.heads) * S * 4; + t.qchunk = @intCast(@min(S, @max(64, score_bytes / per_query / 64 * 64))); + var made: usize = 0; + errdefer for (t.scratch[0..made]) |b| b.deinit(); + for (t.sizes(), 0..) |n, i| { + t.scratch[i] = try t.device.buffer(@max(n, 16), mtl.ResourceOptions.shared); + made += 1; + } + } + + fn buf(t: *const Tower, comptime name: []const u8) mtl.Buffer { + inline for (scratch_names, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return t.scratch[i]; + @compileError("no tower buffer " ++ name); + } + + fn pipe(t: *const Tower, g: Glue) mtl.Pipeline { + return t.glue[@backingInt(g)]; + } + + /// Device bytes the tower owns: scratch and, only for standalone loads, its weight buffers. + pub fn bytes(t: *const Tower) u64 { + var total: u64 = 0; + for (t.scratch) |b| total += b.length(); + if (t.owned) |weights| for (weights.shards.items) |s| { + total += s.buffer.length(); + }; + return total; + } + + /// Makes the residency set follow the tower's buffers (null: stop following, leaving them). + pub fn setResident(t: *Tower, hook: ?mtl.ResidencySet.Follow) void { + if (t.follow) |f| { + for (t.scratch) |b| f.leave(f.ctx, b); + if (t.owned) |weights| for (weights.shards.items) |s| f.leave(f.ctx, s.buffer); + } + t.follow = hook; + if (hook) |f| { + for (t.scratch) |b| f.join(f.ctx, b); + if (t.owned) |weights| for (weights.shards.items) |s| f.join(f.ctx, s.buffer); + } + } + + /// A new BF16 buffer [gh * gw, text_hidden] of the projector's raw output (caller releases); one encode at a time. + pub fn encodeInput(t: *Tower, pixels: []const f32, gh: u32, gw: u32) !mtl.Buffer { + return t.run(pixels, gh, gw, null, false); + } + + /// Copy every BF16 residual into `trace` (pre-norm first), for the matched-input FP64 test. + pub fn traceInput(t: *Tower, pixels: []const f32, gh: u32, gw: u32, trace: mtl.Buffer) !mtl.Buffer { + if (comptime !@import("builtin").is_test) @compileError("vision trace is only for tests"); + return t.run(pixels, gh, gw, trace, true); + } + + fn run(t: *Tower, pixels: []const f32, gh: u32, gw: u32, trace: ?mtl.Buffer, comptime capture: bool) !mtl.Buffer { + const v = t.cfg; + const tokens: usize = @as(usize, gh) * gw; + if (tokens == 0 or tokens > t.max_tokens) return error.ImageTooLarge; + if (pixels.len != tokens * image.token_width) return error.ImageGrid; + const P: u32 = @intCast(tokens * v.merge * v.merge); + const hd: u32 = v.hidden / v.heads; + @memcpy(t.buf("pix").slice(f32, pixels.len), pixels); + const S: usize = @as(usize, P) + 1; + tables.fill(gh, gw, hd, t.buf("taps").slice(u32, P * 4), t.buf("weights").slice(f32, P * 4), t.buf("cs").slice(f32, S * hd), t.buf("sn").slice(f32, S * hd)); + const out = try t.device.buffer(tokens * v.text_hidden * 2, mtl.ResourceOptions.shared); + errdefer out.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = t.queue.commandBuffer(); + t.encode(cb, P, out, capture, trace); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2 vision: command buffer failed: {s}", .{msg}); + return error.GpuFailed; + } + return out; + } + + fn ref(t: *const Tower, comptime name: []const u8) Ref { + return .{ .buf = t.buf(name) }; + } + + fn encode(t: *Tower, cb: mtl.CommandBuffer, P: u32, out: mtl.Buffer, comptime capture: bool, trace: ?mtl.Buffer) void { + var e = cb.compute(.serial); + const v = t.cfg; + const h: u32 = v.hidden; + const S: u32 = P + 1; + const hd: u32 = h / v.heads; + const ff: u32 = h * v.mlp_ratio; + const tokens: u32 = P / (v.merge * v.merge); + // pixels as bf16, the patch projection, then class row + patches with their position embedding + const n: u32 = P * image.patch_width; + e.setPipeline(t.pipe(.pack)); + e.setBuffer(t.buf("pix"), 0, 0); + e.setBuffer(t.buf("pixb"), 0, 1); + e.setValue(n, 2); + e.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + t.gemm.run(e, .bf16_nt, t.ref("pixb"), t.patch_w, t.ref("pe"), .{ .m = P, .n = h, .k = image.patch_width, .lda = image.patch_width, .ldb = image.patch_width, .ldd = h }); + e.setPipeline(t.pipe(.embed)); + for ([_]Ref{ t.ref("pe"), t.pos_table, t.ref("taps"), t.ref("weights"), t.cls, t.cls_pos, t.ref("x") }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(Embed{ .patches = P, .width = h }, 7); + e.dispatchThreads(mtl.Size.of(h, S, 1), mtl.Size.of(256, 1, 1)); + // the pre-LayerNorm's output is the residual stream: x and xn trade places + var res = t.ref("x"); + var tmp = t.ref("xn"); + t.layerNorm(e, res, t.pre_w, t.pre_b, tmp, S); + std.mem.swap(Ref, &res, &tmp); + const trace_bytes: usize = @as(usize, S) * h * 2; + if (capture) e = copyTrace(cb, e, res, trace.?, 0, trace_bytes); + const att = t.ref("att"); + const scale: f32 = 1.0 / @sqrt(@as(f32, @floatFromInt(hd))); + for (t.layers, 1..) |l, stage| { + t.layerNorm(e, res, l.ln1_w, l.ln1_b, tmp, S); + var r0: u32 = 0; + while (r0 < S) : (r0 += chunk_rows) { + const m = @min(chunk_rows, S - r0); + for (0..3) |which| t.gemm.run(e, .bf16f_nt, tmp.at(@as(usize, r0) * h * 2), l.w[which], t.ref("acc").at(which * h * 4), .{ .m = m, .n = h, .k = h, .lda = h, .ldb = h, .ldd = 3 * h }); + e.setPipeline(t.pipe(.qkv)); + for ([_]Ref{ t.ref("acc"), l.b[0], l.b[1], l.b[2], t.ref("cs"), t.ref("sn"), t.ref("q"), t.ref("k"), t.ref("v") }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(Qkv{ .rows = S, .heads = v.heads, .dim = hd, .r0 = r0 }, 9); + e.dispatchThreads(mtl.Size.of(hd, 3 * v.heads, m), mtl.Size.of(hd, @max(1, 256 / hd), 1)); + } + var q0: u32 = 0; + while (q0 < S) : (q0 += t.qchunk) { + const lc = @min(t.qchunk, S - q0); + const stride: u32 = S * hd; + t.gemm.run(e, .f32_nt, t.ref("q").at(@as(usize, q0) * hd * 4), t.ref("k"), t.ref("s"), .{ .m = lc, .n = S, .k = hd, .lda = hd, .ldb = hd, .ldd = S, .batch = v.heads, .sa = stride, .sb = stride, .sd = lc * S }); + e.setPipeline(t.pipe(.softmax)); + e.setBuffer(t.buf("s"), 0, 0); + e.setValue(S, 1); + e.setValue(scale, 2); + e.dispatchGroups(mtl.Size.of(@as(usize, v.heads) * lc, 1, 1), mtl.Size.of(256, 1, 1)); + t.gemm.run(e, .f32_nn, t.ref("s"), t.ref("v"), t.ref("o"), .{ .m = lc, .n = hd, .k = S, .lda = S, .ldb = hd, .ldd = hd, .batch = v.heads, .sa = lc * S, .sb = stride, .sd = lc * hd }); + e.setPipeline(t.pipe(.heads)); + e.setBuffer(t.buf("o"), 0, 0); + e.setBuffer(att.buf, att.off, 1); + e.setValue(Heads{ .rows = lc, .r0 = q0, .heads = v.heads, .dim = hd }, 2); + e.dispatchThreads(mtl.Size.of(h, lc, 1), mtl.Size.of(256, 1, 1)); + } + r0 = 0; + while (r0 < S) : (r0 += chunk_rows) { + const m = @min(chunk_rows, S - r0); + t.gemm.run(e, .bf16f_nt, att.at(@as(usize, r0) * h * 2), l.w[3], t.ref("acc"), .{ .m = m, .n = h, .k = h, .lda = h, .ldb = h, .ldd = h }); + t.residual(e, l.b[3], l.ls1, res.at(@as(usize, r0) * h * 2), m, h); + } + t.layerNorm(e, res, l.ln2_w, l.ln2_b, tmp, S); + r0 = 0; + while (r0 < S) : (r0 += chunk_rows) { + const m = @min(chunk_rows, S - r0); + t.gemm.run(e, .bf16f_nt, tmp.at(@as(usize, r0) * h * 2), l.fc1_w, t.ref("acc"), .{ .m = m, .n = ff, .k = h, .lda = h, .ldb = h, .ldd = ff }); + e.setPipeline(t.pipe(.bias_gelu)); + e.setBuffer(t.buf("acc"), 0, 0); + e.setBuffer(l.fc1_b.buf, l.fc1_b.off, 1); + e.setBuffer(t.buf("mid"), 0, 2); + e.setValue(ff, 3); + e.dispatchThreads(mtl.Size.of(ff, m, 1), mtl.Size.of(256, 1, 1)); + t.gemm.run(e, .bf16f_nt, t.ref("mid"), l.fc2_w, t.ref("acc"), .{ .m = m, .n = h, .k = ff, .lda = ff, .ldb = ff, .ldd = h }); + t.residual(e, l.fc2_b, l.ls2, res.at(@as(usize, r0) * h * 2), m, h); + } + if (capture) e = copyTrace(cb, e, res, trace.?, stage * trace_bytes, trace_bytes); + } + // the merger over the patch rows (rows 1 .. of one image): 4 patches a token + const merged: u32 = v.merge * v.merge * h; + t.gemm.run(e, .bf16_nt, res.at(@as(usize, h) * 2), t.proj_in, t.ref("p1"), .{ .m = tokens, .n = v.proj_hidden, .k = merged, .lda = merged, .ldb = merged, .ldd = v.proj_hidden }); + e.setPipeline(t.pipe(.gelu_rows)); + e.setBuffer(t.buf("p1"), 0, 0); + e.setValue(v.proj_hidden, 1); + e.dispatchThreads(mtl.Size.of(v.proj_hidden, tokens, 1), mtl.Size.of(256, 1, 1)); + t.gemm.run(e, .bf16_nt, t.ref("p1"), t.proj_out, .{ .buf = out }, .{ .m = tokens, .n = v.text_hidden, .k = v.proj_hidden, .lda = v.proj_hidden, .ldb = v.proj_hidden, .ldd = v.text_hidden }); + e.end(); + } + + fn copyTrace(cb: mtl.CommandBuffer, encoder: mtl.ComputeEncoder, src: Ref, dst: mtl.Buffer, off: usize, n: usize) mtl.ComputeEncoder { + encoder.end(); + const blit = cb.blit(); + blit.copy(src.buf, src.off, dst, off, n); + blit.end(); + return cb.compute(.serial); + } + + fn layerNorm(t: *const Tower, e: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, y: Ref, rows: u32) void { + e.setPipeline(t.pipe(.layer_norm)); + for ([_]Ref{ x, w, b, y }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + e.setValue(Rows{ .rows = rows, .width = t.cfg.hidden, .eps = t.cfg.eps }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + /// x rows += lambda * (acc + bias) over the first `rows` rows of the fp32 sums. + fn residual(t: *const Tower, e: mtl.ComputeEncoder, bias: Ref, lambda: Ref, x: Ref, rows: u32, width: u32) void { + e.setPipeline(t.pipe(.residual)); + e.setBuffer(t.buf("acc"), 0, 0); + e.setBuffer(bias.buf, bias.off, 1); + e.setBuffer(lambda.buf, lambda.off, 2); + e.setBuffer(x.buf, x.off, 3); + e.setValue(width, 4); + e.dispatchThreads(mtl.Size.of(width, rows, 1), mtl.Size.of(256, 1, 1)); + } +}; diff --git a/zig/src/families/inkling2/metal/vision_checkpoint_test.zig b/zig/src/families/inkling2/metal/vision_checkpoint_test.zig new file mode 100644 index 00000000000..fcbd14003b0 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_checkpoint_test.zig @@ -0,0 +1,34 @@ +//! Load selected tensors from the one original Mini shard without allocating its text experts. +const std = @import("std"); +const t = std.testing; +const config = @import("../config.zig"); + +pub fn directory() ![]const u8 { + return @import("sys").getenv("TF_INKLING2_METAL_DIR") orelse error.SkipZigTest; +} + +pub fn loadConfig(a: std.mem.Allocator, dir: []const u8) !config.Config { + const path = try std.fs.path.join(a, &.{ dir, "config.json" }); + defer a.free(path); + const json = try std.Io.Dir.cwd().readFileAlloc(t.io, path, a, .limited(1 << 20)); + defer a.free(json); + var why: config.Why = .{}; + const c = try config.parse(a, json, &why); + try t.expectEqual(@as(u32, 24), c.text.layers); + try t.expectEqual(@as(u32, 2304), c.text.hidden); + return c; +} + +pub fn shard(a: std.mem.Allocator, dir: []const u8, tensor: []const u8) ![:0]u8 { + const path = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); + defer a.free(path); + const json = try std.Io.Dir.cwd().readFileAlloc(t.io, path, a, .limited(4 << 20)); + defer a.free(json); + const Index = struct { weight_map: std.json.ArrayHashMap([]const u8) }; + const doc = try std.json.parseFromSlice(Index, a, json, .{ .ignore_unknown_fields = true }); + defer doc.deinit(); + const file = doc.value.weight_map.map.get(tensor) orelse return error.MissingTensor; + const joined = try std.fs.path.join(a, &.{ dir, file }); + defer a.free(joined); + return a.dupeSentinel(u8, joined, 0); +} diff --git a/zig/src/families/inkling2/metal/vision_gemm.zig b/zig/src/families/inkling2/metal/vision_gemm.zig new file mode 100644 index 00000000000..57983a37282 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_gemm.zig @@ -0,0 +1,103 @@ +//! Tensor-unit GEMMs of the image tower (vision_gemm.metal): 64 x 128 x 256 tiles, fp32 sums. +const std = @import("std"); +const mtl = @import("metal"); + +/// A buffer and the byte offset a view starts at. +pub const Ref = struct { + buf: mtl.Buffer, + off: usize = 0, + + pub fn at(r: Ref, bytes: usize) Ref { + return .{ .buf = r.buf, .off = r.off + bytes }; + } +}; + +/// bf16 x w^T to bf16, bf16 x w^T to fp32 (an epilogue rounds once), fp32 x w^T, fp32 x w. +pub const Kind = enum(u8) { bf16_nt, bf16f_nt, f32_nt, f32_nn }; + +/// y [M, N] = x [M, K] w, rows `lda` / `ldb` / `ldd` apart ([N, K] w for nt, [K, N] for the fp32 nn), `batch` times. +pub const Shape = struct { + m: u32, + n: u32, + k: u32, + lda: u32, + ldb: u32, + ldd: u32, + batch: u32 = 1, + sa: u32 = 0, + sb: u32 = 0, + sd: u32 = 0, +}; + +pub const Gemm = struct { + pipes: [4][2][2]?mtl.Pipeline = @splat(@splat(@splat(null))), + /// Without tensor units, bf16 x w^T for up to `rows_max` rows on 8x8 MMAs with the tile kernel's bits (null: tiles) + rows: ?mtl.Pipeline = null, + + /// The pipelines of `wanted` from `lib` (the library holds every kind; unused ones cost nothing to leave out). + pub fn init(device: mtl.Device, lib: mtl.Library, wanted: []const Kind) !Gemm { + var g: Gemm = .{}; + errdefer g.deinit(); + for (wanted) |kind| for (0..2) |m| for (0..2) |n| { + var name: [48]u8 = undefined; + const text = try std.fmt.bufPrint(&name, "ik2_gemm_{s}_{d}{d}", .{ @tagName(kind), m, n }); + g.pipes[@backingInt(kind)][m][n] = try mtl.Pipeline.init(device, lib, text, false); + }; + for (wanted) |kind| if (kind == .bf16_nt and !device.tensorUnits()) { + g.rows = try mtl.Pipeline.init(device, lib, "ik2_gemm_bf16_nt_rows", false); + }; + return g; + } + + /// Most rows the small GEMM takes (one 8x8 MMA row block). + pub const rows_max = 8; + + pub fn deinit(g: *Gemm) void { + if (g.rows) |p| p.deinit(); + g.rows = null; + for (&g.pipes) |*a| for (a) |*b| for (b) |*p| if (p.*) |pipe| { + pipe.deinit(); + p.* = null; + }; + } + + /// Encodes d = a w for `s` (the kernel's parameter array rides in the encoder's bytes). + pub fn run(g: *const Gemm, e: mtl.ComputeEncoder, kind: Kind, a: Ref, b: Ref, d: Ref, s: Shape) void { + if (kind == .f32_nt or kind == .f32_nn) { + g.runExact(e, kind, a, b, d, s); + return; + } + if (kind == .bf16_nt and s.m <= rows_max and s.batch == 1 and s.n % 16 == 0 and s.k % 8 == 0) if (g.rows) |small| { + e.setPipeline(small); + e.setBuffer(a.buf, a.off, 0); + e.setBuffer(b.buf, b.off, 1); + const p = [16]i32{ @intCast(s.m), @intCast(s.n), @intCast(s.k), @intCast(s.lda), @intCast(s.ldb), @intCast(s.ldd), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(d.buf, d.off, 3); + e.dispatchGroups(mtl.Size.of(s.n / 16, 1, 1), mtl.Size.of(32, 1, 1)); + return; + }; + const tn: u32 = (s.n + 127) / 128; + const tm: u32 = (s.m + 63) / 64; + const pipe = g.pipes[@backingInt(kind)][@intFromBool(s.m % 64 == 0)][@intFromBool(s.n % 128 == 0)].?; + e.setPipeline(pipe); + e.setBuffer(a.buf, a.off, 0); + e.setBuffer(b.buf, b.off, 1); + const p = [16]i32{ @intCast(s.m), @intCast(s.n), @intCast(s.k), @intCast(s.lda), @intCast(s.ldb), @intCast(s.ldd), @intCast(tn), @intCast(tm), 2, @intCast(s.k / 256), @intCast(s.sa), @intCast(s.sb), @intCast(s.sd), 0, 0, 0 }; + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(d.buf, d.off, 3); + e.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, @as(usize, s.batch) * 2), mtl.Size.of(32, 4, 2)); + } + + /// One thread, one output, a full fp32 dot. No tensor-unit operand cut. + fn runExact(g: *const Gemm, e: mtl.ComputeEncoder, kind: Kind, a: Ref, b: Ref, d: Ref, s: Shape) void { + e.setPipeline(g.pipes[@backingInt(kind)][0][0].?); + e.setBuffer(a.buf, a.off, 0); + e.setBuffer(b.buf, b.off, 1); + const p = [16]i32{ @intCast(s.m), @intCast(s.n), @intCast(s.k), @intCast(s.lda), @intCast(s.ldb), @intCast(s.ldd), 0, 0, 0, 0, @intCast(s.sa), @intCast(s.sb), @intCast(s.sd), 0, 0, 0 }; + e.setBytes(std.mem.asBytes(&p), 2); + e.setBuffer(d.buf, d.off, 3); + if (s.m == 0 or s.n == 0 or s.batch == 0) return; + e.dispatchThreads(mtl.Size.of(s.n, s.m, s.batch), mtl.Size.of(32, 8, 1)); + } +}; diff --git a/zig/src/families/inkling2/metal/vision_image.zig b/zig/src/families/inkling2/metal/vision_image.zig new file mode 100644 index 00000000000..a5d03834769 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_image.zig @@ -0,0 +1,109 @@ +//! Inkling 2's image processor for the Metal tower: merge-block patches, resized only to fit the token budget. +const std = @import("std"); +const core = @import("core"); +const base = @import("../image.zig"); + +const picture = core.picture; +const identity = picture.identity; + +/// The tower's native patch side, the merge side, and so the pixels one image token covers (40 x 40). +pub const patch = base.patch; +pub const merge = base.merge; +pub const cell = base.side; +/// The learned position table's side. +pub const grid = base.grid; +/// One patch's values: rows, columns, channels (HWC), the order the patch projection's weight reads. +pub const patch_width = base.patch_width; +/// One token's values: its 4 patches in merge-block order (row, column), each `patch_width`. +pub const token_width = merge * merge * patch_width; +/// Image tokens an image of this pixel size takes: its 40-pixel cells. +pub const tokensOf = base.tokensFor; + +/// The processor's rescale factor and mean / std (all channels), applied as two roundings like the reference. +const rescale: f32 = 0.00392156862745098; +const mean: f32 = 0.5; +const std_dev: f32 = 0.5; +const pad_value: f32 = -1.0; + +/// An image as tower input: `tokens` = gh * gw rows of the language model's, `pixels` = tokens * token_width f32. +pub const Prepared = struct { + pixels: []f32, + gh: u32, + gw: u32, + tokens: u32, + hash: u64, +}; + +pub const Error = picture.Error || error{NoImageBudget}; + +/// The words for a refusal the server cannot word itself. +pub fn problem(err: anyerror) ?[]const u8 { + if (err == error.NoImageBudget) return "the request has no image token budget left"; + return picture.decoderProblem(err); +} + +fn cells(n: usize) usize { + return (n + cell - 1) / cell; +} + +/// The patches of `rgb` (w x h, three bytes a pixel) padded to whole cells, in token raster and merge-block order. +pub fn patchify(gpa: std.mem.Allocator, rgb: []const u8, w: usize, h: usize) ![]f32 { + const rows = cells(h); + const cols = cells(w); + const out = try gpa.alloc(f32, rows * cols * token_width); + errdefer gpa.free(out); + for (0..rows) |tr| for (0..cols) |tc| { + const token = out[(tr * cols + tc) * token_width ..][0..token_width]; + for (0..merge * merge) |q| { + const y0 = tr * cell + (q / merge) * patch; + const x0 = tc * cell + (q % merge) * patch; + const dst = token[q * patch_width ..][0..patch_width]; + for (0..patch) |py| for (0..patch) |px| for (0..3) |c| { + const y = y0 + py; + const x = x0 + px; + const v: f32 = if (y < h and x < w) @floatFromInt(rgb[(y * w + x) * 3 + c]) else pad_value; + dst[(py * patch + px) * 3 + c] = (v * rescale - mean) / std_dev; + }; + } + }; + return out; +} + +/// The largest size within `budget` tokens that keeps the aspect: only an over-budget image is resized. +fn fit(w: usize, h: usize, budget: usize) [2]usize { + var nw = w; + var nh = h; + if (cells(w) * cells(h) <= budget) return .{ w, h }; + const scale = @sqrt(@as(f64, @floatFromInt(budget * cell * cell)) / @as(f64, @floatFromInt(w * h))); + nw = @max(1, @as(usize, @intFromFloat(@floor(@as(f64, @floatFromInt(w)) * scale)))); + nh = @max(1, @as(usize, @intFromFloat(@floor(@as(f64, @floatFromInt(h)) * scale)))); + while (cells(nw) * cells(nh) > budget) { + if (nw >= nh and nw > 1) nw -= 1 else if (nh > 1) nh -= 1 else break; + } + return .{ nw, nh }; +} + +/// Oriented RGB to tower input within `max_tokens`; the hash covers `bytes_hash` and the grid. +pub fn fromRgb(gpa: std.mem.Allocator, rgb: picture.Rgb, bytes_hash: u64, max_tokens: u32) !Prepared { + if (max_tokens == 0) return error.NoImageBudget; + const size = fit(rgb.width, rgb.height, max_tokens); + var resized: ?[]u8 = null; + defer if (resized) |r| gpa.free(r); + var pixels = rgb.pixels; + if (size[0] != rgb.width or size[1] != rgb.height) { + resized = try picture.resample.resize(gpa, .torch, .of(rgb.pixels, rgb.width, rgb.height), size[0], size[1]); + pixels = resized.?; + } + const gh: u32 = @intCast(cells(size[1])); + const gw: u32 = @intCast(cells(size[0])); + const out = try patchify(gpa, pixels, size[0], size[1]); + return .{ .pixels = out, .gh = gh, .gw = gw, .tokens = gh * gw, .hash = identity.withGrid(bytes_hash, .{ gh, gw }) }; +} + +/// Image bytes (PNG, JPEG, WebP) to tower input on the HTTP thread, at most `max_tokens` tokens. +pub fn prepare(io: std.Io, gpa: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !Prepared { + if (max_tokens == 0) return error.NoImageBudget; + var rgb = try base.decode(io, gpa, bytes, .{}); + defer rgb.deinit(gpa); + return fromRgb(gpa, rgb, identity.ofBytes(0x1c2d, bytes), max_tokens); +} diff --git a/zig/src/families/inkling2/metal/vision_image_test.zig b/zig/src/families/inkling2/metal/vision_image_test.zig new file mode 100644 index 00000000000..0dbc5e03876 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_image_test.zig @@ -0,0 +1,234 @@ +//! Mini's image preprocessing from PNG/JPEG against the HF formulas (pad, rescale, normalize, 40-pixel patch tokens). +const std = @import("std"); +const core = @import("core"); +const config = @import("../config.zig"); +const image = @import("vision_image.zig"); +const tables = @import("vision_tables.zig"); + +const picture = core.picture; +const t = std.testing; + +const png_rgba = @embedFile("../fixtures/media_rgba.png"); +const raw_rgba = @embedFile("../fixtures/media_rgba.raw"); // 45 x 37, four bytes a pixel +const png_rgb = @embedFile("../fixtures/media_rgb.png"); +const raw_rgb = @embedFile("../fixtures/media_rgb.raw"); // 41 x 43 +const jpeg_photo = @embedFile("../fixtures/media_photo.jpg"); +const raw_photo = @embedFile("../fixtures/media_photo.raw"); // 50 x 30 + +pub fn rgbImage(a: std.mem.Allocator, w: usize, h: usize) !picture.Rgb { + const px = try a.alloc(u8, w * h * 3); + for (0..h) |y| for (0..w) |x| { + px[(y * w + x) * 3] = @intCast(x * 255 / @max(w - 1, 1)); + px[(y * w + x) * 3 + 1] = @intCast(y * 255 / @max(h - 1, 1)); + px[(y * w + x) * 3 + 2] = @intCast((x + y) % 256); + }; + return .{ .width = w, .height = h, .pixels = px }; +} + +test "the processor pads to 40-pixel cells with -1, normalizes to [-1, 1], and orders merge blocks then patches" { + try t.expectEqual(@as(usize, 2), image.tokensOf(41, 40)); + try t.expectEqual(@as(usize, 1), image.tokensOf(40, 40)); + try t.expectEqual(@as(usize, 6), image.tokensOf(81, 80)); + var rgb = try rgbImage(t.allocator, 50, 30); + defer rgb.deinit(t.allocator); + const p = try image.fromRgb(t.allocator, rgb, 7, 16); + defer t.allocator.free(p.pixels); + try t.expectEqual(@as(u32, 1), p.gh); + try t.expectEqual(@as(u32, 2), p.gw); + try t.expectEqual(@as(usize, 2 * image.token_width), p.pixels.len); + // token 0, patch 0 (rows 0..19, cols 0..19), pixel (0, 0) channel 0: byte 0 -> -1 + try t.expectEqual(@as(f32, -1.0), p.pixels[0]); + // token 0, patch 1 = columns 20.., pixel (0, 0): x = 20 of 50 -> byte 20 * 255 / 49 + const byte: f32 = @floatFromInt(20 * 255 / 49); + try t.expectApproxEqAbs(byte / 255.0 * 2 - 1, p.pixels[image.patch_width], 1e-6); + // token 0, patch 2 starts at row 20 of a 30-high image: its rows 10.. are padding, (-1 / 255 - 0.5) / 0.5 + const pad: f32 = (-1.0 / 255.0 - 0.5) / 0.5; + try t.expectApproxEqAbs(pad, p.pixels[2 * image.patch_width + (10 * image.patch + 0) * 3], 1e-6); + // the same image under a one-token budget is resized to fit, aspect kept + const small = try image.fromRgb(t.allocator, rgb, 7, 1); + defer t.allocator.free(small.pixels); + try t.expectEqual(@as(u32, 1), small.tokens); + try t.expect(small.hash != p.hash); + try t.expectError(error.NoImageBudget, image.fromRgb(t.allocator, rgb, 7, 0)); + try t.expect(image.problem(error.NoImageBudget) != null); +} + +test "position taps are the half-pixel bilinear grid and the rotary table turns columns on the first frequencies" { + const hd = 8; + const n = comptime tables.patches(1, 2); + var taps: [n * 4]u32 = undefined; + var wts: [n * 4]f32 = undefined; + var cs: [(n + 1) * hd]f32 = undefined; + var sn: [(n + 1) * hd]f32 = undefined; + tables.fill(1, 2, hd, &taps, &wts, &cs, &sn); + // patch 0 sits at (0, 0) of a 2 x 4 patch grid: row source 7.5 on the 32-cell table, column source 3.5 + try t.expectEqual([4]u32{ 7 * 32 + 3, 7 * 32 + 4, 8 * 32 + 3, 8 * 32 + 4 }, taps[0..4].*); + try t.expectEqual([4]f32{ 0.25, 0.25, 0.25, 0.25 }, wts[0..4].*); + try t.expectEqual(@as(f32, 1.0), cs[0]); + try t.expectEqual(@as(f32, 0.0), sn[0]); + // patch 1 (row 0, column 1): positions (1, 2); pair 0 turns with a column frequency, pair 2 with a row one + try t.expectApproxEqAbs(@cos(@as(f32, 2.0)), cs[2 * hd], 1e-6); + try t.expectApproxEqAbs(@cos(@as(f32, 1.0)), cs[2 * hd + 4], 1e-6); + try t.expectApproxEqAbs(@sin(@as(f32, 2.0)), sn[2 * hd + 1], 1e-6); + var weight_sum: f32 = 0; + for (wts[4..8]) |w| weight_sum += w; + try t.expectApproxEqAbs(@as(f32, 1.0), weight_sum, 1e-5); +} + +test "Mini's vision config is the tower this engine runs: 23 layers, 16 heads of 64, patch 20, merge 2, 1e-5 norms" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + var why: config.Why = .{}; + const c = (try config.parse(arena.allocator(), @embedFile("../fixtures/mini_config.json"), &why)).vision; + try t.expectEqual(@as(u32, 1024), c.hidden); + try t.expectEqual(@as(u32, 23), c.layers); + try t.expectEqual(@as(u32, 16), c.heads); + try t.expectEqual(@as(u32, image.patch), c.patch); + try t.expectEqual(@as(u32, image.merge), c.merge); + try t.expectEqual(@as(u32, image.grid), c.grid); + try t.expectEqual(@as(u32, 4), c.mlp_ratio); + try t.expectEqual(@as(u32, 4096), c.proj_hidden); + try t.expectEqual(@as(u32, 2304), c.text_hidden); + try t.expectEqual(@as(usize, 1200), image.patch_width); // the checkpoint's patch_embedding.weight [1024, 1200] +} + +/// convert_to_rgb of an RGBA uint8 image (integer arithmetic on int32, as the processor's). +fn composite(a: std.mem.Allocator, rgba: []const u8, w: usize, h: usize) ![]u8 { + const out = try a.alloc(u8, w * h * 3); + for (0..h) |y| for (0..w) |x| { + const alpha: i32 = rgba[(y * w + x) * 4 + 3]; + const bg: i32 = if (((y / 8) + (x / 8)) % 2 == 0) 204 else 153; + for (0..3) |c| { + const v: i32 = rgba[(y * w + x) * 4 + c]; + out[(y * w + x) * 3 + c] = @intCast(@divFloor(v * alpha + bg * (255 - alpha) + 127, 255)); + } + }; + return out; +} + +/// pixel_values of one image as the model's patch embedding reads them: [tokens, merge row, merge column, 20, 20, 3]. +fn oracle(a: std.mem.Allocator, rgb: []const u8, w: usize, h: usize) ![]f32 { + const rows = (h + 39) / 40; + const cols = (w + 39) / 40; + // padded [3][rows * 40][cols * 40] on the 0..255 scale, filled with -1 + const hh = rows * 40; + const ww = cols * 40; + const padded = try a.alloc(f32, 3 * hh * ww); + @memset(padded, -1.0); + for (0..3) |c| for (0..h) |y| for (0..w) |x| { + padded[(c * hh + y) * ww + x] = @floatFromInt(rgb[(y * w + x) * 3 + c]); + }; + for (padded) |*v| v.* = (v.* * 0.00392156862745098 - 0.5) / 0.5; + const out = try a.alloc(f32, rows * cols * 4 * 20 * 20 * 3); + var at: usize = 0; + // image.reshape(C, rows, 40, cols, 40).permute(1, 3, 2, 4, 0): token (row, col) holds [40, 40, 3] ... + for (0..rows) |tr| for (0..cols) |tc| { + // ... which reshape(-1, 2, 20, 2, 20, 3).transpose(2, 3) reorders to [merge row, merge col, 20, 20, 3] + for (0..2) |mr| for (0..2) |mc| for (0..20) |py| for (0..20) |px| for (0..3) |c| { + out[at] = padded[(c * hh + tr * 40 + mr * 20 + py) * ww + tc * 40 + mc * 20 + px]; + at += 1; + }; + }; + return out; +} + +fn expectPixels(want: []const f32, got: []const f32, tol: f32) !void { + try t.expectEqual(want.len, got.len); + for (want, got, 0..) |w, g, i| if (!std.math.isFinite(g) or @abs(w - g) > tol) { + std.debug.print("pixel {d}: want {d}, got {d}\n", .{ i, w, g }); + return error.TestExpectedEqual; + }; +} + +test "an RGB PNG becomes the processor's patches: whole cells, -1 padding, merge-block order" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p = try image.prepare(t.io, a, png_rgb, 16); + try t.expectEqual(@as(u32, 2), p.gh); + try t.expectEqual(@as(u32, 2), p.gw); + try t.expectEqual(@as(u32, 4), p.tokens); + try t.expectEqual(@as(usize, image.tokensOf(41, 43)), p.tokens); + try expectPixels(try oracle(a, raw_rgb, 41, 43), p.pixels, 1e-6); +} + +test "an RGBA PNG is composited over the 8-pixel 204/153 checkerboard before padding" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p = try image.prepare(t.io, a, png_rgba, 16); + try t.expectEqual(@as(u32, 1), p.gh); + try t.expectEqual(@as(u32, 2), p.gw); + const rgb = try composite(a, raw_rgba, 45, 37); + try expectPixels(try oracle(a, rgb, 45, 37), p.pixels, 1e-6); + // a fully transparent pixel shows the checkerboard itself, never the colour under the alpha + try t.expectEqual(@as(u8, 0), raw_rgba[3]); + try t.expectApproxEqAbs((@as(f32, 204) / 255.0 - 0.5) / 0.5, p.pixels[0], 1e-6); +} + +test "a JPEG decodes through the native path to the same grid and pixels within the decoder's rounding" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p = image.prepare(t.io, a, jpeg_photo, 16) catch |err| switch (err) { + error.NoJpegLibrary, error.JpegLibraryVersion => return error.SkipZigTest, + else => return err, + }; + try t.expectEqual(@as(u32, 1), p.gh); + try t.expectEqual(@as(u32, 2), p.gw); + // Pillow's libjpeg and the engine's may differ by a few levels of IDCT rounding; padding and layout must not + try expectPixels(try oracle(a, raw_photo, 50, 30), p.pixels, 4.0 / 127.5); +} + +test "JPEG EXIF orientation changes the grid and turns the samples before patchification" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const exif = "\xff\xe1\x00\x22Exif\x00\x00II*\x00\x08\x00\x00\x00" ++ + "\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00"; + const turned_jpeg = try std.mem.concat(a, u8, &.{ jpeg_photo[0..2], exif, jpeg_photo[2..] }); + const p = image.prepare(t.io, a, turned_jpeg, 16) catch |err| switch (err) { + error.NoJpegLibrary, error.JpegLibraryVersion => return error.SkipZigTest, + else => return err, + }; + try t.expectEqual(@as(u32, 2), p.gh); + try t.expectEqual(@as(u32, 1), p.gw); + const rotated = try a.alloc(u8, raw_photo.len); + for (0..30) |y| for (0..50) |x| { + @memcpy(rotated[(x * 30 + (29 - y)) * 3 ..][0..3], raw_photo[(y * 50 + x) * 3 ..][0..3]); + }; + try expectPixels(try oracle(a, rotated, 30, 50), p.pixels, 4.0 / 127.5); +} + +test "an image over the token budget is resized to fit and keeps the grid it reports; a budget of 0 refuses" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const one = try image.prepare(t.io, a, png_rgb, 1); + try t.expectEqual(@as(u32, 1), one.tokens); + try t.expectEqual(@as(usize, image.token_width), one.pixels.len); + const pad: f32 = -1.0 - 2.0 / 255.0; + var saw_pad = false; + for (one.pixels) |v| { + try t.expect(v >= pad - 1e-6 and v <= 1.0); + saw_pad = saw_pad or @abs(v - pad) < 1e-6; + } + try t.expect(saw_pad); + const whole = try image.prepare(t.io, a, png_rgb, 16); + try t.expect(one.hash != whole.hash); // the hash covers the grid, so cached rows are never reused across budgets + const again = try image.prepare(t.io, a, png_rgb, 16); + try t.expectEqual(whole.hash, again.hash); + try t.expectError(error.NoImageBudget, image.prepare(t.io, a, png_rgb, 0)); +} + +test "bytes that are not a supported picture are refused with words for the client" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try t.expectError(error.Invalid, image.prepare(t.io, a, "not a picture", 16)); + try t.expectError(error.Invalid, image.prepare(t.io, a, "", 16)); + // a PNG cut in the middle of its pixel data + try t.expect(std.meta.isError(image.prepare(t.io, a, png_rgb[0 .. png_rgb.len / 2], 16))); + try t.expect(image.problem(error.NoImageBudget) != null); + try t.expect(image.problem(error.Invalid) == null); // the server words Invalid itself +} diff --git a/zig/src/families/inkling2/metal/vision_real_test.zig b/zig/src/families/inkling2/metal/vision_real_test.zig new file mode 100644 index 00000000000..bfca2dbce85 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_real_test.zig @@ -0,0 +1,85 @@ +//! Run the original 23-layer tower against the independent FP64 tower formula. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const fixture = @import("vision_checkpoint_test.zig"); +const oracle = @import("vision_test.zig"); +const image = @import("vision_image.zig"); +const vision = @import("vision.zig"); +const t = std.testing; + +const Gpu = struct { + device: mtl.Device, + queue: mtl.Queue, + + fn init() !Gpu { + const device = mtl.Device.init() catch return error.SkipZigTest; + errdefer device.deinit(); + return .{ .device = device, .queue = device.queue() catch return error.SkipZigTest }; + } + fn deinit(g: Gpu) void { + g.queue.deinit(); + g.device.deinit(); + } +}; + +test "original Mini vision projector matches the FP64 oracle on square and padded rectangular images" { + const dir = try fixture.directory(); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg = try fixture.loadConfig(a, dir); + try t.expectEqual(@as(u32, 23), cfg.vision.layers); + const gpu = try Gpu.init(); + defer gpu.deinit(); + const path = try fixture.shard(a, dir, "model.visual.backbone.embeddings.patch_embedding.weight"); + var store = ck.Checkpoint.init(t.allocator); + defer store.deinit(); + try store.addFileSelected(gpu.device, path, "", "model.visual."); + try t.expectEqual(@as(usize, 422), store.tensors.count()); + const tower = try vision.Tower.loadFromCheckpoint(t.allocator, gpu.device, gpu.queue, &cfg, .{ .max_tokens = 2 }, &store); + defer tower.deinit(); + const patch = try store.get("model.visual.backbone.embeddings.patch_embedding.weight"); + try t.expectEqual(patch.buffer.id, tower.patch_w.buf.id); + try t.expectEqual(patch.offset, tower.patch_w.off); + try t.expect(tower.bytes() < store.residentBytes()); + for ([_][2]usize{ .{ 40, 40 }, .{ 79, 34 } }) |wh| { + var rgb = try @import("vision_image_test.zig").rgbImage(a, wh[0], wh[1]); + defer rgb.deinit(a); + const p = try image.fromRgb(a, rgb, 1, 2); + const out = try tower.encodeInput(p.pixels, p.gh, p.gw); + defer out.deinit(); + const want = try oracle.reference(a, &store, cfg.vision, p.pixels, p.gh, p.gw); + const got = out.slice(u16, want.len); + const width = cfg.vision.text_hidden; + for (0..p.tokens) |row| { + const err = oracle.compare(got[row * width ..][0..width], want[row * width ..][0..width]); + if (err.rms >= 0.05) { + std.debug.print("vision {d}x{d} row {d}: relative RMS error {d}, worst column {d}\n", .{ wh[0], wh[1], row, err.rms, err.max_abs }); + try diagnose(tower, &store, p, got); + return error.VisionProjectorMismatch; + } + } + } +} + +fn diagnose(tower: *vision.Tower, store: *const ck.Checkpoint, p: vision.Prepared, got: []const u16) !void { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg = tower.cfg; + const n = cfg.layers + 1; + const words = (@as(usize, p.tokens) * cfg.merge * cfg.merge + 1) * cfg.hidden * n; + const trace = try tower.device.buffer(words * 2, mtl.ResourceOptions.shared); + defer trace.deinit(); + const out = try tower.traceInput(p.pixels, p.gh, p.gw, trace); + defer out.deinit(); + try t.expectEqualSlices(u16, got, out.slice(u16, got.len)); + const errs = try a.alloc(oracle.Error, n); + const expected = try oracle.evaluate(a, store, cfg, p.pixels, p.gh, p.gw, trace.slice(u16, words), errs); + for (errs, 0..) |err, i| { + std.debug.print("vision stage {d} with matched BF16 input: rel RMS {d}, max abs {d}\n", .{ i, err.rms, err.max_abs }); + } + const err = oracle.compare(got, expected); + std.debug.print("vision projector with matched BF16 input: rel RMS {d}, max abs {d}\n", .{ err.rms, err.max_abs }); +} diff --git a/zig/src/families/inkling2/metal/vision_tables.zig b/zig/src/families/inkling2/metal/vision_tables.zig new file mode 100644 index 00000000000..7a006227eff --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_tables.zig @@ -0,0 +1,38 @@ +//! The image tower's per-image index tables: the processor's bilinear position taps and axial rotary rows. +const std = @import("std"); +const base = @import("../image.zig"); + +/// The vision rotary base (Inkling2VisionConfig's rope_parameters carry none, so the library default 10000 holds). +pub const rope_theta: f64 = 10000; + +/// Table sizes for an image: patches = tokens * merge^2, sequence rows = patches + 1 (the class row first). +pub fn patches(gh: u32, gw: u32) usize { + return @as(usize, gh) * gw * base.merge * base.merge; +} + +/// Fills taps and weights ([patches * 4]) and cos / sin ([(patches + 1) * head_dim], class row first). +pub fn fill(gh: u32, gw: u32, head_dim: u32, taps: []u32, weights: []f32, cos: []f32, sin: []f32) void { + const n = patches(gh, gw); + var none: [0]f32 = .{}; + base.positionTaps(.{ .pixels = &none, .rows = gh, .cols = gw }, taps[0 .. n * 4], weights[0 .. n * 4]); + const nf = head_dim / 4; + var inv: [64]f32 = undefined; + for (0..nf) |j| inv[j] = @floatCast(1.0 / std.math.pow(f64, rope_theta, @as(f64, @floatFromInt(j)) / @as(f64, @floatFromInt(nf)))); + for (0..head_dim) |d| { + cos[d] = 1.0; + sin[d] = 0.0; + } + for (0..n) |i| { + const at = base.place(i, gw); + const pos = [2]f32{ @floatFromInt(at[1] + 1), @floatFromInt(at[0] + 1) }; // column first (recomposition_frequencies) + for (0..head_dim / 2) |p| { + const on_row = p >= nf; + const angle = pos[@intFromBool(on_row)] * inv[p % nf]; + const row = (i + 1) * head_dim; + cos[row + 2 * p] = @cos(angle); + cos[row + 2 * p + 1] = @cos(angle); + sin[row + 2 * p] = @sin(angle); + sin[row + 2 * p + 1] = @sin(angle); + } + } +} diff --git a/zig/src/families/inkling2/metal/vision_test.zig b/zig/src/families/inkling2/metal/vision_test.zig new file mode 100644 index 00000000000..9246fbc8841 --- /dev/null +++ b/zig/src/families/inkling2/metal/vision_test.zig @@ -0,0 +1,463 @@ +//! Mini's image tower on the GPU: GEMMs and the tower against an f64 reference on a synthetic single-shard checkpoint. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("inkling2_metal"); +const frags = @import("../../../core/frags.zig"); +const config = @import("../config.zig"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const gm = @import("vision_gemm.zig"); +const image = @import("vision_image.zig"); +const vision = @import("vision.zig"); +const rgbImage = @import("vision_image_test.zig").rgbImage; + +fn bf(x: f32) u16 { + const u: u32 = @bitCast(x); + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +fn unbf(h: u16) f64 { + return @as(f32, @bitCast(@as(u32, h) << 16)); +} + +fn rb(x: f64) f64 { + return unbf(bf(@floatCast(x))); +} + +fn shape(a: std.mem.Allocator, dims: []const usize) ![]const usize { + return a.dupe(usize, dims); +} + +const t = std.testing; + +const Gpu = struct { + device: mtl.Device, + queue: mtl.Queue, + lib: mtl.Library, + + fn init() !Gpu { + const device = mtl.Device.init() catch return error.SkipZigTest; + errdefer device.deinit(); + const queue = device.queue() catch return error.SkipZigTest; + errdefer queue.deinit(); + const src = try frags.source(device, t.allocator, sources.vision); + defer t.allocator.free(src); + return .{ .device = device, .queue = queue, .lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()) }; + } + fn deinit(g: Gpu) void { + g.lib.deinit(); + g.queue.deinit(); + g.device.deinit(); + } +}; + +fn gemmCase(g: Gpu, gemm: *const gm.Gemm, kind: gm.Kind, m: u32, n: u32, k: u32, nn: bool) !void { + const wide = kind == .f32_nt or kind == .f32_nn; + const out32 = wide or kind == .bf16f_nt; + const a = try g.device.buffer(@as(usize, m) * k * (if (wide) @as(usize, 4) else 2), mtl.ResourceOptions.shared); + defer a.deinit(); + const b = try g.device.buffer(@as(usize, n) * k * (if (wide) @as(usize, 4) else 2), mtl.ResourceOptions.shared); + defer b.deinit(); + const d = try g.device.buffer(@as(usize, m) * n * (if (out32) @as(usize, 4) else 2), mtl.ResourceOptions.shared); + defer d.deinit(); + var prng = std.Random.DefaultPrng.init(m * 7 + n); + const rng = prng.random(); + const av = try t.allocator.alloc(f64, @as(usize, m) * k); + defer t.allocator.free(av); + const bv = try t.allocator.alloc(f64, @as(usize, n) * k); + defer t.allocator.free(bv); + for (av, 0..) |*v, i| { + const x = rng.float(f32) * 2 - 1; + if (wide) a.slice(f32, av.len)[i] = x else a.slice(u16, av.len)[i] = bf(x); + v.* = if (wide) x else unbf(bf(x)); + } + for (bv, 0..) |*v, i| { + const x = rng.float(f32) * 2 - 1; + if (wide) b.slice(f32, bv.len)[i] = x else b.slice(u16, bv.len)[i] = bf(x); + v.* = if (wide) x else unbf(bf(x)); + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = g.queue.commandBuffer(); + const e = cb.compute(.serial); + gemm.run(e, kind, .{ .buf = a }, .{ .buf = b }, .{ .buf = d }, .{ .m = m, .n = n, .k = k, .lda = k, .ldb = if (nn) n else k, .ldd = n }); + e.end(); + cb.commit(); + cb.wait(); + try t.expect(cb.failure() == null); + for (0..m) |r| for (0..n) |c| { + var s: f64 = 0; + for (0..k) |i| s += av[r * k + i] * (if (nn) bv[i * n + c] else bv[c * k + i]); + const got: f64 = if (out32) d.slice(f32, @as(usize, m) * n)[r * n + c] else unbf(d.slice(u16, @as(usize, m) * n)[r * n + c]); + const want = if (out32) s else rb(s); + try t.expectApproxEqAbs(want, got, if (out32) 5e-3 + 2e-3 * @abs(want) else 1e-3 + 1e-2 * @abs(want)); + }; +} + +test "the tensor-unit GEMMs: every kind, whole and ragged tiles, K past and short of 256" { + const g = try Gpu.init(); + defer g.deinit(); + var gemm = try gm.Gemm.init(g.device, g.lib, &.{ .bf16_nt, .bf16f_nt, .f32_nt, .f32_nn }); + defer gemm.deinit(); + for ([_][3]u32{ .{ 64, 128, 256 }, .{ 70, 130, 300 }, .{ 9, 32, 32 }, .{ 3, 200, 128 } }) |s| { + try gemmCase(g, &gemm, .bf16_nt, s[0], s[1], s[2], false); + try gemmCase(g, &gemm, .bf16f_nt, s[0], s[1], s[2], false); + try gemmCase(g, &gemm, .f32_nt, s[0], s[1], s[2], false); + try gemmCase(g, &gemm, .f32_nn, s[0], s[1], s[2], true); + } +} + +// ---- the tower ---- + +const Named = struct { name: []const u8, dims: []const usize, scale: f32, bias: f32 }; + +fn writeShard(a: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, file: []const u8, specs: []const Named, seed: u64) !void { + var header: std.ArrayList(u8) = .empty; + var data: std.ArrayList(u8) = .empty; + try header.append(a, '{'); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (specs, 0..) |s, i| { + var n: usize = 1; + for (s.dims) |d| n *= d; + const v = try a.alloc(u16, n); + for (v) |*h| h.* = bf(s.bias + s.scale * (rng.float(f32) * 2 - 1)); + if (i != 0) try header.append(a, ','); + try header.print(a, "\"{s}\":{{\"dtype\":\"BF16\",\"shape\":[", .{s.name}); + for (s.dims, 0..) |d, j| try header.print(a, "{s}{d}", .{ if (j != 0) "," else "", d }); + try header.print(a, "],\"data_offsets\":[{d},{d}]}}", .{ data.items.len, data.items.len + n * 2 }); + try data.appendSlice(a, std.mem.sliceAsBytes(v)); + } + try header.append(a, '}'); + while (header.items.len % 8 != 0) try header.append(a, ' '); + var out: std.ArrayList(u8) = .empty; + try out.resize(a, 8); + std.mem.writeInt(u64, out.items[0..8], header.items.len, .little); + try out.appendSlice(a, header.items); + try out.appendSlice(a, data.items); + try dir.writeFile(io, .{ .sub_path = file, .data = out.items }); +} + +extern "c" fn erf(x: f64) f64; +fn gelu(x: f64) f64 { + return 0.5 * x * (1 + erf(x / @sqrt(2.0))); +} + +fn layerNorm(x: []const f64, w: []const u16, b: []const u16, eps: f64, out: []f64) void { + const n: f64 = @floatFromInt(x.len); + var mean: f64 = 0; + for (x) |v| mean += v; + mean /= n; + var vr: f64 = 0; + for (x) |v| vr += (v - mean) * (v - mean); + const inv = 1.0 / @sqrt(vr / n + eps); + for (x, out, w, b) |v, *o, g, bi| o.* = rb((v - mean) * inv * unbf(g) + unbf(bi)); +} + +/// out [rows, n] = sum x [rows, k] w^T (+ bias), unrounded: the caller rounds where the model does. +fn lin(x: []const f64, rows: usize, k: usize, w: []const u16, n: usize, bias: ?[]const u16, out: []f64) void { + for (0..rows) |r| for (0..n) |o| { + var s: f64 = 0; + for (0..k) |i| s += x[r * k + i] * unbf(w[o * k + i]); + out[r * n + o] = s + if (bias) |b| unbf(b[o]) else 0; + }; +} + +fn roundAll(v: []f64) void { + for (v) |*e| e.* = rb(e.*); +} + +fn coord(p: usize, pixels: usize, table: usize) f64 { + const x: f64 = @floatFromInt(p); + const scale = @as(f64, @floatFromInt(table)) / @as(f64, @floatFromInt(pixels)); + return std.math.clamp((x + 0.5) * scale - 0.5, 0, @as(f64, @floatFromInt(table - 1))); +} + +fn oracleTables(gh: usize, gw: usize, merge: usize, side: usize, hd: usize, taps: []u32, wts: []f64, cs: []f64, sn: []f64) void { + @memset(cs[0..hd], 1); + @memset(sn[0..hd], 0); + var p: usize = 0; + for (0..gh) |ty| for (0..gw) |tx| for (0..merge) |dy| for (0..merge) |dx| { + const py = ty * merge + dy; + const px = tx * merge + dx; + const y = coord(py, gh * merge, side); + const x = coord(px, gw * merge, side); + const top: usize = @intFromFloat(@floor(y)); + const left: usize = @intFromFloat(@floor(x)); + const fy = y - @floor(y); + const fx = x - @floor(x); + for (0..2) |j| for (0..2) |i| { + const k = p * 4 + j * 2 + i; + taps[k] = @intCast(@min(top + j, side - 1) * side + @min(left + i, side - 1)); + wts[k] = (if (j == 0) 1 - fy else fy) * (if (i == 0) 1 - fx else fx); + }; + const frequencies = hd / 4; + for (0..hd) |d| { + const pair = d / 2; + const axial_pos: f64 = @floatFromInt(if (pair < frequencies) px + 1 else py + 1); + const exponent = @as(f64, @floatFromInt(pair % frequencies)) / @as(f64, @floatFromInt(frequencies)); + const angle = axial_pos / std.math.pow(f64, 10000, exponent); + cs[(p + 1) * hd + d] = @cos(angle); + sn[(p + 1) * hd + d] = @sin(angle); + } + p += 1; + }; +} + +/// Tower's f64 reference over the checkpoint's `model.visual.*` tensors; each op rounds to bf16 where the model's does. +pub fn reference(a: std.mem.Allocator, w: *const ck.Checkpoint, c: config.Vision, pixels: []const f32, gh: u32, gw: u32) ![]f64 { + return evaluate(a, w, c, pixels, gh, gw, &.{}, &.{}); +} + +pub const Error = struct { rms: f64, max_abs: f64 }; + +fn replay(x: []f64, captured: []const u16, layer: usize, errs: []Error) void { + if (errs.len == 0) return; + const expected = captured[layer * x.len ..][0..x.len]; + errs[layer] = compare(expected, x); + for (x, expected) |*v, b| v.* = unbf(b); +} + +pub fn compare(got: []const u16, want: []const f64) Error { + var abs: f64 = 0; + var err: f64 = 0; + var mag: f64 = 0; + for (got, want) |b, v| { + const d = @abs(unbf(b) - v); + if (!std.math.isFinite(d)) return .{ .rms = std.math.inf(f64), .max_abs = std.math.inf(f64) }; + abs = @max(abs, d); + err += d * d; + mag += v * v; + } + return .{ .rms = @sqrt(err / @max(mag, 0x1p-100)), .max_abs = abs }; +} + +/// After each stage, record its local error and substitute the GPU's actual BF16 rows for the next stage. +pub fn evaluate(a: std.mem.Allocator, w: *const ck.Checkpoint, c: config.Vision, pixels: []const f32, gh: u32, gw: u32, captured: []const u16, errs: []Error) ![]f64 { + const h: usize = c.hidden; + const hd = h / c.heads; + const P = @as(usize, gh) * gw * c.merge * c.merge; + const S = P + 1; + const pre = "model.visual.backbone."; + const get = struct { + fn f(m: *const ck.Checkpoint, comptime fmt: []const u8, args: anytype) []const u16 { + var buf: [128]u8 = undefined; + return (m.get(std.fmt.bufPrint(&buf, fmt, args) catch unreachable) catch unreachable).host(u16); + } + }.f; + const taps = try a.alloc(u32, P * 4); + const wts = try a.alloc(f64, P * 4); + const cs = try a.alloc(f64, S * hd); + const sn = try a.alloc(f64, S * hd); + oracleTables(gh, gw, c.merge, c.grid, hd, taps, wts, cs, sn); + const pix = try a.alloc(f64, P * image.patch_width); + for (pix, pixels[0..pix.len]) |*o, v| o.* = unbf(bf(v)); + const pe = try a.alloc(f64, P * h); + lin(pix, P, image.patch_width, get(w, pre ++ "embeddings.patch_embedding.weight", .{}), h, null, pe); + roundAll(pe); + var x = try a.alloc(f64, S * h); + const table = get(w, pre ++ "embeddings.position_embedding", .{}); + const cls = get(w, pre ++ "embeddings.class_embedding", .{}); + const cls_pos = get(w, pre ++ "embeddings.cls_position_embedding", .{}); + for (0..h) |i| x[i] = rb(unbf(cls[i]) + unbf(cls_pos[i])); + for (0..P) |p| for (0..h) |i| { + var s: f64 = 0; + for (0..4) |k| s += unbf(table[taps[p * 4 + k] * h + i]) * wts[p * 4 + k]; + x[(p + 1) * h + i] = rb(pe[p * h + i] + rb(s)); + }; + const tmp = try a.alloc(f64, S * h); + for (0..S) |r| layerNorm(x[r * h ..][0..h], get(w, pre ++ "ln_pre.weight", .{}), get(w, pre ++ "ln_pre.bias", .{}), c.eps, tmp[r * h ..][0..h]); + @memcpy(x, tmp); + replay(x, captured, 0, errs); + const q = try a.alloc(f64, S * h); + const k = try a.alloc(f64, S * h); + const v = try a.alloc(f64, S * h); + const att = try a.alloc(f64, S * h); + const ff = h * c.mlp_ratio; + const mid = try a.alloc(f64, S * ff); + const branch = try a.alloc(f64, S * h); + for (0..c.layers) |l| { + for (0..S) |r| layerNorm(x[r * h ..][0..h], get(w, pre ++ "layers.{d}.ln_1.weight", .{l}), get(w, pre ++ "layers.{d}.ln_1.bias", .{l}), c.eps, tmp[r * h ..][0..h]); + lin(tmp, S, h, get(w, pre ++ "layers.{d}.self_attn.q_proj.weight", .{l}), h, get(w, pre ++ "layers.{d}.self_attn.q_proj.bias", .{l}), q); + lin(tmp, S, h, get(w, pre ++ "layers.{d}.self_attn.k_proj.weight", .{l}), h, get(w, pre ++ "layers.{d}.self_attn.k_proj.bias", .{l}), k); + lin(tmp, S, h, get(w, pre ++ "layers.{d}.self_attn.v_proj.weight", .{l}), h, get(w, pre ++ "layers.{d}.self_attn.v_proj.bias", .{l}), v); + roundAll(q); + roundAll(k); + roundAll(v); + for ([_][]f64{ q, k }) |m| { + const raw = try a.dupe(f64, m); + for (0..S) |r| for (0..h) |i| { + const d = i % hd; + const partner = raw[r * h + (i ^ 1)]; + const cc: f64 = cs[r * hd + d]; + const ss: f64 = sn[r * hd + d]; + m[r * h + i] = rb(if (d % 2 == 0) raw[r * h + i] * cc - partner * ss else raw[r * h + i] * cc + partner * ss); + }; + } + const scale = 1.0 / @sqrt(@as(f64, @floatFromInt(hd))); + for (0..c.heads) |hh| for (0..S) |r| { + const sc = try a.alloc(f64, S); + var top: f64 = -std.math.inf(f64); + for (0..S) |j| { + var s: f64 = 0; + for (0..hd) |d| s += q[r * h + hh * hd + d] * k[j * h + hh * hd + d]; + sc[j] = rb(rb(s) * scale); + top = @max(top, sc[j]); + } + var z: f64 = 0; + for (sc) |*s| { + s.* = @exp(s.* - top); + z += s.*; + } + for (sc) |*s| s.* = rb(s.* / z); + for (0..hd) |d| { + var o: f64 = 0; + for (0..S) |j| o += sc[j] * v[j * h + hh * hd + d]; + att[r * h + hh * hd + d] = rb(o); + } + }; + lin(att, S, h, get(w, pre ++ "layers.{d}.self_attn.out_proj.weight", .{l}), h, get(w, pre ++ "layers.{d}.self_attn.out_proj.bias", .{l}), branch); + const ls1 = get(w, pre ++ "layers.{d}.ls_1.gamma", .{l}); + for (0..S) |r| for (0..h) |i| { + x[r * h + i] = rb(x[r * h + i] + rb(unbf(ls1[i]) * rb(branch[r * h + i]))); + }; + for (0..S) |r| layerNorm(x[r * h ..][0..h], get(w, pre ++ "layers.{d}.ln_2.weight", .{l}), get(w, pre ++ "layers.{d}.ln_2.bias", .{l}), c.eps, tmp[r * h ..][0..h]); + lin(tmp, S, h, get(w, pre ++ "layers.{d}.mlp.c_fc.weight", .{l}), ff, get(w, pre ++ "layers.{d}.mlp.c_fc.bias", .{l}), mid); + for (mid) |*e| e.* = rb(gelu(rb(e.*))); + lin(mid, S, ff, get(w, pre ++ "layers.{d}.mlp.c_proj.weight", .{l}), h, get(w, pre ++ "layers.{d}.mlp.c_proj.bias", .{l}), branch); + const ls2 = get(w, pre ++ "layers.{d}.ls_2.gamma", .{l}); + for (0..S) |r| for (0..h) |i| { + x[r * h + i] = rb(x[r * h + i] + rb(unbf(ls2[i]) * rb(branch[r * h + i]))); + }; + replay(x, captured, l + 1, errs); + } + const tokens = P / (c.merge * c.merge); + const p1 = try a.alloc(f64, tokens * c.proj_hidden); + lin(x[h..], tokens, h * c.merge * c.merge, get(w, "model.visual.proj_in.weight", .{}), c.proj_hidden, null, p1); + for (p1) |*e| e.* = rb(gelu(rb(e.*))); + const out = try a.alloc(f64, tokens * c.text_hidden); + lin(p1, tokens, c.proj_hidden, get(w, "model.visual.proj_out.weight", .{}), c.text_hidden, null, out); + roundAll(out); + return out; +} + +/// Vision tower at test widths: 3 layers, width 128 over 2 heads of 64, MLP 4x, a 160-wide projector to text width. +fn towerConfig(a: std.mem.Allocator) !config.Config { + var why: config.Why = .{}; + var c = try config.parse(a, @embedFile("../fixtures/mini_config.json"), &why); + c.text.hidden = 128; + c.vision.hidden = 128; + c.vision.layers = 3; + c.vision.heads = 2; + c.vision.proj_hidden = 160; + c.vision.text_hidden = c.text.hidden; + return c; +} + +/// A tower's tensors in file order: one text tensor first (model.llm.* before model.visual.*), then the vision ones. +fn towerSpecs(a: std.mem.Allocator, c: config.Vision) ![]const Named { + const h: usize = c.hidden; + const ff = h * c.mlp_ratio; + var specs: std.ArrayList(Named) = .empty; + const pre = "model.visual.backbone."; + try specs.append(a, .{ .name = "model.llm.norm.weight", .dims = try shape(a, &.{2304}), .scale = 1, .bias = 0 }); + try specs.append(a, .{ .name = pre ++ "embeddings.class_embedding", .dims = try shape(a, &.{h}), .scale = 0.5, .bias = 0 }); + try specs.append(a, .{ .name = pre ++ "embeddings.cls_position_embedding", .dims = try shape(a, &.{h}), .scale = 0.5, .bias = 0 }); + try specs.append(a, .{ .name = pre ++ "embeddings.patch_embedding.weight", .dims = try shape(a, &.{ h, image.patch_width }), .scale = 0.15, .bias = 0 }); + try specs.append(a, .{ .name = pre ++ "embeddings.position_embedding", .dims = try shape(a, &.{ c.grid * c.grid, h }), .scale = 0.5, .bias = 0 }); + try specs.append(a, .{ .name = pre ++ "ln_pre.weight", .dims = try shape(a, &.{h}), .scale = 0.1, .bias = 1 }); + try specs.append(a, .{ .name = pre ++ "ln_pre.bias", .dims = try shape(a, &.{h}), .scale = 0.1, .bias = 0 }); + try specs.append(a, .{ .name = "model.visual.proj_in.weight", .dims = try shape(a, &.{ c.proj_hidden, h * 4 }), .scale = 0.2, .bias = 0 }); + try specs.append(a, .{ .name = "model.visual.proj_out.weight", .dims = try shape(a, &.{ c.text_hidden, c.proj_hidden }), .scale = 0.3, .bias = 0 }); + const per_layer = [_]struct { []const u8, usize, usize, f32, f32 }{ + .{ "ln_1.weight", h, 0, 0.1, 1 }, .{ "ln_1.bias", h, 0, 0.1, 0 }, .{ "ln_2.weight", h, 0, 0.1, 1 }, .{ "ln_2.bias", h, 0, 0.1, 0 }, + .{ "ls_1.gamma", h, 0, 0.3, 0.6 }, .{ "ls_2.gamma", h, 0, 0.3, 0.6 }, .{ "self_attn.q_proj.weight", h, h, 0.3, 0 }, .{ "self_attn.k_proj.weight", h, h, 0.3, 0 }, + .{ "self_attn.v_proj.weight", h, h, 0.3, 0 }, .{ "self_attn.out_proj.weight", h, h, 0.3, 0 }, .{ "self_attn.q_proj.bias", h, 0, 0.1, 0 }, .{ "self_attn.k_proj.bias", h, 0, 0.1, 0 }, + .{ "self_attn.v_proj.bias", h, 0, 0.1, 0 }, .{ "self_attn.out_proj.bias", h, 0, 0.1, 0 }, .{ "mlp.c_fc.weight", ff, h, 0.3, 0 }, .{ "mlp.c_fc.bias", ff, 0, 0.1, 0 }, + .{ "mlp.c_proj.weight", h, ff, 0.2, 0 }, .{ "mlp.c_proj.bias", h, 0, 0.1, 0 }, + }; + for (0..c.layers) |l| for (per_layer) |p| { + const dims: []const usize = if (p[2] == 0) try a.dupe(usize, &.{p[1]}) else try a.dupe(usize, &.{ p[1], p[2] }); + try specs.append(a, .{ .name = try std.fmt.allocPrint(a, pre ++ "layers.{d}.{s}", .{ l, p[0] }), .dims = dims, .scale = p[3], .bias = p[4] }); + }; + return specs.items; +} + +/// The reference's error against the tower's output rows, relative to the reference's magnitude. +pub fn relative(got: []const u16, want: []const f64) !f64 { + var err: f64 = 0; + var mag: f64 = 0; + for (got, want) |gv, wv| { + err += (unbf(gv) - wv) * (unbf(gv) - wv); + mag += wv * wv; + } + try t.expect(mag > 0); + return @sqrt(err / mag); +} + +test "the tower matches the f64 reference on a synthetic single-shard checkpoint read through its index" { + const g = try Gpu.init(); + defer g.deinit(); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg = try towerConfig(a); + const c = cfg.vision; + const specs = try towerSpecs(a, c); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try writeShard(a, t.io, tmp.dir, "model-00001-of-00001.safetensors", specs, 0x7157); + try tmp.dir.writeFile(t.io, .{ .sub_path = "model.safetensors.index.json", .data = try indexFor(a, specs) }); + const path = try tmp.dir.realPathFileAlloc(t.io, ".", a); + const shard = try a.dupeSentinel(u8, try std.fs.path.join(a, &.{ path, "model-00001-of-00001.safetensors" }), 0); + var store = ck.Checkpoint.init(t.allocator); + defer store.deinit(); + try store.addFileSelected(g.device, shard, "", "model.visual."); + + const tower = try vision.Tower.load(t.allocator, t.io, path, g.device, g.queue, &cfg, .{ .max_tokens = 16 }); + defer tower.deinit(); + try t.expect(tower.bytes() > 0); + + for ([_][2]usize{ .{ 80, 40 }, .{ 40, 40 }, .{ 61, 83 } }) |wh| { + var rgb = try rgbImage(a, wh[0], wh[1]); + defer rgb.deinit(a); + const prepared = try image.fromRgb(a, rgb, 1, 16); + try t.expectEqual(@as(u32, @intCast(image.tokensOf(wh[0], wh[1]))), prepared.tokens); + const out = try tower.encodeInput(prepared.pixels, prepared.gh, prepared.gw); + defer out.deinit(); + const want = try reference(a, &store, c, prepared.pixels, prepared.gh, prepared.gw); + try t.expect(try relative(out.slice(u16, want.len), want) < 0.03); + } + + // refusals: more tokens than the scratch holds, and pixels that are not that many tokens + var rgb = try rgbImage(a, 80, 40); + defer rgb.deinit(a); + const prepared = try image.fromRgb(a, rgb, 1, 16); + try t.expectError(error.ImageTooLarge, tower.encodeInput(prepared.pixels, 5, 4)); + try t.expectError(error.ImageGrid, tower.encodeInput(prepared.pixels[1..], prepared.gh, prepared.gw)); +} + +/// The index of the release: every tensor in the one shard, text tensors included. +fn indexFor(a: std.mem.Allocator, specs: []const Named) ![]u8 { + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(a, "{\"metadata\":{},\"weight_map\":{"); + for (specs, 0..) |s, i| try out.print(a, "{s}\"{s}\":\"model-00001-of-00001.safetensors\"", .{ if (i == 0) "" else ",", s.name }); + try out.appendSlice(a, "}}"); + return out.items; +} + +test "a tower refuses a checkpoint without vision tensors and a head width its kernels cannot run" { + const g = try Gpu.init(); + defer g.deinit(); + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + var cfg = try towerConfig(arena.allocator()); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try tmp.dir.realPathFileAlloc(t.io, ".", t.allocator); + defer t.allocator.free(path); + cfg.vision.heads = 5; // 128 / 5 + try t.expectError(error.UnsupportedVisionGeometry, vision.Tower.load(t.allocator, t.io, path, g.device, g.queue, &cfg, .{})); + cfg.vision.heads = 2; + try tmp.dir.writeFile(t.io, .{ .sub_path = "model.safetensors.index.json", .data = "{\"weight_map\":{}}" }); + try t.expectError(error.NoVisionTensors, vision.Tower.load(t.allocator, t.io, path, g.device, g.queue, &cfg, .{})); +} diff --git a/zig/src/inkling2_media_checks.zig b/zig/src/inkling2_media_checks.zig new file mode 100644 index 00000000000..b0813b7b794 --- /dev/null +++ b/zig/src/inkling2_media_checks.zig @@ -0,0 +1,5 @@ +//! Metal device checks for Inkling 2 Mini's image tower: kernels, the 23-layer tower and the original checkpoint. +test { + _ = @import("families/inkling2/metal/vision_test.zig"); + _ = @import("families/inkling2/metal/vision_real_test.zig"); +} diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index 515fab34fc3..747a0ae69d2 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -1,4 +1,4 @@ -//! Text-only Inkling 2 Mini on Metal, with exact prompt reuse and budgeted stream state. +//! Inkling 2 Mini on Metal: text and images, with exact prompt reuse and budgeted stream state. const std = @import("std"); const mtl = @import("metal"); const api = @import("engine_api"); @@ -8,6 +8,7 @@ const st = @import("../families/inkling2/metal/state.zig"); const backend = @import("../families/inkling2/metal/backend.zig"); const dspark = @import("../families/inkling2/metal/dspark.zig"); const admit = @import("../families/inkling2/metal/admit.zig"); +const vision = @import("../families/inkling2/metal/vision.zig"); const Host = struct { gpa: std.mem.Allocator, @@ -16,6 +17,8 @@ const Host = struct { metal: *backend.Metal, drafter: ?*dspark.Drafter = null, drafted: ?lanes.drafted.Drafted = null, + vision: ?*vision.Tower = null, + markers: [1]u32 = undefined, warm: mtl.keepalive.Target, clock: lanes.backend.WallClock, config: lanes.Config = undefined, @@ -33,13 +36,26 @@ const Host = struct { if (h.drafted) |*d| d.deinit(); if (h.drafter) |d| d.deinit(); h.metal.deinit(); + if (h.vision) |v| v.deinit(); h.model.deinit(); h.gpa.destroy(h); } + + fn encode(ctx: *anyopaque, image: lanes.stream.Image) !mtl.Buffer { + const h: *Host = @ptrCast(@alignCast(ctx)); + const tower = h.vision orelse return error.InklingVisionDisabled; + return tower.encodeInput(image.pixels, image.gh, image.gw); + } + + fn prepare(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, cap: u32) !api.PreparedImage { + const h: *Host = @ptrCast(@alignCast(ctx)); + const p = try vision.prepare(h.io, a, bytes, cap); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; + } }; pub fn refusal(o: api.Open) ?[]const u8 { - if (o.vision != null or o.cfg_enabled or o.cfg_batched) return "inkling2_loop: this Metal engine serves text only; images and audio are unsupported"; + if (o.cfg_enabled or o.cfg_batched) return "inkling2_loop: classifier-free guidance is unsupported; images need --vision and audio is unsupported"; if (o.loops != null) return "inkling2_loop: the model has exactly three core passes; --loops cannot override them"; if (o.mtp_drafts != null or o.mtp_confidence != null) return "inkling2_loop: use --drafter for the checkpoint's DSpark head; external draft controls remain unsupported"; if (o.precision != null) return "inkling2_loop: the checkpoint's NVFP4, MXFP8 and BF16 arithmetic is fixed; serve without --precision"; @@ -82,6 +98,14 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope return null; } else null; errdefer if (drafter) |d| d.deinit(); + const tower = if (o.vision) |v| vision.Tower.load(gpa, io, o.dir, model.device, model.queue, &model.config, .{ .max_tokens = v.image_tokens }) catch |err| { + problem.* = try std.fmt.allocPrint(a, "Inkling 2 Mini cannot load its image tower ({s})", .{@errorName(err)}); + if (drafter) |d| d.deinit(); + model.deinit(); + return null; + } else null; + errdefer if (tower) |t| t.deinit(); + const image_rows: u64 = if (o.vision) |v| @as(u64, v.image_tokens) * st.hidden * 2 else 0; var ram: u64 = 0; if (@import("builtin").os.tag.isDarwin()) { var len: usize = @sizeOf(u64); @@ -89,7 +113,9 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope } const scratch: u64 = st.scratchBytes(st.batch_rows) + st.scratchBytes(st.prompt_rows); const resident = model.checkpoint.residentBytes() + scratch + if (drafter) |d| d.fixedBytes() + dspark.Drafter.scoreBytes(0) else 0; - const budget = cacheBudget(ram, model.device.maxWorkingSet(), @import("sys").getenv("INKLING2_LOAD_LIMIT_GB"), resident) catch { + const image_bytes: u64 = if (tower) |t| t.bytes() + image_rows else 0; + const budget = cacheBudget(ram, model.device.maxWorkingSet(), @import("sys").getenv("INKLING2_LOAD_LIMIT_GB"), resident + image_bytes) catch { + if (tower) |t| t.deinit(); if (drafter) |d| d.deinit(); model.deinit(); problem.* = "INKLING2_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 75% of RAM"; @@ -102,6 +128,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope const fits = longest(budget, model.config.text.max_context, streams, draft_fixed, draft_token, draft_shared_token); const window: i64 = o.context orelse @intCast(fits); if (contextProblem(window, fits)) |why| { + if (tower) |t| t.deinit(); if (drafter) |d| d.deinit(); model.deinit(); problem.* = why; @@ -115,9 +142,11 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.io = io; h.model = model; h.drafter = drafter; + h.vision = tower; + h.markers = .{model.config.image_token}; const reserved = if (drafter != null) streams * dspark.Drafter.streamBytes(@intCast(window)) + dspark.Drafter.scoreBytes(@intCast(window)) - dspark.Drafter.scoreBytes(0) else 0; if (reserved > budget) return error.DSparkReservationExceeded; - h.metal = try backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget - reserved }); + h.metal = try backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget - reserved, .images = if (tower != null) .{ .ctx = h, .encode = Host.encode } else null }); errdefer h.metal.deinit(); try h.metal.warm(); h.drafted = null; @@ -135,6 +164,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.core = lanes.Engine.init(gpa, &h.config, if (h.drafted) |*d| d.backend() else h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .decode_share = o.decode_share, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter_dir) |dir| .{ .kind = "DSpark", .name = o.drafter_name orelse dir } else null } }); + if (o.vision) |v| h.host.info_.vision = .{ .ctx = h, .prepare = Host.prepare, .image_token = model.config.image_token, .markers = &h.markers, .part_type = "image", .image_tokens = v.image_tokens, .max_images = v.max_images, .explain = vision.problem }; h.cache = null; h.cache_cap = if (o.prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; if (h.cache_cap > 0) { @@ -214,6 +244,13 @@ test "Inkling native admission keeps DSpark opt-in and refuses learned modes" { try std.testing.expect(contextProblem(10, 10) == null); } +test "Inkling native admission serves images under --vision and still refuses guidance" { + var o: api.Open = .{ .dir = "checkpoint", .model_type = "inkling2_loop", .vision = .{} }; + try std.testing.expect(refusal(o) == null); + o.cfg_enabled = true; + try std.testing.expect(refusal(o) != null); +} + test "Inkling native open publishes the exact admission refusal" { var problem: []const u8 = "not published"; const o: api.Open = .{ .dir = "unused", .model_type = "inkling2_loop", .learn_conversations = true }; diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 7ebb3010bb1..e8462e4915a 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -155,8 +155,8 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (std.mem.eql(u8, o.model_type, "glm5_next")) return openGlm(a, gpa, io, o, problem); if (isGemma4(o.model_type)) return @import("gemma4.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "unlimited-ocr")) return @import("uocr.zig").open(a, gpa, io, o, problem); - if (o.vision != null and !std.mem.eql(u8, o.model_type, "step5_vl") and !std.mem.eql(u8, o.model_type, "minimax_m3_vl")) { - problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4, Step-5, MiniMax-M3.1-Flash and Unlimited-OCR-2 only, not {s} checkpoints", .{o.model_type}); + if (o.vision != null and !std.mem.eql(u8, o.model_type, "step5_vl") and !std.mem.eql(u8, o.model_type, "minimax_m3_vl") and !std.mem.eql(u8, o.model_type, "inkling2_loop")) { + problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash, Qwen3.8-27B, Qwen3.8 Flash Next, Gemma 4, Step-5, MiniMax-M3.1-Flash, Inkling 2 Mini and Unlimited-OCR-2 only, not {s} checkpoints", .{o.model_type}); return null; } if (std.mem.eql(u8, o.model_type, "glm_moe_dsa")) return openGlmDsa(a, gpa, io, o, problem); diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig index 36aa5a5e9ce..42cf21e2fcb 100644 --- a/zig/tests/contract/metal_inkling2_controls_host.zig +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -8,4 +8,5 @@ test { _ = @import("metal_inkling2_runtime_controls.zig"); _ = @import("metal_inkling2_dspark_controls.zig"); _ = @import("metal_inkling2_split_controls.zig"); + _ = @import("metal_inkling2_vision_controls.zig"); } diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index 57f7558ce6d..21358e9780c 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -10,15 +10,18 @@ pub const Suites = struct { loop: @import("metal_inkling2_loop.zig").Suite, runtime: @import("metal_inkling2_runtime.zig").Suite, dspark: @import("metal_inkling2_dspark.zig").Suite, + vision: @import("metal_inkling2_vision.zig").Suite, - pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !Suites { - var s = Suites{ + /// The probes' contexts point into the suites, so the set is built where it stays. + pub fn init(s: *Suites, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + s.* = .{ .attention = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .glue = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .experts = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .loop = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .vision = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, }; errdefer s.deinit(); try s.attention.collect(only); @@ -27,7 +30,7 @@ pub const Suites = struct { try s.loop.collect(only); try s.runtime.collect(only); try s.dspark.collect(only); - return s; + try s.vision.collect(only); } pub fn deinit(s: *Suites) void { @@ -37,5 +40,6 @@ pub const Suites = struct { s.loop.deinit(); s.runtime.deinit(); s.dspark.deinit(); + s.vision.deinit(); } }; diff --git a/zig/tests/contract/metal_inkling2_vision.zig b/zig/tests/contract/metal_inkling2_vision.zig new file mode 100644 index 00000000000..9ec2fb41814 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision.zig @@ -0,0 +1,116 @@ +//! Independently referenced Mini image-tower gates; controls compile a private copy of the production source. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const g = @import("contract").gates; +const sources = @import("inkling2_metal"); +const controls = @import("metal_inkling2_vision_controls.zig"); +const gm = tf.inkling2_metal_host.vision.gemm; +const gemm = @import("metal_inkling2_vision_gemm.zig"); +const rows = @import("metal_inkling2_vision_rows.zig"); +const glue = @import("metal_inkling2_vision_glue.zig"); + +const Held = struct { + ptr: *anyopaque, + drop: *const fn (std.mem.Allocator, *anyopaque) void, +}; + +fn wanted(only: ?[]const u8, name: []const u8) bool { + return std.mem.indexOf(u8, name, only orelse return true) != null; +} + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + held: std.ArrayList(Held) = .empty, + production_lib: ?mtl.Library = null, + mm: ?*gm.Gemm = null, + + fn hold(s: *Suite, comptime T: type, value: T) !*T { + var v = value; + errdefer v.deinit(); + const p = try s.a.create(T); + errdefer s.a.destroy(p); + p.* = v; + const drop = struct { + fn release(a: std.mem.Allocator, ptr: *anyopaque) void { + const t: *T = @ptrCast(@alignCast(ptr)); + t.deinit(); + a.destroy(t); + } + }.release; + try s.held.append(s.a, .{ .ptr = p, .drop = drop }); + return p; + } + + fn library(s: *Suite, text: []const u8) !mtl.Library { + const src = try tf.frags.source(s.device, s.a, text); + defer s.a.free(src); + return mtl.Library.fromSource(s.device, src, mtl.CompileOptions.mlx()); + } + + fn production(s: *Suite) !mtl.Library { + if (s.production_lib == null) s.production_lib = try s.library(sources.vision); + return s.production_lib.?; + } + + fn mutated(s: *Suite, kind: controls.Kind) !mtl.Library { + const text = try controls.source(s.a, sources.vision, kind); + defer s.a.free(text); + return s.library(text); + } + + fn plain(s: *Suite, comptime M: type, only: ?[]const u8) !void { + inline for (std.enums.values(M.Kind)) |k| { + const label = comptime M.name(k); + if (wanted(only, label)) { + const p = try s.hold(M.Probe, try M.Probe.init(s.a, s.device, s.queue, try s.production(), k, label)); + try s.kernels.append(s.a, p.kernel(null)); + } + const control = comptime @field(controls.Kind, @tagName(k)); + const e = comptime controls.edit(control); + if (wanted(only, e.label)) { + const lib = try s.mutated(control); + defer lib.deinit(); + const p = try s.hold(M.Probe, try M.Probe.init(s.a, s.device, s.queue, lib, k, e.label)); + try s.kernels.append(s.a, p.kernel(e.gate)); + } + } + } + + fn gemmControl(s: *Suite, only: ?[]const u8, kind: controls.Kind, run: gm.Kind) !void { + const e = controls.edit(kind); + if (!wanted(only, e.label)) return; + const lib = try s.mutated(kind); + defer lib.deinit(); + const mm = try s.hold(gm.Gemm, try gm.Gemm.init(s.device, lib, &.{run})); + const p = try s.hold(gemm.Probe, gemm.Probe.init(s.a, s.device, s.queue, mm, run, e.label)); + try s.kernels.append(s.a, p.kernel(e.gate)); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(gm.Kind)) |k| if (wanted(only, gemm.name(k))) { + if (s.mm == null) s.mm = try s.hold(gm.Gemm, try gm.Gemm.init(s.device, try s.production(), std.enums.values(gm.Kind))); + const p = try s.hold(gemm.Probe, gemm.Probe.init(s.a, s.device, s.queue, s.mm.?, k, gemm.name(k))); + try s.kernels.append(s.a, p.kernel(null)); + }; + try s.gemmControl(only, .gemm_tail, .bf16f_nt); + // Without tensor units a few-row GEMM runs the 8x8 simdgroup kernel; its fault is only in that text. + if (!s.device.tensorUnits()) try s.gemmControl(only, .gemm_rows, .bf16_nt); + try s.plain(rows, only); + try s.plain(glue, only); + } + + pub fn deinit(s: *Suite) void { + var i = s.held.items.len; + while (i > 0) { + i -= 1; + const p = s.held.items[i]; + p.drop(s.a, p.ptr); + } + s.held.deinit(s.a); + if (s.production_lib) |lib| lib.deinit(); + } +}; diff --git a/zig/tests/contract/metal_inkling2_vision_controls.zig b/zig/tests/contract/metal_inkling2_vision_controls.zig new file mode 100644 index 00000000000..c357ba87980 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision_controls.zig @@ -0,0 +1,110 @@ +//! One host-checkable source-planted fault for every Inkling 2 Mini image-tower kernel family. +const std = @import("std"); +const contract = @import("contract"); + +pub const Kind = enum { pack, embed, qkv, heads, bias_gelu, gelu_rows, residual, layer_norm, softmax, gemm_tail, gemm_rows }; + +pub const Edit = struct { label: []const u8, from: []const u8, to: []const u8, gate: contract.spec.Gate }; + +pub fn edit(kind: Kind) Edit { + const g = contract.spec.Gate; + return switch (kind) { + .pack => .{ + .label = "control: metal inkling2 vision ik2v_pack writes past payload", + .from = "if (i < n) y[i] = bfloat(x[i]);", + .to = "if (i < n) y[i] = bfloat(x[i]); if (i == 0) y[n] = bfloat(0);", + .gate = g.repeat, + }, + .embed => .{ + .label = "control: metal inkling2 vision ik2v_embed reuses the first bilinear weight", + .from = "* weights[i * 4 + k];", + .to = "* weights[i * 4];", + .gate = g.shapes, + }, + .qkv => .{ + .label = "control: metal inkling2 vision ik2v_qkv swaps rotary pairing", + .from = "const uint e = d ^ 1u;", + .to = "const uint e = d ^ 2u;", + .gate = g.shapes, + }, + .heads => .{ + .label = "control: metal inkling2 vision ik2v_heads ignores the chunk's first row", + .from = "ulong(p.r0 + at.y)", + .to = "ulong(at.y)", + .gate = g.shapes, + }, + .bias_gelu => .{ + .label = "control: metal inkling2 vision ik2v_bias_gelu drops the bias", + .from = "ik2v_gelu(tf_vis_bf(acc[i] + float(b[at.x])))", + .to = "ik2v_gelu(tf_vis_bf(acc[i]))", + .gate = g.shapes, + }, + .gelu_rows => .{ + .label = "control: metal inkling2 vision ik2v_gelu_rows loses the sign", + .from = "ik2v_gelu(float(y[i]))", + .to = "ik2v_gelu(fabs(float(y[i])))", + .gate = g.shapes, + }, + .residual => .{ + .label = "control: metal inkling2 vision ik2v_residual omits LayerScale", + .from = "float(lambda[at.x]) * branch", + .to = "branch", + .gate = g.shapes, + }, + .layer_norm => .{ + .label = "control: metal inkling2 vision ik2v_layer_norm repeats channels", + .from = "#define IK2V_ROW(i) float(xr[i])", + .to = "#define IK2V_ROW(i) float(xr[(i) % 2])", + .gate = g.shapes, + }, + .softmax => .{ + .label = "control: metal inkling2 vision ik2v_softmax ignores NaN exp", + .from = "const float e = metal::precise::exp(s[i] - m);", + .to = "const float e = isnan(s[i] - m) ? 0.0f : metal::precise::exp(s[i] - m);", + .gate = g.nonfinite, + }, + .gemm_tail => .{ + .label = "control: metal inkling2 vision ik2_gemm_bf16f_nt drops ragged K tail", + .from = "gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home);", + .to = "gemm_block(acc, A, B, lda, ldb, P[2] - 1, (P[2] - 1) / 256, rows, cols, home);", + .gate = g.shapes, + }, + .gemm_rows => .{ + .label = "control: metal inkling2 vision ik2_gemm_bf16_nt_rows feeds block 1 the weights of block 0", + .from = "simdgroup_multiply_accumulate(acc1, fa, fb1, acc1);", + .to = "simdgroup_multiply_accumulate(acc1, fa, fb0, acc1);", + .gate = g.shapes, + }, + }; +} + +pub fn source(a: std.mem.Allocator, production: []const u8, kind: Kind) ![]u8 { + const e = edit(kind); + if (std.mem.count(u8, production, e.from) != 1) return error.ControlEditMissing; + return std.mem.replaceOwned(u8, a, production, e.from, e.to); +} + +test "every vision control applies once and changes only its anchor" { + const production = @import("inkling2_metal").vision; + const a = std.testing.allocator; + for (std.enums.values(Kind)) |kind| { + const e = edit(kind); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, production, e.from)); + try std.testing.expect(!std.mem.eql(u8, e.from, e.to)); + const changed = try source(a, production, kind); + defer a.free(changed); + const at = std.mem.indexOf(u8, production, e.from).?; + try std.testing.expectEqualStrings(production[0..at], changed[0..at]); + try std.testing.expectEqualStrings(e.to, changed[at..][0..e.to.len]); + try std.testing.expectEqualStrings(production[at + e.from.len ..], changed[at + e.to.len ..]); + try std.testing.expectError(error.ControlEditMissing, source(a, "", kind)); + } +} + +test "a repeated vision control anchor is ambiguous and refuses to prove a fault" { + const a = std.testing.allocator; + const production = @import("inkling2_metal").vision; + const twice = try std.mem.concat(a, u8, &.{ production, production }); + defer a.free(twice); + for (std.enums.values(Kind)) |kind| try std.testing.expectError(error.ControlEditMissing, source(a, twice, kind)); +} diff --git a/zig/tests/contract/metal_inkling2_vision_gemm.zig b/zig/tests/contract/metal_inkling2_vision_gemm.zig new file mode 100644 index 00000000000..22ffc0b260a --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision_gemm.zig @@ -0,0 +1,191 @@ +//! Mini vision GEMMs: both orientations, three precision pairs, padded pitches, batches and tile tails. +const std = @import("std"); +const mtl = @import("metal"); +const rows = @import("contract").rows; +const u = @import("metal_inkling2_vision_util.zig"); +const r = @import("rig.zig"); +const stress = @import("metal_inkling2_vision_stress.zig"); +const gm = @import("tensorfold").inkling2_metal_host.vision.gemm; +const c = u.c; +const g = u.g; +pub const Kind = gm.Kind; + +pub fn name(k: Kind) []const u8 { + return switch (k) { + .bf16_nt => "metal inkling2 vision gemm bf16_nt", + .bf16f_nt => "metal inkling2 vision gemm bf16f_nt", + .f32_nt => "metal inkling2 vision gemm f32_nt", + .f32_nn => "metal inkling2 vision gemm f32_nn", + }; +} + +const tiles: [3]c.Tile = .{ .{ .size = 64 }, .{ .size = 128 }, .{ .size = 256, .min = 2 } }; +const edges = [_]c.Shape{ + .{ .rows = 64, .n = 128, .k = 256 }, .{ .rows = 64, .n = 129, .k = 257 }, + .{ .rows = 65, .n = 128, .k = 255 }, .{ .rows = 65, .n = 129, .k = 257 }, +}; +const bf16_nt = [_]c.Shape{ + .{ .rows = 7, .n = 1024, .k = 1200 }, // patch embedding and projector rows of a one-token image + .{ .rows = 8, .n = 4096, .k = 4096 }, + .{ .rows = 8, .n = 2304, .k = 4096 }, +} ++ edges; +const bf16f_nt = [_]c.Shape{ + .{ .rows = 9, .n = 1024, .k = 1024 }, .{ .rows = 9, .n = 4096, .k = 1024 }, .{ .rows = 9, .n = 1024, .k = 4096 }, +} ++ edges; +const f32_nt = [_]c.Shape{.{ .rows = 17, .n = 17, .k = 64 }} ++ edges; +const f32_nn = [_]c.Shape{.{ .rows = 17, .n = 64, .k = 17 }} ++ edges; + +fn depth(s: c.Shape) usize { + return s.k + 1; +} + +pub const Probe = struct { + arena: std.heap.ArenaAllocator, + rig: r.Rig, + gemm: *const gm.Gemm, + kind: Kind, + label: []const u8, + s: gm.Shape = undefined, + a: []const f32 = &.{}, + b: []const f32 = &.{}, + ar: r.Ref = undefined, + br: r.Ref = undefined, + out: r.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, gemm: *const gm.Gemm, k: Kind, label: []const u8) Probe { + return .{ .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .gemm = gemm, .kind = k, .label = label }; + } + + pub fn deinit(p: *Probe) void { + p.rig.deinit(); + p.arena.deinit(); + } + + fn wide(p: *const Probe) bool { + return p.kind == .f32_nt or p.kind == .f32_nn; + } + + fn elem(p: *const Probe) c.Elem { + return if (p.wide() or p.kind == .bf16f_nt) .f32 else .bf16; + } + + fn nn(p: *const Probe) bool { + return p.kind == .f32_nn; + } + + const vt = g.hooks(Probe); + + pub fn kernel(p: *Probe, control_gate: ?c.Gate) g.Kernel { + return .{ .ctx = p, .vt = &vt, .control = control_gate, .spec = .{ + .name = p.label, + .accum = .f32, + .depth = depth, + .out = p.elem(), + .tiles = tiles, + .served = switch (p.kind) { + .bf16_nt => &bf16_nt, + .bf16f_nt => &bf16f_nt, + .f32_nt => &f32_nt, + .f32_nn => &f32_nn, + }, + } }; + } + + fn bIndex(p: *const Probe, col: usize, k: usize) usize { + return if (p.nn()) k * p.s.ldb + col else col * p.s.ldb + k; + } + + fn input(p: *Probe, a: std.mem.Allocator, values: []const f32) !r.Ref { + if (p.wide()) return p.rig.input(std.mem.sliceAsBytes(values)); + const words = try a.alloc(u16, values.len); + for (values, words) |v, *w| w.* = c.toBf16(v); + return p.rig.input(std.mem.sliceAsBytes(words)); + } + + fn sample(p: *const Probe, fill: g.Fill, rng: std.Random, left: bool, k: usize, n: usize) f32 { + if (fill == .stress) { + const pair = stress.pair(k, n); + return if (left) pair.left else pair.right; + } + // A bf16-dyadic fits in 10 fraction bits, so the M5 operand cut still matched. Wide inputs do not. + if (p.wide()) return @bitCast(0x3f000000 | (rng.int(u32) & 0x007ffffe)); + return c.fromBf16(u.dyadic(rng, 255, 128)); + } + + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + const a = u.reset(&p.arena, &p.rig); + const lda = s.k + 4; + const ldb = (if (p.nn()) s.n else s.k) + 4; + const sa = s.rows * lda + 12; + const sb = (if (p.nn()) s.k else s.n) * ldb + 12; + p.s = .{ .m = @intCast(s.rows), .n = @intCast(s.n), .k = @intCast(s.k), .lda = @intCast(lda), .ldb = @intCast(ldb), .ldd = @intCast(s.n), .batch = if (p.wide()) 2 else 1, .sa = @intCast(sa), .sb = @intCast(sb), .sd = @intCast(s.rows * s.n) }; + const left = try a.alloc(f32, p.s.batch * sa); + const right = try a.alloc(f32, p.s.batch * sb); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + @memset(left, std.math.nan(f32)); + @memset(right, std.math.nan(f32)); + for (0..p.s.batch) |b| { + for (0..s.rows) |i| for (0..s.k) |k| { + left[b * sa + i * lda + k] = sample(p, fill, rng, true, k, s.k); + }; + for (0..s.n) |j| for (0..s.k) |k| { + right[b * sb + p.bIndex(j, k)] = sample(p, fill, rng, false, k, s.k); + }; + } + if (fill == .nonfinite) { + left[0] = std.math.nan(f32); + left[lda + 1] = std.math.inf(f32); + left[2 * lda + 2] = -std.math.inf(f32); + left[3 * lda] = std.math.inf(f32); + left[3 * lda + s.k - 1] = -std.math.inf(f32); + } + p.a = left; + p.b = right; + p.ar = try p.input(a, left); + p.br = try p.input(a, right); + p.out = try p.rig.output(p.count() * c.size(p.elem())); + return true; + } + + fn ref(x: r.Ref) gm.Ref { + return .{ .buf = x.buf, .off = x.off }; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + p.gemm.run(pass.e, p.kind, ref(p.ar), ref(p.br), ref(p.out), p.s); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return @as(usize, p.s.batch) * p.s.m * p.s.n; + } + + fn product(p: *const Probe, b: usize, i: usize, j: usize, k: usize) f64 { + return @as(f64, p.a[b * p.s.sa + i * p.s.lda + k]) * p.b[b * p.s.sb + p.bIndex(j, k)]; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + for (0..p.s.batch) |b| for (0..p.s.m) |i| for (0..p.s.n) |j| { + var sum: f64 = 0; + var abs: f64 = 0; + for (0..p.s.k) |k| { + const v = p.product(b, i, j, k); + sum += v; + abs += @abs(v); + } + const o = b * p.s.sd + i * p.s.n + j; + want[o] = sum; + mag[o] = abs; + }; + } + + pub fn simulate(p: *Probe, accum: c.Accum, order: g.Order, out: []f64) !void { + const a = p.rig.a; + const terms = try a.alloc(f64, p.s.k); + defer a.free(terms); + for (terms, 0..) |*v, k| v.* = p.product(0, 0, 0, k); + @memset(out, rows.sumIn(accum, order, terms)); // every stress cell has the same dot + } +}; diff --git a/zig/tests/contract/metal_inkling2_vision_glue.zig b/zig/tests/contract/metal_inkling2_vision_glue.zig new file mode 100644 index 00000000000..35e197cccc1 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision_glue.zig @@ -0,0 +1,279 @@ +//! Image tower glue: patch/position embedding, head layout and rotary, and BF16 epilogue roundings. +const std = @import("std"); +const mtl = @import("metal"); +const u = @import("metal_inkling2_vision_util.zig"); +const r = @import("rig.zig"); +const math = @import("contract").rows; +const c = u.c; +const g = u.g; + +pub const Kind = enum { pack, embed, qkv, heads, bias_gelu, gelu_rows, residual }; +pub fn name(comptime k: Kind) []const u8 { + return "metal inkling2 vision ik2v_" ++ @tagName(k); +} + +const pack_shapes = [_]c.Shape{ .{ .rows = 8, .n = 1200, .k = 0 }, .{ .rows = 4, .n = 1200, .k = 0 } }; +const base_shapes = [_]c.Shape{ .{ .rows = 9, .n = 1024, .k = 0 }, .{ .rows = 4, .n = 1024, .k = 0 } }; +const mlp_shapes = [_]c.Shape{ .{ .rows = 9, .n = 4096, .k = 0 }, .{ .rows = 1, .n = 4096, .k = 0 }, .{ .rows = 5, .n = 257, .k = 0 } }; +const dim = 64; +const r0 = 2; +const Embed = extern struct { patches: u32, width: u32 }; +const Qkv = extern struct { rows: u32, heads: u32, dim: u32, r0: u32 }; +const Heads = extern struct { rows: u32, r0: u32, heads: u32, dim: u32 }; +fn noDepth(_: c.Shape) usize { + return 0; +} +fn four(_: c.Shape) usize { + return 4; +} + +pub const Probe = struct { + rig: r.Rig, + arena: std.heap.ArenaAllocator, + pipe: mtl.Pipeline, + kind: Kind, + label: []const u8, + s: c.Shape = undefined, + refs: [9]r.Ref = undefined, + nrefs: usize = 0, + clear: []const r.Ref = &.{}, + restore: []const u16 = &.{}, + want: []f64 = &.{}, + mag: []f64 = &.{}, + pe: []const u16 = &.{}, + table: []const u16 = &.{}, + taps: []const u32 = &.{}, + tap_weights: []const f32 = &.{}, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, lib: mtl.Library, k: Kind, label: []const u8) !Probe { + const pipe = switch (k) { + inline else => |tag| try mtl.Pipeline.init(device, lib, "ik2v_" ++ @tagName(tag), false), + }; + return .{ .rig = .{ .a = a, .device = device, .queue = queue }, .arena = .init(a), .pipe = pipe, .kind = k, .label = label }; + } + + pub fn deinit(p: *Probe) void { + p.rig.deinit(); + p.arena.deinit(); + p.pipe.deinit(); + } + + const vt = g.hooks(Probe); + + pub fn kernel(p: *Probe, gate: ?c.Gate) g.Kernel { + return .{ .ctx = p, .vt = &vt, .control = gate, .spec = .{ + .name = p.label, + .accum = if (p.kind == .embed) .f32 else .none, + .depth = if (p.kind == .embed) four else noDepth, + .out = if (p.kind == .qkv) .f32 else .bf16, + .store = if (p.kind == .qkv) .bf16 else null, + .in_place = p.kind == .gelu_rows or p.kind == .residual, + .served = switch (p.kind) { + .pack => &pack_shapes, + .bias_gelu, .gelu_rows => &mlp_shapes, + else => &base_shapes, + }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "four dyadic taps into a rounded BF16 position row" }, + } }; + } + + fn add(p: *Probe, v: r.Ref) void { + p.refs[p.nrefs] = v; + p.nrefs += 1; + } + fn input(p: *Probe, v: anytype) !void { + p.add(try p.rig.input(std.mem.sliceAsBytes(v))); + } + fn output(p: *Probe, n: usize) !void { + p.add(try p.rig.output(n)); + } + + fn bf(a: std.mem.Allocator, rng: std.Random, n: usize, nf: bool) ![]u16 { + const v = try a.alloc(u16, n); + u.fillDyadic(rng, v, 127, 64); + if (nf) @memcpy(v[0..3], &[_]u16{ u.nan_bits, u.pinf_bits, u.ninf_bits }); + return v; + } + + fn fp(a: std.mem.Allocator, rng: std.Random, n: usize, nf: bool) ![]f32 { + const v = try a.alloc(f32, n); + for (v) |*x| { + x.* = rng.float(f32) * 4 - 2; + } + if (nf) @memcpy(v[0..3], &[_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }); + return v; + } + + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + const a = u.reset(&p.arena, &p.rig); + p.s = s; + p.nrefs = 0; + p.clear = &.{}; + p.restore = &.{}; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const n = s.rows * s.n; + const nf = fill == .nonfinite; + p.want = try a.alloc(f64, switch (p.kind) { + .embed => n + s.n, + .qkv => 3 * (s.rows + r0) * s.n, + .heads => (s.rows + r0) * s.n, + else => n, + }); + p.mag = try a.alloc(f64, p.want.len); + @memset(p.want, 0); + @memset(p.mag, 0); + switch (p.kind) { + .embed => { + const pe = try bf(a, rng, n, nf); + const cls = try bf(a, rng, s.n, nf); + const cpos = try bf(a, rng, s.n, false); + const table = try bf(a, rng, s.n * 1024, false); + const taps = try a.alloc(u32, s.rows * 4); + const weights = try a.alloc(f32, s.rows * 4); + for (taps, weights) |*i, *w| { + i.* = rng.uintLessThan(u32, 1024); + w.* = if (fill == .stress) 0.25 else @as(f32, @floatFromInt(rng.uintLessThan(u32, 32))) / 32; + } + try p.input(pe); + try p.input(table); + try p.input(taps); + try p.input(weights); + try p.input(cls); + try p.input(cpos); + try p.output(p.want.len * 2); + for (0..s.n) |i| { + p.want[i] = u.val(cls[i]) + u.val(cpos[i]); + } + p.pe = pe; + p.table = table; + p.taps = taps; + p.tap_weights = weights; + p.embedRows(.none, .sequential, p.want); + }, + .qkv => { + const span = (s.rows + r0) * s.n; + const acc = try fp(a, rng, 3 * n, nf); + try p.input(acc); + var biases: [3][]u16 = undefined; + for (&biases) |*b| { + b.* = try bf(a, rng, s.n, false); + try p.input(b.*); + } + const cs = try a.alloc(f32, (s.rows + r0) * dim); + const sn = try a.alloc(f32, (s.rows + r0) * dim); + for (cs, sn, 0..) |*co, *si, i| { + co.* = if ((i / dim) % 2 == 0) 0.75 else 0.25; + si.* = if (i % 4 < 2) 0.5 else -0.5; + } + try p.input(cs); + try p.input(sn); + for (0..3) |_| try p.output(span * 4); + p.clear = p.refs[6..9]; + for (0..3) |k| for (0..s.rows) |i| for (0..s.n) |j| { + const row = (i * 3 + k) * s.n; + const v = u.bf(@as(f64, acc[row + j]) + u.val(biases[k][j])); + const partner = u.bf(@as(f64, acc[row + (j ^ 1)]) + u.val(biases[k][j ^ 1])); + const trig = (i + r0) * dim + j % dim; + const o = k * span + ((j / dim) * (s.rows + r0) + i + r0) * dim + j % dim; + p.want[o] = if (k == 2) v else v * cs[trig] + (if (j % 2 == 0) -partner else partner) * sn[trig]; + }; + }, + .heads => { + const x = try fp(a, rng, n, nf); + try p.input(x); + try p.output(p.want.len * 2); + p.clear = p.refs[1..2]; + for (0..s.rows) |i| for (0..s.n) |j| { + p.want[(i + r0) * s.n + j] = x[((j / dim) * s.rows + i) * dim + j % dim]; + }; + }, + .pack, .bias_gelu, .gelu_rows, .residual => { + const x = if (p.kind != .gelu_rows) try fp(a, rng, n, nf) else &.{}; + const old = if (p.kind == .gelu_rows or p.kind == .residual) try bf(a, rng, n, nf) else &.{}; + const b = if (p.kind == .residual or p.kind == .bias_gelu) try bf(a, rng, s.n, false) else &.{}; + const w = if (p.kind == .residual) try bf(a, rng, s.n, false) else &.{}; + if (x.len > 0) try p.input(x); + if (b.len > 0) try p.input(b); + if (w.len > 0) try p.input(w); + try p.output(n * 2); + p.restore = old; + for (p.want, p.mag, 0..) |*y, *m, i| { + const j = i % s.n; + switch (p.kind) { + .pack => y.* = x[i], + .residual => y.* = u.val(old[i]) + u.bf(u.val(w[j]) * u.bf(@as(f64, x[i]) + u.val(b[j]))), + .bias_gelu, .gelu_rows => { + const z = if (p.kind == .gelu_rows) u.val(old[i]) else u.bf(@as(f64, x[i]) + u.val(b[j])); + y.* = math.gelu(z); + m.* = @abs(z); + }, + else => unreachable, + } + } + }, + } + return true; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.pipe); + for (p.refs[0..p.nrefs], 0..) |x, i| e.setBuffer(x.buf, x.off, i); + if (p.restore.len > 0) { + const b = std.mem.sliceAsBytes(p.restore); + @memcpy(p.rig.bytes(p.refs[p.nrefs - 1], b.len), b); + } + for (p.clear) |x| @memset(p.rig.bytes(x, p.want.len / p.clear.len * c.size(if (p.kind == .qkv) .f32 else .bf16)), 0); + const n: u32 = @intCast(p.s.rows); + const w: u32 = @intCast(p.s.n); + switch (p.kind) { + .pack => e.setValue(n * w, 2), + .embed => e.setValue(Embed{ .patches = n, .width = w }, 7), + .heads => e.setValue(Heads{ .rows = n, .r0 = r0, .heads = w / dim, .dim = dim }, 2), + .qkv => e.setValue(Qkv{ .rows = n + r0, .heads = w / dim, .dim = dim, .r0 = r0 }, 9), + else => e.setValue(w, p.nrefs), + } + if (p.kind == .qkv) { + e.dispatchThreads(mtl.Size.of(dim, 3 * w / dim, n), mtl.Size.of(dim, 4, 1)); + } else { + const grid = if (p.kind == .pack) mtl.Size.of(w * n, 1, 1) else mtl.Size.of(w, n + @as(u32, @intFromBool(p.kind == .embed)), 1); + e.dispatchThreads(grid, mtl.Size.of(256, 1, 1)); + } + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.want.len; + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + @memcpy(want, p.want); + @memcpy(mag, p.mag); + } + + pub fn bounds(_: *Probe, want: []const f64, mag: []const f64, allow: []f64) !void { + for (want, mag, allow) |y, m, *b| { + // GELU's erf polynomial has absolute error <= 1.5e-7; all other dyadic epilogues use no inexact sums. + const d = m * 0x1p-19; + b.* = d + (@abs(y) + d) * c.unit(.bf16) + 0x1p-133; + } + } + + fn embedRows(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) void { + const width = p.s.n; + for (0..p.s.rows) |i| for (0..width) |j| { + var terms: [4]f64 = undefined; + for (&terms, 0..) |*x, k| { + x.* = u.val(p.table[p.taps[i * 4 + k] * width + j]) * p.tap_weights[i * 4 + k]; + } + const pos = math.sumIn(acc, order, &terms); + out[(i + 1) * width + j] = u.val(p.pe[i * width + j]) + u.bf(pos); + }; + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + @memcpy(out[0..p.s.n], p.want[0..p.s.n]); + p.embedRows(acc, order, out); + } +}; diff --git a/zig/tests/contract/metal_inkling2_vision_rows.zig b/zig/tests/contract/metal_inkling2_vision_rows.zig new file mode 100644 index 00000000000..bdc56f583bc --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision_rows.zig @@ -0,0 +1,192 @@ +//! The image tower's LayerNorm and attention softmax rows. +const std = @import("std"); +const mtl = @import("metal"); +const rows = @import("contract").rows; +const u = @import("metal_inkling2_vision_util.zig"); +const r = @import("rig.zig"); +const c = u.c; +const g = u.g; + +pub const Kind = enum { layer_norm, softmax }; + +pub fn kernelName(comptime k: Kind) []const u8 { + return "ik2v_" ++ @tagName(k); +} + +pub fn name(comptime k: Kind) []const u8 { + return "metal inkling2 vision " ++ kernelName(k); +} + +const layer_shapes = [_]c.Shape{ .{ .rows = 9, .n = 1024, .k = 1024 }, .{ .rows = 5, .n = 1024, .k = 1024 } }; +const softmax_shapes = [_]c.Shape{ .{ .rows = 9, .n = 1025, .k = 1025 }, .{ .rows = 5, .n = 5, .k = 5 }, .{ .rows = 9, .n = 16385, .k = 16385 } }; + +fn depth(s: c.Shape) usize { + return (s.k + 255) / 256 + 12; +} + +pub const Probe = struct { + rig: r.Rig, + pipe: mtl.Pipeline, + arena: std.heap.ArenaAllocator, + kind: Kind, + label: []const u8, + s: c.Shape = undefined, + words: []const u16 = &.{}, + weights: []const u16 = &.{}, + bias: []const u16 = &.{}, + scores: []const f32 = &.{}, + refs: [3]r.Ref = undefined, + out: r.Ref = undefined, + stress: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, lib: mtl.Library, k: Kind, label: []const u8) !Probe { + const pipe = switch (k) { + inline else => |tag| try mtl.Pipeline.init(device, lib, kernelName(tag), false), + }; + return .{ .rig = .{ .a = a, .device = device, .queue = queue }, .pipe = pipe, .arena = .init(a), .kind = k, .label = label }; + } + + pub fn deinit(p: *Probe) void { + p.rig.deinit(); + p.arena.deinit(); + p.pipe.deinit(); + } + + const vt = g.hooks(Probe); + + pub fn kernel(p: *Probe, control_gate: ?c.Gate) g.Kernel { + const soft = p.kind == .softmax; + return .{ .ctx = p, .vt = &vt, .control = control_gate, .spec = .{ + .name = p.label, + .accum = .f32, + .depth = depth, + .ops = 12, + .in_place = soft, + .out = if (soft) .f32 else .bf16, + .store = if (soft) .bf16 else null, + .tiles = .{ .{}, .{}, .{ .size = 256 } }, + .served = if (soft) &softmax_shapes else &layer_shapes, + .sums = .{ .f16 = if (soft) 0 else 100, .bf16 = 0, .exact = !soft, .why = "BF16 store limits discrimination in normalized outputs; exp terms are not dyadic" }, + } }; + } + + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + const a = u.reset(&p.arena, &p.rig); + p.s = s; + p.stress = fill == .stress; + if (p.kind == .softmax) { + const x = try a.alloc(f32, s.rows * s.k); + var prng = std.Random.DefaultPrng.init(seed); + for (x) |*v| v.* = prng.random().float(f32) * 16 - 8; + if (fill == .nonfinite) { + x[0] = std.math.nan(f32); + x[s.k + s.k / 2] = std.math.inf(f32); + x[2 * s.k] = -std.math.inf(f32); + x[3 * s.k] = std.math.inf(f32); + x[4 * s.k - 1] = -std.math.inf(f32); + } + p.scores = x; + p.out = try p.rig.output(x.len * 4); + return true; + } + const base = try rows.Rows.init(a, .layer_norm, s); + base.fill(fill, seed); + p.words = base.x; + p.weights = base.w; + p.bias = base.b; + p.out = try p.rig.output(s.rows * s.k * 2); + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(p.words)); + p.refs[1] = try p.rig.input(std.mem.sliceAsBytes(p.weights)); + p.refs[2] = try p.rig.input(std.mem.sliceAsBytes(p.bias)); + return true; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const w: u32 = @intCast(p.s.k); + const n: u32 = @intCast(p.s.rows); + e.setPipeline(p.pipe); + if (p.kind == .softmax) { + const data = std.mem.sliceAsBytes(p.scores); + @memcpy(p.rig.bytes(p.out, data.len), data); + e.setBuffer(p.out.buf, p.out.off, 0); + e.setValue(w, 1); + e.setValue(@as(f32, 0.125), 2); + } else { + for (p.refs, 0..) |x, i| e.setBuffer(x.buf, x.off, i); + e.setBuffer(p.out.buf, p.out.off, 3); + e.setValue([3]u32{ n, w, @bitCast(@as(f32, 1e-5)) }, 4); + } + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + try p.rig.finish(pass); + } + + pub fn count(p: *const Probe) usize { + return p.s.rows * p.s.k; + } + + fn roundSum(v: []const f64, acc: c.Accum, order: g.Order) f64 { + return rows.sumIn(acc, order, v); + } + + fn calculate(p: *Probe, acc: c.Accum, order: g.Order, want: []f64, mags: ?[]f64) !void { + const k = p.s.k; + const kf: f64 = @floatFromInt(k); + const a = p.rig.a; + const terms = try a.alloc(f64, k); + defer a.free(terms); + for (0..p.s.rows) |i| { + const out = want[i * k ..][0..k]; + const mag = if (mags) |m| m[i * k ..][0..k] else null; + if (p.kind == .softmax) { + var top = -std.math.inf(f64); + const src = p.scores[i * k ..][0..k]; + for (terms, src) |*x, v| { + x.* = u.val(u.word(u.val(u.word(v)) / 8)); + top = @max(top, x.*); + } + for (terms) |*x| x.* = @exp(x.* - top); + const z = roundSum(terms, acc, order); + for (out, terms) |*y, x| y.* = x / z; + if (mag) |m| for (m, out) |*x, y| { + x.* = @abs(y); + }; + continue; + } + var abs: f64 = 0; + for (terms, 0..) |*x, j| { + x.* = u.val(p.words[i * k + j]); + abs += @abs(x.*); + } + const mean = roundSum(terms, acc, order) / kf; + for (terms) |*x| x.* = (x.* - mean) * (x.* - mean); + const inv = 1 / @sqrt(roundSum(terms, acc, order) / kf + 1e-5); + for (out, 0..) |*y, j| { + const x = u.val(p.words[i * k + j]) - mean; + const w = u.val(p.weights[j]); + const b = u.val(p.bias[j]); + y.* = x * inv * w + b; + if (mag) |m| m[j] = @abs(w) * inv * (@abs(x) + abs / kf) + @abs(b); + } + } + } + + pub fn bounds(p: *Probe, want: []const f64, mag: []const f64, allow: []f64) !void { + // Affine cancellation can make |y| much smaller than the terms whose rounding influences it. + const work = if (p.stress and p.kind != .softmax) 12 else depth(p.s) + 16; + const delta = c.gamma(@floatFromInt(work), c.unit(.f32)); + for (want, mag, allow) |y, m, *b| { + const error_f32 = m * delta; + b.* = error_f32 + (error_f32 + @abs(y)) * c.unit(.bf16) + 0x1p-133; + } + } + + pub fn reference(p: *Probe, out: []f64, mag: []f64) !void { + try p.calculate(.none, .sequential, out, mag); + } + + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + try p.calculate(acc, order, out, null); + } +}; diff --git a/zig/tests/contract/metal_inkling2_vision_stress.zig b/zig/tests/contract/metal_inkling2_vision_stress.zig new file mode 100644 index 00000000000..77d0fb1c01a --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision_stress.zig @@ -0,0 +1,22 @@ +//! An exact FP32 dot whose FP16 and BF16 reductions lose the four unit terms in each 128-element panel. + +pub const Row = struct { left: f32, right: f32 }; + +pub fn pair(i: usize, n: usize) Row { + if (i / 128 == n / 128) return .{ .left = 0, .right = 0 }; + const panel = i % 128; + const lane = panel % 32; + const value: f32 = switch (lane) { + 0 => 128, + 2 => 32, + 4, 5 => 64, + else => 0, + }; + if (value == 0) return .{ .left = 0, .right = 0 }; + return switch (panel / 32) { + 0 => .{ .left = 128, .right = value }, + 1 => .{ .left = 1, .right = 1 }, + 2 => .{ .left = 128, .right = -value }, + else => .{ .left = 0, .right = 0 }, + }; +} diff --git a/zig/tests/contract/metal_inkling2_vision_util.zig b/zig/tests/contract/metal_inkling2_vision_util.zig new file mode 100644 index 00000000000..a4dad858cb1 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_vision_util.zig @@ -0,0 +1,50 @@ +//! Values and buffers shared by the Inkling 2 Mini image-tower contract probes. +const std = @import("std"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +pub const c = contract.spec; +pub const g = contract.gates; + +pub const nan_bits: u16 = 0x7fc0; +pub const pinf_bits: u16 = 0x7f80; +pub const ninf_bits: u16 = 0xff80; + +/// float64 of a bf16 word. +pub fn val(v: u16) f64 { + return c.fromBf16(v); +} + +/// A float64 rounded to bf16 (round to nearest even) and back: the reference's node rounding. +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +pub fn word(v: f64) u16 { + return c.toBf16(@floatCast(v)); +} + +/// A random multiple of 1/denom with magnitude at most span/denom, exact in bf16 when span <= 256. +pub fn dyadic(rng: std.Random, span: i32, denom: f32) u16 { + const k: f32 = @floatFromInt(rng.intRangeAtMost(i32, -span, span)); + return c.toBf16(k / denom); +} + +pub fn fillDyadic(rng: std.Random, out: []u16, span: i32, denom: f32) void { + for (out) |*v| v.* = dyadic(rng, span, denom); +} + +/// Probes call this first in `prepare`: frees the last shape's buffers and host data; returns the arena's allocator. +pub fn reset(arena: *std.heap.ArenaAllocator, rig: *rig_.Rig) std.mem.Allocator { + rig.reset(); + _ = arena.reset(.retain_capacity); + return arena.allocator(); +} + +test "dyadic values are exact in bf16" { + var prng = std.Random.DefaultPrng.init(1); + for (0..1000) |_| { + const w = dyadic(prng.random(), 64, 16); + try std.testing.expectEqual(w, word(val(w))); + } +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 80256bff275..09bff108136 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -45,6 +45,7 @@ pub fn requireMapped(d: limits.MetalLaunch) !void { /// Only launches the loader can build on this device enter the limits compiler; declarations are checked first. pub fn supported(device: mtl.Device, d: limits.MetalLaunch) bool { + if (std.mem.eql(u8, d.name, "metal inkling2 vision ik2_gemm_bf16_nt_rows")) return !device.tensorUnits(); if (std.mem.startsWith(u8, d.name, "qwen27 prompt ")) return device.tensorUnits() == (std.mem.indexOf(u8, d.name, " m5 ") != null); if (std.mem.startsWith(u8, d.name, "lfm2 masked prompt ")) return @import("metal_support.zig").tensor(tf.lfm2_moe.source.optionalAvailable(device), d.name); @@ -214,6 +215,11 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp const t = try @import("metal_flint.zig").limitsText(a, device, d.name); return .{ .decl = d, .function = fun, .here = t.here, .pre_m5 = t.pre_m5 }; } + if (std.mem.startsWith(u8, d.name, "metal inkling2 vision ")) { + if (!assemble) return undefined; + const raw = @import("inkling2_metal").vision; + return .{ .decl = d, .function = fun, .here = try tf.frags.source(device, a, raw), .pre_m5 = try preM5(a, "", raw) }; + } if (std.mem.startsWith(u8, d.name, "metal inkling2 ")) { if (!assemble) return undefined; const body = if (std.mem.startsWith(u8, d.name, "metal inkling2 dspark ")) diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index edb0c193a02..c78c29340ff 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -354,7 +354,8 @@ pub fn main(init: std.process.Init) !u8 { var ling_mla_set = ling_mla.Suite{ .a = a, .device = device, .queue = queue }; defer ling_mla_set.deinit(); try ling_mla_set.collect(&kernels, o.only); - var inkling2_suites = try @import("metal_inkling2_main.zig").Suites.create(a, device, queue, &kernels, o.only); + var inkling2_suites: @import("metal_inkling2_main.zig").Suites = undefined; + try inkling2_suites.init(a, device, queue, &kernels, o.only); defer inkling2_suites.deinit(); for ([_][]const Reg{ &common, if (tensor) &m5_only else &.{} }) |list| for (list) |v| { if (!wanted(o, v.name)) continue; From 29d03a55bdd7e0e24b309bf5a935440819ab3eed Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:50:23 +0100 Subject: [PATCH 300/361] inkling2 metal: log each picture the tower runs with the SHA-256 of its BF16 rows - One info line per image the tower computes (the picture's content hash, rows, SHA-256 of the rows the splice takes); a picture a restored prefix covers logs nothing. - Host test for the digest's hex. --- zig/src/families/inkling2/metal/images.zig | 9 +++++++++ zig/src/families/inkling2/metal/vision_image_test.zig | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/zig/src/families/inkling2/metal/images.zig b/zig/src/families/inkling2/metal/images.zig index 6147760f053..b296958ac9b 100644 --- a/zig/src/families/inkling2/metal/images.zig +++ b/zig/src/families/inkling2/metal/images.zig @@ -11,6 +11,13 @@ pub const Encoder = struct { encode: *const fn (ctx: *anyopaque, image: lanes.stream.Image) anyerror!mtl.Buffer, }; +/// The SHA-256 of a picture's BF16 rows as lowercase hex, the tower output the splice takes. +pub fn digestHex(rows: []const u8) [64]u8 { + var sum: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(rows, &sum, .{}); + return std.fmt.bytesToHex(sum, .lower); +} + pub const Rows = struct { gpa: std.mem.Allocator, whole: []fwd.ImageRows, @@ -36,6 +43,8 @@ pub const Rows = struct { self.whole[self.made] = .{ .row = im.at, .rows = im.tokens, .buf = buffer }; self.made += 1; if (buffer.length() < @as(usize, im.tokens) * state.hidden * 2) return error.BadInklingImageRows; + const bytes = buffer.slice(u8, @as(usize, im.tokens) * state.hidden * 2); + std.log.info("inkling2 image tower: picture={x:0>16} rows={d} sha256={s}", .{ im.hash, im.tokens, digestHex(bytes) }); } return self; } diff --git a/zig/src/families/inkling2/metal/vision_image_test.zig b/zig/src/families/inkling2/metal/vision_image_test.zig index 0dbc5e03876..731d352302d 100644 --- a/zig/src/families/inkling2/metal/vision_image_test.zig +++ b/zig/src/families/inkling2/metal/vision_image_test.zig @@ -3,6 +3,7 @@ const std = @import("std"); const core = @import("core"); const config = @import("../config.zig"); const image = @import("vision_image.zig"); +const images = @import("images.zig"); const tables = @import("vision_tables.zig"); const picture = core.picture; @@ -232,3 +233,8 @@ test "bytes that are not a supported picture are refused with words for the clie try t.expect(image.problem(error.NoImageBudget) != null); try t.expect(image.problem(error.Invalid) == null); // the server words Invalid itself } + +test "a picture's rows are logged as the lowercase SHA-256 of their BF16 bytes" { + try t.expectEqualStrings("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", &images.digestHex("abc")); + try t.expectEqualStrings("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", &images.digestHex("")); +} From 313131b5eda15378194ae40e4fd284bf177a8a16 Mon Sep 17 00:00:00 2001 From: BlivionIaG <15323295+BlivionIaG@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:55:06 +0100 Subject: [PATCH 301/361] docs: the changelog line names the tower log line - The #4704 bullet says each picture the tower runs logs its content hash, rows and the SHA-256 of its BF16 rows. --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a678b4d3d20..6dab531697f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -215,7 +215,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: a plan for Inkling 2 Mini on CUDA and Metal in slices a contributor can claim (#4274). Thanks @akol1. -- Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. +- Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. Each picture the tower runs logs one `inkling2 image tower:` line with the picture's content hash, its rows and the SHA-256 of the BF16 rows it hands to the splice. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. - Docs: the Flash Next HIP recipe adds the measured four-rank serve path and fixes its receipt link (#4669). Thanks @timmyit. From 6862833353405f97d0c3be59ca0d551abb627859 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:56:20 +0000 Subject: [PATCH 302/361] changelog: #4704's line from lines/4704.txt in place of its own --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dab531697f..59a6da526cd 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 +- Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. Each picture the tower runs logs one `inkling2 image tower:` line with the picture's content hash, its rows and the SHA-256 of the BF16 rows it hands to the splice. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. + - Settings: `TF_Q27_KV_GROW` (Metal) and `TF_QWEN_KV_SNAPSHOT_GPU` (CUDA) are checked at startup and refused by name like every registered setting; their accepted values are unchanged, except that `TF_QWEN_KV_SNAPSHOT_GPU` text other than `0` or `1`, which was read as off, is now refused. `docs/environment.md` now covers `TF_CUDA_POOL_AFTER_WARMUP`, `TF_GLM_WIDE_EXPERT_TILE`, `TF_Q27_KV_GROW`, `TF_QWEN35_CHUNK` and `TF_QWEN_KV_SNAPSHOT_GPU`, and `docs/run-guide.md` covers `tensorfold start --startup-timeout` (#4963). - Qwen 3.8-27B on Metal M5: 5-bit and 6-bit group-64 checkpoints split K for decode and prompt rows as v1.3.4 did again, so their sums run in v1.3.4's order; #4419 had moved them onto the 4-bit M5 split tables, and its register-direct kernels stay, at the restored splits. Gemma 4 and 4-bit are unchanged (#4962). @@ -215,8 +217,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Docs: a plan for Inkling 2 Mini on CUDA and Metal in slices a contributor can claim (#4274). Thanks @akol1. -- Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. Each picture the tower runs logs one `inkling2 image tower:` line with the picture's content hash, its rows and the SHA-256 of the BF16 rows it hands to the splice. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. - - Docs: the Flash Next HIP recipe adds the measured four-rank serve path and fixes its receipt link (#4669). Thanks @timmyit. - Desktop: the app changelog lists the Room, Kanban and saved-bot changes (#4376). Thanks @garvrao80. From c2c43669ee3603a155b0bcdeb371938561ea04c5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:48:05 +0000 Subject: [PATCH 303/361] flashnext cuda: non-final one-rank prompt chunks skip the unread last MLP On one rank, a prompt chunk before the last whose pass has no stream, keep or MoE-add hook runs its head as .none, and head(.none) returns before it reads the residual streams. Nothing read the last layer's MLP stream write-back and read-out, its experts or its MoE adds. The pass now stops after that layer's mixer, whose cache and state writes still run. Nothing that is read changes, so tokens keep their bits. Tensor-parallel passes keep the whole last layer. Rank 0's MTP prefill asks for the streams while rank 1 sees only the logits flag, so a skip on one rank alone would leave the ranks' MoE collectives out of step. A pass with drafts, kept rows or training adds also runs the layer as before. The serving pin for cuda_batch.zig moves to the new bytes. --- zig/src/families/flashnext/cuda_batch.zig | 7 +++++++ zig/tests/fixtures/gradient-serving.tsv | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/zig/src/families/flashnext/cuda_batch.zig b/zig/src/families/flashnext/cuda_batch.zig index 2cbc4547fa0..852e62ffa28 100644 --- a/zig/src/families/flashnext/cuda_batch.zig +++ b/zig/src/families/flashnext/cuda_batch.zig @@ -550,6 +550,7 @@ pub fn Pass(comptime Tri: type) type { if (keep.mix_branch != 0) try self.sumSlices(s.part, keep.mix_branch, true, n * dims, self.out_slices); const sl = zs.slices(self.zero_slices, s.cap, n, self.out_slices); self.zero_slices = false; + if (layer + 1 == self.m.layers.len and self.unreadTail()) break; // head(.none) reads none of these rows if (hc.fuses(self, lw.mlp_hc, n, keep.mlp_hc)) { try self.tri.hcWritebackNorm(s.h, s.h, s.pss, s.part, s.inj, s.dummy, s.dummy, lw.mlp_hc.scale.ptr, s.norm, eps, sl.stride, n, dims, streams, 4, 1, 1, sl.count); try hc.readoutNative(self, lw.mlp_hc, 0, n); @@ -564,6 +565,12 @@ pub fn Pass(comptime Tri: type) type { try self.head(logits_host); } + /// A non-final prompt chunk on one rank that nothing taps: its last layer's MLP stream and experts go unread. + fn unreadTail(self: *const Self) bool { + const h = self.hooks; + return self.m.collective == null and h.logits == .none and h.streams == 0 and h.keep == null and h.moe_add == null; + } + pub fn complete(self: *Self) !void { if (self.m.collective) |c| return c.finish(self.stream); try self.stream.synchronize(); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 9576448fadd..07552991029 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -115,7 +115,7 @@ zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0b zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw zig/src/cuda/vit.zig 3a22b6aaf70bcf83a1d3c7624c8c554e262e69d12be07b6e6b389702f77b5877 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw -zig/src/families/flashnext/cuda_batch.zig b368dc5784c9d7e82d9e29ce26f37b3471d31a21e12a144127d365bdcc4ead96 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged +zig/src/families/flashnext/cuda_batch.zig 8610c07449aa7068535f0c547fff3339091b2a1c74f61a4dc64d470eb8cd736d raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged; this change: a one-rank prompt chunk before the last that nothing taps skips its last layer's MLP stream and experts, which head(.none) never reads; outputs unchanged zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged zig/src/families/flashnext/cuda_collective.zig bf475ffb46b3440fcad280f46e34de25cd22b79ed96a0b587d0869e7451d3519 raw adds sumBlock, the in-place FP32 reduce-scatter with sum's peer check, deadline and abort; no served change on its own zig/src/families/flashnext/cuda_compare_main.zig ade014dfec88f0b386076cdc093ea20710d7bf36c33ff566ca2caf472064695b raw main dfd9ac5ef4 (#2585: the TF_FLASHNEXT_* startup check), c274b45cc1 (the check through the flashnext module) From e641337d0b42217d0bbacda29ef1cb5b951505d0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:04:00 +0000 Subject: [PATCH 304/361] changelog: flashnext cuda: non-final one-rank prompt chunks skip the unread last MLP --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 59a6da526cd..a908459d206 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,8 @@ 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. - 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). +- Flash Next on CUDA: on one GPU, a prompt chunk before the last skips its last layer's MLP stream and experts, which nothing reads; tokens unchanged, and tensor-parallel passes run as before (#4885). + - CONTRIBUTING: exactness is bit for bit. A changed reduction order or rounding point must keep every output bit, by default and with any switch on; an FP64 reference no longer makes a different result acceptable (#4888). - 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. From 3e1c4c582e60ceddac4d981f83839b778f8a5c9f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:29:32 +0000 Subject: [PATCH 305/361] changelog: #4885's line from lines/4885.txt in place of its own --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a908459d206..3b06866ca33 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 +- Flash Next on CUDA: on one GPU, a prompt chunk before the last skips its last layer's MLP stream and experts, which nothing reads; tokens unchanged, and tensor-parallel passes run as before (#4885). + - Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. Each picture the tower runs logs one `inkling2 image tower:` line with the picture's content hash, its rows and the SHA-256 of the BF16 rows it hands to the splice. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. - Settings: `TF_Q27_KV_GROW` (Metal) and `TF_QWEN_KV_SNAPSHOT_GPU` (CUDA) are checked at startup and refused by name like every registered setting; their accepted values are unchanged, except that `TF_QWEN_KV_SNAPSHOT_GPU` text other than `0` or `1`, which was read as off, is now refused. `docs/environment.md` now covers `TF_CUDA_POOL_AFTER_WARMUP`, `TF_GLM_WIDE_EXPERT_TILE`, `TF_Q27_KV_GROW`, `TF_QWEN35_CHUNK` and `TF_QWEN_KV_SNAPSHOT_GPU`, and `docs/run-guide.md` covers `tensorfold start --startup-timeout` (#4963). @@ -89,7 +91,6 @@ 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. - 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). -- Flash Next on CUDA: on one GPU, a prompt chunk before the last skips its last layer's MLP stream and experts, which nothing reads; tokens unchanged, and tensor-parallel passes run as before (#4885). - CONTRIBUTING: exactness is bit for bit. A changed reduction order or rounding point must keep every output bit, by default and with any switch on; an FP64 reference no longer makes a different result acceptable (#4888). From 6eb6d13e8d35d36abb2da6f60e7007362d826778 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:14:41 +0000 Subject: [PATCH 306/361] zonos3: ZONOS3 Mini's backbone on CUDA, checked against the reference's dumps fp32 rows over the published bf16 weights (model.pth read without Python), one row-kernel path for prompt and decode rows. zonos3-generate --check compares every sublayer with tools/dump_golden.py lm captures of Zyphra/ZONOS3-Mini. --- zig/build/cuda.zig | 1 + zig/build/cuda_kernels.zig | 1 + zig/build/zonos3.zig | 14 + zig/kernels/cuda/zonos3.cu | 335 +++++++++++++++++++++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/zonos3/config.zig | 131 +++++++++ zig/src/families/zonos3/cuda/engine.zig | 320 ++++++++++++++++++++++ zig/src/families/zonos3/cuda/kernels.zig | 199 ++++++++++++++ zig/src/families/zonos3/cuda/weights.zig | 175 ++++++++++++ zig/src/families/zonos3/generate.zig | 158 +++++++++++ zig/src/families/zonos3/npy.zig | 88 ++++++ zig/src/families/zonos3/zonos3.zig | 16 ++ 12 files changed, 1439 insertions(+) create mode 100644 zig/build/zonos3.zig create mode 100644 zig/kernels/cuda/zonos3.cu create mode 100644 zig/src/families/zonos3/config.zig create mode 100644 zig/src/families/zonos3/cuda/engine.zig create mode 100644 zig/src/families/zonos3/cuda/kernels.zig create mode 100644 zig/src/families/zonos3/cuda/weights.zig create mode 100644 zig/src/families/zonos3/generate.zig create mode 100644 zig/src/families/zonos3/npy.zig create mode 100644 zig/src/families/zonos3/zonos3.zig diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 844e11d6f37..f4066b32f90 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -175,6 +175,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const d3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, mods.core) } } }); const d3_exe = b.addExecutable(.{ .name = "drama3-generate", .root_module = d3_tool }); b.step("drama3-generate", "Drama generation and replay controls on CUDA").dependOn(&b.addInstallArtifact(d3_exe, .{}).step); + @import("zonos3.zig").install(b, target, optimize, cuda, mods.core); } /// The Kolibri-1 CUDA family over the runtime, the core and the lane core. const kolibri1Module = @import("kolibri.zig").module; diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index e5e96219b6a..ea696953e37 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -198,6 +198,7 @@ pub const kernels = [_]Kernel{ .{ .name = "drama3", .flags = &.{"-O3"} }, .{ .name = "drama3_fp8", .flags = &.{"-O3"} }, .{ .name = "drama3_codec", .flags = &.{"-O3"} }, + .{ .name = "zonos3", .flags = glue }, // ours: ZONOS3 Mini's fp32 row kernels over bf16 weights }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. diff --git a/zig/build/zonos3.zig b/zig/build/zonos3.zig new file mode 100644 index 00000000000..4f3c9067c95 --- /dev/null +++ b/zig/build/zonos3.zig @@ -0,0 +1,14 @@ +//! ZONOS3 Mini's CUDA family module and its zonos3-generate tool. +const std = @import("std"); + +/// The family over a runtime and the core; torch_pth is the Python-free .pth reader Drama 3's codec loads with. +pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) *std.Build.Module { + const pth = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/codec_pth.zig"), .target = target, .optimize = optimize }); + return b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/zonos3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "torch_pth", .module = pth } } }); +} + +pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) void { + const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "zonos3", .module = module(b, target, optimize, cuda, core) } } }); + const exe = b.addExecutable(.{ .name = "zonos3-generate", .root_module = tool }); + b.step("zonos3-generate", "ZONOS3 Mini's backbone on CUDA against the reference's dumps").dependOn(&b.addInstallArtifact(exe, .{}).step); +} diff --git a/zig/kernels/cuda/zonos3.cu b/zig/kernels/cuda/zonos3.cu new file mode 100644 index 00000000000..d0ebe4cd91e --- /dev/null +++ b/zig/kernels/cuda/zonos3.cu @@ -0,0 +1,335 @@ +// ours: ZONOS3 Mini's backbone on CUDA: fp32 rows over bf16 weights, one fixed order a row for prompt and decode. +#include +#include +#include +#include "common/reduce.cuh" +#include "common/act.cuh" + +typedef __nv_bfloat16 bf16; + +namespace { + +__device__ __forceinline__ float b2f(bf16 x) { return __bfloat162float(x); } + +using tf_common::block_max_tree; +using tf_common::block_sum_tree; +using tf_common::rms_scale; +using tf_common::warp_sum; + +// Eight bf16 weights against eight fp32 inputs, in index order. +__device__ __forceinline__ float dot8(const uint4& w, const float* x, float acc) { + float f[8]; + tf_common::unpack8(w, f); +#pragma unroll + for (int i = 0; i < 8; ++i) acc = fmaf(f[i], x[i], acc); + return acc; +} + +} // namespace + +// Frame rows [T, 11] to the sum of their eleven embeddings, column 0 first: tables bf16 [rows, D], ten audio then text. +extern "C" __global__ void z3_embed(const int* __restrict__ rows, const bf16* __restrict__ tables, int audio_rows, + float* __restrict__ out, int D) { + const int* r = rows + (size_t)blockIdx.x * 11; + float* o = out + (size_t)blockIdx.x * D; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + float s = 0.f; +#pragma unroll + for (int c = 0; c < 11; ++c) s += b2f(tables[((size_t)c * audio_rows + r[c]) * D + i]); + o[i] = s; + } +} + +// y = x * rsqrt(mean(x^2) + eps) * w (w bf16, or null for a weightless norm); a block a row, D a multiple of 32. +extern "C" __global__ void __launch_bounds__(256) z3_rmsnorm(const float* __restrict__ x, int x_stride, + const bf16* __restrict__ w, float* __restrict__ y, + int y_stride, int D, float eps) { + __shared__ float part[32]; + const float* xr = x + (size_t)blockIdx.x * x_stride; + float* yr = y + (size_t)blockIdx.x * y_stride; + float ss = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) ss = fmaf(xr[i], xr[i], ss); + const float inv = rms_scale(block_sum_tree(ss, part, blockDim.x >> 5), D, eps); + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float v = xr[i] * inv; + yr[i] = w ? v * b2f(w[i]) : v; + } +} + +// Full AttnRes: a row's S sources (bank [S][cap][D]) mixed by softmax over s of sum(rms_norm(source) * query). +extern "C" __global__ void __launch_bounds__(256) z3_attnres(const float* __restrict__ bank, int S, int cap, + const bf16* __restrict__ query, float* __restrict__ out, + int D, float eps) { + __shared__ float part[32]; + __shared__ float wgt[64]; + const size_t row = blockIdx.x; + for (int s = 0; s < S; ++s) { + const float* x = bank + ((size_t)s * cap + row) * D; + float ss = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) ss = fmaf(x[i], x[i], ss); + const float inv = rms_scale(block_sum_tree(ss, part, blockDim.x >> 5), D, eps); + float d = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) d = fmaf(x[i] * inv, b2f(query[i]), d); + d = block_sum_tree(d, part, blockDim.x >> 5); + if (threadIdx.x == 0) wgt[s] = d; + } + __syncthreads(); + if (threadIdx.x == 0) { + float m = wgt[0]; + for (int s = 1; s < S; ++s) m = fmaxf(m, wgt[s]); + float total = 0.f; + for (int s = 0; s < S; ++s) { + wgt[s] = expf(wgt[s] - m); + total += wgt[s]; + } + for (int s = 0; s < S; ++s) wgt[s] /= total; + } + __syncthreads(); + float* o = out + row * D; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + float a = 0.f; + for (int s = 0; s < S; ++s) a = fmaf(bank[((size_t)s * cap + row) * D + i], wgt[s], a); + o[i] = a; + } +} + +// y[r, n] = sum_k W[n, k] x[r / xrep, k] (+ bias[n]): W bf16 [N, K], K a multiple of 8. A warp an output, x staged +// in K * 4 bytes of dynamic shared. With picks, row r reads W + picks[r] * pick_stride. +extern "C" __global__ void __launch_bounds__(256) z3_linear(const bf16* __restrict__ W, const float* __restrict__ x, + int x_stride, int xrep, int K, int N, + float* __restrict__ y, int y_stride, + const bf16* __restrict__ bias, + const int* __restrict__ picks, long long pick_stride) { + extern __shared__ float xs[]; + const int r = blockIdx.y; + const float* xr = x + (size_t)(r / xrep) * x_stride; + for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = xr[i]; + __syncthreads(); + const int lane = threadIdx.x & 31; + const int n = blockIdx.x * 8 + (threadIdx.x >> 5); + const bf16* base = picks ? W + (size_t)picks[r] * (size_t)pick_stride : W; + const uint4* wr = reinterpret_cast(base + (size_t)min(n, N - 1) * K); + const int chunks = K >> 3; + float acc = 0.f; + for (int c = lane; c < chunks; c += 32) acc = dot8(wr[c], xs + c * 8, acc); + acc = warp_sum(acc); + if (lane == 0 && n < N) y[(size_t)r * y_stride + n] = bias ? acc + b2f(bias[n]) : acc; +} + +// GDN depthwise causal conv (kernel 4, the newest input last) + SiLU over C channels; state keeps the last 3 inputs. +extern "C" __global__ void z3_conv_silu(const float* __restrict__ proj, int ps, int T, const bf16* __restrict__ w, + float* __restrict__ state, float* __restrict__ out, int C) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + const float w0 = b2f(w[c * 4 + 0]), w1 = b2f(w[c * 4 + 1]), w2 = b2f(w[c * 4 + 2]), w3 = b2f(w[c * 4 + 3]); + float s0 = state[c * 3 + 0], s1 = state[c * 3 + 1], s2 = state[c * 3 + 2]; + for (int t = 0; t < T; ++t) { + const float x = proj[(size_t)t * ps + c]; + float acc = s0 * w0; + acc = fmaf(s1, w1, acc); + acc = fmaf(s2, w2, acc); + acc = fmaf(x, w3, acc); + out[(size_t)t * C + c] = tf_common::silu(acc); + s0 = s1; + s1 = s2; + s2 = x; + } + state[c * 3 + 0] = s0; + state[c * 3 + 1] = s1; + state[c * 3 + 2] = s2; +} + +// A row's GDN inputs for head blockIdx.y: l2-normed q (scaled by 128^-1/2) and k in place, decay and beta. +// conv is [T][3 * 512] (q | k | v); proj rows hold a at a_off + h and b at a_off + 4 + h. +extern "C" __global__ void __launch_bounds__(128) z3_gdn_prep(float* __restrict__ conv, const float* __restrict__ proj, + int ps, int a_off, const bf16* __restrict__ A_log, + const bf16* __restrict__ dt_bias, + float* __restrict__ gates) { + __shared__ float part[32]; + const int t = blockIdx.x, h = blockIdx.y; + float* q = conv + (size_t)t * 1536 + h * 128; + float* k = q + 512; + const float qv = q[threadIdx.x], kv = k[threadIdx.x]; + const float qs = block_sum_tree(qv * qv, part, 4); + const float ks = block_sum_tree(kv * kv, part, 4); + q[threadIdx.x] = qv * rsqrtf(qs + 1e-6f) * 0.088388347648318447f; + k[threadIdx.x] = kv * rsqrtf(ks + 1e-6f); + if (threadIdx.x == 0) { + const float* p = proj + (size_t)t * ps + a_off; + gates[(t * 4 + h) * 2 + 0] = expf(-expf(b2f(A_log[h])) * tf_common::softplusf_(p[h] + b2f(dt_bias[h]))); + gates[(t * 4 + h) * 2 + 1] = tf_common::sigmoidf_(p[4 + h]); + } +} + +// GDN recurrence, token by token in fp32: a thread a value row of head blockIdx.x's state S [4][128][128]. +extern "C" __global__ void __launch_bounds__(128) z3_gdn(const float* __restrict__ conv, + const float* __restrict__ gates, int T, + float* __restrict__ S, float* __restrict__ o) { + const int h = blockIdx.x, v = threadIdx.x; + float* srow = S + ((size_t)h * 128 + v) * 128; + float row[128]; + for (int j = 0; j < 128; ++j) row[j] = srow[j]; + for (int t = 0; t < T; ++t) { + const float* q = conv + (size_t)t * 1536 + h * 128; + const float* k = q + 512; + const float val = q[1024 + v]; + const float decay = gates[(t * 4 + h) * 2 + 0], beta = gates[(t * 4 + h) * 2 + 1]; + float pred = 0.f; + for (int j = 0; j < 128; ++j) { + row[j] *= decay; + pred = fmaf(row[j], k[j], pred); + } + const float delta = beta * (val - pred); + float out = 0.f; + for (int j = 0; j < 128; ++j) { + row[j] = fmaf(delta, k[j], row[j]); + out = fmaf(row[j], q[j], out); + } + o[(size_t)t * 512 + h * 128 + v] = out; + } + for (int j = 0; j < 128; ++j) srow[j] = row[j]; +} + +// y = rms_norm(o, w, 1e-5) * silu(z) per head of 128: o [T][512], z in proj rows at z_off. +extern "C" __global__ void __launch_bounds__(128) z3_gated_norm(const float* __restrict__ o, + const float* __restrict__ proj, int ps, int z_off, + const bf16* __restrict__ w, float* __restrict__ y) { + __shared__ float part[32]; + const int t = blockIdx.x, h = blockIdx.y, i = threadIdx.x; + const float x = o[(size_t)t * 512 + h * 128 + i]; + const float inv = rms_scale(block_sum_tree(x * x, part, 4), 128, 1e-5f); + y[(size_t)t * 512 + h * 128 + i] = x * inv * b2f(w[i]) * tf_common::silu(proj[(size_t)t * ps + z_off + h * 128 + i]); +} + +// Attention inputs of row blockIdx.x at position pos0 + row: q [16][32] rms-normed, scaled by |temp| and rotated in +// place; k [4][32] rms-normed and rotated into the cache row, v copied. A warp a head; pairs rotate (2m, 2m + 1). +extern "C" __global__ void __launch_bounds__(512) z3_attn_prep(float* __restrict__ q, const float* __restrict__ kv, + const bf16* __restrict__ temp, int pos0, + float* __restrict__ kc, float* __restrict__ vc, + float theta) { + const int t = blockIdx.x, lane = threadIdx.x & 31, h = threadIdx.x >> 5; + const float pos = (float)(pos0 + t); + const float freq = powf(theta, -(float)(lane & ~1) / 32.f); + const float ang = pos * freq; + const float c = cosf(ang), s = sinf(ang); + float* qr = q + (size_t)t * 512 + threadIdx.x; + float x = *qr; + x = x * rms_scale(warp_sum(x * x), 32, 1e-6f) * fabsf(b2f(temp[h])); + float other = __shfl_xor_sync(0xffffffffu, x, 1); + *qr = (lane & 1) ? other * s + x * c : x * c - other * s; + if (h < 4) { + const float* kr = kv + (size_t)t * 256; + float kx = kr[threadIdx.x]; + kx = kx * rms_scale(warp_sum(kx * kx), 32, 1e-6f); + other = __shfl_xor_sync(0xffffffffu, kx, 1); + const size_t at = (size_t)(pos0 + t) * 128 + threadIdx.x; + kc[at] = (lane & 1) ? other * s + kx * c : kx * c - other * s; + vc[at] = kr[128 + threadIdx.x]; + } +} + +// Causal attention of (row blockIdx.x, head blockIdx.y) over cache rows 0 .. pos0 + row, then the head's sigmoid gate. +// Keys go to threads by index mod 256 and the block folds in a fixed order, so a row's bits depend on its position. +extern "C" __global__ void __launch_bounds__(256) z3_attention(const float* __restrict__ q, + const float* __restrict__ kc, + const float* __restrict__ vc, + const float* __restrict__ gate, int pos0, + float* __restrict__ out) { + __shared__ float part[32]; + __shared__ float acc[256][33]; + const int t = blockIdx.x, h = blockIdx.y, kh = h >> 2; + const int L = pos0 + t + 1; + float qv[32]; + const float* qr = q + (size_t)t * 512 + h * 32; +#pragma unroll + for (int i = 0; i < 32; ++i) qv[i] = qr[i]; + const float scale = 0.17677669529663688f; + float m = -INFINITY; + for (int j = threadIdx.x; j < L; j += blockDim.x) { + const float* k = kc + (size_t)j * 128 + kh * 32; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 32; ++i) d = fmaf(qv[i], k[i], d); + m = fmaxf(m, d * scale); + } + m = block_max_tree(m, part, 8); + float a[33]; +#pragma unroll + for (int i = 0; i < 33; ++i) a[i] = 0.f; + for (int j = threadIdx.x; j < L; j += blockDim.x) { + const float* k = kc + (size_t)j * 128 + kh * 32; + const float* v = vc + (size_t)j * 128 + kh * 32; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 32; ++i) d = fmaf(qv[i], k[i], d); + const float e = expf(d * scale - m); + a[32] += e; +#pragma unroll + for (int i = 0; i < 32; ++i) a[i] = fmaf(e, v[i], a[i]); + } +#pragma unroll + for (int i = 0; i < 33; ++i) acc[threadIdx.x][i] = a[i]; + __syncthreads(); + if (threadIdx.x < 33) { + float s = 0.f; + for (int w = 0; w < 256; ++w) s += acc[w][threadIdx.x]; + acc[0][threadIdx.x] = s; + } + __syncthreads(); + if (threadIdx.x < 32) { + const float g = tf_common::sigmoidf_(gate[(size_t)t * 16 + h]); + out[(size_t)t * 512 + h * 32 + threadIdx.x] = acc[0][threadIdx.x] / acc[0][32] * g; + } +} + +// out[r, i] = in[r, a_off + i] * silu(in[r, b_off + i]) for i < n. +extern "C" __global__ void z3_mul_silu(const float* __restrict__ in, int stride, int a_off, int b_off, int n, + float* __restrict__ out) { + const float* r = in + (size_t)blockIdx.y * stride; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) out[(size_t)blockIdx.y * n + i] = r[a_off + i] * tf_common::silu(r[b_off + i]); +} + +// A row's two experts: the top two of logits - bias (ties to the lower index), weights softmax of their raw logits. +extern "C" __global__ void z3_route(const float* __restrict__ logits, const float* __restrict__ bias, int E, + int* __restrict__ picks, float* __restrict__ w) { + if (threadIdx.x != 0) return; + const float* l = logits + (size_t)blockIdx.x * E; + int b0 = -1, b1 = -1; + float v0 = -INFINITY, v1 = -INFINITY; + for (int e = 0; e < E; ++e) { + const float v = l[e] - bias[e]; + if (b0 < 0 || v > v0) { + b1 = b0; + v1 = v0; + b0 = e; + v0 = v; + } else if (b1 < 0 || v > v1) { + b1 = e; + v1 = v; + } + } + const float m = fmaxf(l[b0], l[b1]); + const float e0 = expf(l[b0] - m), e1 = expf(l[b1] - m); + picks[blockIdx.x * 2] = b0; + picks[blockIdx.x * 2 + 1] = b1; + w[blockIdx.x * 2] = e0 / (e0 + e1); + w[blockIdx.x * 2 + 1] = e1 / (e0 + e1); +} + +// out[r] = down[2r] * w[2r] + down[2r + 1] * w[2r + 1], the first pick first. +extern "C" __global__ void z3_combine(const float* __restrict__ down, const float* __restrict__ w, int n, + float* __restrict__ out) { + const size_t r = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float a = down[(2 * r) * n + i] * w[2 * r]; + a += down[(2 * r + 1) * n + i] * w[2 * r + 1]; + out[r * n + i] = a; +} + +// Logits in place: cap * tanh(x / cap). +extern "C" __global__ void z3_softcap(float* __restrict__ x, long long n, float cap) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = cap * tanhf(x[i] / cap); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index bf53d71117e..4730d6064b7 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -205,6 +205,7 @@ pub const drama3: []const u8 = if (available) &Blob("fatbin_drama3").bytes else pub const drama3_fp8: []const u8 = if (available) &Blob("fatbin_drama3_fp8").bytes else &.{}; pub const drama3_codec: []const u8 = if (available) &Blob("fatbin_drama3_codec").bytes else &.{}; pub const drama3_staged_gemv: []const u8 = if (available) &Blob("fatbin_drama3_staged_gemv").bytes else &.{}; +pub const zonos3: []const u8 = if (available) &Blob("fatbin_zonos3").bytes else &.{}; pub const gdn_train: []const u8 = if (available) &Blob("fatbin_gdn_train").bytes else &.{}; pub const train_q4: []const u8 = if (available) &Blob("fatbin_train_q4").bytes else &.{}; pub const train_attn: []const u8 = if (available) &Blob("fatbin_train_attn").bytes else &.{}; diff --git a/zig/src/families/zonos3/config.zig b/zig/src/families/zonos3/config.zig new file mode 100644 index 00000000000..a934b7c3361 --- /dev/null +++ b/zig/src/families/zonos3/config.zig @@ -0,0 +1,131 @@ +//! ZONOS3 Mini's geometry (params.json "model"): load() refuses a checkpoint unlike the one the kernels are built for. +const std = @import("std"); + +pub const dim = 1024; +pub const layers = 11; +pub const heads = 16; +pub const kv_heads = 4; +pub const head_dim = 32; +pub const rope_theta: f32 = 10000.0; +pub const eps: f32 = 1.0e-5; +pub const softcap: f32 = 15.0; +pub const max_seqlen = 32768; +// every gdn_period-th layer is a global attention layer, the rest are Gated DeltaNet +pub const gdn_period = 4; +pub const gdn_heads = 4; +pub const gdn_dim = 128; +pub const gdn_inner = gdn_heads * gdn_dim; // 512 +pub const gdn_conv = 3 * gdn_inner; // q | k | v +pub const gdn_kernel = 4; +pub const gdn_proj = 4 * gdn_inner + 2 * gdn_heads; // qkv | z | a | b = 2056 +pub const attn_inner = heads * head_dim; // 512 +pub const kv_width = kv_heads * head_dim; // 128 +// feed-forward: layer 0 dense, the rest a latent mixture of experts +pub const ffn_hidden = 2048; +pub const experts = 64; +pub const top_k = 2; +pub const moe_hidden = 1536; +pub const moe_latent = 256; +// frames: [code 0 .. code 9, text] +pub const codebooks = 10; +pub const codebook_size = 4096; +pub const eoa_id = 4096; +pub const audio_pad_id = 4097; +pub const audio_vocab = codebook_size + 2; +pub const frame_width = codebooks + 1; +pub const text_vocab = 8196; // SuperBPE 8192 + 4; also the text column's padding row +pub const head_rows = codebooks * audio_vocab; // 40980 +pub const sources = 2 * layers + 1; // Full AttnRes bank: the embedding and two a layer +pub const speaker_dim = 192; +pub const conditions = 3; // loudness, fmax, speaking rate +pub const max_buckets = 30; + +pub fn usesGdn(layer: usize) bool { + return (layer + 1) % gdn_period != 0; +} + +pub const Config = struct { + /// Buckets of each condition table; id == count is the table's unknown row. + buckets: [conditions]u32, + + pub fn load(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "params.json" }); + defer gpa.free(path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(text); + return parse(gpa, text); + } + + pub fn parse(gpa: std.mem.Allocator, text: []const u8) !Config { + var tree = try std.json.parseFromSlice(std.json.Value, gpa, text, .{}); + defer tree.deinit(); + const root = try object(tree.value); + const m = if (root.get("model")) |v| try object(v) else root; + const ints = .{ + .{ "n_layers", layers }, .{ "dim", dim }, .{ "head_dim", head_dim }, + .{ "n_heads", heads }, .{ "n_kv_heads", kv_heads }, .{ "max_seqlen", max_seqlen }, + .{ "n_codebooks", codebooks }, .{ "codebook_size", codebook_size }, .{ "eoa_id", eoa_id }, + .{ "audio_pad_id", audio_pad_id }, .{ "text_vocab", text_vocab }, .{ "moe_n_experts", experts }, + .{ "moe_router_topk", top_k }, .{ "moe_start_from_layer", 1 }, .{ "moe_end_from_layer", 0 }, + .{ "speaker_embedding_dim", speaker_dim }, .{ "condition_count", conditions }, + }; + inline for (ints) |e| if (try int(m, e[0]) != e[1]) return refuse(e[0]); + const strings = .{ + .{ "attention_pattern", "gdn3_global1" }, .{ "residual_type", "full_attnres" }, + .{ "moe_router_type", "linear" }, .{ "moe_balancing_strategy", "quantile" }, + .{ "dtype", "bfloat16" }, + }; + inline for (strings) |e| { + const v = m.get(e[0]) orelse return refuse(e[0]); + if (v != .string or !std.mem.eql(u8, v.string, e[1])) return refuse(e[0]); + } + const floats = .{ + .{ "norm_eps", eps }, .{ "rope_theta", rope_theta }, .{ "loss_softcap", softcap }, + .{ "ffn_dim_multiplier", 2.0 }, .{ "moe_ffn_dim_multiplier", 1.5 }, .{ "moe_alpha", 0.25 }, + }; + inline for (floats) |e| if (@as(f32, @floatCast(try float(m, e[0]))) != @as(f32, e[1])) return refuse(e[0]); + const off = .{ "use_xsa", "moe_router_use_eda" }; + inline for (off) |name| { + const v = m.get(name) orelse return refuse(name); + if (v != .bool or v.bool) return refuse(name); + } + var c: Config = undefined; + const counts = m.get("condition_bucket_counts") orelse return refuse("condition_bucket_counts"); + if (counts != .array or counts.array.items.len != conditions) return refuse("condition_bucket_counts"); + for (counts.array.items, 0..) |v, i| { + if (v != .integer or v.integer < 1 or v.integer > max_buckets) return refuse("condition_bucket_counts"); + c.buckets[i] = @intCast(v.integer); + } + return c; + } + + fn refuse(name: []const u8) error{UnsupportedCheckpoint} { + std.log.err("zonos3: params.json {s} is not ZONOS3 Mini's", .{name}); + return error.UnsupportedCheckpoint; + } + + fn object(v: std.json.Value) !std.json.ObjectMap { + return if (v == .object) v.object else error.BadConfig; + } + + fn int(m: std.json.ObjectMap, name: []const u8) !i64 { + const v = m.get(name) orelse return refuse(name); + return if (v == .integer) v.integer else refuse(name); + } + + fn float(m: std.json.ObjectMap, name: []const u8) !f64 { + const v = m.get(name) orelse return refuse(name); + return switch (v) { + .float => |f| f, + .integer => |n| @floatFromInt(n), + else => refuse(name), + }; + } +}; + +test "layer kinds: one global attention layer in four" { + var gdn: usize = 0; + for (0..layers) |l| gdn += @intFromBool(usesGdn(l)); + try std.testing.expectEqual(@as(usize, 9), gdn); + try std.testing.expect(!usesGdn(3) and !usesGdn(7) and usesGdn(10)); +} diff --git a/zig/src/families/zonos3/cuda/engine.zig b/zig/src/families/zonos3/cuda/engine.zig new file mode 100644 index 00000000000..55318d7c56d --- /dev/null +++ b/zig/src/families/zonos3/cuda/engine.zig @@ -0,0 +1,320 @@ +//! ZONOS3 Mini's backbone on one GPU: frame rows in, the next frame's logits out; the prompt and each decode row run +//! the same row kernels in fp32, so a row's bits do not depend on how the rows before it were chunked. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("../config.zig"); +const wts = @import("weights.zig"); +const kern = @import("kernels.zig"); + +const D = cfg.dim; +const W = cfg.frame_width; +const Buf = cuda.DeviceBuffer; + +pub const Options = struct { + device: u32 = 0, + max_ctx: usize = 4096, // positions (prompt rows + frames), at most the model's 32768 + max_rows: usize = 64, // rows a pass + + pub fn validate(o: Options) !void { + if (o.max_ctx < 2 or o.max_ctx > cfg.max_seqlen) return error.BadContext; + if (o.max_rows == 0 or o.max_rows > 1024) return error.BadPrefillRows; + } +}; + +/// A prompt row whose summed embedding a vector replaces (the speaker row, the condition rows). +pub const Replace = struct { row: usize, vec: [D]f32 }; + +/// Per-sublayer probe of a pass under the oracle's dump names, called with device fp32 rows [rows, width]. +pub const Probe = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void, + + fn at(p: Probe, comptime f: []const u8, layer: usize, ptr: u64, rows: usize, width: usize) !void { + var nb: [48]u8 = undefined; + try p.f(p.ctx, try std.fmt.bufPrint(&nb, f, .{layer}), ptr, rows, width); + } +}; + +pub const Engine = struct { + gpa: std.mem.Allocator, + o: Options, + c: cfg.Config, + driver: cuda.Driver, + ctx: cuda.Context, + stream: cuda.Stream, + k: kern.Kernels, + w: *wts.Weights, + bufs: std.ArrayList(Buf), + position: usize = 0, + // state + kv: [cfg.layers][2]u64, // attention layers: K, V fp32 [max_ctx][4][32] + conv: [cfg.layers]u64, // GDN layers: the last 3 conv inputs, fp32 [1536][3] + gstate: [cfg.layers]u64, // GDN layers: fp32 [4][128][128] + state: u64, // the conv and recurrent states in one block (zeroed per request) + state_bytes: usize, + // scratch (R = max_rows) + rows: u64, // i32 [R][11] + bank: u64, // fp32 [sources][R][D] + mixed: u64, // [R][D] + xn: u64, // [R][D] + rn: u64, // [R][D] the router's norm + proj: u64, // [R][4096]: the GDN projection, the dense FFN's two halves + conv_out: u64, // [R][1536] + gates: u64, // [R][4][2] + o32: u64, // [R][512] + y: u64, // [R][512] + q: u64, // [R][512] + kvraw: u64, // [R][256] + gate: u64, // [R][16] + act: u64, // [R][2048] + rl: u64, // [R][64] + picks: u64, // i32 [R][2] + rw: u64, // [R][2] + latent: u64, // [R][256] + gu: u64, // [2R][3072] + hid: u64, // [2R][1536] + down: u64, // [2R][256] + comb: u64, // [R][256] + logits: u64, // [R][head_rows] + row_up: u64, // [D] a replaced row on its way in + + pub fn create(gpa: std.mem.Allocator, io: std.Io, model_dir: []const u8, o: Options) !*Engine { + try o.validate(); + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.* = undefined; + e.gpa = gpa; + e.o = o; + e.position = 0; + e.bufs = .empty; + e.c = try cfg.Config.load(gpa, io, model_dir); + e.driver = try cuda.Driver.open(); + errdefer e.driver.close(); + e.ctx = try cuda.Context.init(&e.driver, std.math.cast(c_int, o.device) orelse return error.NoSuchCudaDevice); + errdefer e.ctx.deinit(); + e.stream = try cuda.Stream.init(&e.driver, true); + errdefer e.stream.deinit(); + e.k = try kern.Kernels.load(&e.driver); + errdefer e.k.unload(); + e.w = try wts.load(gpa, io, &e.driver, model_dir, e.c); + errdefer { + e.w.deinit(); + gpa.destroy(e.w); + } + errdefer e.freeState(); + try e.allocState(); + try e.reset(); + return e; + } + + pub fn destroy(e: *Engine) void { + e.stream.synchronize() catch {}; + e.freeState(); + e.w.deinit(); + e.gpa.destroy(e.w); + e.k.unload(); + e.stream.deinit(); + e.ctx.deinit(); + e.driver.close(); + e.gpa.destroy(e); + } + + fn freeState(e: *Engine) void { + for (e.bufs.items) |*b| b.free(); + e.bufs.deinit(e.gpa); + } + + fn alloc(e: *Engine, bytes: usize) !u64 { + var b = try Buf.alloc(&e.driver, @max(bytes, 256)); + errdefer b.free(); + try e.bufs.append(e.gpa, b); + return b.ptr; + } + + fn allocState(e: *Engine) !void { + const R = e.o.max_rows; + const kvb = e.o.max_ctx * cfg.kv_width * 4; + const conv_b = cfg.gdn_conv * 3 * 4; + const gs_b = cfg.gdn_heads * cfg.gdn_dim * cfg.gdn_dim * 4; + var n_gdn: usize = 0; + for (0..cfg.layers) |li| n_gdn += @intFromBool(cfg.usesGdn(li)); + e.state_bytes = n_gdn * (conv_b + gs_b); + e.state = try e.alloc(e.state_bytes); + var g: usize = 0; + for (0..cfg.layers) |li| { + if (cfg.usesGdn(li)) { + e.kv[li] = .{ 0, 0 }; + e.conv[li] = e.state + g * (conv_b + gs_b); + e.gstate[li] = e.conv[li] + conv_b; + g += 1; + } else { + e.kv[li] = .{ try e.alloc(kvb), try e.alloc(kvb) }; + e.conv[li] = 0; + e.gstate[li] = 0; + } + } + e.rows = try e.alloc(R * W * 4); + e.bank = try e.alloc(cfg.sources * R * D * 4); + e.mixed = try e.alloc(R * D * 4); + e.xn = try e.alloc(R * D * 4); + e.rn = try e.alloc(R * D * 4); + e.proj = try e.alloc(R * 2 * cfg.ffn_hidden * 4); + e.conv_out = try e.alloc(R * cfg.gdn_conv * 4); + e.gates = try e.alloc(R * cfg.gdn_heads * 2 * 4); + e.o32 = try e.alloc(R * cfg.gdn_inner * 4); + e.y = try e.alloc(R * cfg.gdn_inner * 4); + e.q = try e.alloc(R * cfg.attn_inner * 4); + e.kvraw = try e.alloc(R * 2 * cfg.kv_width * 4); + e.gate = try e.alloc(R * cfg.heads * 4); + e.act = try e.alloc(R * cfg.ffn_hidden * 4); + e.rl = try e.alloc(R * cfg.experts * 4); + e.picks = try e.alloc(R * cfg.top_k * 4); + e.rw = try e.alloc(R * cfg.top_k * 4); + e.latent = try e.alloc(R * cfg.moe_latent * 4); + e.gu = try e.alloc(R * cfg.top_k * 2 * cfg.moe_hidden * 4); + e.hid = try e.alloc(R * cfg.top_k * cfg.moe_hidden * 4); + e.down = try e.alloc(R * cfg.top_k * cfg.moe_latent * 4); + e.comb = try e.alloc(R * cfg.moe_latent * 4); + e.logits = try e.alloc(R * cfg.head_rows * 4); + e.row_up = try e.alloc(D * 4); + } + + fn buf(e: *Engine, ptr: u64) Buf { + return .{ .d = &e.driver, .ptr = ptr, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + fn put(e: *Engine, dst: u64, bytes: []const u8) !void { + try e.buf(dst).uploadAsync(0, bytes, e.stream.handle); + } + + pub fn download(e: *Engine, src: u64, out: []u8) !void { + try e.buf(src).downloadAsync(0, out, e.stream.handle); + try e.stream.synchronize(); + } + + /// A new request: zero recurrent states, position 0. Cache rows are written before they are read. + pub fn reset(e: *Engine) !void { + var b = e.buf(e.state); + b.len = e.state_bytes; + try b.fill8(0, e.stream.handle); + try e.stream.synchronize(); + e.position = 0; + } + + fn slot(e: *const Engine, source: usize) u64 { + return e.bank + source * e.o.max_rows * D * 4; + } + + /// The next rows (int32 [n][11]) at the current position; afterwards `logits` holds the last row's + /// [codebooks][audio_vocab] (every row's under a probe, which needs the rows in one pass). + pub fn run(e: *Engine, rows: []const [W]i32, replaced: []const Replace, probe: ?Probe) !void { + if (rows.len == 0) return error.NoRows; + if (e.position + rows.len > e.o.max_ctx) return error.ContextFull; + if (probe != null and rows.len > e.o.max_rows) return error.ProbeNeedsOnePass; + for (rows) |r| { + for (r[0..cfg.codebooks]) |code| if (code < 0 or code >= cfg.audio_vocab) return error.BadFrameRow; + if (r[cfg.codebooks] < 0 or r[cfg.codebooks] >= e.w.text_rows) return error.BadFrameRow; + } + var at: usize = 0; + while (at < rows.len) { + const t = @min(e.o.max_rows, rows.len - at); + try e.pass(rows[at..][0..t], at, replaced, at + t == rows.len, probe); + at += t; + } + } + + fn pass(e: *Engine, rows: []const [W]i32, first: usize, replaced: []const Replace, last: bool, probe: ?Probe) !void { + const k = &e.k; + const s = e.stream; + const t = rows.len; + const R = e.o.max_rows; + const pos0 = e.position; + try e.put(e.rows, std.mem.sliceAsBytes(rows)); + try k.embed(s, e.rows, e.w.tables, cfg.audio_vocab, e.mixed, D, t); + if (probe) |p| try p.f(p.ctx, "emb_sum", e.mixed, t, D); + for (replaced) |r| if (r.row >= first and r.row < first + t) { + try e.put(e.row_up, std.mem.asBytes(&r.vec)); + try e.buf(e.mixed).copyFrom((r.row - first) * D * 4, e.row_up, D * 4, s.handle); + }; + if (probe) |p| try p.f(p.ctx, "emb_cond", e.mixed, t, D); + try k.rmsnorm(s, e.mixed, D, 0, e.slot(0), D, D, cfg.eps, t); + if (probe) |p| try p.f(p.ctx, "emb_norm", e.slot(0), t, D); + const q = e.w.queries; + for (&e.w.layers, 0..) |*L, li| { + const attn_out = e.slot(2 * li + 1); + const ffn_out = e.slot(2 * li + 2); + try k.attnres(s, e.bank, 2 * li + 1, R, q + 2 * li * D * 2, e.mixed, D, cfg.eps, t); + if (probe) |p| try p.at("attnres_attn_{d}", li, e.mixed, t, D); + try k.rmsnorm(s, e.mixed, D, L.attention_norm, e.xn, D, D, cfg.eps, t); + if (probe) |p| try p.at("attn_in_{d}", li, e.xn, t, D); + switch (L.mix) { + .gdn => |g| { + const ps = cfg.gdn_proj; + try k.linear(s, g.in_proj, e.xn, D, D, ps, e.proj, ps, t, .{}); + try k.convSilu(s, e.proj, ps, t, g.conv, e.conv[li], e.conv_out, cfg.gdn_conv); + if (probe) |p| try p.at("gdn_conv_{d}", li, e.conv_out, t, cfg.gdn_conv); + try k.gdnPrep(s, e.conv_out, e.proj, ps, 4 * cfg.gdn_inner, g.a_log, g.dt_bias, e.gates, t); + try k.gdn(s, e.conv_out, e.gates, t, e.gstate[li], e.o32); + if (probe) |p| try p.at("gdn_recurrent_{d}", li, e.o32, t, cfg.gdn_inner); + try k.gatedNorm(s, e.o32, e.proj, ps, cfg.gdn_conv, g.out_weight, e.y, t); + if (probe) |p| try p.at("gdn_gated_{d}", li, e.y, t, cfg.gdn_inner); + try k.linear(s, g.wo, e.y, cfg.gdn_inner, cfg.gdn_inner, D, attn_out, D, t, .{}); + }, + .attn => |a| { + try k.linear(s, a.wq, e.xn, D, D, cfg.attn_inner, e.q, cfg.attn_inner, t, .{}); + try k.linear(s, a.wkv, e.xn, D, D, 2 * cfg.kv_width, e.kvraw, 2 * cfg.kv_width, t, .{}); + try k.linear(s, a.gater, e.xn, D, D, cfg.heads, e.gate, cfg.heads, t, .{}); + try k.attnPrep(s, e.q, e.kvraw, a.temp, pos0, e.kv[li][0], e.kv[li][1], cfg.rope_theta, t); + try k.attention(s, e.q, e.kv[li][0], e.kv[li][1], e.gate, pos0, e.y, t); + try k.linear(s, a.wo, e.y, cfg.attn_inner, cfg.attn_inner, D, attn_out, D, t, .{}); + }, + } + if (probe) |p| try p.at("attn_out_{d}", li, attn_out, t, D); + try k.attnres(s, e.bank, 2 * li + 2, R, q + (2 * li + 1) * D * 2, e.mixed, D, cfg.eps, t); + if (probe) |p| try p.at("attnres_ffn_{d}", li, e.mixed, t, D); + try k.rmsnorm(s, e.mixed, D, L.ffn_norm, e.xn, D, D, cfg.eps, t); + if (probe) |p| try p.at("ffn_in_{d}", li, e.xn, t, D); + switch (L.ffn) { + .dense => |f| { + const hidden = cfg.ffn_hidden; + try k.linear(s, f.w_in, e.xn, D, D, 2 * hidden, e.proj, 2 * hidden, t, .{}); + try k.mulSilu(s, e.proj, 2 * hidden, 0, hidden, hidden, e.act, t); + try k.linear(s, f.w_out, e.act, hidden, hidden, D, ffn_out, D, t, .{}); + }, + .moe => |m| { + const hidden = cfg.moe_hidden; + const latent = cfg.moe_latent; + try k.rmsnorm(s, e.xn, D, m.eda, e.rn, D, D, cfg.eps, t); + try k.linear(s, m.router, e.rn, D, D, cfg.experts, e.rl, cfg.experts, t, .{}); + if (probe) |p| try p.at("router_logits_{d}", li, e.rl, t, cfg.experts); + try k.route(s, e.rl, m.bias, cfg.experts, e.picks, e.rw, t); + try k.linear(s, m.latent_down, e.xn, D, D, latent, e.latent, latent, t, .{}); + try k.linear(s, m.gate_up, e.latent, latent, latent, 2 * hidden, e.gu, 2 * hidden, t * cfg.top_k, .{ .picks = e.picks, .pick_stride = 2 * hidden * latent, .xrep = cfg.top_k }); + try k.mulSilu(s, e.gu, 2 * hidden, hidden, 0, hidden, e.hid, t * cfg.top_k); + try k.linear(s, m.down, e.hid, hidden, hidden, latent, e.down, latent, t * cfg.top_k, .{ .picks = e.picks, .pick_stride = latent * hidden }); + try k.combine(s, e.down, e.rw, latent, e.comb, t); + try k.linear(s, m.latent_up, e.comb, latent, latent, D, ffn_out, D, t, .{}); + }, + } + if (probe) |p| try p.at("ffn_out_{d}", li, ffn_out, t, D); + } + try k.attnres(s, e.bank, cfg.sources, R, q + (cfg.sources - 1) * D * 2, e.mixed, D, cfg.eps, t); + if (probe) |p| try p.f(p.ctx, "attnres_final", e.mixed, t, D); + try k.rmsnorm(s, e.mixed, D, e.w.out_norm, e.xn, D, D, cfg.eps, t); + if (probe) |p| try p.f(p.ctx, "out_norm", e.xn, t, D); + if (probe != null) { + try k.linear(s, e.w.head, e.xn, D, D, cfg.head_rows, e.logits, cfg.head_rows, t, .{}); + try k.softcap(s, e.logits, t * cfg.head_rows, cfg.softcap); + if (probe) |p| try p.f(p.ctx, "logits", e.logits, t, cfg.head_rows); + } else if (last) { + try k.linear(s, e.w.head, e.xn + (t - 1) * D * 4, D, D, cfg.head_rows, e.logits, cfg.head_rows, 1, .{}); + try k.softcap(s, e.logits, cfg.head_rows, cfg.softcap); + } + e.position = pos0 + t; + } + + /// The last row's logits [codebooks][audio_vocab] to the host. + pub fn lastLogits(e: *Engine, out: *[cfg.head_rows]f32) !void { + try e.download(e.logits, std.mem.asBytes(out)); + } +}; diff --git a/zig/src/families/zonos3/cuda/kernels.zig b/zig/src/families/zonos3/cuda/kernels.zig new file mode 100644 index 00000000000..f7d30779c6c --- /dev/null +++ b/zig/src/families/zonos3/cuda/kernels.zig @@ -0,0 +1,199 @@ +//! ZONOS3 Mini's launches: zonos3.cu by symbol. Every row kernel takes prompt rows and the decode row alike. +const std = @import("std"); +const cuda = @import("cuda"); + +const names = .{ + "z3_embed", "z3_rmsnorm", "z3_attnres", "z3_linear", "z3_conv_silu", "z3_gdn_prep", "z3_gdn", + "z3_gated_norm", "z3_attn_prep", "z3_attention", "z3_mul_silu", "z3_route", "z3_combine", "z3_softcap", +}; + +pub const F = enum(u8) { embed, rmsnorm, attnres, linear, conv_silu, gdn_prep, gdn, gated_norm, attn_prep, attention, mul_silu, route, combine, softcap }; + +const n_fns = @typeInfo(F).@"enum".field_names.len; + +pub const Kernels = struct { + mod: cuda.Module, + fns: [n_fns]cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var k: Kernels = undefined; + k.mod = try cuda.Module.load(d, cuda.kernels.zonos3); + errdefer k.mod.unload(); + inline for (names, 0..) |name, j| k.fns[j] = try k.mod.function(name); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } + + fn go(k: *const Kernels, which: F, s: cuda.Stream, gx: usize, gy: usize, block: usize, shared: usize, a: *cuda.Args) !void { + try cuda.launch.launch(k.fns[@backingInt(which)], .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy), .z = 1 }, .block = .{ .x = @intCast(block) }, .shared = @intCast(shared) }, s, a); + } + + fn i(x: usize) i32 { + return @intCast(x); + } + + pub fn embed(k: *const Kernels, s: cuda.Stream, rows: u64, tables: u64, audio_rows: usize, out: u64, d: usize, t: usize) !void { + var a: cuda.Args = .{}; + a.add(rows); + a.add(tables); + a.add(i(audio_rows)); + a.add(out); + a.add(i(d)); + try k.go(.embed, s, t, 1, 256, 0, &a); + } + + /// w == 0: the weightless norm. + pub fn rmsnorm(k: *const Kernels, s: cuda.Stream, x: u64, xs: usize, w: u64, y: u64, ys: usize, d: usize, eps: f32, t: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(i(xs)); + a.add(w); + a.add(y); + a.add(i(ys)); + a.add(i(d)); + a.add(eps); + try k.go(.rmsnorm, s, t, 1, 256, 0, &a); + } + + pub fn attnres(k: *const Kernels, s: cuda.Stream, bank: u64, n_src: usize, cap: usize, query: u64, out: u64, d: usize, eps: f32, t: usize) !void { + var a: cuda.Args = .{}; + a.add(bank); + a.add(i(n_src)); + a.add(i(cap)); + a.add(query); + a.add(out); + a.add(i(d)); + a.add(eps); + try k.go(.attnres, s, t, 1, 256, 0, &a); + } + + pub const Linear = struct { bias: u64 = 0, picks: u64 = 0, pick_stride: usize = 0, xrep: usize = 1 }; + + /// y [rows, n] = x [rows / xrep, kdim] W^T: bf16 weights, fp32 rows xs / ys elements apart. + pub fn linear(k: *const Kernels, s: cuda.Stream, w: u64, x: u64, xs: usize, kdim: usize, n: usize, y: u64, ys: usize, rows: usize, o: Linear) !void { + var a: cuda.Args = .{}; + a.add(w); + a.add(x); + a.add(i(xs)); + a.add(i(o.xrep)); + a.add(i(kdim)); + a.add(i(n)); + a.add(y); + a.add(i(ys)); + a.add(o.bias); + a.add(o.picks); + a.add(@as(i64, @intCast(o.pick_stride))); + try k.go(.linear, s, (n + 7) / 8, rows, 256, kdim * 4, &a); + } + + pub fn convSilu(k: *const Kernels, s: cuda.Stream, proj: u64, ps: usize, t: usize, w: u64, state: u64, out: u64, c: usize) !void { + var a: cuda.Args = .{}; + a.add(proj); + a.add(i(ps)); + a.add(i(t)); + a.add(w); + a.add(state); + a.add(out); + a.add(i(c)); + try k.go(.conv_silu, s, (c + 255) / 256, 1, 256, 0, &a); + } + + pub fn gdnPrep(k: *const Kernels, s: cuda.Stream, conv: u64, proj: u64, ps: usize, a_off: usize, a_log: u64, dt_bias: u64, gates: u64, t: usize) !void { + var a: cuda.Args = .{}; + a.add(conv); + a.add(proj); + a.add(i(ps)); + a.add(i(a_off)); + a.add(a_log); + a.add(dt_bias); + a.add(gates); + try k.go(.gdn_prep, s, t, 4, 128, 0, &a); + } + + pub fn gdn(k: *const Kernels, s: cuda.Stream, conv: u64, gates: u64, t: usize, state: u64, o: u64) !void { + var a: cuda.Args = .{}; + a.add(conv); + a.add(gates); + a.add(i(t)); + a.add(state); + a.add(o); + try k.go(.gdn, s, 4, 1, 128, 0, &a); + } + + pub fn gatedNorm(k: *const Kernels, s: cuda.Stream, o: u64, proj: u64, ps: usize, z_off: usize, w: u64, y: u64, t: usize) !void { + var a: cuda.Args = .{}; + a.add(o); + a.add(proj); + a.add(i(ps)); + a.add(i(z_off)); + a.add(w); + a.add(y); + try k.go(.gated_norm, s, t, 4, 128, 0, &a); + } + + pub fn attnPrep(k: *const Kernels, s: cuda.Stream, q: u64, kv: u64, temp: u64, pos0: usize, kc: u64, vc: u64, theta: f32, t: usize) !void { + var a: cuda.Args = .{}; + a.add(q); + a.add(kv); + a.add(temp); + a.add(i(pos0)); + a.add(kc); + a.add(vc); + a.add(theta); + try k.go(.attn_prep, s, t, 1, 512, 0, &a); + } + + pub fn attention(k: *const Kernels, s: cuda.Stream, q: u64, kc: u64, vc: u64, gate: u64, pos0: usize, out: u64, t: usize) !void { + var a: cuda.Args = .{}; + a.add(q); + a.add(kc); + a.add(vc); + a.add(gate); + a.add(i(pos0)); + a.add(out); + try k.go(.attention, s, t, 16, 256, 0, &a); + } + + /// out [rows, n] = in[a_off ..] * silu(in[b_off ..]). + pub fn mulSilu(k: *const Kernels, s: cuda.Stream, in: u64, stride: usize, a_off: usize, b_off: usize, n: usize, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(i(stride)); + a.add(i(a_off)); + a.add(i(b_off)); + a.add(i(n)); + a.add(out); + try k.go(.mul_silu, s, (n + 255) / 256, rows, 256, 0, &a); + } + + pub fn route(k: *const Kernels, s: cuda.Stream, logits: u64, bias: u64, e: usize, picks: u64, w: u64, t: usize) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(bias); + a.add(i(e)); + a.add(picks); + a.add(w); + try k.go(.route, s, t, 1, 32, 0, &a); + } + + pub fn combine(k: *const Kernels, s: cuda.Stream, down: u64, w: u64, n: usize, out: u64, t: usize) !void { + var a: cuda.Args = .{}; + a.add(down); + a.add(w); + a.add(i(n)); + a.add(out); + try k.go(.combine, s, (n + 255) / 256, t, 256, 0, &a); + } + + pub fn softcap(k: *const Kernels, s: cuda.Stream, x: u64, n: usize, cap: f32) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(n))); + a.add(cap); + try k.go(.softcap, s, (n + 255) / 256, 1, 256, 0, &a); + } +}; diff --git a/zig/src/families/zonos3/cuda/weights.zig b/zig/src/families/zonos3/cuda/weights.zig new file mode 100644 index 00000000000..72ccf65a50b --- /dev/null +++ b/zig/src/families/zonos3/cuda/weights.zig @@ -0,0 +1,175 @@ +//! ZONOS3 Mini's weights as published (model.pth, bf16) on the device; the speaker and condition rows stay on the host. +const std = @import("std"); +const cuda = @import("cuda"); +const pth = @import("torch_pth"); +const cfg = @import("../config.zig"); + +const D = cfg.dim; + +pub const Gdn = struct { in_proj: u64, conv: u64, out_weight: u64, a_log: u64, dt_bias: u64, wo: u64 }; +pub const Attn = struct { wq: u64, wkv: u64, wo: u64, temp: u64, gater: u64 }; +pub const Dense = struct { w_in: u64, w_out: u64 }; +pub const Moe = struct { gate_up: u64, down: u64, latent_down: u64, latent_up: u64, router: u64, eda: u64, bias: u64 }; + +pub const Layer = struct { + attention_norm: u64, + ffn_norm: u64, + mix: union(enum) { gdn: Gdn, attn: Attn }, + ffn: union(enum) { dense: Dense, moe: Moe }, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(cuda.DeviceBuffer), + bytes: usize, + tables: u64, // bf16 [10 * audio_vocab + text_rows][D]: the ten audio tables, then the text table + text_rows: usize, + queries: u64, // bf16 [sources][D] + layers: [cfg.layers]Layer, + out_norm: u64, + head: u64, // bf16 [head_rows][D] + // host rows that replace a prompt row's summed embedding + speaker_w: []f32, // [D][speaker_dim] + speaker_b: []f32, // [D] + conditions: [cfg.conditions][]f32, // [buckets + 1][D] + + pub fn deinit(w: *Weights) void { + for (w.bufs.items) |*b| b.free(); + w.bufs.deinit(w.gpa); + w.gpa.free(w.speaker_w); + w.gpa.free(w.speaker_b); + for (w.conditions) |c| w.gpa.free(c); + } + + /// The speaker row: speaker_projection(vec) in fp32. + pub fn speakerRow(w: *const Weights, vec: *const [cfg.speaker_dim]f32, out: *[D]f32) void { + for (out, 0..) |*o, n| { + var acc: f32 = 0; + for (vec, w.speaker_w[n * cfg.speaker_dim ..][0..cfg.speaker_dim]) |x, m| acc = @mulAdd(f32, m, x, acc); + o.* = acc + w.speaker_b[n]; + } + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + a: *const pth.Archive, + w: *Weights, + + fn device(l: *Loader, bytes: []const u8) !u64 { + var b = try cuda.DeviceBuffer.alloc(l.d, @max(bytes.len, 256)); + errdefer b.free(); + try b.upload(0, bytes); + try l.w.bufs.append(l.gpa, b); + l.w.bytes += bytes.len; + return b.ptr; + } + + fn one(l: *Loader, name: []const u8, shape: []const u64) !u64 { + const raw = try l.a.readRaw(l.gpa, name, .bf16, shape); + defer l.gpa.free(raw); + return l.device(raw); + } + + fn host(l: *Loader, name: []const u8, shape: []const u64) ![]f32 { + const raw = try l.a.readRaw(l.gpa, name, .bf16, shape); + defer l.gpa.free(raw); + const out = try l.gpa.alloc(f32, raw.len / 2); + for (out, 0..) |*o, i| o.* = @bitCast(@as(u32, std.mem.readInt(u16, raw[i * 2 ..][0..2], .little)) << 16); + return out; + } +}; + +fn fmt(buf: []u8, comptime f: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(buf, f, args) catch unreachable; +} + +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, dir: []const u8, c: cfg.Config) !*Weights { + const path = try std.fs.path.join(gpa, &.{ dir, "model.pth" }); + defer gpa.free(path); + var archive = try pth.Archive.open(gpa, io, path); + defer archive.close(); + const w = try gpa.create(Weights); + errdefer gpa.destroy(w); + w.* = undefined; + w.gpa = gpa; + w.bufs = .empty; + w.bytes = 0; + w.speaker_w = &.{}; + w.speaker_b = &.{}; + w.conditions = @splat(&.{}); + errdefer w.deinit(); + var l: Loader = .{ .gpa = gpa, .d = d, .a = &archive, .w = w }; + var nb: [160]u8 = undefined; + + // the eleven embedding tables in one buffer + const text = try archive.tensor("multi_embedder.embedders.10.weight"); + if (text.shape.len != 2 or text.shape[1] != D or text.shape[0] < cfg.text_vocab + 1) return error.ShapeMismatch; + w.text_rows = @intCast(text.shape[0]); + { + const audio = cfg.audio_vocab * D * 2; + const all = try gpa.alloc(u8, cfg.codebooks * audio + w.text_rows * D * 2); + defer gpa.free(all); + for (0..cfg.codebooks) |cb| { + const raw = try archive.readRaw(gpa, fmt(&nb, "multi_embedder.embedders.{d}.weight", .{cb}), .bf16, &.{ cfg.audio_vocab, D }); + defer gpa.free(raw); + @memcpy(all[cb * audio ..][0..audio], raw); + } + const raw = try archive.readRaw(gpa, "multi_embedder.embedders.10.weight", .bf16, &.{ w.text_rows, D }); + defer gpa.free(raw); + @memcpy(all[cfg.codebooks * audio ..], raw); + w.tables = try l.device(all); + } + w.queries = try l.one("block_attnres_queries", &.{ cfg.sources, D }); + w.out_norm = try l.one("out_norm.weight", &.{D}); + w.head = try l.one("multi_output.weight", &.{ cfg.head_rows, D }); + w.speaker_w = try l.host("speaker_projection.weight", &.{ D, cfg.speaker_dim }); + w.speaker_b = try l.host("speaker_projection.bias", &.{D}); + for (&w.conditions, 0..) |*t, i| t.* = try l.host(fmt(&nb, "condition_embeddings.{d}.weight", .{i}), &.{ c.buckets[i] + 1, D }); + + const pre = "layers.{d}."; + for (&w.layers, 0..) |*L, li| { + L.attention_norm = try l.one(fmt(&nb, pre ++ "attention_norm.weight", .{li}), &.{D}); + L.ffn_norm = try l.one(fmt(&nb, pre ++ "ffn_norm.weight", .{li}), &.{D}); + const at = pre ++ "attention."; + if (cfg.usesGdn(li)) { + L.mix = .{ .gdn = .{ + .in_proj = try l.one(fmt(&nb, at ++ "in_proj.weight", .{li}), &.{ cfg.gdn_proj, D }), + .conv = try l.one(fmt(&nb, at ++ "conv.weight", .{li}), &.{ cfg.gdn_conv, 1, cfg.gdn_kernel }), + .out_weight = try l.one(fmt(&nb, at ++ "out_weight", .{li}), &.{cfg.gdn_dim}), + .a_log = try l.one(fmt(&nb, at ++ "A_log", .{li}), &.{cfg.gdn_heads}), + .dt_bias = try l.one(fmt(&nb, at ++ "dt_bias", .{li}), &.{cfg.gdn_heads}), + .wo = try l.one(fmt(&nb, at ++ "wo.weight", .{li}), &.{ D, cfg.gdn_inner }), + } }; + } else { + L.mix = .{ .attn = .{ + .wq = try l.one(fmt(&nb, at ++ "wq.weight", .{li}), &.{ cfg.attn_inner, D }), + .wkv = try l.one(fmt(&nb, at ++ "wkv.weight", .{li}), &.{ 2, cfg.kv_width, D }), + .wo = try l.one(fmt(&nb, at ++ "wo.weight", .{li}), &.{ D, cfg.attn_inner }), + .temp = try l.one(fmt(&nb, at ++ "temp", .{li}), &.{ 1, cfg.heads, 1 }), + .gater = try l.one(fmt(&nb, at ++ "gater.weight", .{li}), &.{ cfg.heads, D }), + } }; + } + const ff = pre ++ "feed_forward."; + if (li == 0) { + L.ffn = .{ .dense = .{ + .w_in = try l.one(fmt(&nb, ff ++ "w_in.weight", .{li}), &.{ 2, cfg.ffn_hidden, D }), + .w_out = try l.one(fmt(&nb, ff ++ "w_out.weight", .{li}), &.{ D, cfg.ffn_hidden }), + } }; + } else { + const bias = try archive.readRaw(gpa, fmt(&nb, ff ++ "router.balancing_biases", .{li}), .f32, &.{cfg.experts}); + defer gpa.free(bias); + L.ffn = .{ .moe = .{ + .gate_up = try l.one(fmt(&nb, ff ++ "experts.gate_up_proj", .{li}), &.{ cfg.experts, 2 * cfg.moe_hidden, cfg.moe_latent }), + .down = try l.one(fmt(&nb, ff ++ "experts.down_proj", .{li}), &.{ cfg.experts, cfg.moe_latent, cfg.moe_hidden }), + .latent_down = try l.one(fmt(&nb, ff ++ "latent_down.weight", .{li}), &.{ cfg.moe_latent, D }), + .latent_up = try l.one(fmt(&nb, ff ++ "latent_up.weight", .{li}), &.{ D, cfg.moe_latent }), + .router = try l.one(fmt(&nb, ff ++ "router.router_linear.weight", .{li}), &.{ cfg.experts, D }), + .eda = try l.one(fmt(&nb, ff ++ "router.rmsnorm_eda.weight", .{li}), &.{D}), + .bias = try l.device(bias), + } }; + } + } + return w; +} diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig new file mode 100644 index 00000000000..6a6f49a8aec --- /dev/null +++ b/zig/src/families/zonos3/generate.zig @@ -0,0 +1,158 @@ +//! zonos3-generate: ZONOS3 Mini's backbone on one CUDA GPU against the PyTorch reference's dumps. +const std = @import("std"); +const z3 = @import("zonos3"); + +const cfg = z3.config; +const W = cfg.frame_width; +const D = cfg.dim; + +const usage = + \\usage: zonos3-generate --model LM_DIR --check DUMP_DIR [--max-rows 64] [--max-ctx 4096] + \\ + \\--check runs DUMP_DIR/input_ids.npy (prompt rows [n, 11]) with DUMP_DIR/input_ids.cond.json through the backbone + \\and compares every sublayer with the reference's .npy captures (tools/dump_golden.py lm of Zyphra/ZONOS3-Mini). + \\The last stderr line is "RESULT zonos3 check PASS|FAIL ...". + \\ +; + +const Check = struct { + gpa: std.mem.Allocator, + io: std.Io, + e: *z3.Engine, + dir: []const u8, + n: usize = 0, + fails: usize = 0, + missing: usize = 0, + worst: f64 = 1.0, + worst_rel: f64 = 0, + + fn probe(ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void { + const c: *Check = @ptrCast(@alignCast(ctx)); + var nb: [96]u8 = undefined; + const path = try std.fs.path.join(c.gpa, &.{ c.dir, try std.fmt.bufPrint(&nb, "{s}.npy", .{name}) }); + defer c.gpa.free(path); + const bytes = std.Io.Dir.cwd().readFileAlloc(c.io, path, c.gpa, .limited(1 << 30)) catch { + c.missing += 1; + std.debug.print(" {s:<20} (no reference tensor)\n", .{name}); + return; + }; + defer c.gpa.free(bytes); + const arr = try z3.npy.parse(bytes); + if (arr.numel() != rows * width) return error.ReferenceShape; + const ref = try arr.floats(c.gpa); + defer c.gpa.free(ref); + const mine = try c.gpa.alloc(f32, rows * width); + defer c.gpa.free(mine); + try c.e.download(ptr, std.mem.sliceAsBytes(mine)); + var worst_row: f64 = 1; + var at: usize = 0; + var max_d: f64 = 0; + var max_ref: f64 = 0; + for (0..rows) |r| { + var d: f64 = 0; + var a2: f64 = 0; + var b2: f64 = 0; + for (mine[r * width ..][0..width], ref[r * width ..][0..width]) |x, y| { + d += @as(f64, x) * y; + a2 += @as(f64, x) * x; + b2 += @as(f64, y) * y; + max_d = @max(max_d, @abs(@as(f64, x) - y)); + max_ref = @max(max_ref, @abs(@as(f64, y))); + } + const cos: f64 = if (a2 > 0 and b2 > 0) d / @sqrt(a2 * b2) else if (a2 == b2) 1.0 else 0.0; + if (cos < worst_row) { + worst_row = cos; + at = r; + } + } + const rel = if (max_ref > 0) max_d / max_ref else max_d; + const ok = worst_row >= 0.9999; + c.n += 1; + c.fails += @intFromBool(!ok); + c.worst = @min(c.worst, worst_row); + c.worst_rel = @max(c.worst_rel, rel); + std.debug.print(" {s:<20} rows {d:>4} worst-row cos {d:.7} (row {d}) max|d| {e:.3} of {e:.3} {s}\n", .{ name, rows, worst_row, at, max_d, max_ref, if (ok) "ok" else "LOW" }); + } +}; + +/// The dump's prompt: rows and the rows a speaker or condition vector replaces. +fn loadPrompt(gpa: std.mem.Allocator, io: std.Io, e: *z3.Engine, dir: []const u8, rows: *[][W]i32, replaced: *std.ArrayList(z3.Replace)) !void { + const ids_path = try std.fs.path.join(gpa, &.{ dir, "input_ids.npy" }); + defer gpa.free(ids_path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, ids_path, gpa, .limited(1 << 28)); + defer gpa.free(bytes); + const arr = try z3.npy.parse(bytes); + if (arr.rank != 2 or arr.shape[1] != W) return error.BadPromptRows; + const flat = try arr.ints(gpa); + defer gpa.free(flat); + rows.* = try gpa.alloc([W]i32, arr.shape[0]); + for (rows.*, 0..) |*r, i| r.* = flat[i * W ..][0..W].*; + + const cond_path = try std.fs.path.join(gpa, &.{ dir, "input_ids.cond.json" }); + defer gpa.free(cond_path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, cond_path, gpa, .limited(1 << 22)); + defer gpa.free(text); + var tree = try std.json.parseFromSlice(std.json.Value, gpa, text, .{}); + defer tree.deinit(); + const o = tree.value.object; + const speaker_row = o.get("speaker_row").?.integer; + if (speaker_row >= 0) { + const v = o.get("speaker_embedding").?.array.items; + if (v.len != cfg.speaker_dim) return error.BadSpeakerEmbedding; + var vec: [cfg.speaker_dim]f32 = undefined; + for (&vec, v) |*x, j| x.* = switch (j) { + .float => |f| @floatCast(f), + .integer => |n| @floatFromInt(n), + else => return error.BadSpeakerEmbedding, + }; + var r: z3.Replace = .{ .row = @intCast(speaker_row), .vec = undefined }; + e.w.speakerRow(&vec, &r.vec); + try replaced.append(gpa, r); + } + const first: usize = @intCast(o.get("condition_row").?.integer); + for (o.get("condition_buckets").?.array.items, 0..) |b, i| { + const bucket: usize = @intCast(b.integer); + if (i >= cfg.conditions or bucket > e.c.buckets[i]) return error.BadConditionBucket; + var r: z3.Replace = .{ .row = first + i, .vec = undefined }; + @memcpy(&r.vec, e.w.conditions[i][bucket * D ..][0..D]); + try replaced.append(gpa, r); + } +} + +pub fn main(init: std.process.Init) !u8 { + const arena = init.arena.allocator(); + const gpa = std.heap.c_allocator; + const io = init.io; + const argv = try init.minimal.args.toSlice(arena); + var model: []const u8 = ""; + var check: ?[]const u8 = null; + var opts: z3.Options = .{}; + var i: usize = 1; + while (i + 1 < argv.len) : (i += 2) { + const k = argv[i]; + const v = argv[i + 1]; + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); + return 2; + } + } + const dir = check orelse { + std.debug.print("{s}", .{usage}); + return 2; + }; + if (model.len == 0 or i != argv.len) { + std.debug.print("{s}", .{usage}); + return 2; + } + const e = try z3.Engine.create(gpa, io, model, opts); + defer e.destroy(); + var rows: [][W]i32 = &.{}; + var replaced: std.ArrayList(z3.Replace) = .empty; + try loadPrompt(gpa, io, e, dir, &rows, &replaced); + var c: Check = .{ .gpa = gpa, .io = io, .e = e, .dir = dir }; + std.debug.print("zonos3 check: {d} prompt rows, {d} replaced, {d} MiB of weights\n", .{ rows.len, replaced.items.len, e.w.bytes >> 20 }); + try e.run(rows, replaced.items, .{ .ctx = &c, .f = Check.probe }); + const pass = c.fails == 0 and c.n > 0; + std.debug.print("RESULT zonos3 check {s} probes={d} low={d} missing={d} worst_row_cos={d:.7} worst_rel_diff={e:.3}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, c.worst_rel }); + return if (pass) 0 else 1; +} diff --git a/zig/src/families/zonos3/npy.zig b/zig/src/families/zonos3/npy.zig new file mode 100644 index 00000000000..04cea5abd7f --- /dev/null +++ b/zig/src/families/zonos3/npy.zig @@ -0,0 +1,88 @@ +//! NumPy .npy arrays (versions 1 to 3, C order, little-endian f4 / i4 / i8) read for the reference checks. +const std = @import("std"); + +pub const Array = struct { + shape: [4]usize = @splat(1), + rank: usize = 0, + kind: enum { f32, i32, i64 }, + data: []const u8, + + pub fn numel(a: Array) usize { + var n: usize = 1; + for (a.shape[0..a.rank]) |d| n *= d; + return n; + } + + /// The elements as f32 (caller frees). + pub fn floats(a: Array, gpa: std.mem.Allocator) ![]f32 { + const out = try gpa.alloc(f32, a.numel()); + for (out, 0..) |*o, i| o.* = switch (a.kind) { + .f32 => @bitCast(std.mem.readInt(u32, a.data[i * 4 ..][0..4], .little)), + .i32 => @floatFromInt(std.mem.readInt(i32, a.data[i * 4 ..][0..4], .little)), + .i64 => @floatFromInt(std.mem.readInt(i64, a.data[i * 8 ..][0..8], .little)), + }; + return out; + } + + /// The elements as i32 (caller frees); float values must be whole numbers. + pub fn ints(a: Array, gpa: std.mem.Allocator) ![]i32 { + const out = try gpa.alloc(i32, a.numel()); + errdefer gpa.free(out); + for (out, 0..) |*o, i| o.* = switch (a.kind) { + .f32 => blk: { + const f: f32 = @bitCast(std.mem.readInt(u32, a.data[i * 4 ..][0..4], .little)); + if (f != @trunc(f) or @abs(f) > 1e9) return error.NotAnInteger; + break :blk @intFromFloat(f); + }, + .i32 => std.mem.readInt(i32, a.data[i * 4 ..][0..4], .little), + .i64 => std.math.cast(i32, std.mem.readInt(i64, a.data[i * 8 ..][0..8], .little)) orelse return error.NotAnInteger, + }; + return out; + } +}; + +pub fn parse(bytes: []const u8) !Array { + if (bytes.len < 12 or !std.mem.eql(u8, bytes[0..6], "\x93NUMPY")) return error.NotNpy; + const long = bytes[6] >= 2; + const hlen: usize = if (long) std.mem.readInt(u32, bytes[8..12], .little) else std.mem.readInt(u16, bytes[8..10], .little); + const start: usize = if (long) 12 else 10; + if (bytes.len < start + hlen) return error.NotNpy; + const head = bytes[start..][0..hlen]; + if (std.mem.indexOf(u8, head, "'fortran_order': False") == null) return error.UnsupportedNpy; + const descr_at = (std.mem.indexOf(u8, head, "'descr': '") orelse return error.NotNpy) + "'descr': '".len; + const descr = head[descr_at..][0..3]; + var a: Array = .{ .kind = undefined, .data = bytes[start + hlen ..] }; + var width: usize = 4; + if (std.mem.eql(u8, descr, " Date: Mon, 16 Nov 2026 22:18:12 +0000 Subject: [PATCH 307/361] zonos3: the frame sampler and the generation loop on the host, checked against the reference's greedy frames --- zig/src/families/zonos3/generate.zig | 40 +++++- zig/src/families/zonos3/generation.zig | 94 ++++++++++++++ zig/src/families/zonos3/sampler.zig | 166 +++++++++++++++++++++++++ zig/src/families/zonos3/zonos3.zig | 5 + 4 files changed, 301 insertions(+), 4 deletions(-) create mode 100644 zig/src/families/zonos3/generation.zig create mode 100644 zig/src/families/zonos3/sampler.zig diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index 6a6f49a8aec..5859cb9bff2 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -8,10 +8,13 @@ const D = cfg.dim; const usage = \\usage: zonos3-generate --model LM_DIR --check DUMP_DIR [--max-rows 64] [--max-ctx 4096] + \\ zonos3-generate --model LM_DIR --frames-check GEN_DIR [--max-frames 2000] \\ \\--check runs DUMP_DIR/input_ids.npy (prompt rows [n, 11]) with DUMP_DIR/input_ids.cond.json through the backbone \\and compares every sublayer with the reference's .npy captures (tools/dump_golden.py lm of Zyphra/ZONOS3-Mini). - \\The last stderr line is "RESULT zonos3 check PASS|FAIL ...". + \\--frames-check generates greedily (temperature 0, the other sampling defaults) after GEN_DIR's prompt and compares + \\the frames with GEN_DIR/rows.npy, the reference's generation of the same request. + \\The last stderr line is "RESULT zonos3 check PASS|FAIL ..." or "RESULT zonos3 frames PASS|FAIL ...". \\ ; @@ -119,6 +122,32 @@ fn loadPrompt(gpa: std.mem.Allocator, io: std.Io, e: *z3.Engine, dir: []const u8 } } +fn nowNs(io: std.Io) i128 { + return @intCast(std.Io.Clock.awake.now(io).toNanoseconds()); +} + +fn framesCheck(gpa: std.mem.Allocator, io: std.Io, e: *z3.Engine, dir: []const u8, prompt: []const [W]i32, replaced: []const z3.Replace, max_frames: usize) !u8 { + const path = try std.fs.path.join(gpa, &.{ dir, "rows.npy" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 28)); + defer gpa.free(bytes); + const arr = try z3.npy.parse(bytes); + if (arr.rank != 2 or arr.shape[1] != W) return error.BadReferenceRows; + const want = try arr.ints(gpa); + defer gpa.free(want); + const t0 = nowNs(io); + const r = try z3.generation.generate(gpa, e, prompt, replaced, .{ .temperature = 0 }, max_frames); + defer gpa.free(r.rows); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + const n = @min(r.rows.len, arr.shape[0]); + var same: usize = 0; + while (same < n and std.mem.eql(i32, &r.rows[same], want[same * W ..][0..W])) same += 1; + const pass = same == arr.shape[0] and r.rows.len == arr.shape[0]; + if (!pass and same < n) std.debug.print("first difference at frame {d}: mine {any} reference {any}\n", .{ same, r.rows[same], want[same * W ..][0..W] }); + std.debug.print("RESULT zonos3 frames {s} identical={d} mine={d} reference={d} eos_frame={?d} prompt_rows={d} seconds={d:.3} frames_per_s={d:.1}\n", .{ if (pass) "PASS" else "FAIL", same, r.rows.len, arr.shape[0], r.eos_frame, prompt.len, seconds, @as(f64, @floatFromInt(r.rows.len)) / seconds }); + return if (pass) 0 else 1; +} + pub fn main(init: std.process.Init) !u8 { const arena = init.arena.allocator(); const gpa = std.heap.c_allocator; @@ -126,21 +155,23 @@ pub fn main(init: std.process.Init) !u8 { const argv = try init.minimal.args.toSlice(arena); var model: []const u8 = ""; var check: ?[]const u8 = null; + var frames_check: ?[]const u8 = null; + var max_frames: usize = 2000; var opts: z3.Options = .{}; var i: usize = 1; while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } } - const dir = check orelse { + const dir = check orelse frames_check orelse { std.debug.print("{s}", .{usage}); return 2; }; - if (model.len == 0 or i != argv.len) { + if (model.len == 0 or i != argv.len or (check != null and frames_check != null)) { std.debug.print("{s}", .{usage}); return 2; } @@ -149,6 +180,7 @@ pub fn main(init: std.process.Init) !u8 { var rows: [][W]i32 = &.{}; var replaced: std.ArrayList(z3.Replace) = .empty; try loadPrompt(gpa, io, e, dir, &rows, &replaced); + if (frames_check != null) return framesCheck(gpa, io, e, dir, rows, replaced.items, max_frames); var c: Check = .{ .gpa = gpa, .io = io, .e = e, .dir = dir }; std.debug.print("zonos3 check: {d} prompt rows, {d} replaced, {d} MiB of weights\n", .{ rows.len, replaced.items.len, e.w.bytes >> 20 }); try e.run(rows, replaced.items, .{ .ctx = &c, .f = Check.probe }); diff --git a/zig/src/families/zonos3/generation.zig b/zig/src/families/zonos3/generation.zig new file mode 100644 index 00000000000..10d1085e43b --- /dev/null +++ b/zig/src/families/zonos3/generation.zig @@ -0,0 +1,94 @@ +//! One request's frames: the prompt, then a frame a step until the end-of-audio countdown or the frame budget. +const std = @import("std"); +const cfg = @import("config.zig"); +const sampler = @import("sampler.zig"); + +const C = cfg.codebooks; +const W = cfg.frame_width; + +pub const Result = struct { + /// Generated rows [n][11] (codes, then the text placeholder), the finishing row included; caller frees. + rows: [][W]i32, + /// The first end-of-audio frame among the generated rows, aligned across the delayed codebooks. + eos_frame: ?usize, +}; + +/// Codebooks whose delayed stream has not started are padding, unless the prompt already ends in audio. +fn coldStart(row: *[C]i32, generated: usize, has_audio_prefix: bool) void { + if (has_audio_prefix or generated >= C - 1) return; + for (row[generated + 1 ..]) |*code| code.* = cfg.audio_pad_id; +} + +/// `engine` has run(rows, replaced, probe) and lastLogits(out): the backbone, or a stand-in under test. +pub fn generate(gpa: std.mem.Allocator, engine: anytype, prompt: []const [W]i32, replaced: anytype, sampling: sampler.Sampling, max_frames: usize) !Result { + if (prompt.len == 0 or max_frames == 0) return error.NoRows; + const logits = try gpa.create([C][cfg.audio_vocab]f32); + defer gpa.destroy(logits); + var rows: std.ArrayList([W]i32) = .empty; + errdefer rows.deinit(gpa); + var codes: std.ArrayList([C]i32) = .empty; + defer codes.deinit(gpa); + var has_audio_prefix = false; + for (prompt[prompt.len - 1][0..C]) |code| has_audio_prefix = has_audio_prefix or code != cfg.audio_pad_id; + try engine.run(prompt, replaced, null); + var eos_frame: ?usize = null; + var countdown: usize = 0; + while (true) { + try engine.lastLogits(@ptrCast(logits)); + const generated = rows.items.len; + var row = sampler.sample(logits, codes.items, generated, cfg.eoa_id, sampling); + coldStart(&row, generated, has_audio_prefix); + try codes.append(gpa, row); + var full: [W]i32 = undefined; + full[0..C].* = row; + full[C] = cfg.text_vocab; + try rows.append(gpa, full); + var finished = rows.items.len >= max_frames; + if (eos_frame == null) { + var last: ?usize = null; + for (row, 0..) |code, cb| if (code == cfg.eoa_id) { + last = cb; + }; + if (last) |cb| { + eos_frame = generated -| cb; + countdown = C + 1; + } + } + if (countdown > 0) { + countdown -= 1; + if (countdown == 0) finished = true; + } + if (finished) break; + try engine.run(rows.items[generated..], &.{}, null); + } + return .{ .rows = try rows.toOwnedSlice(gpa), .eos_frame = eos_frame }; +} + +test "generation: an end-of-audio code in codebook 0 ends the request eleven rows later" { + const t = std.testing; + const Fake = struct { + calls: usize = 0, + pub fn run(f: *@This(), rows: []const [W]i32, _: anytype, _: anytype) !void { + f.calls += rows.len; + } + pub fn lastLogits(f: *@This(), out: *[cfg.head_rows]f32) !void { + @memset(out, 0); + // row 2 on: codebook 0 says end of audio; the others say code 7 + for (0..C) |cb| { + const best: usize = if (cb == 0 and f.calls >= 3) cfg.eoa_id else 7; + out[cb * cfg.audio_vocab + best] = 5; + } + } + }; + var fake: Fake = .{}; + var prompt = [_][W]i32{@splat(cfg.audio_pad_id)}; + prompt[0][C] = 2; + const r = try generate(t.allocator, &fake, &prompt, @as([]const u8, &.{}), .{ .temperature = 0, .repetition_penalty = 1 }, 100); + defer t.allocator.free(r.rows); + try t.expectEqual(@as(?usize, 2), r.eos_frame); + try t.expectEqual(@as(usize, 2 + C + 1), r.rows.len); + // the cold start pads the codebooks whose delayed stream has not begun + try t.expectEqual(@as(i32, 7), r.rows[0][0]); + try t.expectEqual(@as(i32, cfg.audio_pad_id), r.rows[0][1]); + try t.expectEqual(@as(i32, 7), r.rows[1][1]); +} diff --git a/zig/src/families/zonos3/sampler.zig b/zig/src/families/zonos3/sampler.zig new file mode 100644 index 00000000000..aef729ed58f --- /dev/null +++ b/zig/src/families/zonos3/sampler.zig @@ -0,0 +1,166 @@ +//! ZONOS3's frame sampler on the host, the reference's sample_tts for one request: specials masked, a repetition +//! penalty over each codebook's recent codes, temperature, top-k, top-p and min-p, then one draw a codebook. +const std = @import("std"); +const cfg = @import("config.zig"); + +const V = cfg.audio_vocab; +const C = cfg.codebooks; + +pub const Sampling = struct { + temperature: f32 = 0.75, + top_k: u32 = 80, + top_p: f32 = 0.69, + min_p: f32 = 0.0, + repetition_window: u32 = 96, + repetition_penalty: f32 = 2.4, + repetition_codebooks: i32 = 6, + seed: u64 = 0, + + /// The settings as every sampler applies them: top_k < 1 is the whole codebook, a negative count every codebook. + pub fn clamped(s: Sampling) Sampling { + var c = s; + c.temperature = @max(s.temperature, 1e-6); + c.top_k = if (s.top_k >= 1) s.top_k else cfg.codebook_size; + c.top_p = @min(@max(s.top_p, 0.0), 1.0); + c.min_p = @max(s.min_p, 0.0); + c.repetition_penalty = @max(s.repetition_penalty, 1.0); + c.repetition_codebooks = if (s.repetition_codebooks < 0) C else @min(s.repetition_codebooks, C); + return c; + } +}; + +/// A draw in [0, 1) that depends only on the request's seed, the frame and the codebook. +pub fn uniform(seed: u64, frame: u64, codebook: u64) f32 { + var z = seed +% 0x9E3779B97F4A7C15 *% (frame *% C + codebook + 1); + z = (z ^ (z >> 30)) *% 0xBF58476D1CE4E5B9; + z = (z ^ (z >> 27)) *% 0x94D049BB133111EB; + z ^= z >> 31; + return @as(f32, @floatFromInt(z >> 40)) * (1.0 / 16777216.0); +} + +fn argmax(x: []const f32) usize { + var best: usize = 0; + for (x, 0..) |v, i| if (v > x[best]) { + best = i; + }; + return best; +} + +/// Frame `frame`'s codes from its logits [codebooks][audio_vocab] (overwritten). `recent` holds the generated rows so +/// far, oldest first; `stop` is the one special id a codebook may draw. +pub fn sample(logits: *[C][V]f32, recent: []const [C]i32, frame: u64, stop: i32, sampling: Sampling) [C]i32 { + const s = sampling.clamped(); + const window: usize = if (s.repetition_window > 0 and s.repetition_penalty > 1.0 and s.repetition_codebooks > 0) @min(s.repetition_window, recent.len) else 0; + var out: [C]i32 = undefined; + var order: [V]u16 = undefined; + for (logits, 0..) |*l, cb| { + for (l[cfg.codebook_size..], cfg.codebook_size..) |*v, id| { + if (id == cfg.audio_pad_id or id != stop) v.* = -std.math.inf(f32); + } + if (cb < s.repetition_codebooks) { + var seen: [cfg.codebook_size]bool = @splat(false); + for (recent[recent.len - window ..]) |row| { + const code = row[cb]; + if (code < 0 or code >= cfg.codebook_size or seen[@intCast(code)]) continue; + seen[@intCast(code)] = true; + const v = &l[@intCast(code)]; + v.* = if (v.* > 0) v.* / s.repetition_penalty else v.* * s.repetition_penalty; + } + } + for (l) |*v| v.* /= s.temperature; + const greedy = argmax(l); + for (&order, 0..) |*o, i| o.* = @intCast(i); + const Desc = struct { + fn lt(x: *const [V]f32, a: u16, b: u16) bool { + return x[a] > x[b] or (x[a] == x[b] and a < b); + } + }; + std.mem.sort(u16, &order, l, Desc.lt); + if (s.top_k < V) { + const kth = l[order[s.top_k - 1]]; + for (l) |*v| if (v.* < kth) { + v.* = -std.math.inf(f32); + }; + } + // softmax, in descending order so the nucleus cut reads the running sum + const top = l[order[0]]; + var total: f32 = 0; + for (l) |*v| { + v.* = @exp(v.* - top); + total += v.*; + } + for (l) |*v| v.* /= total; + if (s.top_p > 0 and s.top_p < 1) { + var before: f32 = 0; + var kept: f32 = 0; + for (order) |id| { + const p = l[id]; + if (before > s.top_p) l[id] = 0 else kept += p; + before += p; + } + const norm = @max(kept, 1e-8); + for (l) |*v| v.* /= norm; + } + if (s.min_p > 0) { + const floor = s.min_p * l[order[0]]; + var kept: f32 = 0; + for (l) |*v| { + if (v.* < floor) v.* = 0; + kept += v.*; + } + const norm = @max(kept, 1e-8); + for (l) |*v| v.* /= norm; + } + var sum: f32 = 0; + for (l) |v| sum += v; + if (!(sum > 0)) { + out[cb] = @intCast(greedy); + continue; + } + const target = uniform(s.seed, frame, cb) * sum; + var run: f32 = 0; + var pick: usize = greedy; + for (l, 0..) |p, id| { + if (p <= 0) continue; + run += p; + pick = id; + if (run > target) break; + } + out[cb] = @intCast(pick); + } + return out; +} + +test "sampler: specials other than the stop id are never drawn, and a zero temperature takes the best code" { + const t = std.testing; + const logits = try t.allocator.create([C][V]f32); + defer t.allocator.destroy(logits); + for (logits, 0..) |*l, cb| { + for (l, 0..) |*v, i| v.* = @as(f32, @floatFromInt((i * 7 + cb) % 97)) * 0.01; + l[cfg.audio_pad_id] = 50; + l[100 + cb] = 9; + } + const got = sample(logits, &.{}, 0, cfg.eoa_id, .{ .temperature = 0 }); + for (got, 0..) |code, cb| try t.expectEqual(@as(i32, @intCast(100 + cb)), code); +} + +test "sampler: a repeated code is penalised in the first codebooks only" { + const t = std.testing; + const logits = try t.allocator.create([C][V]f32); + defer t.allocator.destroy(logits); + for (logits) |*l| { + @memset(l, 0); + l[5] = 2.0; + l[6] = 1.5; + } + const recent = [_][C]i32{@splat(5)}; + const got = sample(logits, &recent, 1, cfg.eoa_id, .{ .temperature = 0 }); + for (got, 0..) |code, cb| try t.expectEqual(@as(i32, if (cb < 6) 6 else 5), code); +} + +test "sampler: the same seed, frame and codebook give the same draw" { + const t = std.testing; + try t.expectEqual(uniform(42, 3, 1), uniform(42, 3, 1)); + try t.expect(uniform(42, 3, 1) != uniform(42, 3, 2)); + try t.expect(uniform(42, 3, 1) < 1.0 and uniform(42, 3, 1) >= 0.0); +} diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index 01d70ea7335..c05c44d410a 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -1,6 +1,8 @@ //! Zyphra ZONOS3 Mini text to speech (GDN and global attention backbone, Full AttnRes, latent MoE) on one CUDA GPU. pub const config = @import("config.zig"); pub const npy = @import("npy.zig"); +pub const sampler = @import("sampler.zig"); +pub const generation = @import("generation.zig"); pub const weights = @import("cuda/weights.zig"); pub const kernels = @import("cuda/kernels.zig"); pub const engine = @import("cuda/engine.zig"); @@ -9,8 +11,11 @@ pub const Engine = engine.Engine; pub const Options = engine.Options; pub const Probe = engine.Probe; pub const Replace = engine.Replace; +pub const Sampling = sampler.Sampling; test { _ = config; _ = npy; + _ = sampler; + _ = generation; } From 57fd2ef15cc65e62aa3b4161057f4171588de4a3 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:26:29 +0000 Subject: [PATCH 308/361] zonos3: the codec decoder on CUDA in fp32, checked against the reference's captures and audio Nested torch checkpoints (generator.pt, the decoder heads) read without Python; frames decode in any chunks to the same samples as one pass. --- zig/build/cuda_kernels.zig | 1 + zig/build/zonos3.zig | 2 +- zig/kernels/cuda/zonos3_codec.cu | 244 ++++++++++++++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/zonos3/cuda/codec.zig | 264 ++++++++++++++++++ .../families/zonos3/cuda/codec_kernels.zig | 188 +++++++++++++ .../families/zonos3/cuda/codec_weights.zig | 243 ++++++++++++++++ zig/src/families/zonos3/generate.zig | 97 ++++++- zig/src/families/zonos3/zonos3.zig | 4 + 9 files changed, 1038 insertions(+), 6 deletions(-) create mode 100644 zig/kernels/cuda/zonos3_codec.cu create mode 100644 zig/src/families/zonos3/cuda/codec.zig create mode 100644 zig/src/families/zonos3/cuda/codec_kernels.zig create mode 100644 zig/src/families/zonos3/cuda/codec_weights.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index ea696953e37..4ad41f2d080 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -199,6 +199,7 @@ pub const kernels = [_]Kernel{ .{ .name = "drama3_fp8", .flags = &.{"-O3"} }, .{ .name = "drama3_codec", .flags = &.{"-O3"} }, .{ .name = "zonos3", .flags = glue }, // ours: ZONOS3 Mini's fp32 row kernels over bf16 weights + .{ .name = "zonos3_codec", .flags = glue }, // ours: ZONOS3's codec decoder in fp32 }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. diff --git a/zig/build/zonos3.zig b/zig/build/zonos3.zig index 4f3c9067c95..e6c7c746bd4 100644 --- a/zig/build/zonos3.zig +++ b/zig/build/zonos3.zig @@ -8,7 +8,7 @@ pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui } pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) void { - const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "zonos3", .module = module(b, target, optimize, cuda, core) } } }); + const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "cuda", .module = cuda }, .{ .name = "zonos3", .module = module(b, target, optimize, cuda, core) } } }); const exe = b.addExecutable(.{ .name = "zonos3-generate", .root_module = tool }); b.step("zonos3-generate", "ZONOS3 Mini's backbone on CUDA against the reference's dumps").dependOn(&b.addInstallArtifact(exe, .{}).step); } diff --git a/zig/kernels/cuda/zonos3_codec.cu b/zig/kernels/cuda/zonos3_codec.cu new file mode 100644 index 00000000000..b1c63c12297 --- /dev/null +++ b/zig/kernels/cuda/zonos3_codec.cu @@ -0,0 +1,244 @@ +// ours: ZONOS3's codec decoder (ZAC) on CUDA in fp32: causal transformer stages, ConvNeXt blocks and the +// multi-resolution iSTFT tail. A row or sample depends only on its position, never on how a stream was chunked. +#include +#include +#include "common/reduce.cuh" + +namespace { + +using tf_common::block_max_tree; +using tf_common::block_sum_tree; +using tf_common::warp_sum; + +} // namespace + +// y[r, n] = sum_k W[n, k] x[r, k] (+ bias[n]): fp32 W [N, K], a warp an output, x staged in K * 4 bytes of shared. +extern "C" __global__ void __launch_bounds__(256) zc_linear(const float* __restrict__ W, const float* __restrict__ x, + int x_stride, int K, int N, float* __restrict__ y, + int y_stride, const float* __restrict__ bias) { + extern __shared__ float xs[]; + const int r = blockIdx.y; + const float* xr = x + (size_t)r * x_stride; + for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = xr[i]; + __syncthreads(); + const int lane = threadIdx.x & 31; + const int n = blockIdx.x * 8 + (threadIdx.x >> 5); + const float* wr = W + (size_t)min(n, N - 1) * K; + float acc = 0.f; + for (int k = lane; k < K; k += 32) acc = fmaf(wr[k], xs[k], acc); + acc = warp_sum(acc); + if (lane == 0 && n < N) y[(size_t)r * y_stride + n] = bias ? acc + bias[n] : acc; +} + +// LayerNorm over D: y = (x - mean) / sqrt(var + eps) * w + b; a block a row. +extern "C" __global__ void __launch_bounds__(256) zc_layernorm(const float* __restrict__ x, const float* __restrict__ w, + const float* __restrict__ b, float* __restrict__ y, + int D, float eps) { + __shared__ float part[32]; + const float* xr = x + (size_t)blockIdx.x * D; + float* yr = y + (size_t)blockIdx.x * D; + float s = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) s += xr[i]; + const float mean = block_sum_tree(s, part, blockDim.x >> 5) / D; + float v = 0.f; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float d = xr[i] - mean; + v = fmaf(d, d, v); + } + const float inv = 1.f / sqrtf(block_sum_tree(v, part, blockDim.x >> 5) / D + eps); + for (int i = threadIdx.x; i < D; i += blockDim.x) yr[i] = (xr[i] - mean) * inv * w[i] + b[i]; +} + +// Rows of [q | k | v] (each D = heads * 64) at positions pos0 + row: q and k rotate in adjacent pairs, in place; +// the rotated k and v go to the caches' row pos0 + row. A block a (row, head), a thread a pair. +extern "C" __global__ void __launch_bounds__(32) zc_attn_prep(float* __restrict__ qkv, int D, int pos0, + float* __restrict__ kc, float* __restrict__ vc) { + const int t = blockIdx.x, h = blockIdx.y, m = threadIdx.x; + const float freq = expf((float)m * (-9.210340371976184f * 2.f / 64.f)); + const float phase = (float)(pos0 + t) * freq; + const float c = cosf(phase), s = sinf(phase); + float* q = qkv + (size_t)t * 3 * D + h * 64 + 2 * m; + const float qr = q[0], qi = q[1]; + q[0] = qr * c - qi * s; + q[1] = qr * s + qi * c; + const float kr = q[D], ki = q[D + 1]; + const size_t at = (size_t)(pos0 + t) * D + h * 64 + 2 * m; + kc[at] = kr * c - ki * s; + kc[at + 1] = kr * s + ki * c; + vc[at] = q[2 * D]; + vc[at + 1] = q[2 * D + 1]; +} + +// Causal local attention of (row, head) at position p = pos0 + row over cache rows max(0, p - ctx + 1) .. p. +// Keys go to threads by offset from the window's first row, and the block folds in a fixed order. +extern "C" __global__ void __launch_bounds__(128) zc_attention(const float* __restrict__ qkv, int D, + const float* __restrict__ kc, + const float* __restrict__ vc, int pos0, int ctx, + float* __restrict__ out) { + __shared__ float part[32]; + __shared__ float acc[128][65]; + const int t = blockIdx.x, h = blockIdx.y; + const int p = pos0 + t; + const int lo = max(0, p - ctx + 1); + float qv[64]; + const float* qr = qkv + (size_t)t * 3 * D + h * 64; +#pragma unroll + for (int i = 0; i < 64; ++i) qv[i] = qr[i]; + float m = -INFINITY; + for (int j = lo + threadIdx.x; j <= p; j += blockDim.x) { + const float* k = kc + (size_t)j * D + h * 64; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 64; ++i) d = fmaf(qv[i], k[i], d); + m = fmaxf(m, d * 0.125f); + } + m = block_max_tree(m, part, 4); + float a[65]; +#pragma unroll + for (int i = 0; i < 65; ++i) a[i] = 0.f; + for (int j = lo + threadIdx.x; j <= p; j += blockDim.x) { + const float* k = kc + (size_t)j * D + h * 64; + const float* v = vc + (size_t)j * D + h * 64; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 64; ++i) d = fmaf(qv[i], k[i], d); + const float e = expf(d * 0.125f - m); + a[64] += e; +#pragma unroll + for (int i = 0; i < 64; ++i) a[i] = fmaf(e, v[i], a[i]); + } +#pragma unroll + for (int i = 0; i < 65; ++i) acc[threadIdx.x][i] = a[i]; + __syncthreads(); + if (threadIdx.x < 65) { + float s = 0.f; + for (int w = 0; w < 128; ++w) s += acc[w][threadIdx.x]; + acc[0][threadIdx.x] = s; + } + __syncthreads(); + if (threadIdx.x < 64) out[(size_t)t * D + h * 64 + threadIdx.x] = acc[0][threadIdx.x] / acc[0][64]; +} + +// x[r, i] += scale[i] * y[r, i] (scale null: a plain residual add). +extern "C" __global__ void zc_add_scaled(float* __restrict__ x, const float* __restrict__ y, + const float* __restrict__ scale, int D) { + const size_t r = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < D) x[r * D + i] += scale ? scale[i] * y[r * D + i] : y[r * D + i]; +} + +// GELU (erf) in place. +extern "C" __global__ void zc_gelu(float* __restrict__ x, long long n) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = 0.5f * x[i] * (1.f + erff(x[i] * 0.70710678118654752f)); +} + +// Patch up by 2: in [T][C] to out [2T][C / 2], out[2t + j][c] = in[t][2c + j]. +extern "C" __global__ void zc_patch_up(const float* __restrict__ in, float* __restrict__ out, int C) { + const size_t r = blockIdx.y; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c < C / 2) out[r * (C / 2) + c] = in[(r >> 1) * C + 2 * c + (r & 1)]; +} + +// Causal depthwise conv (kernel 7) + bias over T rows of C channels; hist [C][6] holds the 6 inputs before them. +extern "C" __global__ void zc_dwconv(const float* __restrict__ x, int T, const float* __restrict__ w, + const float* __restrict__ b, float* __restrict__ hist, float* __restrict__ out, + int C) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float s[7]; +#pragma unroll + for (int j = 0; j < 6; ++j) s[j] = hist[c * 6 + j]; + for (int t = 0; t < T; ++t) { + s[6] = x[(size_t)t * C + c]; + float acc = b[c]; +#pragma unroll + for (int j = 0; j < 7; ++j) acc = fmaf(w[c * 7 + j], s[j], acc); + out[(size_t)t * C + c] = acc; +#pragma unroll + for (int j = 0; j < 6; ++j) s[j] = s[j + 1]; + } +#pragma unroll + for (int j = 0; j < 6; ++j) hist[c * 6 + j] = s[j]; +} + +// out[t] = table[codes[t][col]]: codes int32 [T][10], table [4096][D]. +extern "C" __global__ void zc_gather(const int* __restrict__ codes, int col, const float* __restrict__ table, + float* __restrict__ out, int D) { + const size_t t = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < D) out[t * D + i] = table[(size_t)codes[t * 10 + col] * D + i]; +} + +// z[t] += tables[i][codes[t][1 + i]] for the nine residual codebooks in order: tables [9][4096][D]. +extern "C" __global__ void zc_latent(const int* __restrict__ codes, const float* __restrict__ tables, + float* __restrict__ z, int D) { + const size_t t = blockIdx.y; + const int d = blockIdx.x * blockDim.x + threadIdx.x; + if (d >= D) return; + float a = z[t * D + d]; +#pragma unroll + for (int i = 0; i < 9; ++i) a += tables[((size_t)i * 4096 + codes[t * 10 + 1 + i]) * D + d]; + z[t * D + d] = a; +} + +// The head's [log-magnitude | phase] rows (each half bins wide) to [real | imaginary] in place, magnitude at most 100. +extern "C" __global__ void zc_spec(float* __restrict__ y, int half) { + float* r = y + (size_t)blockIdx.y * 2 * half; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= half) return; + const float mag = expf(fminf(r[i], 4.605170185988092f)); + const float ph = r[half + i]; + r[i] = mag * cosf(ph); + r[half + i] = mag * sinf(ph); +} + +// Centered overlap-add of windowed frames [F][N] at hop: out[i] is sample n0 + i, frames in ascending order, over the +// window envelope (win2 = window squared) of the same frames. +extern "C" __global__ void zc_ola(const float* __restrict__ frames, const float* __restrict__ win2, int F, int N, + int hop, long long n0, long long count, float* __restrict__ out) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + const long long p = n0 + i + N / 2; + long long f0 = (p - N) / hop + 1; + if (p - N < 0) f0 = 0; + long long f1 = p / hop; + if (f1 > F - 1) f1 = F - 1; + float s = 0.f, e = 0.f; + for (long long f = f0; f <= f1; ++f) { + const int o = (int)(p - f * hop); + s += frames[(size_t)f * N + o]; + e += win2[o]; + } + out[i] = s / e; +} + +// The mixer: out[i] = sum_b sum_j w[b][j] s_b[n0 + i + j - 63], zero outside [0, total); s rows are `total` apart. +extern "C" __global__ void zc_mix(const float* __restrict__ s, long long total, const float* __restrict__ w, + long long n0, long long count, float* __restrict__ out) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + float a = 0.f; + for (int b = 0; b < 2; ++b) + for (int j = 0; j < 127; ++j) { + const long long p = n0 + i + j - 63; + if (p >= 0 && p < total) a = fmaf(w[b * 127 + j], s[(size_t)b * total + p], a); + } + out[i] = a; +} + +// 44160 to 44100 Hz: output m = 735 q + c is sum_j kernel[c][j] x[736 q + j - 17], zero outside [0, total). +extern "C" __global__ void zc_resample(const float* __restrict__ x, long long total, const float* __restrict__ kernel, + long long m0, long long count, float* __restrict__ out) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + const long long m = m0 + i; + const long long q = m / 735; + const int c = (int)(m % 735); + float a = 0.f; + for (int j = 0; j < 770; ++j) { + const long long p = 736 * q + j - 17; + if (p >= 0 && p < total) a = fmaf(kernel[c * 770 + j], x[p], a); + } + out[i] = a; +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 4730d6064b7..de60773ce91 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -206,6 +206,7 @@ pub const drama3_fp8: []const u8 = if (available) &Blob("fatbin_drama3_fp8").byt pub const drama3_codec: []const u8 = if (available) &Blob("fatbin_drama3_codec").bytes else &.{}; pub const drama3_staged_gemv: []const u8 = if (available) &Blob("fatbin_drama3_staged_gemv").bytes else &.{}; pub const zonos3: []const u8 = if (available) &Blob("fatbin_zonos3").bytes else &.{}; +pub const zonos3_codec: []const u8 = if (available) &Blob("fatbin_zonos3_codec").bytes else &.{}; pub const gdn_train: []const u8 = if (available) &Blob("fatbin_gdn_train").bytes else &.{}; pub const train_q4: []const u8 = if (available) &Blob("fatbin_train_q4").bytes else &.{}; pub const train_attn: []const u8 = if (available) &Blob("fatbin_train_attn").bytes else &.{}; diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig new file mode 100644 index 00000000000..8451112bb23 --- /dev/null +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -0,0 +1,264 @@ +//! ZONOS3's codec decoder on one GPU: undelayed code frames [n][10] in, 44.1 kHz fp32 samples out. The trunk keeps +//! its state (ConvNeXt histories, each transformer layer's keys and values), so frames may arrive in any chunks. +const std = @import("std"); +const cuda = @import("cuda"); +const kern = @import("codec_kernels.zig"); +const wts = @import("codec_weights.zig"); + +const Buf = cuda.DeviceBuffer; +const W = wts.width; + +pub const sample_rate = 44100; +pub const frame_samples = 2940; // output samples a code frame +const internal_frame = 2944; // 44160 Hz samples a code frame +const head_rate = 16; // head frames a code frame + +pub const Options = struct { + max_frames: usize = 2048, // code frames a request + pass_frames: usize = 32, // code frames a pass through the trunk + + pub fn validate(o: Options) !void { + if (o.max_frames == 0 or o.max_frames > 8192) return error.BadFrameBudget; + if (o.pass_frames == 0 or o.pass_frames > o.max_frames) return error.BadPassFrames; + } +}; + +/// A capture of a pass under the reference's dump names: device fp32 rows [rows, width]. +pub const Probe = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void, +}; + +pub const Codec = struct { + gpa: std.mem.Allocator, + o: Options, + d: *const cuda.Driver, + stream: cuda.Stream, + k: kern.Kernels, + w: *wts.Weights, + bufs: std.ArrayList(Buf), + frames: usize = 0, // code frames decoded + // state + sem_hist: [wts.sem_blocks]u64, // [W][6] + head_hist: [wts.head_blocks]u64, + hist: u64, // every history in one block (zeroed per request) + hist_bytes: usize, + kv: [5][][2]u64, // per stage and layer: K, V [max rows of the stage][d] + spec_frames: [2]u64, // windowed head frames [16 * max_frames][n_fft] + // scratch (R = 16 * pass_frames rows) + codes: u64, // i32 [pass][10] + xa: u64, // [R][W] (or [pass][1280]) + xb: u64, + n: u64, + o_: u64, + att: u64, + big: u64, // [R][3072] + // the tail, whole request + branches: u64, // [2][internal samples] + mixed: u64, // [internal samples] + audio: u64, // [samples] + + /// The codec on a context the caller made current, launching on `stream`. + pub fn create(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, stream: cuda.Stream, generator: []const u8, head: []const u8, o: Options) !*Codec { + try o.validate(); + const c = try gpa.create(Codec); + errdefer gpa.destroy(c); + c.* = undefined; + c.gpa = gpa; + c.o = o; + c.d = d; + c.stream = stream; + c.frames = 0; + c.bufs = .empty; + for (&c.kv) |*layers| layers.* = &.{}; + c.k = try kern.Kernels.load(d); + errdefer c.k.unload(); + c.w = try wts.load(gpa, io, d, generator, head); + errdefer { + c.w.deinit(); + gpa.destroy(c.w); + } + errdefer c.freeState(); + try c.allocState(); + try c.reset(); + return c; + } + + pub fn destroy(c: *Codec) void { + c.stream.synchronize() catch {}; + c.freeState(); + c.w.deinit(); + c.gpa.destroy(c.w); + c.k.unload(); + c.gpa.destroy(c); + } + + fn freeState(c: *Codec) void { + for (c.bufs.items) |*b| b.free(); + c.bufs.deinit(c.gpa); + for (c.kv) |layers| c.gpa.free(layers); + } + + fn alloc(c: *Codec, bytes: usize) !u64 { + var b = try Buf.alloc(c.d, @max(bytes, 256)); + errdefer b.free(); + try c.bufs.append(c.gpa, b); + return b.ptr; + } + + fn allocState(c: *Codec) !void { + const T = c.o.max_frames; + const R = head_rate * c.o.pass_frames; + const one = W * 6 * 4; + c.hist_bytes = (wts.sem_blocks + wts.head_blocks) * one; + c.hist = try c.alloc(c.hist_bytes); + for (&c.sem_hist, 0..) |*h, i| h.* = c.hist + i * one; + for (&c.head_hist, 0..) |*h, i| h.* = c.hist + (wts.sem_blocks + i) * one; + for (&c.kv, wts.stages, 0..) |*layers, shape, si| { + layers.* = try c.gpa.alloc([2]u64, c.w.stages[si].layers.len); + const bytes = (T << @intCast(si)) * shape.d * 4; + for (layers.*) |*pair| pair.* = .{ try c.alloc(bytes), try c.alloc(bytes) }; + } + for (&c.spec_frames, wts.n_ffts) |*f, n| f.* = try c.alloc(head_rate * T * n * 4); + c.codes = try c.alloc(c.o.pass_frames * 10 * 4); + c.xa = try c.alloc(R * W * 4); + c.xb = try c.alloc(R * W * 4); + c.n = try c.alloc(R * W * 4); + c.o_ = try c.alloc(R * W * 4); + c.att = try c.alloc(R * W * 4); + c.big = try c.alloc(R * 3072 * 4); + c.branches = try c.alloc(2 * T * internal_frame * 4); + c.mixed = try c.alloc(T * internal_frame * 4); + c.audio = try c.alloc(T * frame_samples * 4); + } + + fn buf(c: *Codec, ptr: u64) Buf { + return .{ .d = c.d, .ptr = ptr, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + pub fn download(c: *Codec, src: u64, out: []u8) !void { + try c.buf(src).downloadAsync(0, out, c.stream.handle); + try c.stream.synchronize(); + } + + /// A new request: zero histories, no frames. Cache rows are written before they are read. + pub fn reset(c: *Codec) !void { + var b = c.buf(c.hist); + b.len = c.hist_bytes; + try b.fill8(0, c.stream.handle); + try c.stream.synchronize(); + c.frames = 0; + } + + /// The next code frames (every code below 4096). Under a probe they must fit one pass. + pub fn decode(c: *Codec, codes: []const [10]i32, probe: ?Probe) !void { + if (c.frames + codes.len > c.o.max_frames) return error.FrameBudget; + if (probe != null and codes.len > c.o.pass_frames) return error.ProbeNeedsOnePass; + for (codes) |row| for (row) |code| if (code < 0 or code >= wts.codebook_size) return error.BadCode; + var at: usize = 0; + while (at < codes.len) { + const t = @min(c.o.pass_frames, codes.len - at); + try c.pass(codes[at..][0..t], probe); + at += t; + } + } + + fn convnext(c: *Codec, b: wts.Block, hist: u64, x: u64, rows: usize) !void { + const k = &c.k; + const s = c.stream; + try k.dwconv(s, x, rows, b.dw_w, b.dw_b, hist, c.o_, W); + try k.layernorm(s, c.o_, b.ln_w, b.ln_b, c.n, W, 1e-6, rows); + try k.linear(s, b.pw1_w, b.pw1_b, c.n, W, W, wts.hidden, c.big, wts.hidden, rows); + try k.gelu(s, c.big, rows * wts.hidden); + try k.linear(s, b.pw2_w, b.pw2_b, c.big, wts.hidden, wts.hidden, W, c.o_, W, rows); + try k.addScaled(s, x, c.o_, 0, W, rows); + } + + fn layer(c: *Codec, shape: wts.StageShape, L: wts.Layer, kv: [2]u64, x: u64, rows: usize, pos0: usize) !void { + const k = &c.k; + const s = c.stream; + const d = shape.d; + try k.layernorm(s, x, L.n1w, L.n1b, c.n, d, 1e-5, rows); + try k.linear(s, L.qkv, 0, c.n, d, d, 3 * d, c.big, 3 * d, rows); + try k.attnPrep(s, c.big, d, pos0, kv[0], kv[1], rows); + try k.attention(s, c.big, d, kv[0], kv[1], pos0, shape.ctx, c.att, rows); + try k.linear(s, L.attn_out, 0, c.att, d, d, d, c.o_, d, rows); + try k.addScaled(s, x, c.o_, L.attn_scale, d, rows); + try k.layernorm(s, x, L.n2w, L.n2b, c.n, d, 1e-5, rows); + try k.linear(s, L.ffn0, 0, c.n, d, d, shape.ff, c.big, shape.ff, rows); + try k.gelu(s, c.big, rows * shape.ff); + try k.linear(s, L.ffn1, 0, c.big, shape.ff, shape.ff, d, c.o_, d, rows); + try k.addScaled(s, x, c.o_, L.ffn_scale, d, rows); + } + + fn pass(c: *Codec, codes: []const [10]i32, probe: ?Probe) !void { + const k = &c.k; + const s = c.stream; + const w = c.w; + const t = codes.len; + try c.buf(c.codes).uploadAsync(0, std.mem.sliceAsBytes(codes), s.handle); + // the latent: the semantic code through its head, plus the nine residual codes + var x = c.xa; + var y = c.xb; + try k.gather(s, c.codes, 0, w.sem_table, x, W, t); + for (w.sem, c.sem_hist) |b, h| try c.convnext(b, h, x, t); + try k.linear(s, w.sem_out_w, w.sem_out_b, x, W, W, wts.latent_dim, y, wts.latent_dim, t); + try k.latent(s, c.codes, w.res_tables, y, wts.latent_dim, t); + if (probe) |p| try p.f(p.ctx, "latent", y, t, wts.latent_dim); + std.mem.swap(u64, &x, &y); + // the stages: x holds the stage's input rows + var rows = t; + for (wts.stages, w.stages, c.kv, 0..) |shape, st, kv, si| { + const pos0 = c.frames << @intCast(si); + try k.linear(s, st.in_proj, 0, x, shape.in, shape.in, shape.d, y, shape.d, rows); + for (st.layers, kv) |L, pair| try c.layer(shape, L, pair, y, rows, pos0); + if (shape.out == 0) { + std.mem.swap(u64, &x, &y); + if (probe) |p| try p.f(p.ctx, "stage_8", x, rows, shape.d); + break; + } + try k.linear(s, st.out_proj, 0, y, shape.d, shape.d, shape.out, x, shape.out, rows); + if (probe) |p| { + var nb: [16]u8 = undefined; + try p.f(p.ctx, try std.fmt.bufPrint(&nb, "stage_{d}", .{2 * si}), x, rows, shape.out); + } + rows *= 2; + try k.patchUp(s, x, y, shape.out, rows); + std.mem.swap(u64, &x, &y); + } + // the head: ConvNeXt blocks, a norm, then each branch's spectrum to windowed frames + for (w.head, c.head_hist) |b, h| try c.convnext(b, h, x, rows); + try k.layernorm(s, x, w.head_ln_w, w.head_ln_b, c.n, W, 1e-6, rows); + if (probe) |p| try p.f(p.ctx, "trunk", c.n, rows, W); + const row0 = c.frames * head_rate; + for (wts.n_ffts, 0..) |n, b| { + try k.linear(s, w.outs_w[b], w.outs_b[b], c.n, W, W, n + 2, c.big, n + 2, rows); + if (probe) |p| try p.f(p.ctx, if (b == 0) "y0" else "y1", c.big, rows, n + 2); + try k.spec(s, c.big, n / 2 + 1, rows); + try k.linear(s, w.synth[b], 0, c.big, n + 2, n + 2, n, c.spec_frames[b] + row0 * n * 4, n, rows); + } + c.frames += t; + } + + /// Every decoded frame's samples to the host (frames * 2940, caller frees): the request's whole audio. + pub fn finish(c: *Codec, gpa: std.mem.Allocator, probe: ?Probe) ![]f32 { + const k = &c.k; + const s = c.stream; + const total = c.frames * internal_frame; + const samples = c.frames * frame_samples; + if (c.frames == 0) return gpa.alloc(f32, 0); + for (wts.n_ffts, 0..) |n, b| { + const out = c.branches + b * total * 4; + try k.ola(s, c.spec_frames[b], c.w.win2[b], c.frames * head_rate, n, wts.hop, 0, total, out); + if (probe) |p| try p.f(p.ctx, if (b == 0) "s0" else "s1", out, 1, total); + } + try k.mix(s, c.branches, total, c.w.mixer, 0, total, c.mixed); + if (probe) |p| try p.f(p.ctx, "mixer", c.mixed, 1, total); + try k.resample(s, c.mixed, total, c.w.resampler, 0, samples, c.audio); + if (probe) |p| try p.f(p.ctx, "audio", c.audio, 1, samples); + const pcm = try gpa.alloc(f32, samples); + errdefer gpa.free(pcm); + try c.download(c.audio, std.mem.sliceAsBytes(pcm)); + return pcm; + } +}; diff --git a/zig/src/families/zonos3/cuda/codec_kernels.zig b/zig/src/families/zonos3/cuda/codec_kernels.zig new file mode 100644 index 00000000000..d625f42b9e0 --- /dev/null +++ b/zig/src/families/zonos3/cuda/codec_kernels.zig @@ -0,0 +1,188 @@ +//! The codec decoder's launches: zonos3_codec.cu by symbol. +const std = @import("std"); +const cuda = @import("cuda"); + +const names = .{ + "zc_linear", "zc_layernorm", "zc_attn_prep", "zc_attention", "zc_add_scaled", "zc_gelu", "zc_patch_up", + "zc_dwconv", "zc_gather", "zc_latent", "zc_spec", "zc_ola", "zc_mix", "zc_resample", +}; + +pub const F = enum(u8) { linear, layernorm, attn_prep, attention, add_scaled, gelu, patch_up, dwconv, gather, latent, spec, ola, mix, resample }; + +const n_fns = @typeInfo(F).@"enum".field_names.len; + +pub const Kernels = struct { + mod: cuda.Module, + fns: [n_fns]cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var k: Kernels = undefined; + k.mod = try cuda.Module.load(d, cuda.kernels.zonos3_codec); + errdefer k.mod.unload(); + inline for (names, 0..) |name, j| k.fns[j] = try k.mod.function(name); + return k; + } + + pub fn unload(k: *Kernels) void { + k.mod.unload(); + } + + fn go(k: *const Kernels, which: F, s: cuda.Stream, gx: usize, gy: usize, block: usize, shared: usize, a: *cuda.Args) !void { + try cuda.launch.launch(k.fns[@backingInt(which)], .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy), .z = 1 }, .block = .{ .x = @intCast(block) }, .shared = @intCast(shared) }, s, a); + } + + fn i(x: usize) i32 { + return @intCast(x); + } + + fn l(x: usize) i64 { + return @intCast(x); + } + + /// y [rows, n] = x [rows, kdim] W^T (+ bias when not 0), all fp32. + pub fn linear(k: *const Kernels, s: cuda.Stream, w: u64, bias: u64, x: u64, xs: usize, kdim: usize, n: usize, y: u64, ys: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(w); + a.add(x); + a.add(i(xs)); + a.add(i(kdim)); + a.add(i(n)); + a.add(y); + a.add(i(ys)); + a.add(bias); + try k.go(.linear, s, (n + 7) / 8, rows, 256, kdim * 4, &a); + } + + pub fn layernorm(k: *const Kernels, s: cuda.Stream, x: u64, w: u64, b: u64, y: u64, d: usize, eps: f32, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(w); + a.add(b); + a.add(y); + a.add(i(d)); + a.add(eps); + try k.go(.layernorm, s, rows, 1, 256, 0, &a); + } + + pub fn attnPrep(k: *const Kernels, s: cuda.Stream, qkv: u64, d: usize, pos0: usize, kc: u64, vc: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(i(d)); + a.add(i(pos0)); + a.add(kc); + a.add(vc); + try k.go(.attn_prep, s, rows, d / 64, 32, 0, &a); + } + + pub fn attention(k: *const Kernels, s: cuda.Stream, qkv: u64, d: usize, kc: u64, vc: u64, pos0: usize, ctx: usize, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(qkv); + a.add(i(d)); + a.add(kc); + a.add(vc); + a.add(i(pos0)); + a.add(i(ctx)); + a.add(out); + try k.go(.attention, s, rows, d / 64, 128, 0, &a); + } + + /// x += scale * y per channel; scale == 0 is a plain add. + pub fn addScaled(k: *const Kernels, s: cuda.Stream, x: u64, y: u64, scale: u64, d: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(y); + a.add(scale); + a.add(i(d)); + try k.go(.add_scaled, s, (d + 255) / 256, rows, 256, 0, &a); + } + + pub fn gelu(k: *const Kernels, s: cuda.Stream, x: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(l(n)); + try k.go(.gelu, s, (n + 255) / 256, 1, 256, 0, &a); + } + + /// in [rows / 2][c] to out [rows][c / 2]. + pub fn patchUp(k: *const Kernels, s: cuda.Stream, in: u64, out: u64, c: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(out); + a.add(i(c)); + try k.go(.patch_up, s, (c / 2 + 255) / 256, rows, 256, 0, &a); + } + + pub fn dwconv(k: *const Kernels, s: cuda.Stream, x: u64, t: usize, w: u64, b: u64, hist: u64, out: u64, c: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(i(t)); + a.add(w); + a.add(b); + a.add(hist); + a.add(out); + a.add(i(c)); + try k.go(.dwconv, s, (c + 255) / 256, 1, 256, 0, &a); + } + + pub fn gather(k: *const Kernels, s: cuda.Stream, codes: u64, col: usize, table: u64, out: u64, d: usize, t: usize) !void { + var a: cuda.Args = .{}; + a.add(codes); + a.add(i(col)); + a.add(table); + a.add(out); + a.add(i(d)); + try k.go(.gather, s, (d + 255) / 256, t, 256, 0, &a); + } + + pub fn latent(k: *const Kernels, s: cuda.Stream, codes: u64, tables: u64, z: u64, d: usize, t: usize) !void { + var a: cuda.Args = .{}; + a.add(codes); + a.add(tables); + a.add(z); + a.add(i(d)); + try k.go(.latent, s, (d + 255) / 256, t, 256, 0, &a); + } + + pub fn spec(k: *const Kernels, s: cuda.Stream, y: u64, half: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(y); + a.add(i(half)); + try k.go(.spec, s, (half + 255) / 256, rows, 256, 0, &a); + } + + pub fn ola(k: *const Kernels, s: cuda.Stream, frames: u64, win2: u64, f: usize, n: usize, hop: usize, n0: usize, count: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(frames); + a.add(win2); + a.add(i(f)); + a.add(i(n)); + a.add(i(hop)); + a.add(l(n0)); + a.add(l(count)); + a.add(out); + try k.go(.ola, s, (count + 255) / 256, 1, 256, 0, &a); + } + + pub fn mix(k: *const Kernels, s: cuda.Stream, branches: u64, total: usize, w: u64, n0: usize, count: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(branches); + a.add(l(total)); + a.add(w); + a.add(l(n0)); + a.add(l(count)); + a.add(out); + try k.go(.mix, s, (count + 255) / 256, 1, 256, 0, &a); + } + + pub fn resample(k: *const Kernels, s: cuda.Stream, x: u64, total: usize, kernel: u64, m0: usize, count: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(l(total)); + a.add(kernel); + a.add(l(m0)); + a.add(l(count)); + a.add(out); + try k.go(.resample, s, (count + 255) / 256, 1, 256, 0, &a); + } +}; diff --git a/zig/src/families/zonos3/cuda/codec_weights.zig b/zig/src/families/zonos3/cuda/codec_weights.zig new file mode 100644 index 00000000000..1ecaea3b60b --- /dev/null +++ b/zig/src/families/zonos3/cuda/codec_weights.zig @@ -0,0 +1,243 @@ +//! The codec decoder's weights as published (fp32): the generator's quantizer, semantic head and resampler, and a +//! head checkpoint's decoder stages and iSTFT head. Weight norms and the code tables are folded once on the host. +const std = @import("std"); +const cuda = @import("cuda"); +const pth = @import("torch_pth"); + +pub const latent_dim = 1024; +pub const width = 768; // the semantic head's and the iSTFT head's width, and stages 2..8's +pub const hidden = 2048; // ConvNeXt hidden width +pub const codebook_size = 4096; +pub const codebook_dim = 8; +pub const residuals = 9; +pub const sem_blocks = 4; +pub const head_blocks = 8; +pub const hop = 184; // internal samples a head frame (44160 Hz / 240) +pub const n_ffts = [2]usize{ 736, 2208 }; +pub const fir = 127; +pub const resample_in = 736; +pub const resample_out = 735; +pub const resample_taps = 770; + +pub const StageShape = struct { in: usize, d: usize, ff: usize, ctx: usize, out: usize }; + +/// The five transformer stages, 15 Hz to 240 Hz; out 0: the last stage's features feed the head as they are. +pub const stages = [5]StageShape{ + .{ .in = 1024, .d = 1280, .ff = 5120, .ctx = 150, .out = 1280 }, + .{ .in = 640, .d = 768, .ff = 3072, .ctx = 300, .out = 768 }, + .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 768 }, + .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 768 }, + .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 0 }, +}; + +pub const Layer = struct { n1w: u64, n1b: u64, n2w: u64, n2b: u64, qkv: u64, attn_out: u64, ffn0: u64, ffn1: u64, attn_scale: u64, ffn_scale: u64 }; +pub const Stage = struct { in_proj: u64, out_proj: u64, layers: []Layer }; +pub const Block = struct { dw_w: u64, dw_b: u64, ln_w: u64, ln_b: u64, pw1_w: u64, pw1_b: u64, pw2_w: u64, pw2_b: u64 }; + +pub const Weights = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(cuda.DeviceBuffer), + bytes: usize, + sem_table: u64, // [4096][width]: the semantic codebook through its output projection + res_tables: u64, // [9][4096][latent_dim] + sem: [sem_blocks]Block, + sem_out_w: u64, // [latent_dim][width] + sem_out_b: u64, + stages: [5]Stage, + head: [head_blocks]Block, + head_ln_w: u64, + head_ln_b: u64, + outs_w: [2]u64, // [n_fft + 2][width] + outs_b: [2]u64, + synth: [2]u64, // [n_fft][n_fft + 2]: windowed inverse real FFT of [real | imaginary] + win2: [2]u64, // [n_fft] window squared + mixer: u64, // [2][fir] + resampler: u64, // [resample_out][resample_taps] + + pub fn deinit(w: *Weights) void { + for (w.bufs.items) |*b| b.free(); + w.bufs.deinit(w.gpa); + for (w.stages) |st| w.gpa.free(st.layers); + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + w: *Weights, + + fn device(l: *Loader, values: []const f32) !u64 { + const bytes = std.mem.sliceAsBytes(values); + var b = try cuda.DeviceBuffer.alloc(l.d, @max(bytes.len, 256)); + errdefer b.free(); + try b.upload(0, bytes); + try l.w.bufs.append(l.gpa, b); + l.w.bytes += bytes.len; + return b.ptr; + } + + fn one(l: *Loader, a: *const pth.Archive, name: []const u8, shape: []const u64) !u64 { + const v = try a.readF32(l.gpa, name, shape); + defer l.gpa.free(v); + return l.device(v); + } + + /// A weight-normed 1 x 1 convolution's matrix [out][in]: v * (g / |v|), the norm over each output's inputs. + fn normed(l: *Loader, a: *const pth.Archive, comptime prefix: []const u8, out: usize, in: usize) ![]f32 { + const v = try a.readF32(l.gpa, prefix ++ "weight_v", &.{ out, in, 1 }); + errdefer l.gpa.free(v); + const g = try a.readF32(l.gpa, prefix ++ "weight_g", &.{ out, 1, 1 }); + defer l.gpa.free(g); + for (0..out) |o| { + var ss: f64 = 0; + for (v[o * in ..][0..in]) |x| ss += @as(f64, x) * x; + const scale = g[o] / @as(f32, @floatCast(@sqrt(ss))); + for (v[o * in ..][0..in]) |*x| x.* *= scale; + } + return v; + } + + /// A quantizer's table [4096][out]: each code vector through the output projection. + fn table(l: *Loader, a: *const pth.Archive, comptime prefix: []const u8, out: usize, dst: []f32) !void { + const m = try l.normed(a, prefix ++ "out_proj.", out, codebook_dim); + defer l.gpa.free(m); + const bias = try a.readF32(l.gpa, prefix ++ "out_proj.bias", &.{out}); + defer l.gpa.free(bias); + const codes = try a.readF32(l.gpa, prefix ++ "codebook.weight", &.{ codebook_size, codebook_dim }); + defer l.gpa.free(codes); + for (0..codebook_size) |c| for (0..out) |o| { + var acc: f32 = 0; + for (m[o * codebook_dim ..][0..codebook_dim], codes[c * codebook_dim ..][0..codebook_dim]) |wv, x| acc = @mulAdd(f32, wv, x, acc); + dst[c * out + o] = acc + bias[o]; + }; + } + + fn block(l: *Loader, a: *const pth.Archive, comptime f: []const u8, index: usize) !Block { + var nb: [8][96]u8 = undefined; + const n = struct { + fn of(buf: []u8, comptime ff: []const u8, comptime tail: []const u8, i: usize) []const u8 { + return std.fmt.bufPrint(buf, ff ++ tail, .{i}) catch unreachable; + } + }.of; + return .{ + .dw_w = try l.one(a, n(&nb[0], f, "dwconv.weight", index), &.{ width, 1, 7 }), + .dw_b = try l.one(a, n(&nb[1], f, "dwconv.bias", index), &.{width}), + .ln_w = try l.one(a, n(&nb[2], f, "norm.weight", index), &.{width}), + .ln_b = try l.one(a, n(&nb[3], f, "norm.bias", index), &.{width}), + .pw1_w = try l.one(a, n(&nb[4], f, "pwconv1.weight", index), &.{ hidden, width }), + .pw1_b = try l.one(a, n(&nb[5], f, "pwconv1.bias", index), &.{hidden}), + .pw2_w = try l.one(a, n(&nb[6], f, "pwconv2.weight", index), &.{ width, hidden }), + .pw2_b = try l.one(a, n(&nb[7], f, "pwconv2.bias", index), &.{width}), + }; + } +}; + +/// The windowed inverse real FFT as a matrix [n][n + 2] over [real | imaginary] bins, periodic Hann. +fn synthesis(gpa: std.mem.Allocator, n: usize, win2: []f32) ![]f32 { + const half = n / 2 + 1; + const m = try gpa.alloc(f32, n * 2 * half); + const nf: f64 = @floatFromInt(n); + for (0..n) |t| { + const win = 0.5 - 0.5 * @cos(2.0 * std.math.pi * @as(f64, @floatFromInt(t)) / nf); + win2[t] = @floatCast(win * win); + for (0..half) |k| { + const edge = k == 0 or k == n / 2; + const gain: f64 = (if (edge) @as(f64, 1.0) else 2.0) * win / nf; + const angle = 2.0 * std.math.pi * @as(f64, @floatFromInt((k * t) % n)) / nf; + m[t * 2 * half + k] = @floatCast(gain * @cos(angle)); + m[t * 2 * half + half + k] = if (edge) 0 else @floatCast(-gain * @sin(angle)); + } + } + return m; +} + +fn fmt(buf: []u8, comptime f: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(buf, f, args) catch unreachable; +} + +/// `generator`: autoencoder/generator.pt; `head`: a decoder's checkpoint (autoencoder/heads//step_*.pt). +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, generator: []const u8, head: []const u8) !*Weights { + const w = try gpa.create(Weights); + errdefer gpa.destroy(w); + w.* = undefined; + w.gpa = gpa; + w.bufs = .empty; + w.bytes = 0; + for (&w.stages) |*st| st.layers = &.{}; + errdefer w.deinit(); + var l: Loader = .{ .gpa = gpa, .d = d, .w = w }; + var nb: [128]u8 = undefined; + { + var g = try pth.Archive.openNested(gpa, io, generator); + defer g.close(); + const q = "generator/quantizer."; + const sem = try gpa.alloc(f32, codebook_size * width); + defer gpa.free(sem); + try l.table(&g, q ++ "semantic_quantizer.quantizers.0.", width, sem); + w.sem_table = try l.device(sem); + const res = try gpa.alloc(f32, residuals * codebook_size * latent_dim); + defer gpa.free(res); + inline for (0..residuals) |i| try l.table(&g, q ++ std.fmt.comptimePrint("quantizer.quantizers.{d}.", .{i}), latent_dim, res[i * codebook_size * latent_dim ..][0 .. codebook_size * latent_dim]); + w.res_tables = try l.device(res); + for (&w.sem, 0..) |*b, i| b.* = try l.block(&g, "generator/semantic_head.{d}.", i); + const out = try l.normed(&g, "generator/semantic_head.4.", latent_dim, width); + defer gpa.free(out); + w.sem_out_w = try l.device(out); + w.sem_out_b = try l.one(&g, "generator/semantic_head.4.bias", &.{latent_dim}); + w.resampler = try l.one(&g, "generator/to_external.kernel", &.{ resample_out, 1, resample_taps }); + } + var h = try pth.Archive.openNested(gpa, io, head); + defer h.close(); + for (&w.stages, stages, 0..) |*st, shape, si| { + const s = 2 * si; + var count: usize = 0; + while (h.tensors.contains(fmt(&nb, "trainable/stages.{d}.layers.{d}.qkv.weight", .{ s, count }))) count += 1; + if (count == 0) return error.MissingTensor; + st.layers = try gpa.alloc(Layer, count); + st.in_proj = try l.one(&h, fmt(&nb, "trainable/stages.{d}.input_proj.weight", .{s}), &.{ shape.d, shape.in }); + st.out_proj = if (shape.out == 0) 0 else try l.one(&h, fmt(&nb, "trainable/stages.{d}.output_proj.weight", .{s}), &.{ shape.out, shape.d }); + for (st.layers, 0..) |*L, li| { + const p = "trainable/stages.{d}.layers.{d}."; + L.* = .{ + .n1w = try l.one(&h, fmt(&nb, p ++ "norm1.weight", .{ s, li }), &.{shape.d}), + .n1b = try l.one(&h, fmt(&nb, p ++ "norm1.bias", .{ s, li }), &.{shape.d}), + .n2w = try l.one(&h, fmt(&nb, p ++ "norm2.weight", .{ s, li }), &.{shape.d}), + .n2b = try l.one(&h, fmt(&nb, p ++ "norm2.bias", .{ s, li }), &.{shape.d}), + .qkv = try l.one(&h, fmt(&nb, p ++ "qkv.weight", .{ s, li }), &.{ 3 * shape.d, shape.d }), + .attn_out = try l.one(&h, fmt(&nb, p ++ "attention_out.weight", .{ s, li }), &.{ shape.d, shape.d }), + .ffn0 = try l.one(&h, fmt(&nb, p ++ "ffn.0.weight", .{ s, li }), &.{ shape.ff, shape.d }), + .ffn1 = try l.one(&h, fmt(&nb, p ++ "ffn.3.weight", .{ s, li }), &.{ shape.d, shape.ff }), + .attn_scale = try l.one(&h, fmt(&nb, p ++ "attention_scale", .{ s, li }), &.{shape.d}), + .ffn_scale = try l.one(&h, fmt(&nb, p ++ "ffn_scale", .{ s, li }), &.{shape.d}), + }; + } + } + for (&w.head, 0..) |*b, i| b.* = try l.block(&h, "trainable/head.blocks.{d}.", i); + w.head_ln_w = try l.one(&h, "trainable/head.norm.weight", &.{width}); + w.head_ln_b = try l.one(&h, "trainable/head.norm.bias", &.{width}); + for (n_ffts, 0..) |n, b| { + w.outs_w[b] = try l.one(&h, fmt(&nb, "trainable/head.outs.{d}.weight", .{b}), &.{ n + 2, width }); + w.outs_b[b] = try l.one(&h, fmt(&nb, "trainable/head.outs.{d}.bias", .{b}), &.{n + 2}); + const win2 = try gpa.alloc(f32, n); + defer gpa.free(win2); + const m = try synthesis(gpa, n, win2); + defer gpa.free(m); + w.synth[b] = try l.device(m); + w.win2[b] = try l.device(win2); + } + w.mixer = try l.one(&h, "trainable/head.mixer.weight", &.{ 1, 2, fir }); + return w; +} + +test "synthesis: a lone DC bin gives the window over n" { + const t = std.testing; + var win2: [8]f32 = undefined; + const m = try synthesis(t.allocator, 8, &win2); + defer t.allocator.free(m); + for (0..8) |n| { + const win = 0.5 - 0.5 * @cos(2.0 * std.math.pi * @as(f64, @floatFromInt(n)) / 8.0); + try t.expectApproxEqAbs(@as(f32, @floatCast(win / 8.0)), m[n * 10], 1e-7); + try t.expectApproxEqAbs(@as(f32, @floatCast(win * win)), win2[n], 1e-7); + try t.expectEqual(@as(f32, 0), m[n * 10 + 5]); + } +} diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index 5859cb9bff2..ce0a5bd9a65 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -1,6 +1,7 @@ //! zonos3-generate: ZONOS3 Mini's backbone on one CUDA GPU against the PyTorch reference's dumps. const std = @import("std"); const z3 = @import("zonos3"); +const cuda = @import("cuda"); const cfg = z3.config; const W = cfg.frame_width; @@ -9,25 +10,30 @@ const D = cfg.dim; const usage = \\usage: zonos3-generate --model LM_DIR --check DUMP_DIR [--max-rows 64] [--max-ctx 4096] \\ zonos3-generate --model LM_DIR --frames-check GEN_DIR [--max-frames 2000] + \\ zonos3-generate --codec-check DUMP_DIR --generator GENERATOR.pt --head HEAD.pt \\ \\--check runs DUMP_DIR/input_ids.npy (prompt rows [n, 11]) with DUMP_DIR/input_ids.cond.json through the backbone \\and compares every sublayer with the reference's .npy captures (tools/dump_golden.py lm of Zyphra/ZONOS3-Mini). \\--frames-check generates greedily (temperature 0, the other sampling defaults) after GEN_DIR's prompt and compares \\the frames with GEN_DIR/rows.npy, the reference's generation of the same request. - \\The last stderr line is "RESULT zonos3 check PASS|FAIL ..." or "RESULT zonos3 frames PASS|FAIL ...". + \\--codec-check decodes DUMP_DIR/codes.npy ([frames, 10]) with the codec decoder and compares its captures and + \\audio with the reference's (dump_codec.py); --generator is autoencoder/generator.pt, --head a decoder checkpoint. + \\The last stderr line is "RESULT zonos3 PASS|FAIL ...". \\ ; const Check = struct { gpa: std.mem.Allocator, io: std.Io, - e: *z3.Engine, + ctx: *anyopaque, + get: *const fn (ctx: *anyopaque, ptr: u64, out: []u8) anyerror!void, dir: []const u8, n: usize = 0, fails: usize = 0, missing: usize = 0, worst: f64 = 1.0, worst_rel: f64 = 0, + audio_snr_db: f64 = 0, fn probe(ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void { const c: *Check = @ptrCast(@alignCast(ctx)); @@ -46,7 +52,7 @@ const Check = struct { defer c.gpa.free(ref); const mine = try c.gpa.alloc(f32, rows * width); defer c.gpa.free(mine); - try c.e.download(ptr, std.mem.sliceAsBytes(mine)); + try c.get(c.ctx, ptr, std.mem.sliceAsBytes(mine)); var worst_row: f64 = 1; var at: usize = 0; var max_d: f64 = 0; @@ -74,6 +80,15 @@ const Check = struct { c.fails += @intFromBool(!ok); c.worst = @min(c.worst, worst_row); c.worst_rel = @max(c.worst_rel, rel); + if (std.mem.eql(u8, name, "audio")) { + var noise: f64 = 0; + var signal: f64 = 0; + for (mine, ref) |x, y| { + noise += (@as(f64, x) - y) * (@as(f64, x) - y); + signal += @as(f64, y) * y; + } + c.audio_snr_db = 10.0 * @log10(signal / @max(noise, 1e-300)); + } std.debug.print(" {s:<20} rows {d:>4} worst-row cos {d:.7} (row {d}) max|d| {e:.3} of {e:.3} {s}\n", .{ name, rows, worst_row, at, max_d, max_ref, if (ok) "ok" else "LOW" }); } }; @@ -148,6 +163,63 @@ fn framesCheck(gpa: std.mem.Allocator, io: std.Io, e: *z3.Engine, dir: []const u return if (pass) 0 else 1; } +fn codecCheck(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: []const u8, head: []const u8) !u8 { + const path = try std.fs.path.join(gpa, &.{ dir, "codes.npy" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 28)); + defer gpa.free(bytes); + const arr = try z3.npy.parse(bytes); + if (arr.rank != 2 or arr.shape[1] != 10) return error.BadCodes; + const flat = try arr.ints(gpa); + defer gpa.free(flat); + const codes = try gpa.alloc([10]i32, arr.shape[0]); + defer gpa.free(codes); + for (codes, 0..) |*r, j| r.* = flat[j * 10 ..][0..10].*; + + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const t_load = nowNs(io); + const codec = try z3.Codec.create(gpa, io, &driver, stream, generator, head, .{ .max_frames = codes.len, .pass_frames = codes.len }); + defer codec.destroy(); + const Dec = struct { + fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { + try @as(*z3.Codec, @ptrCast(@alignCast(c))).download(ptr, out); + } + }; + var c: Check = .{ .gpa = gpa, .io = io, .ctx = codec, .get = Dec.get, .dir = dir }; + std.debug.print("zonos3 codec check: {d} frames, {d} MiB of weights, loaded in {d:.1} s\n", .{ codes.len, codec.w.bytes >> 20, @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9 }); + const probe: z3.codec.Probe = .{ .ctx = &c, .f = Check.probe }; + try codec.decode(codes, probe); + const pcm = try codec.finish(gpa, probe); + gpa.free(pcm); + // the same frames in uneven chunks, then timed whole + try codec.reset(); + var at: usize = 0; + var step: usize = 1; + while (at < codes.len) : (step = step * 2 + 1) { + const n = @min(step, codes.len - at); + try codec.decode(codes[at..][0..n], null); + at += n; + } + const chunked = try codec.finish(gpa, null); + defer gpa.free(chunked); + try codec.reset(); + const t0 = nowNs(io); + try codec.decode(codes, null); + const whole = try codec.finish(gpa, null); + defer gpa.free(whole); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + const same = std.mem.eql(u8, std.mem.sliceAsBytes(chunked), std.mem.sliceAsBytes(whole)); + const audio_s = @as(f64, @floatFromInt(whole.len)) / z3.codec.sample_rate; + const pass = c.fails == 0 and c.n > 0 and c.missing == 0 and same; + std.debug.print("RESULT zonos3 codec {s} probes={d} low={d} missing={d} worst_row_cos={d:.7} audio_snr_db={d:.1} chunked_equals_whole={} audio_s={d:.2} decode_s={d:.3} x_realtime={d:.1}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, c.audio_snr_db, same, audio_s, seconds, audio_s / seconds }); + return if (pass) 0 else 1; +} + pub fn main(init: std.process.Init) !u8 { const arena = init.arena.allocator(); const gpa = std.heap.c_allocator; @@ -156,17 +228,27 @@ pub fn main(init: std.process.Init) !u8 { var model: []const u8 = ""; var check: ?[]const u8 = null; var frames_check: ?[]const u8 = null; + var codec_check: ?[]const u8 = null; + var generator: []const u8 = ""; + var head: []const u8 = ""; var max_frames: usize = 2000; var opts: z3.Options = .{}; var i: usize = 1; while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } } + if (codec_check) |dir| { + if (i != argv.len or generator.len == 0 or head.len == 0) { + std.debug.print("{s}", .{usage}); + return 2; + } + return codecCheck(gpa, io, dir, generator, head); + } const dir = check orelse frames_check orelse { std.debug.print("{s}", .{usage}); return 2; @@ -181,7 +263,12 @@ pub fn main(init: std.process.Init) !u8 { var replaced: std.ArrayList(z3.Replace) = .empty; try loadPrompt(gpa, io, e, dir, &rows, &replaced); if (frames_check != null) return framesCheck(gpa, io, e, dir, rows, replaced.items, max_frames); - var c: Check = .{ .gpa = gpa, .io = io, .e = e, .dir = dir }; + const Lm = struct { + fn get(ctx: *anyopaque, ptr: u64, out: []u8) anyerror!void { + try @as(*z3.Engine, @ptrCast(@alignCast(ctx))).download(ptr, out); + } + }; + var c: Check = .{ .gpa = gpa, .io = io, .ctx = e, .get = Lm.get, .dir = dir }; std.debug.print("zonos3 check: {d} prompt rows, {d} replaced, {d} MiB of weights\n", .{ rows.len, replaced.items.len, e.w.bytes >> 20 }); try e.run(rows, replaced.items, .{ .ctx = &c, .f = Check.probe }); const pass = c.fails == 0 and c.n > 0; diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index c05c44d410a..5a715657082 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -6,16 +6,20 @@ pub const generation = @import("generation.zig"); pub const weights = @import("cuda/weights.zig"); pub const kernels = @import("cuda/kernels.zig"); pub const engine = @import("cuda/engine.zig"); +pub const codec = @import("cuda/codec.zig"); +pub const codec_weights = @import("cuda/codec_weights.zig"); pub const Engine = engine.Engine; pub const Options = engine.Options; pub const Probe = engine.Probe; pub const Replace = engine.Replace; pub const Sampling = sampler.Sampling; +pub const Codec = codec.Codec; test { _ = config; _ = npy; _ = sampler; _ = generation; + _ = codec_weights; } From 819f35e3c7d03a17bcd6018a5200eda30aba20db Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:32:21 +0000 Subject: [PATCH 309/361] zonos3: text to WAV end to end: the prompt rows, the release's layout, the output stage zonos3-generate --text matches the reference's prompt rows and greedy frames, and its audio matches the reference's CPU fp32 decode. --- zig/src/families/zonos3/generate.zig | 144 +++++++++++++++++++++++- zig/src/families/zonos3/prompt.zig | 158 +++++++++++++++++++++++++++ zig/src/families/zonos3/release.zig | 103 +++++++++++++++++ zig/src/families/zonos3/speech.zig | 118 ++++++++++++++++++++ zig/src/families/zonos3/zonos3.zig | 6 + 5 files changed, 527 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/zonos3/prompt.zig create mode 100644 zig/src/families/zonos3/release.zig create mode 100644 zig/src/families/zonos3/speech.zig diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index ce0a5bd9a65..4a3f301ad87 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -2,6 +2,7 @@ const std = @import("std"); const z3 = @import("zonos3"); const cuda = @import("cuda"); +const core = @import("core"); const cfg = z3.config; const W = cfg.frame_width; @@ -11,6 +12,9 @@ const usage = \\usage: zonos3-generate --model LM_DIR --check DUMP_DIR [--max-rows 64] [--max-ctx 4096] \\ zonos3-generate --model LM_DIR --frames-check GEN_DIR [--max-frames 2000] \\ zonos3-generate --codec-check DUMP_DIR --generator GENERATOR.pt --head HEAD.pt + \\ zonos3-generate --checkpoint RELEASE_DIR --text "..." --wav OUT.wav [--voice-embedding E.npy | --voice-codes C.npy] + \\ [--seed 0] [--temperature 0.75] [--top-k 80] [--top-p 0.69] [--max-frames 2000] [--decoder ID] + \\ [--silence-frames 3] [--reference GEN_DIR] \\ \\--check runs DUMP_DIR/input_ids.npy (prompt rows [n, 11]) with DUMP_DIR/input_ids.cond.json through the backbone \\and compares every sublayer with the reference's .npy captures (tools/dump_golden.py lm of Zyphra/ZONOS3-Mini). @@ -18,7 +22,10 @@ const usage = \\the frames with GEN_DIR/rows.npy, the reference's generation of the same request. \\--codec-check decodes DUMP_DIR/codes.npy ([frames, 10]) with the codec decoder and compares its captures and \\audio with the reference's (dump_codec.py); --generator is autoencoder/generator.pt, --head a decoder checkpoint. - \\The last stderr line is "RESULT zonos3 PASS|FAIL ...". + \\--text speaks the text as typed (line breaks collapsed, no number or date expansion) in the voice of a 192-d + \\speaker embedding (float32 .npy) or of reference codes ([frames, 10] .npy); RELEASE_DIR is a snapshot of + \\Zyphra/ZONOS3-Mini. With --reference the prompt rows, frames and audio are compared with GEN_DIR's (dump_rows.py). + \\The last stderr line is "RESULT zonos3 ...". \\ ; @@ -220,6 +227,130 @@ fn codecCheck(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: [] return if (pass) 0 else 1; } +const Speak = struct { + checkpoint: []const u8 = "", + text: []const u8 = "", + wav: ?[]const u8 = null, + embedding: ?[]const u8 = null, + codes: ?[]const u8 = null, + decoder: ?[]const u8 = null, + reference: ?[]const u8 = null, + sampling: z3.Sampling = .{}, + max_frames: usize = 2000, + silence_frames: usize = 3, +}; + +fn readNpy(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !struct { bytes: []u8, arr: z3.npy.Array } { + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 28)); + return .{ .bytes = bytes, .arr = try z3.npy.parse(bytes) }; +} + +fn speak(gpa: std.mem.Allocator, io: std.Io, a: Speak) !u8 { + var rel = try z3.release.open(gpa, io, a.checkpoint, a.decoder); + defer rel.deinit(); + var tok = try core.tokenizer.loadTokenizer(io, gpa, rel.tokenizer); + defer tok.deinit(); + const t_load = nowNs(io); + const e = try z3.Engine.create(gpa, io, rel.lm, .{ .max_ctx = @min(z3.config.max_seqlen, a.max_frames + 2048) }); + defer e.destroy(); + const codec = try z3.Codec.create(gpa, io, &e.driver, e.stream, rel.generator, rel.head, .{ .max_frames = a.max_frames + 64 }); + defer codec.destroy(); + const load_s = @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9; + + // the prompt + const text = try z3.prompt.collapseLineBreaks(gpa, a.text); + defer gpa.free(text); + const ids = try tok.encode(gpa, text); + defer gpa.free(ids); + var codes: [][z3.config.codebooks]i32 = &.{}; + defer gpa.free(codes); + var speaker: z3.prompt.Speaker = .none; + var vec: [z3.config.speaker_dim]f32 = undefined; + if (a.embedding) |path| { + const f = try readNpy(gpa, io, path); + defer gpa.free(f.bytes); + if (f.arr.numel() != z3.config.speaker_dim or f.arr.kind != .f32) return error.BadSpeakerEmbedding; + const v = try f.arr.floats(gpa); + defer gpa.free(v); + vec = v[0..z3.config.speaker_dim].*; + speaker = .embedding; + } else if (a.codes) |path| { + const f = try readNpy(gpa, io, path); + defer gpa.free(f.bytes); + if (f.arr.rank != 2 or f.arr.shape[1] != z3.config.codebooks) return error.BadReferenceCodes; + const flat = try f.arr.ints(gpa); + defer gpa.free(flat); + codes = try gpa.alloc([z3.config.codebooks]i32, f.arr.shape[0]); + for (codes, 0..) |*r, j| r.* = flat[j * z3.config.codebooks ..][0..z3.config.codebooks].*; + speaker = .{ .reference = codes }; + } + var p = try z3.prompt.build(gpa, ids, speaker, rel.silence, a.silence_frames); + defer p.deinit(gpa); + var replaced: std.ArrayList(z3.Replace) = .empty; + defer replaced.deinit(gpa); + if (p.speaker_row) |row| { + var r: z3.Replace = .{ .row = row, .vec = undefined }; + e.w.speakerRow(&vec, &r.vec); + try replaced.append(gpa, r); + } + // every condition unknown: the last row of its table + for (0..z3.config.conditions) |c| { + var r: z3.Replace = .{ .row = p.condition_row + c, .vec = undefined }; + @memcpy(&r.vec, e.w.conditions[c][e.c.buckets[c] * D ..][0..D]); + try replaced.append(gpa, r); + } + + const t0 = nowNs(io); + const r = try z3.generation.generate(gpa, e, p.rows, replaced.items, a.sampling, a.max_frames); + defer gpa.free(r.rows); + const t1 = nowNs(io); + const frames = try z3.speech.frames(gpa, p.rows[p.rows.len - p.prefill ..], r.rows, r.eos_frame); + defer gpa.free(frames); + try codec.decode(frames, null); + const pcm = try codec.finish(gpa, null); + defer gpa.free(pcm); + z3.speech.output(pcm, rel.headroom_db); + const t2 = nowNs(io); + if (a.wav) |path| { + const bytes = try z3.speech.wav(gpa, pcm, z3.codec.sample_rate); + defer gpa.free(bytes); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = bytes }); + } + const audio_s = @as(f64, @floatFromInt(pcm.len)) / z3.codec.sample_rate; + const gen_s = @as(f64, @floatFromInt(t1 - t0)) / 1e9; + const dec_s = @as(f64, @floatFromInt(t2 - t1)) / 1e9; + var verdict: []const u8 = "OK"; + if (a.reference) |dir| { + // the reference's prompt, frames and audio for the same request + var want_rows: [][W]i32 = &.{}; + var want_replaced: std.ArrayList(z3.Replace) = .empty; + try loadPrompt(gpa, io, e, dir, &want_rows, &want_replaced); + const same_prompt = want_rows.len == p.rows.len and std.mem.eql(u8, std.mem.sliceAsBytes(want_rows), std.mem.sliceAsBytes(p.rows)); + const rows_path = try std.fs.path.join(gpa, &.{ dir, "rows.npy" }); + const f = try readNpy(gpa, io, rows_path); + const want = try f.arr.ints(gpa); + var same: usize = 0; + while (same < @min(r.rows.len, f.arr.shape[0]) and std.mem.eql(i32, &r.rows[same], want[same * W ..][0..W])) same += 1; + const audio_path = try std.fs.path.join(gpa, &.{ dir, "audio.f32" }); + const raw = try std.Io.Dir.cwd().readFileAlloc(io, audio_path, gpa, .limited(1 << 30)); + const ref = std.mem.bytesAsSlice(f32, @as([]align(1) const u8, raw)); + var noise: f64 = 0; + var signal: f64 = 0; + var max_d: f64 = 0; + for (pcm[0..@min(pcm.len, ref.len)], ref[0..@min(pcm.len, ref.len)]) |x, y| { + noise += (@as(f64, x) - y) * (@as(f64, x) - y); + signal += @as(f64, y) * y; + max_d = @max(max_d, @abs(@as(f64, x) - y)); + } + const snr = 10.0 * @log10(signal / @max(noise, 1e-300)); + const pass = same_prompt and same == f.arr.shape[0] and r.rows.len == f.arr.shape[0] and pcm.len == ref.len and snr >= 60; + verdict = if (pass) "PASS" else "FAIL"; + std.debug.print("reference: prompt_rows_equal={} frames_identical={d}/{d} samples={d}/{d} audio_snr_db={d:.1} max_abs_diff={e:.3}\n", .{ same_prompt, same, f.arr.shape[0], pcm.len, ref.len, snr, max_d }); + } + std.debug.print("RESULT zonos3 speech {s} text_tokens={d} prompt_rows={d} frames={d} eos_frame={?d} audio_s={d:.2} load_s={d:.1} generate_s={d:.3} decode_s={d:.3} x_realtime={d:.1}\n", .{ verdict, ids.len, p.rows.len, r.rows.len, r.eos_frame, audio_s, load_s, gen_s, dec_s, audio_s / (gen_s + dec_s) }); + return if (std.mem.eql(u8, verdict, "FAIL")) 1 else 0; +} + pub fn main(init: std.process.Init) !u8 { const arena = init.arena.allocator(); const gpa = std.heap.c_allocator; @@ -231,13 +362,14 @@ pub fn main(init: std.process.Init) !u8 { var codec_check: ?[]const u8 = null; var generator: []const u8 = ""; var head: []const u8 = ""; + var sp: Speak = .{}; var max_frames: usize = 2000; var opts: z3.Options = .{}; var i: usize = 1; while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } @@ -249,6 +381,14 @@ pub fn main(init: std.process.Init) !u8 { } return codecCheck(gpa, io, dir, generator, head); } + if (sp.checkpoint.len > 0) { + if (i != argv.len or sp.text.len == 0 or (sp.embedding != null and sp.codes != null)) { + std.debug.print("{s}", .{usage}); + return 2; + } + sp.max_frames = max_frames; + return speak(gpa, io, sp); + } const dir = check orelse frames_check orelse { std.debug.print("{s}", .{usage}); return 2; diff --git a/zig/src/families/zonos3/prompt.zig b/zig/src/families/zonos3/prompt.zig new file mode 100644 index 00000000000..e2233d85675 --- /dev/null +++ b/zig/src/families/zonos3/prompt.zig @@ -0,0 +1,158 @@ +//! A request's prompt rows in the training layout: [reference prefix | speaker row] [condition rows] text [silence]. +const std = @import("std"); +const cfg = @import("config.zig"); + +const C = cfg.codebooks; +const W = cfg.frame_width; +const pad = cfg.audio_pad_id; + +pub const bos = 2; +pub const eos = 3; +pub const token_offset = 4; // SuperBPE id + 4 is the text id + +/// The voice: a 192-d embedding in the speaker row, or reference codes [frames][10] as a delayed prefix. +pub const Speaker = union(enum) { + none, + embedding, + reference: []const [C]i32, +}; + +pub const Prompt = struct { + rows: [][W]i32, + speaker_row: ?usize, // the row the speaker projection replaces + condition_row: usize, // the first of the condition rows + prefill: usize, // silence rows at the end: decoded as left context with the generated frames + + pub fn deinit(p: *Prompt, gpa: std.mem.Allocator) void { + gpa.free(p.rows); + } +}; + +fn blank() [W]i32 { + var r: [W]i32 = @splat(pad); + r[C] = cfg.text_vocab; + return r; +} + +/// Row `i` of `frames` code frames delayed a row a codebook: codebook j holds frame i - j, padding outside. +fn delayed(codes: []const [C]i32, i: usize) [W]i32 { + var r = blank(); + for (0..C) |j| if (i >= j and i - j < codes.len) { + r[j] = codes[i - j][j]; + }; + return r; +} + +/// `ids`: the text's SuperBPE ids. `silence`: the codec's silence frame, `silence_frames` of it prefilled (0: none). +pub fn build(gpa: std.mem.Allocator, ids: []const u32, speaker: Speaker, silence: [C]i32, silence_frames: usize) !Prompt { + if (ids.len == 0) return error.EmptyText; + var rows: std.ArrayList([W]i32) = .empty; + errdefer rows.deinit(gpa); + var speaker_row: ?usize = null; + switch (speaker) { + .none => {}, + .embedding => { + speaker_row = 0; + try rows.append(gpa, blank()); + }, + .reference => |codes| { + if (codes.len == 0) return error.EmptyReference; + for (codes) |row| for (row) |code| if (code < 0 or code >= cfg.codebook_size) return error.BadReferenceCode; + // the delayed codes and their flushed tail + for (0..codes.len + C - 1) |i| try rows.append(gpa, delayed(codes, i)); + }, + } + const condition_row = rows.items.len; + for (0..cfg.conditions) |_| try rows.append(gpa, blank()); + var text = blank(); + text[C] = bos; + try rows.append(gpa, text); + for (ids) |id| { + if (id + token_offset >= cfg.text_vocab) return error.BadTextToken; + text[C] = @intCast(id + token_offset); + try rows.append(gpa, text); + } + text[C] = eos; + try rows.append(gpa, text); + // the silence frame repeated, delayed, without its flushed tail: generation continues the delay pattern + for (0..silence_frames) |i| { + var r = blank(); + for (0..@min(i + 1, C)) |j| r[j] = silence[j]; + try rows.append(gpa, r); + } + return .{ .rows = try rows.toOwnedSlice(gpa), .speaker_row = speaker_row, .condition_row = condition_row, .prefill = silence_frames }; +} + +fn isSpace(c: u21) bool { + return switch (c) { + 0x09...0x0d, 0x1c...0x20, 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, + else => false, + }; +} + +/// A run of whitespace that holds anything but plain spaces becomes one space (caller frees). +pub fn collapseLineBreaks(gpa: std.mem.Allocator, text: []const u8) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + const view = try std.unicode.Utf8View.init(text); + var it = view.iterator(); + var run_start: ?usize = null; + var run_break = false; + var at: usize = 0; + while (it.nextCodepointSlice()) |slice| : (at += slice.len) { + const c = std.unicode.utf8Decode(slice) catch unreachable; + if (isSpace(c)) { + if (run_start == null) run_start = at; + run_break = run_break or c != ' '; + continue; + } + if (run_start) |s| { + try out.appendSlice(gpa, if (run_break) " " else text[s..at]); + run_start = null; + run_break = false; + } + try out.appendSlice(gpa, slice); + } + if (run_start) |s| try out.appendSlice(gpa, if (run_break) " " else text[s..]); + return out.toOwnedSlice(gpa); +} + +test "prompt: an embedding voice gives the speaker row, three condition rows, the text and the silence rows" { + const t = std.testing; + const silence: [C]i32 = .{ 1918, 746, 3544, 234, 1267, 2914, 3944, 2849, 326, 1337 }; + var p = try build(t.allocator, &.{ 1138, 7 }, .embedding, silence, 3); + defer p.deinit(t.allocator); + try t.expectEqual(@as(usize, 1 + 3 + 4 + 3), p.rows.len); + try t.expectEqual(@as(?usize, 0), p.speaker_row); + try t.expectEqual(@as(usize, 1), p.condition_row); + try t.expectEqual(@as(i32, bos), p.rows[4][C]); + try t.expectEqual(@as(i32, 1142), p.rows[5][C]); + try t.expectEqual(@as(i32, eos), p.rows[7][C]); + try t.expectEqualSlices(i32, &.{ 1918, pad, pad }, p.rows[8][0..3]); + try t.expectEqualSlices(i32, &.{ 1918, 746, 3544, pad }, p.rows[10][0..4]); + try t.expectEqual(@as(i32, cfg.text_vocab), p.rows[10][C]); +} + +test "prompt: reference codes are delayed a row a codebook and flushed with padding" { + const t = std.testing; + var codes: [2][C]i32 = undefined; + for (&codes, 0..) |*row, f| for (row, 0..) |*code, j| { + code.* = @intCast(100 * (f + 1) + j); + }; + var p = try build(t.allocator, &.{5}, .{ .reference = &codes }, @splat(0), 0); + defer p.deinit(t.allocator); + try t.expectEqual(@as(usize, 2 + C - 1 + 3 + 3), p.rows.len); + try t.expectEqual(@as(?usize, null), p.speaker_row); + try t.expectEqual(@as(usize, 11), p.condition_row); + try t.expectEqualSlices(i32, &.{ 100, pad }, p.rows[0][0..2]); + try t.expectEqualSlices(i32, &.{ 200, 101, pad }, p.rows[1][0..3]); + try t.expectEqualSlices(i32, &.{ pad, 201, 102 }, p.rows[2][0..3]); + try t.expectEqual(@as(i32, 209), p.rows[10][9]); +} + +test "collapseLineBreaks: breaks become a space, runs of plain spaces stay" { + const t = std.testing; + const got = try collapseLineBreaks(t.allocator, "one two\n\nthree \t four\n"); + defer t.allocator.free(got); + try t.expectEqualStrings("one two three four ", got); +} diff --git a/zig/src/families/zonos3/release.zig b/zig/src/families/zonos3/release.zig new file mode 100644 index 00000000000..6ef73a04465 --- /dev/null +++ b/zig/src/families/zonos3/release.zig @@ -0,0 +1,103 @@ +//! Where a ZONOS3 Mini release keeps its parts, read from the release's own registries: the checkpoint folder is a +//! snapshot of the Hugging Face repo, whose registries name its files by their path inside it. +const std = @import("std"); +const cfg = @import("config.zig"); + +pub const lm_dir = "lm/zonos3_mini"; +/// The reference servers' default decoder: the pruned multi-resolution iSTFT head. +pub const default_decoder = "keep2_plain"; +/// A decoder's registry: codec_registry.json, or codec_registry_.json. +const registries = [_][]const u8{ "registries/codec_registry.json", "registries/codec_registry_{s}.json" }; + +pub const Release = struct { + arena: std.heap.ArenaAllocator, + root: []const u8, + lm: []const u8, // params.json, model.pth and the tokenizer + tokenizer: []const u8, + generator: []const u8, + head: []const u8, // the chosen decoder's checkpoint + decoder: []const u8, + silence: [cfg.codebooks]i32, // the codec's frame of digital silence + headroom_db: f32, + + pub fn deinit(r: *Release) void { + r.arena.deinit(); + } +}; + +/// A registry's path inside the release: relative, never out of the folder. +fn inside(path: []const u8) ![]const u8 { + if (path.len == 0 or path[0] == '/' or std.mem.indexOf(u8, path, "..") != null or std.mem.indexOf(u8, path, "://") != null) return error.BadRegistry; + return path; +} + +fn string(o: std.json.ObjectMap, name: []const u8) ![]const u8 { + const v = o.get(name) orelse return error.BadRegistry; + return if (v == .string) v.string else error.BadRegistry; +} + +fn readJson(a: std.mem.Allocator, io: std.Io, path: []const u8) !std.json.ObjectMap { + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 22)); + const doc = try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}); + return if (doc == .object) doc.object else error.BadRegistry; +} + +/// `decoder`: a decoder id (the folder of its head under autoencoder/heads), or null for the default. +pub fn open(gpa: std.mem.Allocator, io: std.Io, root: []const u8, decoder: ?[]const u8) !Release { + var arena = std.heap.ArenaAllocator.init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const id = decoder orelse default_decoder; + for (id) |ch| if (!std.ascii.isAlphanumeric(ch) and ch != '_' and ch != '-') return error.NoSuchDecoder; + const lm = try std.fs.path.join(a, &.{ root, lm_dir }); + const model = (try readJson(a, io, try std.fs.path.join(a, &.{ lm, "params.json" }))).get("model") orelse return error.BadConfig; + const codec = try string(model.object, "audio_codec"); + const spec = model.object.get("text_tokenizer_spec") orelse return error.BadConfig; + const tokenizer = try std.fs.path.join(a, &.{ lm, try inside(try string(spec.object, "path")) }); + + var r: Release = .{ .arena = undefined, .root = try a.dupe(u8, root), .lm = lm, .tokenizer = tokenizer, .generator = "", .head = "", .decoder = try a.dupe(u8, id), .silence = undefined, .headroom_db = 0 }; + var found = false; + for (registries) |pattern| { + const name = if (std.mem.indexOf(u8, pattern, "{s}") != null) try std.fmt.allocPrint(a, "registries/codec_registry_{s}.json", .{id}) else pattern; + const doc = readJson(a, io, try std.fs.path.join(a, &.{ root, name })) catch |e| switch (e) { + error.FileNotFound => continue, + else => return e, + }; + var it = doc.iterator(); + while (it.next()) |e| { + if (e.value_ptr.* != .object) continue; + const entry = e.value_ptr.object; + if (!std.mem.eql(u8, string(entry, "codec") catch "", codec)) continue; + const d = (entry.get("decoder") orelse continue).object; + const campaign = try inside(try string(d, "campaign")); + if (!std.mem.eql(u8, std.fs.path.basename(campaign), id)) continue; + r.generator = try std.fs.path.join(a, &.{ root, try inside(try string(entry, "checkpoint")) }); + r.head = try std.fs.path.join(a, &.{ root, campaign, try inside(try string(d, "checkpoint")) }); + if (d.get("headroom_db")) |h| r.headroom_db = switch (h) { + .float => |f| @floatCast(f), + .integer => |n| @floatFromInt(n), + else => return error.BadRegistry, + }; + found = true; + } + } + if (!found) return error.NoSuchDecoder; + const silence = try readJson(a, io, try std.fmt.allocPrint(a, "{s}/registries/silence_frame_{s}.json", .{ root, try inside(codec) })); + const frame = silence.get("frame") orelse return error.BadRegistry; + if (frame != .array or frame.array.items.len != cfg.codebooks) return error.BadRegistry; + for (&r.silence, frame.array.items) |*code, v| { + if (v != .integer or v.integer < 0 or v.integer >= cfg.codebook_size) return error.BadRegistry; + code.* = @intCast(v.integer); + } + r.arena = arena; + return r; +} + +test "inside: a path in the release, never out of the folder" { + const t = std.testing; + try t.expectEqualStrings("autoencoder/generator.pt", try inside("autoencoder/generator.pt")); + try t.expectError(error.BadRegistry, inside("autoencoder/../../x")); + try t.expectError(error.BadRegistry, inside("/abs/path")); + try t.expectError(error.BadRegistry, inside("hf://owner/repo/x")); + try t.expectError(error.BadRegistry, inside("")); +} diff --git a/zig/src/families/zonos3/speech.zig b/zig/src/families/zonos3/speech.zig new file mode 100644 index 00000000000..75a6f2d8a2e --- /dev/null +++ b/zig/src/families/zonos3/speech.zig @@ -0,0 +1,118 @@ +//! From generated rows to served audio: the undelayed code frames to decode, then the output gain and soft limiter. +const std = @import("std"); +const cfg = @import("config.zig"); + +const C = cfg.codebooks; +const W = cfg.frame_width; + +/// The decoder's headroom: the default output gain is -3 dB. +pub const headroom_db: f32 = 3.0; +/// The limiter's knee, -1 dBFS: samples at or below it pass unchanged. +pub const knee: f32 = 0.8912509381337456; + +/// The frames to decode: the prompt's silence rows `prefill` then `generated`, each codebook's delay removed, up to +/// the first end-of-audio frame (`eos_frame` counts generated rows) or the last complete frame. Caller frees. +pub fn frames(gpa: std.mem.Allocator, prefill: []const [W]i32, generated: []const [W]i32, eos_frame: ?usize) ![][C]i32 { + const n = prefill.len + generated.len; + var target: usize = n -| (C - 1); + if (eos_frame) |f| target = @min(target, f + prefill.len); + for (0..n) |i| { + const row = if (i < prefill.len) prefill[i] else generated[i - prefill.len]; + var last: ?usize = null; + for (row[0..C], 0..) |code, cb| if (code == cfg.eoa_id) { + last = cb; + }; + if (last) |cb| target = @min(target, i -| cb); + } + const out = try gpa.alloc([C]i32, target); + errdefer gpa.free(out); + for (out, 0..) |*frame, f| for (frame, 0..) |*code, cb| { + const i = f + cb; + const row = if (i < prefill.len) prefill[i] else generated[i - prefill.len]; + if (row[cb] < 0 or row[cb] >= cfg.codebook_size) return error.FrameHoldsNoCode; + code.* = row[cb]; + }; + return out; +} + +/// The decoder's samples to the served ones in place: the headroom gain, then the soft limiter above the knee. +pub fn output(pcm: []f32, headroom: f32) void { + const gain: f32 = @floatCast(std.math.pow(f64, 10.0, -@as(f64, headroom) / 20.0)); + const width = 1.0 - knee; + for (pcm) |*s| { + const x = s.* * gain; + const mag = @abs(x); + s.* = if (mag > knee) std.math.copysign(knee + width * std.math.tanh((mag - knee) / width), x) else x; + } +} + +/// Float samples as 16-bit: NaN is 0, clipped to [-1, 1], times 32767, rounded half to even. +pub fn pcm16(x: f32) i16 { + if (std.math.isNan(x)) return 0; + const v = @min(@max(x, -1.0), 1.0) * 32767.0; + const r = @round(v); + const even = if (@abs(v - @trunc(v)) == 0.5) 2.0 * @round(v / 2.0) else r; + return @intFromFloat(even); +} + +/// A mono 16-bit WAV file's bytes (caller frees). +pub fn wav(gpa: std.mem.Allocator, pcm: []const f32, rate: u32) ![]u8 { + const data: u32 = @intCast(pcm.len * 2); + const out = try gpa.alloc(u8, 44 + data); + @memcpy(out[0..4], "RIFF"); + std.mem.writeInt(u32, out[4..8], 36 + data, .little); + @memcpy(out[8..16], "WAVEfmt "); + std.mem.writeInt(u32, out[16..20], 16, .little); + std.mem.writeInt(u16, out[20..22], 1, .little); + std.mem.writeInt(u16, out[22..24], 1, .little); + std.mem.writeInt(u32, out[24..28], rate, .little); + std.mem.writeInt(u32, out[28..32], rate * 2, .little); + std.mem.writeInt(u16, out[32..34], 2, .little); + std.mem.writeInt(u16, out[34..36], 16, .little); + @memcpy(out[36..40], "data"); + std.mem.writeInt(u32, out[40..44], data, .little); + for (pcm, 0..) |x, i| std.mem.writeInt(i16, out[44 + 2 * i ..][0..2], pcm16(x), .little); + return out; +} + +test "frames: the delay comes off, and the first end-of-audio code bounds the audio" { + const t = std.testing; + var rows: [14][W]i32 = undefined; + for (&rows, 0..) |*row, i| { + for (row[0..C], 0..) |*code, cb| code.* = if (i >= cb) @intCast(10 * (i - cb) + cb) else cfg.audio_pad_id; + row[C] = cfg.text_vocab; + } + const all = try frames(t.allocator, rows[0..2], rows[2..], null); + defer t.allocator.free(all); + try t.expectEqual(@as(usize, 5), all.len); + for (all, 0..) |frame, f| for (frame, 0..) |code, cb| try t.expectEqual(@as(i32, @intCast(10 * f + cb)), code); + rows[6][1] = cfg.eoa_id; // frame 5 of codebook 1: the audio ends before frame 5 + rows[6][0] = cfg.eoa_id; + const cut = try frames(t.allocator, rows[0..2], rows[2..], 4); + defer t.allocator.free(cut); + try t.expectEqual(@as(usize, 5), cut.len); + const early = try frames(t.allocator, rows[0..2], rows[2..], 1); + defer t.allocator.free(early); + try t.expectEqual(@as(usize, 3), early.len); +} + +test "output: the gain applies, quiet samples pass and loud ones bend below full scale" { + const t = std.testing; + var pcm = [_]f32{ 0.5, -0.5, 3.0, -3.0 }; + output(&pcm, 0); + try t.expectEqual(@as(f32, 0.5), pcm[0]); + try t.expectEqual(@as(f32, -0.5), pcm[1]); + try t.expect(pcm[2] > knee and pcm[2] <= 1.0); + try t.expectEqual(-pcm[2], pcm[3]); + var half = [_]f32{1.0}; + output(&half, 6.0205999); + try t.expectApproxEqAbs(@as(f32, 0.5), half[0], 1e-6); +} + +test "pcm16: rounds half to even and clips" { + const t = std.testing; + try t.expectEqual(@as(i16, 32767), pcm16(2.0)); + try t.expectEqual(@as(i16, -32767), pcm16(-1.0)); + try t.expectEqual(@as(i16, 0), pcm16(std.math.nan(f32))); + try t.expectEqual(@as(i16, 2), pcm16(2.5 / 32767.0)); +} diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index 5a715657082..1de11d332ed 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -3,6 +3,9 @@ pub const config = @import("config.zig"); pub const npy = @import("npy.zig"); pub const sampler = @import("sampler.zig"); pub const generation = @import("generation.zig"); +pub const prompt = @import("prompt.zig"); +pub const speech = @import("speech.zig"); +pub const release = @import("release.zig"); pub const weights = @import("cuda/weights.zig"); pub const kernels = @import("cuda/kernels.zig"); pub const engine = @import("cuda/engine.zig"); @@ -21,5 +24,8 @@ test { _ = npy; _ = sampler; _ = generation; + _ = prompt; + _ = speech; + _ = release; _ = codec_weights; } From f7fc8e96a7f5ac4920d06112cb71de447df61b38 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:38:06 +0000 Subject: [PATCH 310/361] zonos3: one-line comments --- zig/kernels/cuda/zonos3.cu | 12 ++++-------- zig/kernels/cuda/zonos3_codec.cu | 12 ++++-------- zig/src/families/zonos3/cuda/codec.zig | 3 +-- zig/src/families/zonos3/cuda/codec_weights.zig | 3 +-- zig/src/families/zonos3/cuda/engine.zig | 6 ++---- zig/src/families/zonos3/release.zig | 3 +-- zig/src/families/zonos3/sampler.zig | 6 ++---- zig/src/families/zonos3/speech.zig | 3 +-- 8 files changed, 16 insertions(+), 32 deletions(-) diff --git a/zig/kernels/cuda/zonos3.cu b/zig/kernels/cuda/zonos3.cu index d0ebe4cd91e..b876bbb7714 100644 --- a/zig/kernels/cuda/zonos3.cu +++ b/zig/kernels/cuda/zonos3.cu @@ -93,8 +93,7 @@ extern "C" __global__ void __launch_bounds__(256) z3_attnres(const float* __rest } } -// y[r, n] = sum_k W[n, k] x[r / xrep, k] (+ bias[n]): W bf16 [N, K], K a multiple of 8. A warp an output, x staged -// in K * 4 bytes of dynamic shared. With picks, row r reads W + picks[r] * pick_stride. +// y[r, n] = sum_k W[n, k] x[r / xrep, k] (+ bias[n]): bf16 W [N, K], K % 8 == 0; picks move row r's W by picks[r]. extern "C" __global__ void __launch_bounds__(256) z3_linear(const bf16* __restrict__ W, const float* __restrict__ x, int x_stride, int xrep, int K, int N, float* __restrict__ y, int y_stride, @@ -139,8 +138,7 @@ extern "C" __global__ void z3_conv_silu(const float* __restrict__ proj, int ps, state[c * 3 + 2] = s2; } -// A row's GDN inputs for head blockIdx.y: l2-normed q (scaled by 128^-1/2) and k in place, decay and beta. -// conv is [T][3 * 512] (q | k | v); proj rows hold a at a_off + h and b at a_off + 4 + h. +// GDN inputs of (row, head): q (l2-normed, times 128^-1/2) and k in place in conv [T][q | k | v]; decay and beta. extern "C" __global__ void __launch_bounds__(128) z3_gdn_prep(float* __restrict__ conv, const float* __restrict__ proj, int ps, int a_off, const bf16* __restrict__ A_log, const bf16* __restrict__ dt_bias, @@ -201,8 +199,7 @@ extern "C" __global__ void __launch_bounds__(128) z3_gated_norm(const float* __r y[(size_t)t * 512 + h * 128 + i] = x * inv * b2f(w[i]) * tf_common::silu(proj[(size_t)t * ps + z_off + h * 128 + i]); } -// Attention inputs of row blockIdx.x at position pos0 + row: q [16][32] rms-normed, scaled by |temp| and rotated in -// place; k [4][32] rms-normed and rotated into the cache row, v copied. A warp a head; pairs rotate (2m, 2m + 1). +// Attention inputs of a row at pos0 + row: q rms-normed, times |temp|, rotated in place; k and v to the caches. extern "C" __global__ void __launch_bounds__(512) z3_attn_prep(float* __restrict__ q, const float* __restrict__ kv, const bf16* __restrict__ temp, int pos0, float* __restrict__ kc, float* __restrict__ vc, @@ -228,8 +225,7 @@ extern "C" __global__ void __launch_bounds__(512) z3_attn_prep(float* __restrict } } -// Causal attention of (row blockIdx.x, head blockIdx.y) over cache rows 0 .. pos0 + row, then the head's sigmoid gate. -// Keys go to threads by index mod 256 and the block folds in a fixed order, so a row's bits depend on its position. +// Causal attention of (row, head) over cache rows 0 .. pos0 + row, gated; keys by index mod 256, a fixed fold. extern "C" __global__ void __launch_bounds__(256) z3_attention(const float* __restrict__ q, const float* __restrict__ kc, const float* __restrict__ vc, diff --git a/zig/kernels/cuda/zonos3_codec.cu b/zig/kernels/cuda/zonos3_codec.cu index b1c63c12297..c6480b2e62f 100644 --- a/zig/kernels/cuda/zonos3_codec.cu +++ b/zig/kernels/cuda/zonos3_codec.cu @@ -1,5 +1,4 @@ -// ours: ZONOS3's codec decoder (ZAC) on CUDA in fp32: causal transformer stages, ConvNeXt blocks and the -// multi-resolution iSTFT tail. A row or sample depends only on its position, never on how a stream was chunked. +// ours: ZONOS3's codec decoder on CUDA in fp32; a row or sample depends on its position, never on a stream's chunks. #include #include #include "common/reduce.cuh" @@ -49,8 +48,7 @@ extern "C" __global__ void __launch_bounds__(256) zc_layernorm(const float* __re for (int i = threadIdx.x; i < D; i += blockDim.x) yr[i] = (xr[i] - mean) * inv * w[i] + b[i]; } -// Rows of [q | k | v] (each D = heads * 64) at positions pos0 + row: q and k rotate in adjacent pairs, in place; -// the rotated k and v go to the caches' row pos0 + row. A block a (row, head), a thread a pair. +// Rows [q | k | v] (each D = heads * 64) at pos0 + row: q and k rotate in adjacent pairs; k and v go to the cache row. extern "C" __global__ void __launch_bounds__(32) zc_attn_prep(float* __restrict__ qkv, int D, int pos0, float* __restrict__ kc, float* __restrict__ vc) { const int t = blockIdx.x, h = blockIdx.y, m = threadIdx.x; @@ -69,8 +67,7 @@ extern "C" __global__ void __launch_bounds__(32) zc_attn_prep(float* __restrict_ vc[at + 1] = q[2 * D + 1]; } -// Causal local attention of (row, head) at position p = pos0 + row over cache rows max(0, p - ctx + 1) .. p. -// Keys go to threads by offset from the window's first row, and the block folds in a fixed order. +// Causal local attention of (row, head) at p = pos0 + row over cache rows max(0, p - ctx + 1) .. p, in a fixed order. extern "C" __global__ void __launch_bounds__(128) zc_attention(const float* __restrict__ qkv, int D, const float* __restrict__ kc, const float* __restrict__ vc, int pos0, int ctx, @@ -193,8 +190,7 @@ extern "C" __global__ void zc_spec(float* __restrict__ y, int half) { r[half + i] = mag * sinf(ph); } -// Centered overlap-add of windowed frames [F][N] at hop: out[i] is sample n0 + i, frames in ascending order, over the -// window envelope (win2 = window squared) of the same frames. +// Centered overlap-add of windowed frames [F][N] at hop: out[i] is sample n0 + i over the same frames' window envelope. extern "C" __global__ void zc_ola(const float* __restrict__ frames, const float* __restrict__ win2, int F, int N, int hop, long long n0, long long count, float* __restrict__ out) { const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig index 8451112bb23..6adb119aefb 100644 --- a/zig/src/families/zonos3/cuda/codec.zig +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -1,5 +1,4 @@ -//! ZONOS3's codec decoder on one GPU: undelayed code frames [n][10] in, 44.1 kHz fp32 samples out. The trunk keeps -//! its state (ConvNeXt histories, each transformer layer's keys and values), so frames may arrive in any chunks. +//! ZONOS3's codec decoder on one GPU: code frames [n][10] in any chunks (the trunk keeps its state), 44.1 kHz fp32 out. const std = @import("std"); const cuda = @import("cuda"); const kern = @import("codec_kernels.zig"); diff --git a/zig/src/families/zonos3/cuda/codec_weights.zig b/zig/src/families/zonos3/cuda/codec_weights.zig index 1ecaea3b60b..dff6148d8c5 100644 --- a/zig/src/families/zonos3/cuda/codec_weights.zig +++ b/zig/src/families/zonos3/cuda/codec_weights.zig @@ -1,5 +1,4 @@ -//! The codec decoder's weights as published (fp32): the generator's quantizer, semantic head and resampler, and a -//! head checkpoint's decoder stages and iSTFT head. Weight norms and the code tables are folded once on the host. +//! The codec decoder's published fp32 weights (generator.pt, a head checkpoint); weight norms and code tables folded. const std = @import("std"); const cuda = @import("cuda"); const pth = @import("torch_pth"); diff --git a/zig/src/families/zonos3/cuda/engine.zig b/zig/src/families/zonos3/cuda/engine.zig index 55318d7c56d..fa44709a48e 100644 --- a/zig/src/families/zonos3/cuda/engine.zig +++ b/zig/src/families/zonos3/cuda/engine.zig @@ -1,5 +1,4 @@ -//! ZONOS3 Mini's backbone on one GPU: frame rows in, the next frame's logits out; the prompt and each decode row run -//! the same row kernels in fp32, so a row's bits do not depend on how the rows before it were chunked. +//! ZONOS3 Mini's backbone on one GPU: frame rows in, the next frame's logits out, one fp32 row path for all rows. const std = @import("std"); const cuda = @import("cuda"); const cfg = @import("../config.zig"); @@ -205,8 +204,7 @@ pub const Engine = struct { return e.bank + source * e.o.max_rows * D * 4; } - /// The next rows (int32 [n][11]) at the current position; afterwards `logits` holds the last row's - /// [codebooks][audio_vocab] (every row's under a probe, which needs the rows in one pass). + /// The next rows at the current position; `logits` then holds the last row's (every row's under a one-pass probe). pub fn run(e: *Engine, rows: []const [W]i32, replaced: []const Replace, probe: ?Probe) !void { if (rows.len == 0) return error.NoRows; if (e.position + rows.len > e.o.max_ctx) return error.ContextFull; diff --git a/zig/src/families/zonos3/release.zig b/zig/src/families/zonos3/release.zig index 6ef73a04465..79bfcf4bd97 100644 --- a/zig/src/families/zonos3/release.zig +++ b/zig/src/families/zonos3/release.zig @@ -1,5 +1,4 @@ -//! Where a ZONOS3 Mini release keeps its parts, read from the release's own registries: the checkpoint folder is a -//! snapshot of the Hugging Face repo, whose registries name its files by their path inside it. +//! Where a ZONOS3 Mini release (a snapshot of its Hugging Face repo) keeps its parts, read from its own registries. const std = @import("std"); const cfg = @import("config.zig"); diff --git a/zig/src/families/zonos3/sampler.zig b/zig/src/families/zonos3/sampler.zig index aef729ed58f..29c1e55c3aa 100644 --- a/zig/src/families/zonos3/sampler.zig +++ b/zig/src/families/zonos3/sampler.zig @@ -1,5 +1,4 @@ -//! ZONOS3's frame sampler on the host, the reference's sample_tts for one request: specials masked, a repetition -//! penalty over each codebook's recent codes, temperature, top-k, top-p and min-p, then one draw a codebook. +//! ZONOS3's frame sampler on the host: specials masked, repetition penalty, temperature, top-k, top-p, min-p, one draw. const std = @import("std"); const cfg = @import("config.zig"); @@ -46,8 +45,7 @@ fn argmax(x: []const f32) usize { return best; } -/// Frame `frame`'s codes from its logits [codebooks][audio_vocab] (overwritten). `recent` holds the generated rows so -/// far, oldest first; `stop` is the one special id a codebook may draw. +/// Frame `frame`'s codes from its logits (overwritten); `recent`: generated rows, oldest first; `stop`: the end id. pub fn sample(logits: *[C][V]f32, recent: []const [C]i32, frame: u64, stop: i32, sampling: Sampling) [C]i32 { const s = sampling.clamped(); const window: usize = if (s.repetition_window > 0 and s.repetition_penalty > 1.0 and s.repetition_codebooks > 0) @min(s.repetition_window, recent.len) else 0; diff --git a/zig/src/families/zonos3/speech.zig b/zig/src/families/zonos3/speech.zig index 75a6f2d8a2e..00149a63efb 100644 --- a/zig/src/families/zonos3/speech.zig +++ b/zig/src/families/zonos3/speech.zig @@ -10,8 +10,7 @@ pub const headroom_db: f32 = 3.0; /// The limiter's knee, -1 dBFS: samples at or below it pass unchanged. pub const knee: f32 = 0.8912509381337456; -/// The frames to decode: the prompt's silence rows `prefill` then `generated`, each codebook's delay removed, up to -/// the first end-of-audio frame (`eos_frame` counts generated rows) or the last complete frame. Caller frees. +/// The frames to decode: `prefill` then `generated` rows undelayed, up to the first end of audio or last whole frame. pub fn frames(gpa: std.mem.Allocator, prefill: []const [W]i32, generated: []const [W]i32, eos_frame: ?usize) ![][C]i32 { const n = prefill.len + generated.len; var target: usize = n -| (C - 1); From 29bb4c5d411b4b706d798ed748040cdb2e0f8360 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:38:16 +0000 Subject: [PATCH 311/361] zonos3: served on /v1/audio/speech: a one-lane CUDA host, the release's default voices, its sampling defaults ZONOS3 reads its checkpoints through core's torch.save reader. A release folder has no config.json: it is recognised by lm/zonos3_mini/params.json and its tokenizer loads from there. The speech request gains an optional speaker vector. A release's voices are its own (the server's `zonos` beside Drama 3's voice store), so --voices, --request-voices and --manage-voices are refused with it. --- zig/build/cuda_engines.zig | 1 + zig/build/server.zig | 16 + zig/build/zonos3.zig | 5 +- zig/src/core/root.zig | 2 +- zig/src/core/speech_api.zig | 2 + .../families/zonos3/cuda/codec_weights.zig | 2 +- zig/src/families/zonos3/cuda/weights.zig | 2 +- zig/src/families/zonos3/release.zig | 15 + zig/src/families/zonos3/request.zig | 20 ++ zig/src/families/zonos3/voices.zig | 87 +++++ zig/src/families/zonos3/zonos3.zig | 2 + zig/src/native/cuda_families.zig | 6 +- zig/src/native/cuda_open.zig | 3 +- zig/src/native/cuda_refusal.zig | 4 +- zig/src/native/zonos_host.zig | 312 ++++++++++++++++++ zig/src/native/zonos_open.zig | 56 ++++ zig/src/server/hf_text.zig | 2 +- zig/src/server/main.zig | 3 +- zig/src/server/server.zig | 1 + zig/src/server/speech.zig | 11 +- zig/src/server/speech_voices.zig | 11 +- zig/src/server/zonos_speech.zig | 82 +++++ 22 files changed, 628 insertions(+), 17 deletions(-) create mode 100644 zig/src/families/zonos3/request.zig create mode 100644 zig/src/families/zonos3/voices.zig create mode 100644 zig/src/native/zonos_host.zig create mode 100644 zig/src/native/zonos_open.zig create mode 100644 zig/src/server/zonos_speech.zig diff --git a/zig/build/cuda_engines.zig b/zig/build/cuda_engines.zig index e2ab77a0eb3..f0974d84f2f 100644 --- a/zig/build/cuda_engines.zig +++ b/zig/build/cuda_engines.zig @@ -76,6 +76,7 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .{ .name = "lanes", .module = lanes }, .{ .name = "nemotron", .module = nemotron }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, core) }, + .{ .name = "zonos3", .module = @import("zonos3.zig").module(b, target, optimize, cuda, core) }, .{ .name = "lfm2", .module = lfm2Module(b, target, optimize, cuda, core) }, .{ .name = "core", .module = core }, .{ .name = "flashnext", .module = flashnextModule(b, target, optimize, cuda, core, lanes, qwen_vision, api) }, diff --git a/zig/build/server.zig b/zig/build/server.zig index 6b156cf77ab..5de4163416b 100644 --- a/zig/build/server.zig +++ b/zig/build/server.zig @@ -80,6 +80,22 @@ pub fn addTo( .imports = &.{.{ .name = "json", .module = j }}, })); m.addImport("uocr_chat", b.createModule(.{ .root_source_file = b.path("zig/src/families/uocr/chat.zig"), .target = target, .optimize = optimize })); + // the engines' own ZONOS3 family when the build has one (a file belongs to one module), else its host half alone + if (if (m.import_table.get("native_engines")) |engines| engines.import_table.get("zonos3") else null) |zonos3| { + const source = b.addWriteFiles().add("zonos_request.zig", + \\const r = @import("zonos3").request; + \\pub const config = r.config; + \\pub const prompt = r.prompt; + \\pub const release = r.release; + \\pub const voices = r.voices; + \\pub const temperature = r.temperature; + \\pub const top_p = r.top_p; + \\pub const top_k = r.top_k; + \\pub const silence_frames = r.silence_frames; + \\pub const reference_frames = r.reference_frames; + ); + m.addImport("zonos_request", b.createModule(.{ .root_source_file = source, .target = target, .optimize = optimize, .imports = &.{.{ .name = "zonos3", .module = zonos3 }} })); + } else m.addImport("zonos_request", b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/request.zig"), .target = target, .optimize = optimize })); const family = if (m.import_table.get("native_engines")) |engines| engines.import_table.get("drama3") else null; if (family) |drama3| { const source = b.addWriteFiles().add("drama_prompt.zig", diff --git a/zig/build/zonos3.zig b/zig/build/zonos3.zig index e6c7c746bd4..fa8260feeee 100644 --- a/zig/build/zonos3.zig +++ b/zig/build/zonos3.zig @@ -1,10 +1,9 @@ //! ZONOS3 Mini's CUDA family module and its zonos3-generate tool. const std = @import("std"); -/// The family over a runtime and the core; torch_pth is the Python-free .pth reader Drama 3's codec loads with. +/// The family over a runtime and the core. pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) *std.Build.Module { - const pth = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/codec_pth.zig"), .target = target, .optimize = optimize }); - return b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/zonos3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "torch_pth", .module = pth } } }); + return b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/zonos3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); } pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) void { diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 294bb26e702..070b01a5a36 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -30,7 +30,7 @@ pub const CopyIndex = @import("copy_index.zig").CopyIndex; pub const recurrent_workspace = @import("recurrent_workspace.zig"); pub const tokenizer = @import("tokenizer"); // a module of its own, so the native server shares it pub const proposal_rows = @import("proposal_rows.zig"); -pub const torch_pth = @import("torch_pth.zig"); // torch.save archives read without Python: Drama 3's codec +pub const torch_pth = @import("torch_pth.zig"); // torch.save archives read without Python: Drama 3's codec and ZONOS3's checkpoints pub const wav = @import("wav.zig"); // reference clips in, speech out pub const proposal_vocab = @import("proposal_vocab.zig"); pub const ids_json = @import("ids_json.zig"); diff --git a/zig/src/core/speech_api.zig b/zig/src/core/speech_api.zig index 08ac16a7108..e4443eeb1e4 100644 --- a/zig/src/core/speech_api.zig +++ b/zig/src/core/speech_api.zig @@ -19,6 +19,8 @@ pub const SpeechRequest = struct { /// Plain text frame rows for reference-conditioned semantic CFG; empty means no guidance. unconditioned: []const [11]i32 = &.{}, cfg_gamma: f32 = 1, + /// A speaker embedding for the family's speaker row; empty: the prompt rows carry the voice, or there is none. + speaker: []const f32 = &.{}, }; pub const SpeechInfo = struct { diff --git a/zig/src/families/zonos3/cuda/codec_weights.zig b/zig/src/families/zonos3/cuda/codec_weights.zig index dff6148d8c5..f0fe598b00f 100644 --- a/zig/src/families/zonos3/cuda/codec_weights.zig +++ b/zig/src/families/zonos3/cuda/codec_weights.zig @@ -1,7 +1,7 @@ //! The codec decoder's published fp32 weights (generator.pt, a head checkpoint); weight norms and code tables folded. const std = @import("std"); const cuda = @import("cuda"); -const pth = @import("torch_pth"); +const pth = @import("core").torch_pth; pub const latent_dim = 1024; pub const width = 768; // the semantic head's and the iSTFT head's width, and stages 2..8's diff --git a/zig/src/families/zonos3/cuda/weights.zig b/zig/src/families/zonos3/cuda/weights.zig index 72ccf65a50b..c714dd1e6e9 100644 --- a/zig/src/families/zonos3/cuda/weights.zig +++ b/zig/src/families/zonos3/cuda/weights.zig @@ -1,7 +1,7 @@ //! ZONOS3 Mini's weights as published (model.pth, bf16) on the device; the speaker and condition rows stay on the host. const std = @import("std"); const cuda = @import("cuda"); -const pth = @import("torch_pth"); +const pth = @import("core").torch_pth; const cfg = @import("../config.zig"); const D = cfg.dim; diff --git a/zig/src/families/zonos3/release.zig b/zig/src/families/zonos3/release.zig index 79bfcf4bd97..50a4ae45786 100644 --- a/zig/src/families/zonos3/release.zig +++ b/zig/src/families/zonos3/release.zig @@ -3,6 +3,8 @@ const std = @import("std"); const cfg = @import("config.zig"); pub const lm_dir = "lm/zonos3_mini"; +/// The SuperBPE tokenizer params.json names, inside the language model's folder. +pub const tokenizer_file = "tokenizer/superbpe8192.json"; /// The reference servers' default decoder: the pruned multi-resolution iSTFT head. pub const default_decoder = "keep2_plain"; /// A decoder's registry: codec_registry.json, or codec_registry_.json. @@ -41,6 +43,19 @@ fn readJson(a: std.mem.Allocator, io: std.Io, path: []const u8) !std.json.Object return if (doc == .object) doc.object else error.BadRegistry; } +/// Whether `root` is a ZONOS3 Mini release: it has no config.json, its model's params.json sits under lm/. +pub fn present(io: std.Io, root: []const u8) bool { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = std.fmt.bufPrint(&buf, "{s}/" ++ lm_dir ++ "/params.json", .{root}) catch return false; + std.Io.Dir.cwd().access(io, path, .{}) catch return false; + return true; +} + +/// Where `root`'s tokenizer loads from: a release keeps it beside its language model, any other checkpoint at its root. +pub fn tokenizerAt(a: std.mem.Allocator, io: std.Io, root: []const u8) ![]const u8 { + return if (present(io, root)) std.fs.path.join(a, &.{ root, lm_dir, tokenizer_file }) else root; +} + /// `decoder`: a decoder id (the folder of its head under autoencoder/heads), or null for the default. pub fn open(gpa: std.mem.Allocator, io: std.Io, root: []const u8, decoder: ?[]const u8) !Release { var arena = std.heap.ArenaAllocator.init(gpa); diff --git a/zig/src/families/zonos3/request.zig b/zig/src/families/zonos3/request.zig new file mode 100644 index 00000000000..89bbafb4563 --- /dev/null +++ b/zig/src/families/zonos3/request.zig @@ -0,0 +1,20 @@ +//! What a server needs to turn a speech request into ZONOS3 Mini's prompt rows, with no GPU code behind it. +pub const config = @import("config.zig"); +pub const prompt = @import("prompt.zig"); +pub const release = @import("release.zig"); +pub const voices = @import("voices.zig"); + +/// The release's sampling defaults (registries/generation.json). +pub const temperature: f32 = 0.75; +pub const top_p: f32 = 0.69; +pub const top_k: u32 = 80; +/// Silence frames prefilled after the text: the reference servers' default. +pub const silence_frames = 3; +/// The longest reference prefix: 60 s of the codec's 15 frames a second. +pub const reference_frames = 900; + +test { + _ = prompt; + _ = release; + _ = voices; +} diff --git a/zig/src/families/zonos3/voices.zig b/zig/src/families/zonos3/voices.zig new file mode 100644 index 00000000000..f18474e015f --- /dev/null +++ b/zig/src/families/zonos3/voices.zig @@ -0,0 +1,87 @@ +//! A release's default voices (gguf/voices//.codes.npy and .embedding.npy), ready without an encoder. +const std = @import("std"); +const cfg = @import("config.zig"); +const npy = @import("npy.zig"); + +pub const dir = "gguf/voices"; +pub const max_voices = 256; + +pub const Voice = struct { + name: []const u8, // the clip's first word in lower case, e.g. "savannah" + clip: []const u8, // the clip's file stem, e.g. "Savannah_en-American_F_1" + language: []const u8, // the folder it sits in + codes: []const [cfg.codebooks]i32, // the clip in the codec's codes: the reference prefix + embedding: [cfg.speaker_dim]f32, +}; + +fn lower(a: std.mem.Allocator, s: []const u8) ![]u8 { + const out = try a.dupe(u8, s); + for (out) |*c| c.* = std.ascii.toLower(c.*); + return out; +} + +fn one(a: std.mem.Allocator, io: std.Io, folder: std.Io.Dir, language: []const u8, stem: []const u8, max_frames: usize) !Voice { + var nb: [300]u8 = undefined; + const code_bytes = try folder.readFileAlloc(io, try std.fmt.bufPrint(&nb, "{s}.codes.npy", .{stem}), a, .limited(1 << 24)); + const codes = try npy.parse(code_bytes); + if (codes.rank != 2 or codes.shape[1] != cfg.codebooks or codes.shape[0] == 0) return error.BadVoice; + const flat = try codes.ints(a); + const frames = @min(codes.shape[0], max_frames); + const rows = try a.alloc([cfg.codebooks]i32, frames); + for (rows, 0..) |*row, i| { + row.* = flat[i * cfg.codebooks ..][0..cfg.codebooks].*; + for (row) |code| if (code < 0 or code >= cfg.codebook_size) return error.BadVoice; + } + const emb_bytes = try folder.readFileAlloc(io, try std.fmt.bufPrint(&nb, "{s}.embedding.npy", .{stem}), a, .limited(1 << 20)); + const emb = try npy.parse(emb_bytes); + if (emb.kind != .f32 or emb.numel() != cfg.speaker_dim) return error.BadVoice; + var v: Voice = .{ .name = "", .clip = try a.dupe(u8, stem), .language = try a.dupe(u8, language), .codes = rows, .embedding = undefined }; + const values = try emb.floats(a); + v.embedding = values[0..cfg.speaker_dim].*; + for (v.embedding) |x| if (!std.math.isFinite(x)) return error.BadVoice; + const word = stem[0 .. std.mem.indexOfScalar(u8, stem, '_') orelse stem.len]; + v.name = try lower(a, word); + return v; +} + +/// Every voice under `root`'s voices folder, sorted by name; `a` is an arena. At most `max_frames` of each clip. +pub fn load(a: std.mem.Allocator, io: std.Io, root: []const u8, max_frames: usize) ![]const Voice { + const path = try std.fs.path.join(a, &.{ root, dir }); + var top = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch |e| switch (e) { + error.FileNotFound => return &.{}, + else => return e, + }; + defer top.close(io); + var voices: std.ArrayList(Voice) = .empty; + var languages = top.iterate(); + while (try languages.next(io)) |lang| { + if (lang.kind != .directory) continue; + var folder = try top.openDir(io, lang.name, .{ .iterate = true }); + defer folder.close(io); + var files = folder.iterate(); + while (try files.next(io)) |entry| { + const tail = ".codes.npy"; + if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, tail)) continue; + if (voices.items.len >= max_voices) return error.TooManyVoices; + try voices.append(a, try one(a, io, folder, lang.name, entry.name[0 .. entry.name.len - tail.len], max_frames)); + } + } + std.mem.sort(Voice, voices.items, {}, struct { + fn less(_: void, l: Voice, r: Voice) bool { + return std.mem.lessThan(u8, l.clip, r.clip); + } + }.less); + // a first word two clips share names neither: those go by their whole stem + for (voices.items, 0..) |*v, i| { + var shared = false; + for (voices.items, 0..) |other, j| shared = shared or (i != j and std.ascii.eqlIgnoreCase(other.clip[0..@min(other.clip.len, v.name.len)], v.name) and + (other.clip.len == v.name.len or other.clip[v.name.len] == '_')); + if (shared) v.name = try lower(a, v.clip); + } + return voices.items; +} + +pub fn find(voices: []const Voice, name: []const u8) ?*const Voice { + for (voices) |*v| if (std.ascii.eqlIgnoreCase(v.name, name) or std.mem.eql(u8, v.clip, name)) return v; + return null; +} diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index 1de11d332ed..e5189861089 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -6,6 +6,8 @@ pub const generation = @import("generation.zig"); pub const prompt = @import("prompt.zig"); pub const speech = @import("speech.zig"); pub const release = @import("release.zig"); +pub const voices = @import("voices.zig"); +pub const request = @import("request.zig"); pub const weights = @import("cuda/weights.zig"); pub const kernels = @import("cuda/kernels.zig"); pub const engine = @import("cuda/engine.zig"); diff --git a/zig/src/native/cuda_families.zig b/zig/src/native/cuda_families.zig index 981b8575fee..fa78fccc249 100644 --- a/zig/src/native/cuda_families.zig +++ b/zig/src/native/cuda_families.zig @@ -17,25 +17,27 @@ const inkling2 = @import("inkling2"); /// CUDA families provide metadata, open their lane backend and explain their refusals. pub const registry = .{ nemotron.native, nemotron.omni, nemotron.transcribe, glm.native, minimax.native, qwen35.native, qwen35.native_moe, flashnext.native, kolibri1.native, gemma4.native, gemma4.native31, spark25.native, dory.native, @import("dots_mocr_cuda").native, @import("muse_spark").native, @import("ricursive_cuda").native, @import("lfm2_moe_cuda").native, inkling2.native }; pub const families: []const api.Family = blk: { - var out: [registry.len + 5]api.Family = undefined; + var out: [registry.len + 6]api.Family = undefined; for (registry, 0..) |F, i| out[i] = .{ .model_type = F.model_type, .formats = F.formats, .decision_formats = if (@hasDecl(F, "decision_formats")) F.decision_formats else &.{} }; out[registry.len] = lfm2.family; out[registry.len + 1] = .{ .model_type = "fish_omni", .formats = &.{"fp8-block128"} }; out[registry.len + 2] = .{ .model_type = "qwen4", .formats = @import("qwen4").family.native_host.formats }; out[registry.len + 3] = .{ .model_type = "qwen4_text", .formats = @import("qwen4").family.native_host.formats }; out[registry.len + 4] = .{ .model_type = qwen3.native.model_type, .formats = qwen3.native.formats }; + out[registry.len + 5] = .{ .model_type = "zonos3", .formats = &.{"bf16"} }; const final = out; break :blk &final; }; test "every registered family and d1's decision engine are listed for capabilities" { - try std.testing.expectEqual(@as(usize, registry.len + 5), families.len); + try std.testing.expectEqual(@as(usize, registry.len + 6), families.len); try std.testing.expectEqualStrings("nemotron_h", families[0].model_type); try std.testing.expectEqualStrings("lfm2_moe", families[registry.len - 2].model_type); try std.testing.expectEqualStrings("inkling2_loop", families[registry.len - 1].model_type); try std.testing.expectEqualStrings("qwen4", families[registry.len + 2].model_type); try std.testing.expectEqualStrings("qwen4_text", families[registry.len + 3].model_type); try std.testing.expectEqualStrings("qwen3", families[registry.len + 4].model_type); + try std.testing.expectEqualStrings("zonos3", families[registry.len + 5].model_type); } test "dots.mocr serves its publisher's BF16 weights on CUDA through the dense engine" { diff --git a/zig/src/native/cuda_open.zig b/zig/src/native/cuda_open.zig index 94fd3f771ed..2bcac8657cc 100644 --- a/zig/src/native/cuda_open.zig +++ b/zig/src/native/cuda_open.zig @@ -7,9 +7,10 @@ const Allocator = std.mem.Allocator; /// `opened`: a family outside the table answered (null: refused, `problem` set); `not_mine`: the table decides. pub const Answer = union(enum) { not_mine, opened: ?api.Opened }; -/// Drama's, Qwen4's and LFM2's own engines, by the model type each serves. +/// Drama's, ZONOS3's, Qwen4's and LFM2's own engines, by the model type each serves. pub fn special(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !Answer { if (std.mem.eql(u8, o.model_type, "fish_omni")) return .{ .opened = try @import("drama_open.zig").open(a, gpa, io, o, problem) }; + if (std.mem.eql(u8, o.model_type, "zonos3")) return .{ .opened = try @import("zonos_open.zig").open(a, gpa, io, o, problem) }; if (std.mem.eql(u8, o.model_type, "qwen4") or std.mem.eql(u8, o.model_type, "qwen4_text")) return .{ .opened = try @import("qwen4_cuda.zig").open(a, gpa, io, o, problem) }; const lfm2 = @import("lfm2.zig"); if (!std.mem.eql(u8, o.model_type, lfm2.family.model_type)) return .not_mine; diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index 250789550a1..6d3c4c2b37e 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -63,7 +63,7 @@ pub fn backend(o: api.Open) ?[]const u8 { if (o.speed_up != null) return "--speed-up links two Macs: serve without --speed-up on CUDA"; if (o.prompt_cache_over_cap) return "--prompt-cache-over-cap lifts a Mac's 70% cap: on CUDA the prompt cache takes at most the memory the weights and streams leave, so serve without it"; // Fish and Qwen4 open outside family(), so their --tp is refused here - if (std.mem.eql(u8, o.model_type, "fish_omni") or std.mem.eql(u8, o.model_type, "qwen4") or std.mem.eql(u8, o.model_type, "qwen4_text")) + if (std.mem.eql(u8, o.model_type, "fish_omni") or std.mem.eql(u8, o.model_type, "zonos3") or std.mem.eql(u8, o.model_type, "qwen4") or std.mem.eql(u8, o.model_type, "qwen4_text")) if (unranked(o)) |why| return why; return null; } @@ -158,7 +158,7 @@ test "a family must consume rank options before tensor parallelism is admitted" try std.testing.expect(unranked(.{ .dir = "d", .model_type = "qwen4", .rank = 0, .given = .{ .tp = true, .rank = true } }) == null); try std.testing.expect(family(Single, .{ .dir = "d", .model_type = "m", .rank = 0, .given = .{ .rank = true } }) == null); try std.testing.expectEqualStrings(no_ranks, lfm2(.{ .dir = "d", .model_type = "lfm2", .tp = 2 }).?); - for ([_][]const u8{ "fish_omni", "qwen4", "qwen4_text" }) |m| { + for ([_][]const u8{ "fish_omni", "zonos3", "qwen4", "qwen4_text" }) |m| { try std.testing.expect(backend(.{ .dir = "d", .model_type = m, .tp = 1 }) == null); try std.testing.expectEqualStrings(no_ranks, backend(.{ .dir = "d", .model_type = m, .tp = 2 }).?); } diff --git a/zig/src/native/zonos_host.zig b/zig/src/native/zonos_host.zig new file mode 100644 index 00000000000..8f67dd7dc57 --- /dev/null +++ b/zig/src/native/zonos_host.zig @@ -0,0 +1,312 @@ +//! Native speech from one ZONOS3 Mini family on CUDA: one request at a time, its audio decoded whole at the end. +const std = @import("std"); +const api = @import("engine_api"); +const z3 = @import("zonos3"); +const cuda = @import("cuda"); + +const cfg = z3.config; +const W = cfg.frame_width; +const C = cfg.codebooks; + +pub const default_frames = 2000; // the release's frame budget, 133 s of audio + +pub const Options = struct { + context: u32 = 4096, + device: u32 = 0, + max_frames: ?u32 = null, +}; + +/// The frame budget and the prompt rows a context leaves. +pub fn budget(context: u32, max_frames: ?u32) !struct { frames: u32, prompt: u32 } { + if (context < 1025 or context > cfg.max_seqlen) return error.BadZonosContext; + const frames = max_frames orelse @min(default_frames, context / 2); + if (frames < C + 2 or frames >= context) return error.BadZonosFrames; + return .{ .frames = frames, .prompt = context - frames }; +} + +/// What a request's prompt rows name: [reference prefix | speaker row] conditions, the text from BOS to EOS, silence. +pub const Layout = struct { + condition_row: usize, + prefill: usize, + + pub fn of(rows: []const [W]i32) !Layout { + var first: ?usize = null; + var last: ?usize = null; + for (rows, 0..) |row, i| { + if (row[C] == z3.prompt.bos and first == null) first = i; + if (row[C] == z3.prompt.eos) last = i; + } + const b = first orelse return error.BadPromptLayout; + const e = last orelse return error.BadPromptLayout; + if (b < cfg.conditions or e <= b) return error.BadPromptLayout; + return .{ .condition_row = b - cfg.conditions, .prefill = rows.len - 1 - e }; + } +}; + +const Job = struct { id: api.Id, request: *const api.SpeechRequest, sink: api.Sink }; + +/// The backbone under generation, stopped between rows when the request is cancelled or the host closes. +const Guarded = struct { + h: *Host, + + pub fn run(g: Guarded, rows: []const [W]i32, replaced: []const z3.Replace, probe: ?z3.Probe) !void { + g.h.lock(); + const stop = g.h.cancelled or g.h.closing; + g.h.unlock(); + if (stop) return error.Cancelled; + try g.h.e.run(rows, replaced, probe); + } + + pub fn lastLogits(g: Guarded, out: *[cfg.head_rows]f32) !void { + try g.h.e.lastLogits(out); + } +}; + +const Host = struct { + gpa: std.mem.Allocator, + io: std.Io, + rel: z3.release.Release, + e: *z3.Engine, + codec: *z3.Codec, + info_: api.Info, + mutex: std.Io.Mutex = .init, + wake: std.Io.Condition = .init, + worker: ?std.Thread = null, + job: ?Job = null, + cancelled: bool = false, + closing: bool = false, + failed: bool = false, + + const vtable: api.Engine.VTable = .{ + .info = info, + .submit = submitText, + .submit_speech = submit, + .cancel = cancel, + .status = status, + .memory = memory, + .drain = drain, + }; + + fn self(p: *anyopaque) *Host { + return @ptrCast(@alignCast(p)); + } + fn lock(h: *Host) void { + h.mutex.lockUncancelable(h.io); + } + fn unlock(h: *Host) void { + h.mutex.unlock(h.io); + } + fn info(p: *anyopaque) api.Info { + return self(p).info_; + } + fn submitText(_: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void { + return error.Closed; + } + + fn valid(h: *Host, r: *const api.SpeechRequest) bool { + const sp = h.info_.speech.?; + if (r.frames.len == 0 or r.frames.len > sp.max_prompt_tokens or r.max_frames == 0 or r.max_frames > sp.max_frames) return false; + if (r.pcm.len < @as(usize, r.max_frames) * sp.frame_length) return false; + if (r.speaker.len != 0 and r.speaker.len != cfg.speaker_dim) return false; + for (r.speaker) |x| if (!std.math.isFinite(x)) return false; + if (!std.math.isFinite(r.temperature) or r.temperature < 0) return false; + if (!std.math.isFinite(r.top_p) or r.top_p <= 0 or r.top_p > 1 or r.top_k == 0) return false; + if (r.unconditioned.len != 0 or r.cfg_gamma != 1) return false; + for (r.frames) |row| { + for (row[0..C]) |code| if (code < 0 or code >= cfg.audio_vocab) return false; + if (row[C] < 0 or row[C] >= h.e.w.text_rows) return false; + } + _ = Layout.of(r.frames) catch return false; + return true; + } + + fn submit(p: *anyopaque, id: api.Id, r: *const api.SpeechRequest, sink: api.Sink) api.SpeechSubmitError!void { + const h = self(p); + if (!h.valid(r)) return error.InvalidRequest; + h.lock(); + defer h.unlock(); + if (h.closing or h.failed) return error.Closed; + if (h.job != null) return error.Busy; + r.result.* = .{}; + h.job = .{ .id = id, .request = r, .sink = sink }; + h.cancelled = false; + h.wake.signal(h.io); + } + + fn cancel(p: *anyopaque, id: api.Id) void { + const h = self(p); + h.lock(); + defer h.unlock(); + if (h.job) |j| if (j.id == id) { + h.cancelled = true; + }; + } + + fn status(p: *anyopaque, out: *api.Status, _: []u32) void { + const h = self(p); + h.lock(); + defer h.unlock(); + out.* = .{}; + if (h.job != null) out.running = 1; + } + + fn memory(_: *anyopaque, reset_peak: bool) ?api.Memory { + const u = cuda.usage(reset_peak); + return .{ .active = u.device, .pinned = u.host, .peak = u.peak }; + } + + fn run(h: *Host) void { + const current = if (h.e.ctx.makeCurrent()) |_| true else |_| false; + while (true) { + h.lock(); + const job = h.job orelse { + if (h.closing) { + h.unlock(); + return; + } + h.wake.waitUncancelable(h.io, &h.mutex); + h.unlock(); + continue; + }; + const dead = h.failed or !current; + h.unlock(); + if (dead) { + h.finish(job, .failed, 0, "speech engine closed after execution failure"); + continue; + } + var samples: usize = 0; + const reason = h.serve(job, &samples) catch |err| switch (err) { + error.Cancelled => api.Reason.cancelled, + else => { + h.lock(); + h.failed = true; + h.unlock(); + h.e.stream.synchronize() catch {}; + h.finish(job, .failed, 0, @errorName(err)); + continue; + }, + }; + h.finish(job, reason, samples, ""); + } + } + + /// One request: its prompt rows, frames to the end of audio or the budget, then the whole audio into its buffer. + fn serve(h: *Host, job: Job, samples: *usize) !api.Reason { + const r = job.request; + const gpa = h.gpa; + const layout = try Layout.of(r.frames); + var replaced: [1 + cfg.conditions]z3.Replace = undefined; + var n: usize = 0; + if (r.speaker.len != 0) { + replaced[n].row = 0; + h.e.w.speakerRow(r.speaker[0..cfg.speaker_dim], &replaced[n].vec); + n += 1; + } + // every condition unknown: the last row of its table + for (0..cfg.conditions) |c| { + replaced[n].row = layout.condition_row + c; + @memcpy(&replaced[n].vec, h.e.w.conditions[c][h.e.c.buckets[c] * cfg.dim ..][0..cfg.dim]); + n += 1; + } + const sampling: z3.Sampling = .{ .temperature = r.temperature, .top_k = r.top_k, .top_p = r.top_p, .seed = r.seed }; + try h.e.reset(); + const made = try z3.generation.generate(gpa, Guarded{ .h = h }, r.frames, @as([]const z3.Replace, replaced[0..n]), sampling, r.max_frames); + defer gpa.free(made.rows); + const frames = try z3.speech.frames(gpa, r.frames[r.frames.len - layout.prefill ..], made.rows, made.eos_frame); + defer gpa.free(frames); + try h.codec.reset(); + try h.codec.decode(frames, null); + const pcm = try h.codec.finish(gpa, null); + defer gpa.free(pcm); + if (pcm.len > r.pcm.len) return error.AudioOverflow; + for (pcm) |x| if (!std.math.isFinite(x)) return error.NonFiniteAudio; + z3.speech.output(pcm, h.rel.headroom_db); + @memcpy(r.pcm[0..pcm.len], pcm); + samples.* = pcm.len; + if (r.stream) job.sink.event(job.sink.ctx, job.id, &.{ .audio = pcm.len }); + return if (made.eos_frame != null) .stop else .length; + } + + fn finish(h: *Host, job: Job, reason: api.Reason, samples: usize, message: []const u8) void { + h.lock(); + if (reason == .stop or reason == .length) job.request.result.samples = samples; + job.request.result.reason = reason; + h.job = null; + h.unlock(); + job.sink.event(job.sink.ctx, job.id, &.{ .finished = .{ .reason = reason, .message = message } }); + } + + fn drain(p: *anyopaque) void { + const h = self(p); + h.lock(); + h.closing = true; + h.wake.signal(h.io); + h.unlock(); + if (h.worker) |t| t.join(); + h.worker = null; + } + + fn close(p: *anyopaque) void { + const h = self(p); + drain(h); + h.e.ctx.makeCurrent() catch {}; + h.codec.destroy(); + h.e.destroy(); + h.rel.deinit(); + h.gpa.destroy(h); + } +}; + +/// `dir`: a snapshot of the release's repository. +pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !api.Opened { + const b = try budget(o.context, o.max_frames); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + var rel = try z3.release.open(gpa, io, dir, null); + errdefer rel.deinit(); + const e = try z3.Engine.create(gpa, io, rel.lm, .{ .device = o.device, .max_ctx = o.context }); + errdefer e.destroy(); + const codec = try z3.Codec.create(gpa, io, &e.driver, e.stream, rel.generator, rel.head, .{ .max_frames = b.frames }); + errdefer codec.destroy(); + h.* = .{ + .gpa = gpa, + .io = io, + .rel = rel, + .e = e, + .codec = codec, + .info_ = .{ + .name = "ZONOS3 Mini", + .text_generation = false, + .lanes = 1, + .context_window = o.context, + .plain_only = true, + .prompt_cache = false, + .speech = .{ .sample_rate = z3.codec.sample_rate, .frame_length = z3.codec.frame_samples, .max_frames = b.frames, .max_prompt_tokens = b.prompt }, + }, + }; + h.worker = try std.Thread.spawn(.{}, Host.run, .{h}); + std.log.info("zonos3: decoder {s}, {d} MiB of weights, {d} frames a request", .{ h.rel.decoder, (e.w.bytes + codec.w.bytes) >> 20, b.frames }); + return .{ .engine = .{ .ctx = h, .vtable = &Host.vtable }, .ctx = h, .close = Host.close }; +} + +test "budget: the release's frame budget where the context holds it, the rest for the prompt" { + const t = std.testing; + const d = try budget(4096, null); + try t.expectEqual(@as(u32, 2000), d.frames); + try t.expectEqual(@as(u32, 2096), d.prompt); + try t.expectEqual(@as(u32, 512), (try budget(1025, null)).frames); + try t.expectError(error.BadZonosContext, budget(1024, null)); + try t.expectError(error.BadZonosContext, budget(32769, null)); + try t.expectError(error.BadZonosFrames, budget(4096, 4096)); + try t.expectError(error.BadZonosFrames, budget(4096, 5)); +} + +test "Layout: the condition rows sit before the text and the silence rows after it" { + const t = std.testing; + var p = try z3.prompt.build(t.allocator, &.{ 9, 8 }, .embedding, @splat(1), 3); + defer p.deinit(t.allocator); + const l = try Layout.of(p.rows); + try t.expectEqual(p.condition_row, l.condition_row); + try t.expectEqual(@as(usize, 3), l.prefill); + try t.expectError(error.BadPromptLayout, Layout.of(p.rows[0..3])); +} diff --git a/zig/src/native/zonos_open.zig b/zig/src/native/zonos_open.zig new file mode 100644 index 00000000000..d49e92de4ef --- /dev/null +++ b/zig/src/native/zonos_open.zig @@ -0,0 +1,56 @@ +//! ZONOS3 Mini's open on CUDA: the flags it serves, then the host. +const std = @import("std"); +const api = @import("engine_api"); +const zonos_host = @import("zonos_host.zig"); +const Allocator = std.mem.Allocator; +const setting = @import("cuda_device.zig").setting; + +pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + const settings = @import("sys").environment; + if (try settings.refusal(a, settings.Process{}, .{ .cuda = true, .slide = o.slide, .device = o.device, .segments = o.segments })) |why| { + problem.* = why; + return null; + } + if (try o.slideRefusal(a, "CUDA")) |why| { + problem.* = why; + return null; + } + if (o.cfg_enabled or o.cfg_batched) { + problem.* = "ZONOS3 Mini is served without guidance: serve without --cfg"; + return null; + } + if (o.tp != 1 or o.rank != 0 or (o.lanes_fixed and o.lanes != 1)) { + problem.* = "ZONOS3 Mini serves one request at a time on one CUDA device: use --parallel 1, without tensor parallelism"; + return null; + } + if (o.silence.enabled()) { + problem.* = "ZONOS3 Mini has no silence guard: serve without the silence flags"; + return null; + } + const window = o.context orelse (zonos_host.Options{}).context; + _ = zonos_host.budget(std.math.cast(u32, window) orelse 0, o.max_frames) catch |e| { + problem.* = switch (e) { + error.BadZonosContext => "ZONOS3 Mini supports --context 1025 through 32768", + error.BadZonosFrames => "ZONOS3 Mini's --max-frames must be at least 12 and below --context", + }; + return null; + }; + if (o.vision != null or o.precision != null or o.record != null or o.recall or o.learn != null or + o.learn_conversations or o.speed_up != null or o.slide or o.drafter != null or o.mtp_drafts != null or o.mtp_confidence != null or + (o.prompt_cache_gib != null and o.prompt_cache_gib.? != 0) or + (o.keep != null and o.keep.? != 0) or o.policy.len != 0) + { + problem.* = "ZONOS3 Mini does not support learned weights, speculative drafts, retained prompt caches, or text-engine policies"; + return null; + } + const device = try setting(a, o.device, "TF_CUDA_DEVICE", 0, problem) orelse return null; + const segments = try setting(a, o.segments, "TF_CUDA_SEGMENTS", 1, problem) orelse return null; + if (segments != 1) { + problem.* = "ZONOS3 Mini uses one prompt segment at a time: use --segments 1"; + return null; + } + return zonos_host.open(gpa, io, o.dir, .{ .context = @intCast(window), .device = device, .max_frames = o.max_frames }) catch |e| { + problem.* = try std.fmt.allocPrint(a, "the native ZONOS3 Mini CUDA engine could not load the checkpoint ({s})", .{@errorName(e)}); + return null; + }; +} diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index 3baa7bb2aeb..79700ce0d5a 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -72,7 +72,7 @@ pub const HfText = struct { return t; }; var read: []const u8 = dir; - t.tok = openTokenizer(io, a, gpa, dir, &read) catch |e| { + t.tok = openTokenizer(io, a, gpa, try @import("zonos_request").release.tokenizerAt(a, io, dir), &read) catch |e| { problem.* = try std.fmt.allocPrint(pa, "cannot read {s}/tokenizer.json ({s})", .{ read, @errorName(e) }); return error.Load; }; diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index 833cce6bec1..c65d86ec01e 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -282,7 +282,8 @@ fn fail(message: []const u8) u8 { } fn modelType(a: std.mem.Allocator, io: std.Io, dir: []const u8, problem: *[]const u8) ![]const u8 { - const bytes = (try @import("checkpoint_config").read(a, io, dir, problem)) orelse return "unknown"; + const bytes = (try @import("checkpoint_config").read(a, io, dir, problem)) orelse + return if (@import("zonos_request").release.present(io, dir)) "zonos3" else "unknown"; // a release without config.json const doc = std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}) catch return "unknown"; if (doc != .object) return "unknown"; const t = doc.object.get("model_type") orelse return "unknown"; diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 57125866f36..5c14d0e8bc5 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -61,6 +61,7 @@ pub const Server = struct { text: model_text.Text, config: Config, voices: @import("drama_voice_store.zig").Store = .{}, + zonos: ?*@import("zonos_speech.zig").State = null, // a ZONOS3 Mini release's voices; Drama 3's stay in `voices` keys: ?*auth.Store, late_system: []const u8 = "system", needs_user_after_tool: bool = false, diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index 4f298ad2895..263eaf74d76 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -39,7 +39,7 @@ const modifier_fields = [_][]const u8{ "speed", "task_type", "language", "instru pub const Format = audio_out.Format; /// `rate` and `channels` are the reply's: the model's own rate and mono unless the request asked otherwise. -pub const Plan = struct { input: []const u8, prompt: []const u32, frames: ?[]const [11]i32 = null, refs: []const @import("drama_prompt").Reference = &.{}, reference_rows: u32 = 0, sampling: speech_sampling.Options, format: Format, stream: bool, rate: u32 = 0, channels: u8 = 1, budget_s: ?f64 = null }; +pub const Plan = struct { input: []const u8, prompt: []const u32, frames: ?[]const [11]i32 = null, speaker: []const f32 = &.{}, refs: []const @import("drama_prompt").Reference = &.{}, reference_rows: u32 = 0, sampling: speech_sampling.Options, format: Format, stream: bool, rate: u32 = 0, channels: u8 = 1, budget_s: ?f64 = null }; /// One whole take: its audio, why it ended, and whether it ended in a mid-utterance silence. const Take = struct { pcm: []f32, reason: api.Reason, silence_mid: bool = false, trip: bool = false, jump: ?f64 = null }; @@ -134,7 +134,8 @@ const rate_list = list: { fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused!Plan { if (raw != .object) return cx.refuse("speech request body must be a JSON object"); try checkFields(cx, raw, srv.config.voice.inline_voices); - const sampling = try speech_sampling.parse(cx, raw); + const zonos = @import("zonos_speech.zig"); + const sampling = if (srv.zonos != null) try speech_sampling.parseFrom(cx, raw, .{ .temperature = zonos.temperature, .top_p = zonos.top_p, .top_k = zonos.top_k }, zonos.max_top_k) else try speech_sampling.parse(cx, raw); const model = raw.strField("model") orelse return cx.fail(.request, "model is required: send {s}", .{srv.config.served_name}); if (!listed(srv.config.model_ids, model)) return cx.fail(.request, "model {s} is not served here: send {s}", .{ try pyrepr.repr(cx.a, .{ .string = model }), srv.config.served_name }); @@ -146,6 +147,11 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused const format = try responseFormat(cx, raw.strField("response_format") orelse "wav"); const stream = if (raw.get("stream")) |s| s == .bool and s.bool else false; if (stream and format != .pcm) return cx.refuse("stream=true requires response_format='pcm'"); + if (srv.zonos) |state| { + const made = try zonos.plan(state, cx, srv.text, sp, input, raw.strField("voice") orelse raw.strField("speaker") orelse "default"); + const rate, const channels = try output(cx, raw, sp, stream); + return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .sampling = sampling, .format = format, .stream = stream, .rate = rate, .channels = channels }; + } const refs = try voiceRefs(srv, cx, raw); const rate, const channels = try output(cx, raw, sp, stream); if (try @import("drama_voice.zig").requestPrompt(cx, srv.text, sp, input, refs)) |made| return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .refs = refs, .reference_rows = made.reference_rows, .sampling = sampling, .format = format, .stream = stream, .rate = rate, .channels = channels }; @@ -245,6 +251,7 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf .reference_rows = plan.reference_rows, .unconditioned = guided.rows, .cfg_gamma = guided.gamma, + .speaker = plan.speaker, }; var box: Mailbox = .{ .io = srv.io, .gpa = srv.gpa }; defer box.deinit(); diff --git a/zig/src/server/speech_voices.zig b/zig/src/server/speech_voices.zig index a552f8119d1..0e479f746bb 100644 --- a/zig/src/server/speech_voices.zig +++ b/zig/src/server/speech_voices.zig @@ -1,17 +1,24 @@ -//! A speech server's voices: Drama 3's catalog store, loaded at startup and listed on `/v1/voices`. +//! A speech server's voices, Drama 3's store or a ZONOS3 release's own: loaded at startup, listed on `/v1/voices`. const std = @import("std"); const server = @import("server.zig"); +const zonos = @import("zonos_speech.zig"); -/// Fills `srv.voices` from `--voices` and selects the default voice; voice flags without a speech model are refused. +/// Fills `srv.voices` from `--voices`, or `srv.zonos` for a release, which refuses Drama 3's voice flags. pub fn start(srv: *server.Server, gpa: std.mem.Allocator, io: std.Io, config: server.Config) !void { const voice = config.voice; srv.voices = .{ .gpa = gpa, .io = io, .dir = voice.dir }; if (srv.info.speech == null and (voice.dir != null or voice.inline_voices or voice.manage)) return error.VoicesRequireSpeech; + if (srv.info.speech != null) srv.zonos = try zonos.load(srv.arena.allocator(), io, config.model_dir, voice.default); + if (srv.zonos != null) { + if (voice.dir != null or voice.inline_voices or voice.manage) return error.VoiceFlagsNeedDrama; + return; + } if (voice.dir) |dir| try srv.voices.load(dir); _ = try srv.voices.select(srv.arena.allocator(), voice.default, "default"); } /// The `/v1/voices` reply. pub fn listing(srv: *server.Server, a: std.mem.Allocator) !@import("json").Value { + if (srv.zonos) |state| return zonos.listing(a, state); return srv.voices.listing(a); } diff --git a/zig/src/server/zonos_speech.zig b/zig/src/server/zonos_speech.zig new file mode 100644 index 00000000000..64e934d3279 --- /dev/null +++ b/zig/src/server/zonos_speech.zig @@ -0,0 +1,82 @@ +//! ZONOS3 Mini behind /v1/audio/speech: the release's default voices and a request's prompt rows. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json"); +const errors = @import("errors.zig"); +const pyrepr = @import("pyrepr.zig"); +const text_mod = @import("model_text.zig"); +const req = @import("zonos_request"); +const Allocator = std.mem.Allocator; + +pub const error_prefix = "ZONOS3 request:"; +pub const temperature = req.temperature; +pub const top_p = req.top_p; +pub const top_k = req.top_k; +pub const max_top_k = req.config.codebook_size; + +pub const State = struct { + voices: []const req.voices.Voice, + silence: [req.config.codebooks]i32, + /// The voice "default" names: --default-voice, else savannah, else the first voice. + default: ?*const req.voices.Voice, +}; + +pub const Made = struct { prompt: []const u32, frames: []const [11]i32 }; + +/// The state for a ZONOS3 Mini release at `dir` (from the arena `a`), or null for any other checkpoint. +pub fn load(a: Allocator, io: std.Io, dir: []const u8, default_voice: []const u8) !?*State { + if (dir.len == 0 or !req.release.present(io, dir)) return null; + var rel = try req.release.open(a, io, dir, null); + defer rel.deinit(); + const st = try a.create(State); + st.* = .{ .voices = try req.voices.load(a, io, dir, req.reference_frames), .silence = rel.silence, .default = null }; + const named = !std.mem.eql(u8, default_voice, "default"); + st.default = req.voices.find(st.voices, if (named) default_voice else "savannah"); + if (st.default == null) { + if (named) return error.UnknownDefaultVoice; + if (st.voices.len > 0) st.default = &st.voices[0]; + } + return st; +} + +/// The request's prompt: the voice's reference codes as a delayed prefix, the condition rows, the text, the silence. +pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.SpeechInfo, input: []const u8, voice: []const u8) errors.Refused!Made { + const chosen = if (voice.len == 0 or std.ascii.eqlIgnoreCase(voice, "default")) st.default else req.voices.find(st.voices, voice); + const v = chosen orelse { + if (st.voices.len == 0) return cx.refuse(error_prefix ++ " this release folder has no voices under gguf/voices"); + return cx.fail(.request, error_prefix ++ " unknown voice {s}; see /v1/voices", .{try pyrepr.repr(cx.a, .{ .string = voice })}); + }; + const spoken = req.prompt.collapseLineBreaks(cx.a, input) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + else => cx.refuse("input must be valid UTF-8 text"), + }; + const ids = text.encode(cx.a, spoken, false) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + else => cx.other("the tokenizer cannot encode this prompt"), + }; + const built = req.prompt.build(cx.a, ids, .{ .reference = v.codes }, st.silence, req.silence_frames) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + else => cx.refuse(error_prefix ++ " the text has nothing to speak"), + }; + if (built.rows.len > sp.max_prompt_tokens) + return cx.fail(.request, error_prefix ++ " a prompt of {d} rows exceeds the maximum allowed length of {d} rows", .{ built.rows.len, sp.max_prompt_tokens }); + return .{ .prompt = ids, .frames = built.rows }; +} + +pub fn listing(a: Allocator, st: *const State) !json.Value { + const data = try a.alloc(json.Value, st.voices.len + 1); + data[0] = .{ .string = "default" }; + for (st.voices, data[1..]) |voice, *slot| slot.* = .{ .string = voice.name }; + const details = try a.alloc(json.Value, st.voices.len); + for (st.voices, details) |voice, *slot| { + const entry = try json.newObject(a); + try entry.put(a, "id", .{ .string = voice.name }); + try entry.put(a, "description", .{ .string = try std.fmt.allocPrint(a, "{s} ({s})", .{ voice.clip, voice.language }) }); + slot.* = .{ .object = entry }; + } + const object = try json.newObject(a); + try object.put(a, "voices", .{ .array = data }); + try object.put(a, "details", .{ .array = details }); + if (st.default) |d| try object.put(a, "default", .{ .string = d.name }); + return .{ .object = object }; +} From d5ad72e709edaeb87cf5d20665114b892adf0886 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:14:38 +0000 Subject: [PATCH 312/361] zonos3: streamed replies in growing chunks, the codec's settled samples after each; host tests in test-cuda-host --- zig/build/cuda.zig | 1 + zig/build/zonos3.zig | 13 ++++ zig/kernels/cuda/zonos3_codec.cu | 11 ++-- zig/src/families/zonos3/cuda/codec.zig | 44 +++++++++---- .../families/zonos3/cuda/codec_kernels.zig | 4 +- zig/src/families/zonos3/generate.zig | 10 ++- zig/src/families/zonos3/generation.zig | 6 ++ zig/src/families/zonos3/zonos3.zig | 1 + zig/src/native/zonos_host.zig | 64 ++++++++++++++----- 9 files changed, 117 insertions(+), 37 deletions(-) diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index f4066b32f90..14d279efcb5 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -318,6 +318,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st } const drama3 = @import("drama3_host.zig").hostTests(b, step, cuda, mods.core); const native_modules = engines(b, host, .debug, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision); + @import("zonos3.zig").hostTests(b, step, cuda, mods.core, native_modules.api); b.step("test-qwen-grants-host", "Qwen MTP head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"shared head costs:"} })).step); b.step("test-nemotron-grants-host", "Nemotron shared head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"Nemotron shared prices:"} })).step); b.step("test-nemotron-cuda-steps-host", "Nemotron CUDA's stepped prompt pass on the lanes, stopped before GPU work").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"nemotron cuda steps:"} })).step); diff --git a/zig/build/zonos3.zig b/zig/build/zonos3.zig index fa8260feeee..92409c26c72 100644 --- a/zig/build/zonos3.zig +++ b/zig/build/zonos3.zig @@ -6,6 +6,19 @@ pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui return b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/zonos3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); } +/// The family's host tests (config, prompt, sampler, generation, output stage, release layout) and its host's. +pub fn hostTests(b: *std.Build, step: *std.Build.Step, cuda: *std.Build.Module, core: *std.Build.Module, api: *std.Build.Module) void { + const family = module(b, b.graph.host, .debug, cuda, core); + const run = b.addRunArtifact(b.addTest(.{ .root_module = family })); + const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/zonos_host.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "zonos3", .module = family }, .{ .name = "engine_api", .module = api }, .{ .name = "cuda", .module = cuda } } }); + const run_host = b.addRunArtifact(b.addTest(.{ .root_module = host })); + const own = b.step("test-zonos-host", "ZONOS3 Mini's prompt, sampler, generation, output and host tests without a GPU"); + for ([_]*std.Build.Step{ &run.step, &run_host.step }) |r| { + step.dependOn(r); + own.dependOn(r); + } +} + pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) void { const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "cuda", .module = cuda }, .{ .name = "zonos3", .module = module(b, target, optimize, cuda, core) } } }); const exe = b.addExecutable(.{ .name = "zonos3-generate", .root_module = tool }); diff --git a/zig/kernels/cuda/zonos3_codec.cu b/zig/kernels/cuda/zonos3_codec.cu index c6480b2e62f..cdfe14a7cd9 100644 --- a/zig/kernels/cuda/zonos3_codec.cu +++ b/zig/kernels/cuda/zonos3_codec.cu @@ -209,21 +209,22 @@ extern "C" __global__ void zc_ola(const float* __restrict__ frames, const float* out[i] = s / e; } -// The mixer: out[i] = sum_b sum_j w[b][j] s_b[n0 + i + j - 63], zero outside [0, total); s rows are `total` apart. -extern "C" __global__ void zc_mix(const float* __restrict__ s, long long total, const float* __restrict__ w, - long long n0, long long count, float* __restrict__ out) { +// The mixer: out[i] = sum_b sum_j w[b][j] s_b[n0 + i + j - 63], zero outside [0, total); s rows are `stride` apart. +extern "C" __global__ void zc_mix(const float* __restrict__ s, long long stride, long long total, + const float* __restrict__ w, long long n0, long long count, + float* __restrict__ out) { const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; if (i >= count) return; float a = 0.f; for (int b = 0; b < 2; ++b) for (int j = 0; j < 127; ++j) { const long long p = n0 + i + j - 63; - if (p >= 0 && p < total) a = fmaf(w[b * 127 + j], s[(size_t)b * total + p], a); + if (p >= 0 && p < total) a = fmaf(w[b * 127 + j], s[(size_t)b * stride + p], a); } out[i] = a; } -// 44160 to 44100 Hz: output m = 735 q + c is sum_j kernel[c][j] x[736 q + j - 17], zero outside [0, total). +// 44160 to 44100 Hz: output m0 + i = 735 q + c is sum_j kernel[c][j] x[736 q + j - 17], zero outside [0, total). extern "C" __global__ void zc_resample(const float* __restrict__ x, long long total, const float* __restrict__ kernel, long long m0, long long count, float* __restrict__ out) { const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig index 6adb119aefb..433cbf9a151 100644 --- a/zig/src/families/zonos3/cuda/codec.zig +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -37,6 +37,7 @@ pub const Codec = struct { w: *wts.Weights, bufs: std.ArrayList(Buf), frames: usize = 0, // code frames decoded + emitted: usize = 0, // samples handed out // state sem_hist: [wts.sem_blocks]u64, // [W][6] head_hist: [wts.head_blocks]u64, @@ -68,6 +69,7 @@ pub const Codec = struct { c.d = d; c.stream = stream; c.frames = 0; + c.emitted = 0; c.bufs = .empty; for (&c.kv) |*layers| layers.* = &.{}; c.k = try kern.Kernels.load(d); @@ -147,6 +149,7 @@ pub const Codec = struct { try b.fill8(0, c.stream.handle); try c.stream.synchronize(); c.frames = 0; + c.emitted = 0; } /// The next code frames (every code below 4096). Under a probe they must fit one pass. @@ -239,25 +242,40 @@ pub const Codec = struct { c.frames += t; } - /// Every decoded frame's samples to the host (frames * 2940, caller frees): the request's whole audio. - pub fn finish(c: *Codec, gpa: std.mem.Allocator, probe: ?Probe) ![]f32 { + /// The samples no later frame can change, from where the last call stopped (caller frees); `final` adds the rest. + /// After F frames 2940 F - 1470 samples are settled: the centered iSTFT, the mixer and the resampler look ahead. + pub fn emit(c: *Codec, gpa: std.mem.Allocator, final: bool, probe: ?Probe) ![]f32 { const k = &c.k; const s = c.stream; - const total = c.frames * internal_frame; - const samples = c.frames * frame_samples; - if (c.frames == 0) return gpa.alloc(f32, 0); + const cap = c.o.max_frames * internal_frame; + const total = c.frames * internal_frame; // internal samples the decoded frames cover + const end = if (final) c.frames * frame_samples else (c.frames * frame_samples) -| (frame_samples / 2); + if (end <= c.emitted) return gpa.alloc(f32, 0); + // output [emitted, end) reads the mix from the first block's start to the last block's taps, 63 more a branch + const m0 = (wts.resample_in * (c.emitted / wts.resample_out)) -| 17; + const m1 = @min(total, wts.resample_in * ((end - 1) / wts.resample_out) + wts.resample_taps - 17); + const b0 = m0 -| 63; + const b1 = @min(total, m1 + 63); + // before the end, samples past the decoded frames are never read; at the end they read as zero + const bound = if (final) total else cap; for (wts.n_ffts, 0..) |n, b| { - const out = c.branches + b * total * 4; - try k.ola(s, c.spec_frames[b], c.w.win2[b], c.frames * head_rate, n, wts.hop, 0, total, out); - if (probe) |p| try p.f(p.ctx, if (b == 0) "s0" else "s1", out, 1, total); + const out = c.branches + (b * cap + b0) * 4; + try k.ola(s, c.spec_frames[b], c.w.win2[b], c.frames * head_rate, n, wts.hop, b0, b1 - b0, out); + if (probe) |p| try p.f(p.ctx, if (b == 0) "s0" else "s1", out, 1, b1 - b0); } - try k.mix(s, c.branches, total, c.w.mixer, 0, total, c.mixed); - if (probe) |p| try p.f(p.ctx, "mixer", c.mixed, 1, total); - try k.resample(s, c.mixed, total, c.w.resampler, 0, samples, c.audio); - if (probe) |p| try p.f(p.ctx, "audio", c.audio, 1, samples); - const pcm = try gpa.alloc(f32, samples); + try k.mix(s, c.branches, cap, bound, c.w.mixer, m0, m1 - m0, c.mixed + m0 * 4); + if (probe) |p| try p.f(p.ctx, "mixer", c.mixed + m0 * 4, 1, m1 - m0); + try k.resample(s, c.mixed, bound, c.w.resampler, c.emitted, end - c.emitted, c.audio); + if (probe) |p| try p.f(p.ctx, "audio", c.audio, 1, end - c.emitted); + const pcm = try gpa.alloc(f32, end - c.emitted); errdefer gpa.free(pcm); try c.download(c.audio, std.mem.sliceAsBytes(pcm)); + c.emitted = end; return pcm; } + + /// Every decoded frame's samples not yet emitted (caller frees): after no emit, the request's whole audio. + pub fn finish(c: *Codec, gpa: std.mem.Allocator, probe: ?Probe) ![]f32 { + return c.emit(gpa, true, probe); + } }; diff --git a/zig/src/families/zonos3/cuda/codec_kernels.zig b/zig/src/families/zonos3/cuda/codec_kernels.zig index d625f42b9e0..02af934483d 100644 --- a/zig/src/families/zonos3/cuda/codec_kernels.zig +++ b/zig/src/families/zonos3/cuda/codec_kernels.zig @@ -164,9 +164,11 @@ pub const Kernels = struct { try k.go(.ola, s, (count + 255) / 256, 1, 256, 0, &a); } - pub fn mix(k: *const Kernels, s: cuda.Stream, branches: u64, total: usize, w: u64, n0: usize, count: usize, out: u64) !void { + /// Branch rows `stride` samples apart, read as zero outside [0, total). + pub fn mix(k: *const Kernels, s: cuda.Stream, branches: u64, stride: usize, total: usize, w: u64, n0: usize, count: usize, out: u64) !void { var a: cuda.Args = .{}; a.add(branches); + a.add(l(stride)); a.add(l(total)); a.add(w); a.add(l(n0)); diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index 4a3f301ad87..5849b950dd5 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -203,17 +203,21 @@ fn codecCheck(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: [] try codec.decode(codes, probe); const pcm = try codec.finish(gpa, probe); gpa.free(pcm); - // the same frames in uneven chunks, then timed whole + // the same frames in uneven chunks, the settled samples taken after each, then timed whole try codec.reset(); + var settled: std.ArrayList(f32) = .empty; + defer settled.deinit(gpa); var at: usize = 0; var step: usize = 1; while (at < codes.len) : (step = step * 2 + 1) { const n = @min(step, codes.len - at); try codec.decode(codes[at..][0..n], null); at += n; + const part = try codec.emit(gpa, at == codes.len, null); + defer gpa.free(part); + try settled.appendSlice(gpa, part); } - const chunked = try codec.finish(gpa, null); - defer gpa.free(chunked); + const chunked = settled.items; try codec.reset(); const t0 = nowNs(io); try codec.decode(codes, null); diff --git a/zig/src/families/zonos3/generation.zig b/zig/src/families/zonos3/generation.zig index 10d1085e43b..c6d0f3a1d09 100644 --- a/zig/src/families/zonos3/generation.zig +++ b/zig/src/families/zonos3/generation.zig @@ -21,6 +21,11 @@ fn coldStart(row: *[C]i32, generated: usize, has_audio_prefix: bool) void { /// `engine` has run(rows, replaced, probe) and lastLogits(out): the backbone, or a stand-in under test. pub fn generate(gpa: std.mem.Allocator, engine: anytype, prompt: []const [W]i32, replaced: anytype, sampling: sampler.Sampling, max_frames: usize) !Result { + return generateWatched(gpa, engine, prompt, replaced, sampling, max_frames, null); +} + +/// As generate; `watch`, when given, has row(rows so far, eos frame, finished) and sees every generated row. +pub fn generateWatched(gpa: std.mem.Allocator, engine: anytype, prompt: []const [W]i32, replaced: anytype, sampling: sampler.Sampling, max_frames: usize, watch: anytype) !Result { if (prompt.len == 0 or max_frames == 0) return error.NoRows; const logits = try gpa.create([C][cfg.audio_vocab]f32); defer gpa.destroy(logits); @@ -58,6 +63,7 @@ pub fn generate(gpa: std.mem.Allocator, engine: anytype, prompt: []const [W]i32, countdown -= 1; if (countdown == 0) finished = true; } + if (@TypeOf(watch) != @TypeOf(null)) try watch.row(rows.items, eos_frame, finished); if (finished) break; try engine.run(rows.items[generated..], &.{}, null); } diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index e5189861089..22eaae7122d 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -29,5 +29,6 @@ test { _ = prompt; _ = speech; _ = release; + _ = voices; _ = codec_weights; } diff --git a/zig/src/native/zonos_host.zig b/zig/src/native/zonos_host.zig index 8f67dd7dc57..1ff590543f7 100644 --- a/zig/src/native/zonos_host.zig +++ b/zig/src/native/zonos_host.zig @@ -1,4 +1,4 @@ -//! Native speech from one ZONOS3 Mini family on CUDA: one request at a time, its audio decoded whole at the end. +//! Native speech from one ZONOS3 Mini family on CUDA: one request at a time, streamed in chunks or decoded at the end. const std = @import("std"); const api = @import("engine_api"); const z3 = @import("zonos3"); @@ -62,6 +62,40 @@ const Guarded = struct { } }; +/// Frames a streamed chunk waits for after `spoken` generated frames went out: 1, 2, 4, 8, then 15 (a second). +pub fn chunkFrames(spoken: usize) usize { + return @min(15, 1 + spoken); +} + +/// A request's audio as its rows arrive: streamed requests decode in growing chunks, the rest once at the end. +const Audio = struct { + h: *Host, + job: Job, + prefill: []const [W]i32, + decoded: usize = 0, // frames handed to the codec + samples: usize = 0, // samples in the request's buffer + + pub fn row(s: *Audio, rows: []const [W]i32, eos_frame: ?usize, finished: bool) !void { + const h = s.h; + const r = s.job.request; + if (!finished and !r.stream) return; + const all = try z3.speech.frames(h.gpa, s.prefill, rows, eos_frame); + defer h.gpa.free(all); + const waiting = (s.prefill.len -| s.decoded) + chunkFrames(s.decoded -| s.prefill.len); + if (!finished and all.len - s.decoded < waiting) return; + try h.codec.decode(all[s.decoded..], null); + s.decoded = all.len; + const pcm = try h.codec.emit(h.gpa, finished, null); + defer h.gpa.free(pcm); + if (pcm.len > r.pcm.len - s.samples) return error.AudioOverflow; + for (pcm) |x| if (!std.math.isFinite(x)) return error.NonFiniteAudio; + z3.speech.output(pcm, h.rel.headroom_db); + @memcpy(r.pcm[s.samples..][0..pcm.len], pcm); + s.samples += pcm.len; + if (r.stream and pcm.len > 0) s.job.sink.event(s.job.sink.ctx, s.job.id, &.{ .audio = s.samples }); + } +}; + const Host = struct { gpa: std.mem.Allocator, io: std.Io, @@ -190,7 +224,7 @@ const Host = struct { } } - /// One request: its prompt rows, frames to the end of audio or the budget, then the whole audio into its buffer. + /// One request: its prompt rows, then frames to the end of audio or the budget, their audio into its buffer. fn serve(h: *Host, job: Job, samples: *usize) !api.Reason { const r = job.request; const gpa = h.gpa; @@ -210,20 +244,11 @@ const Host = struct { } const sampling: z3.Sampling = .{ .temperature = r.temperature, .top_k = r.top_k, .top_p = r.top_p, .seed = r.seed }; try h.e.reset(); - const made = try z3.generation.generate(gpa, Guarded{ .h = h }, r.frames, @as([]const z3.Replace, replaced[0..n]), sampling, r.max_frames); - defer gpa.free(made.rows); - const frames = try z3.speech.frames(gpa, r.frames[r.frames.len - layout.prefill ..], made.rows, made.eos_frame); - defer gpa.free(frames); try h.codec.reset(); - try h.codec.decode(frames, null); - const pcm = try h.codec.finish(gpa, null); - defer gpa.free(pcm); - if (pcm.len > r.pcm.len) return error.AudioOverflow; - for (pcm) |x| if (!std.math.isFinite(x)) return error.NonFiniteAudio; - z3.speech.output(pcm, h.rel.headroom_db); - @memcpy(r.pcm[0..pcm.len], pcm); - samples.* = pcm.len; - if (r.stream) job.sink.event(job.sink.ctx, job.id, &.{ .audio = pcm.len }); + var audio: Audio = .{ .h = h, .job = job, .prefill = r.frames[r.frames.len - layout.prefill ..] }; + const made = try z3.generation.generateWatched(gpa, Guarded{ .h = h }, r.frames, @as([]const z3.Replace, replaced[0..n]), sampling, r.max_frames, &audio); + defer gpa.free(made.rows); + samples.* = audio.samples; return if (made.eos_frame != null) .stop else .length; } @@ -301,6 +326,15 @@ test "budget: the release's frame budget where the context holds it, the rest fo try t.expectError(error.BadZonosFrames, budget(4096, 5)); } +test "chunkFrames: a streamed reply's chunks double to a second" { + const t = std.testing; + var spoken: usize = 0; + for ([_]usize{ 1, 2, 4, 8, 15, 15 }) |want| { + try t.expectEqual(want, chunkFrames(spoken)); + spoken += want; + } +} + test "Layout: the condition rows sit before the text and the silence rows after it" { const t = std.testing; var p = try z3.prompt.build(t.allocator, &.{ 9, 8 }, .embedding, @splat(1), 3); From 564e5d22296ad5a1c2504490e1db14f223a0506e Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:17:19 +0000 Subject: [PATCH 313/361] zonos3: a one-line comment --- zig/src/families/zonos3/cuda/codec.zig | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig index 433cbf9a151..e083219eb12 100644 --- a/zig/src/families/zonos3/cuda/codec.zig +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -242,8 +242,7 @@ pub const Codec = struct { c.frames += t; } - /// The samples no later frame can change, from where the last call stopped (caller frees); `final` adds the rest. - /// After F frames 2940 F - 1470 samples are settled: the centered iSTFT, the mixer and the resampler look ahead. + /// The samples no later frame can change since the last call (2940 F - 1470 after F frames); `final` adds the rest. pub fn emit(c: *Codec, gpa: std.mem.Allocator, final: bool, probe: ?Probe) ![]f32 { const k = &c.k; const s = c.stream; From 971a3f5602df03d2ed7676c2b9e85e38329ba030 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:27:07 +0000 Subject: [PATCH 314/361] zonos3: a request's own voice as reference codes (speaker_reference_codes) --- zig/src/server/speech.zig | 9 +++++++-- zig/src/server/zonos_speech.zig | 33 +++++++++++++++++++++++++++------ 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index 263eaf74d76..91682b3e567 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -33,6 +33,9 @@ pub const max_input_chars = 4096; /// The request fields served: the OpenAI ones (``speaker`` is ``voice``'s alias); ``stream*`` are checked apart. const served_fields = [_][]const u8{ "model", "input", "voice", "speaker", "response_format" }; +/// A voice as codes the caller encoded: frames of ten codec codes, a ZONOS3 reference prefix in place of `voice`. +const zonos_codes = "speaker_reference_codes"; + /// The rest of the speech protocol's fields: synthesis modifiers and references this route does not honor. const modifier_fields = [_][]const u8{ "speed", "task_type", "language", "instructions", "ref_audio", "ref_text", "references", "x_vector_only_mode", "stream_codec_output", "suppress_bootstrap_silence", "token_count", "duration_tokens", "initial_codec_chunk_frames", "max_new_tokens", "repetition_penalty", "stage_params" }; @@ -88,7 +91,7 @@ fn checkFields(cx: *Cx, body: Value, inline_voices: bool) errors.Refused!void { return cx.refuse("stream_format must be one of: audio, sse"); } else if (std.mem.eql(u8, key, "sample_rate") or std.mem.eql(u8, key, "channels")) { continue; // checked with the format and stream in prepare - } else if (speech_sampling.isField(key)) { + } else if (speech_sampling.isField(key) or std.mem.eql(u8, key, zonos_codes)) { continue; // validated together before building the prompt } else if (listed(&modifier_fields, key)) { if (value != .null) return cx.fail(.request, "{s} is not supported by this model", .{key}); @@ -147,8 +150,10 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused const format = try responseFormat(cx, raw.strField("response_format") orelse "wav"); const stream = if (raw.get("stream")) |s| s == .bool and s.bool else false; if (stream and format != .pcm) return cx.refuse("stream=true requires response_format='pcm'"); + const codes = raw.field(zonos_codes); + if (codes != null and srv.zonos == null) return cx.fail(.request, "{s} is not supported by this model", .{zonos_codes}); if (srv.zonos) |state| { - const made = try zonos.plan(state, cx, srv.text, sp, input, raw.strField("voice") orelse raw.strField("speaker") orelse "default"); + const made = try zonos.plan(state, cx, srv.text, sp, input, raw.strField("voice") orelse raw.strField("speaker") orelse "default", codes); const rate, const channels = try output(cx, raw, sp, stream); return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .sampling = sampling, .format = format, .stream = stream, .rate = rate, .channels = channels }; } diff --git a/zig/src/server/zonos_speech.zig b/zig/src/server/zonos_speech.zig index 64e934d3279..94a9755a0bf 100644 --- a/zig/src/server/zonos_speech.zig +++ b/zig/src/server/zonos_speech.zig @@ -39,12 +39,33 @@ pub fn load(a: Allocator, io: std.Io, dir: []const u8, default_voice: []const u8 return st; } +/// A request's own voice: 1 to 900 frames of ten codec codes, each below 4096. +fn referenceCodes(cx: *errors.Cx, value: json.Value) errors.Refused![]const [req.config.codebooks]i32 { + const message = error_prefix ++ " speaker_reference_codes must be 1 to 900 frames of ten integers from 0 through 4095"; + const frames = value.items() orelse return cx.refuse(message); + if (frames.len == 0 or frames.len > req.reference_frames) return cx.refuse(message); + const out = try cx.a.alloc([req.config.codebooks]i32, frames.len); + for (frames, out) |frame, *row| { + const codes = frame.items() orelse return cx.refuse(message); + if (codes.len != row.len) return cx.refuse(message); + for (codes, row) |code, *slot| { + if (code != .int) return cx.refuse(message); + slot.* = std.fmt.parseInt(i32, code.int, 10) catch return cx.refuse(message); + if (slot.* < 0 or slot.* >= req.config.codebook_size) return cx.refuse(message); + } + } + return out; +} + /// The request's prompt: the voice's reference codes as a delayed prefix, the condition rows, the text, the silence. -pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.SpeechInfo, input: []const u8, voice: []const u8) errors.Refused!Made { - const chosen = if (voice.len == 0 or std.ascii.eqlIgnoreCase(voice, "default")) st.default else req.voices.find(st.voices, voice); - const v = chosen orelse { - if (st.voices.len == 0) return cx.refuse(error_prefix ++ " this release folder has no voices under gguf/voices"); - return cx.fail(.request, error_prefix ++ " unknown voice {s}; see /v1/voices", .{try pyrepr.repr(cx.a, .{ .string = voice })}); +pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.SpeechInfo, input: []const u8, voice: []const u8, own: ?json.Value) errors.Refused!Made { + const reference = if (own) |value| try referenceCodes(cx, value) else blk: { + const chosen = if (voice.len == 0 or std.ascii.eqlIgnoreCase(voice, "default")) st.default else req.voices.find(st.voices, voice); + const v = chosen orelse { + if (st.voices.len == 0) return cx.refuse(error_prefix ++ " this release folder has no voices under gguf/voices"); + return cx.fail(.request, error_prefix ++ " unknown voice {s}; see /v1/voices", .{try pyrepr.repr(cx.a, .{ .string = voice })}); + }; + break :blk v.codes; }; const spoken = req.prompt.collapseLineBreaks(cx.a, input) catch |e| return switch (e) { error.OutOfMemory => error.OutOfMemory, @@ -54,7 +75,7 @@ pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.Speec error.OutOfMemory => error.OutOfMemory, else => cx.other("the tokenizer cannot encode this prompt"), }; - const built = req.prompt.build(cx.a, ids, .{ .reference = v.codes }, st.silence, req.silence_frames) catch |e| return switch (e) { + const built = req.prompt.build(cx.a, ids, .{ .reference = reference }, st.silence, req.silence_frames) catch |e| return switch (e) { error.OutOfMemory => error.OutOfMemory, else => cx.refuse(error_prefix ++ " the text has nothing to speak"), }; From 411a9fc09f2081146d2b5be50db1c532b3d0b839 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:37:27 +0000 Subject: [PATCH 315/361] zonos3: the codec encoder's acoustic branch on CUDA in fp32, checked against the reference's fp32 run --- zig/build/cuda_kernels.zig | 1 + zig/kernels/cuda/zonos3_encoder.cu | 71 ++++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/zonos3/cuda/codec.zig | 16 +- zig/src/families/zonos3/cuda/codec_layers.zig | 23 ++ zig/src/families/zonos3/cuda/encoder.zig | 239 ++++++++++++++++++ .../families/zonos3/cuda/encoder_weights.zig | 150 +++++++++++ zig/src/families/zonos3/generate.zig | 57 ++++- zig/src/families/zonos3/zonos3.zig | 1 + 9 files changed, 541 insertions(+), 18 deletions(-) create mode 100644 zig/kernels/cuda/zonos3_encoder.cu create mode 100644 zig/src/families/zonos3/cuda/codec_layers.zig create mode 100644 zig/src/families/zonos3/cuda/encoder.zig create mode 100644 zig/src/families/zonos3/cuda/encoder_weights.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 4ad41f2d080..57f9dc0d1d8 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -200,6 +200,7 @@ pub const kernels = [_]Kernel{ .{ .name = "drama3_codec", .flags = &.{"-O3"} }, .{ .name = "zonos3", .flags = glue }, // ours: ZONOS3 Mini's fp32 row kernels over bf16 weights .{ .name = "zonos3_codec", .flags = glue }, // ours: ZONOS3's codec decoder in fp32 + .{ .name = "zonos3_encoder", .flags = glue }, // ours: ZONOS3's codec encoder front end in fp32 }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. diff --git a/zig/kernels/cuda/zonos3_encoder.cu b/zig/kernels/cuda/zonos3_encoder.cu new file mode 100644 index 00000000000..ebf1bdbd9b6 --- /dev/null +++ b/zig/kernels/cuda/zonos3_encoder.cu @@ -0,0 +1,71 @@ +// ours: ZONOS3's codec encoder front end on CUDA in fp32: the resampler in, causal convolutions, Snake, patches. +#include +#include +#include "common/reduce.cuh" + +namespace { + +using tf_common::warp_sum; + +} // namespace + +// 44100 to 44160 Hz: output m = 736 q + c is sum_j kernel[c][j] x[735 q + j - 17], zero outside [0, total). +extern "C" __global__ void ze_resample_in(const float* __restrict__ x, long long total, + const float* __restrict__ kernel, long long count, + float* __restrict__ out) { + const long long m = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (m >= count) return; + const long long q = m / 736; + const int c = (int)(m % 736); + float a = 0.f; + for (int j = 0; j < 769; ++j) { + const long long p = 735 * q + j - 17; + if (p >= 0 && p < total) a = fmaf(kernel[c * 769 + j], x[p], a); + } + out[m] = a; +} + +// out[t, o] = bias[o] + sum_j sum_c W[o][j][c] x[t * stride - pad + j * dilation, c], x zero outside [0, T). +extern "C" __global__ void __launch_bounds__(256) ze_conv(const float* __restrict__ x, int Cin, int T, + const float* __restrict__ W, const float* __restrict__ bias, + int K, int dilation, int stride, int pad, + float* __restrict__ out, int Cout) { + extern __shared__ float xs[]; + const long long t = blockIdx.x; + const int n = K * Cin; + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const long long p = t * stride - pad + (long long)(i / Cin) * dilation; + xs[i] = (p >= 0 && p < T) ? x[p * Cin + i % Cin] : 0.f; + } + __syncthreads(); + const int lane = threadIdx.x & 31; + const int o = blockIdx.y * 8 + (threadIdx.x >> 5); + const float* wr = W + (size_t)min(o, Cout - 1) * n; + float acc = 0.f; + for (int k = lane; k < n; k += 32) acc = fmaf(wr[k], xs[k], acc); + acc = warp_sum(acc); + if (lane == 0 && o < Cout) out[(size_t)t * Cout + o] = acc + bias[o]; +} + +// Snake: y = x + sin^2(alpha x) / (alpha + 1e-9), alpha a channel; rows of C channels. +extern "C" __global__ void ze_snake(const float* __restrict__ x, const float* __restrict__ alpha, int C, + long long n, float* __restrict__ y) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float a = alpha[i % C]; + const float s = sinf(a * x[i]); + y[i] = x[i] + s * s / (a + 1e-9f); +} + +// x += y over n values. +extern "C" __global__ void ze_add(float* __restrict__ x, const float* __restrict__ y, long long n) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] += y[i]; +} + +// Patch down by h: in [T * h][C] to out [T][C * h], out[t][c * h + j] = in[t * h + j][c]. +extern "C" __global__ void ze_patch_down(const float* __restrict__ in, float* __restrict__ out, int C, int h) { + const size_t t = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < C * h) out[t * C * h + i] = in[(t * h + i % h) * C + i / h]; +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index de60773ce91..843f9be7bcd 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -207,6 +207,7 @@ pub const drama3_codec: []const u8 = if (available) &Blob("fatbin_drama3_codec") pub const drama3_staged_gemv: []const u8 = if (available) &Blob("fatbin_drama3_staged_gemv").bytes else &.{}; pub const zonos3: []const u8 = if (available) &Blob("fatbin_zonos3").bytes else &.{}; pub const zonos3_codec: []const u8 = if (available) &Blob("fatbin_zonos3_codec").bytes else &.{}; +pub const zonos3_encoder: []const u8 = if (available) &Blob("fatbin_zonos3_encoder").bytes else &.{}; pub const gdn_train: []const u8 = if (available) &Blob("fatbin_gdn_train").bytes else &.{}; pub const train_q4: []const u8 = if (available) &Blob("fatbin_train_q4").bytes else &.{}; pub const train_attn: []const u8 = if (available) &Blob("fatbin_train_attn").bytes else &.{}; diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig index e083219eb12..7e2fcd11595 100644 --- a/zig/src/families/zonos3/cuda/codec.zig +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -3,6 +3,7 @@ const std = @import("std"); const cuda = @import("cuda"); const kern = @import("codec_kernels.zig"); const wts = @import("codec_weights.zig"); +const stage_layer = @import("codec_layers.zig"); const Buf = cuda.DeviceBuffer; const W = wts.width; @@ -177,20 +178,7 @@ pub const Codec = struct { } fn layer(c: *Codec, shape: wts.StageShape, L: wts.Layer, kv: [2]u64, x: u64, rows: usize, pos0: usize) !void { - const k = &c.k; - const s = c.stream; - const d = shape.d; - try k.layernorm(s, x, L.n1w, L.n1b, c.n, d, 1e-5, rows); - try k.linear(s, L.qkv, 0, c.n, d, d, 3 * d, c.big, 3 * d, rows); - try k.attnPrep(s, c.big, d, pos0, kv[0], kv[1], rows); - try k.attention(s, c.big, d, kv[0], kv[1], pos0, shape.ctx, c.att, rows); - try k.linear(s, L.attn_out, 0, c.att, d, d, d, c.o_, d, rows); - try k.addScaled(s, x, c.o_, L.attn_scale, d, rows); - try k.layernorm(s, x, L.n2w, L.n2b, c.n, d, 1e-5, rows); - try k.linear(s, L.ffn0, 0, c.n, d, d, shape.ff, c.big, shape.ff, rows); - try k.gelu(s, c.big, rows * shape.ff); - try k.linear(s, L.ffn1, 0, c.big, shape.ff, shape.ff, d, c.o_, d, rows); - try k.addScaled(s, x, c.o_, L.ffn_scale, d, rows); + try stage_layer.layer(&c.k, c.stream, .{ .n = c.n, .o = c.o_, .att = c.att, .big = c.big }, shape, L, kv, x, rows, pos0); } fn pass(c: *Codec, codes: []const [10]i32, probe: ?Probe) !void { diff --git a/zig/src/families/zonos3/cuda/codec_layers.zig b/zig/src/families/zonos3/cuda/codec_layers.zig new file mode 100644 index 00000000000..f366906c06a --- /dev/null +++ b/zig/src/families/zonos3/cuda/codec_layers.zig @@ -0,0 +1,23 @@ +//! The codec's causal transformer layer, shared by the decoder's and the encoder's stages. +const cuda = @import("cuda"); +const kern = @import("codec_kernels.zig"); +const wts = @import("codec_weights.zig"); + +/// A layer's scratch rows: the norm's output, a projection's output, attention's output, and the wide rows. +pub const Scratch = struct { n: u64, o: u64, att: u64, big: u64 }; + +/// x [rows][d] at positions pos0 on: x += scale * attention(norm(x)), then x += scale * ffn(norm(x)). +pub fn layer(k: *const kern.Kernels, s: cuda.Stream, sc: Scratch, shape: wts.StageShape, L: wts.Layer, kv: [2]u64, x: u64, rows: usize, pos0: usize) !void { + const d = shape.d; + try k.layernorm(s, x, L.n1w, L.n1b, sc.n, d, 1e-5, rows); + try k.linear(s, L.qkv, 0, sc.n, d, d, 3 * d, sc.big, 3 * d, rows); + try k.attnPrep(s, sc.big, d, pos0, kv[0], kv[1], rows); + try k.attention(s, sc.big, d, kv[0], kv[1], pos0, shape.ctx, sc.att, rows); + try k.linear(s, L.attn_out, 0, sc.att, d, d, d, sc.o, d, rows); + try k.addScaled(s, x, sc.o, L.attn_scale, d, rows); + try k.layernorm(s, x, L.n2w, L.n2b, sc.n, d, 1e-5, rows); + try k.linear(s, L.ffn0, 0, sc.n, d, d, shape.ff, sc.big, shape.ff, rows); + try k.gelu(s, sc.big, rows * shape.ff); + try k.linear(s, L.ffn1, 0, sc.big, shape.ff, shape.ff, d, sc.o, d, rows); + try k.addScaled(s, x, sc.o, L.ffn_scale, d, rows); +} diff --git a/zig/src/families/zonos3/cuda/encoder.zig b/zig/src/families/zonos3/cuda/encoder.zig new file mode 100644 index 00000000000..35149215dff --- /dev/null +++ b/zig/src/families/zonos3/cuda/encoder.zig @@ -0,0 +1,239 @@ +//! ZONOS3's codec encoder on one GPU, the acoustic branch: a lane of 44.1 kHz audio in, its latent rows at 15 Hz out. +const std = @import("std"); +const cuda = @import("cuda"); +const kern = @import("codec_kernels.zig"); +const layers = @import("codec_layers.zig"); +const wts = @import("encoder_weights.zig"); + +const Buf = cuda.DeviceBuffer; + +pub const frame_samples = 2940; // 44.1 kHz samples a code frame +pub const internal_frame = 2944; // 44.16 kHz samples a code frame +pub const lane_frames = 300; // a lane is at most 20 s; a longer clip continues in lanes with 10 s of left context +pub const latent_dim = 1024; +const head_rows = 16; // 240 Hz rows a code frame + +/// A capture under the reference's dump names: device fp32 rows [rows, width]. +pub const Probe = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void, + + fn at(p: Probe, comptime f: []const u8, args: anytype, ptr: u64, rows: usize, width: usize) !void { + var nb: [64]u8 = undefined; + try p.f(p.ctx, try std.fmt.bufPrint(&nb, f, args), ptr, rows, width); + } +}; + +const names = .{ "ze_resample_in", "ze_conv", "ze_snake", "ze_add", "ze_patch_down" }; +const F = enum(u8) { resample_in, conv, snake, add, patch_down }; + +pub const Encoder = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + stream: cuda.Stream, + k: kern.Kernels, + mod: cuda.Module, + fns: [names.len]cuda.Function, + w: *wts.Weights, + bufs: std.ArrayList(Buf), + audio: u64, // the lane's 44.1 kHz samples + wave: u64, // its 44.16 kHz samples, whole frames + p: u64, // front-end rows, three buffers a block's steps rotate through + q: u64, + r: u64, + sc: layers.Scratch, + kv: [2]u64, + latent: u64, // [frames][latent_dim], the last lane's + + /// The encoder on a context the caller made current, launching on `stream`. + pub fn create(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, stream: cuda.Stream, generator: []const u8) !*Encoder { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const e = try gpa.create(Encoder); + errdefer gpa.destroy(e); + e.* = undefined; + e.gpa = gpa; + e.d = d; + e.stream = stream; + e.bufs = .empty; + e.k = try kern.Kernels.load(d); + errdefer e.k.unload(); + e.mod = try cuda.Module.load(d, cuda.kernels.zonos3_encoder); + errdefer e.mod.unload(); + inline for (names, 0..) |name, j| e.fns[j] = try e.mod.function(name); + e.w = try wts.load(gpa, io, d, generator); + errdefer { + e.w.deinit(); + gpa.destroy(e.w); + } + errdefer e.freeState(); + const samples = lane_frames * internal_frame; + const rows = lane_frames * head_rows; + const front = samples * wts.blocks[0].channels * 4; + e.audio = try e.alloc(lane_frames * frame_samples * 4); + e.wave = try e.alloc(samples * 4); + e.p = try e.alloc(front); + e.q = try e.alloc(front); + e.r = try e.alloc(front); + e.sc = .{ .n = try e.alloc(rows * 768 * 4), .o = try e.alloc(rows * 768 * 4), .att = try e.alloc(rows * 768 * 4), .big = try e.alloc(rows * 3072 * 4) }; + e.kv = .{ try e.alloc(rows * 768 * 4), try e.alloc(rows * 768 * 4) }; + e.latent = try e.alloc(lane_frames * latent_dim * 4); + return e; + } + + pub fn destroy(e: *Encoder) void { + e.stream.synchronize() catch {}; + e.freeState(); + e.w.deinit(); + e.gpa.destroy(e.w); + e.mod.unload(); + e.k.unload(); + e.gpa.destroy(e); + } + + fn freeState(e: *Encoder) void { + for (e.bufs.items) |*b| b.free(); + e.bufs.deinit(e.gpa); + } + + fn alloc(e: *Encoder, bytes: usize) !u64 { + var b = try Buf.alloc(e.d, @max(bytes, 256)); + errdefer b.free(); + try e.bufs.append(e.gpa, b); + return b.ptr; + } + + fn buf(e: *Encoder, ptr: u64) Buf { + return .{ .d = e.d, .ptr = ptr, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + pub fn download(e: *Encoder, src: u64, out: []u8) !void { + try e.buf(src).downloadAsync(0, out, e.stream.handle); + try e.stream.synchronize(); + } + + fn go(e: *Encoder, which: F, gx: usize, gy: usize, shared: usize, a: *cuda.Args) !void { + try cuda.launch.launch(e.fns[@backingInt(which)], .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy), .z = 1 }, .block = .{ .x = 256 }, .shared = @intCast(shared) }, e.stream, a); + } + + fn i(x: usize) i32 { + return @intCast(x); + } + + fn l(x: usize) i64 { + return @intCast(x); + } + + /// out [t_out][c_out] from x [t][c_in]: `kernel` taps `dilation` apart, `pad` zeros before the first input. + fn conv(e: *Encoder, x: u64, c_in: usize, t: usize, w: wts.Conv, kernel: usize, dilation: usize, stride: usize, pad: usize, out: u64, c_out: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(i(c_in)); + a.add(i(t)); + a.add(w.w); + a.add(w.b); + a.add(i(kernel)); + a.add(i(dilation)); + a.add(i(stride)); + a.add(i(pad)); + a.add(out); + a.add(i(c_out)); + try e.go(.conv, t / stride, (c_out + 7) / 8, kernel * c_in * 4, &a); + } + + fn snake(e: *Encoder, x: u64, alpha: u64, c: usize, t: usize, y: u64) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(alpha); + a.add(i(c)); + a.add(l(t * c)); + a.add(y); + try e.go(.snake, (t * c + 255) / 256, 1, 0, &a); + } + + fn add(e: *Encoder, x: u64, y: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(y); + a.add(l(n)); + try e.go(.add, (n + 255) / 256, 1, 0, &a); + } + + /// in [rows * h][c] to out [rows][c * h]. + fn patchDown(e: *Encoder, in: u64, out: u64, c: usize, h: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(out); + a.add(i(c)); + a.add(i(h)); + try e.go(.patch_down, (c * h + 255) / 256, rows, 0, &a); + } + + /// A lane's audio (44.1 kHz, at most 20 s, from the lane's start) to `latent`; the frames it covers. + pub fn acoustic(e: *Encoder, audio: []const f32, probe: ?Probe) !usize { + const frames = (audio.len + frame_samples - 1) / frame_samples; + if (frames == 0 or frames > lane_frames) return error.BadLane; + const s = e.stream; + const k = &e.k; + const w = e.w; + var t = frames * internal_frame; + // 44.16 kHz, zero to the end of the last frame + try e.buf(e.audio).uploadAsync(0, std.mem.sliceAsBytes(audio), s.handle); + var wave = e.buf(e.wave); + wave.len = t * 4; + try wave.fill8(0, s.handle); + { + const count = (audio.len * wts.resample_out + wts.resample_in - 1) / wts.resample_in; + var a: cuda.Args = .{}; + a.add(e.audio); + a.add(l(audio.len)); + a.add(w.resampler); + a.add(l(count)); + a.add(e.wave); + try e.go(.resample_in, (count + 255) / 256, 1, 0, &a); + } + if (probe) |p| try p.f(p.ctx, "internal_audio", e.wave, t, 1); + // the front end: x holds the block's rows, y and z are scratch + var x = e.p; + var y = e.q; + var z = e.r; + try e.conv(e.wave, 1, t, w.first, 7, 1, 1, 6, x, wts.blocks[0].channels); + if (probe) |p| try p.f(p.ctx, "lane.0.enc.in", x, t, wts.blocks[0].channels); + for (w.blocks, wts.blocks, 0..) |b, shape, bi| { + const c = shape.channels; + for (b.units, wts.dilations, 0..) |u, dilation, ui| { + try e.snake(x, u.alpha0, c, t, y); + try e.conv(y, c, t, u.wide, 7, dilation, 1, 6 * dilation, z, c); + try e.snake(z, u.alpha1, c, t, y); + try e.conv(y, c, t, u.point, 1, 1, 1, 0, z, c); + try e.add(x, z, t * c); + if (probe) |p| try p.at("lane.0.enc.b{d}.res{d}", .{ bi, ui }, x, t, c); + } + try e.snake(x, b.alpha, c, t, y); + try e.conv(y, c, t, b.down, 2 * shape.stride, 1, shape.stride, shape.stride, z, 2 * c); + t /= shape.stride; + std.mem.swap(u64, &x, &z); + if (probe) |p| try p.at("lane.0.enc.b{d}.conv", .{bi}, x, t, 2 * c); + } + var rows = t / wts.patch; + try e.patchDown(x, y, wts.front_width, wts.patch, rows); + std.mem.swap(u64, &x, &y); + // the stages: x holds a stage's input rows + for (wts.stages, w.stages, 0..) |shape, st, si| { + try k.linear(s, st.in_proj, 0, x, shape.in, shape.in, shape.d, y, shape.d, rows); + if (probe) |p| try p.at("lane.0.stage.{d}.in", .{si}, y, rows, shape.d); + for (st.layers, 0..) |L, li| { + try layers.layer(k, s, e.sc, shape, L, e.kv, y, rows, 0); + if (probe) |p| try p.at("lane.0.stage.{d}.l{d}", .{ si, li }, y, rows, shape.d); + } + try k.linear(s, st.out_proj, 0, y, shape.d, shape.d, shape.out, x, shape.out, rows); + if (probe) |p| try p.at("lane.0.stage.{d}", .{si}, x, rows, shape.out); + if (si + 1 == wts.stages.len) break; + rows /= 2; + try e.patchDown(x, y, shape.out, 2, rows); + std.mem.swap(u64, &x, &y); + } + try e.buf(e.latent).copyFrom(0, x, frames * latent_dim * 4, s.handle); + if (probe) |p| try p.f(p.ctx, "lane.0.acoustic", e.latent, frames, latent_dim); + return frames; + } +}; diff --git a/zig/src/families/zonos3/cuda/encoder_weights.zig b/zig/src/families/zonos3/cuda/encoder_weights.zig new file mode 100644 index 00000000000..eed102cffeb --- /dev/null +++ b/zig/src/families/zonos3/cuda/encoder_weights.zig @@ -0,0 +1,150 @@ +//! The codec encoder's acoustic branch as published (generator.pt, fp32): resampler, conv front end, five stages. +const std = @import("std"); +const cuda = @import("cuda"); +const pth = @import("core").torch_pth; +const dec = @import("codec_weights.zig"); + +pub const resample_in = 735; +pub const resample_out = 736; +pub const resample_taps = 769; +pub const dilations = [3]usize{ 1, 3, 9 }; + +/// A front-end block: three residual units over `channels`, then a strided convolution to twice as many. +pub const BlockShape = struct { channels: usize, stride: usize }; +pub const blocks = [2]BlockShape{ .{ .channels = 64, .stride = 2 }, .{ .channels = 128, .stride = 4 } }; +pub const patch = 23; // front-end frames a 240 Hz row +pub const front_width = 256; + +/// The stages after the patch: 240, 120, 60, 30 and 15 Hz; each but the last is followed by a patch down by 2. +pub const stages = [5]dec.StageShape{ + .{ .in = front_width * patch, .d = 768, .ff = 3072, .ctx = 480, .out = 384 }, + .{ .in = 768, .d = 768, .ff = 3072, .ctx = 480, .out = 384 }, + .{ .in = 768, .d = 768, .ff = 3072, .ctx = 480, .out = 384 }, + .{ .in = 768, .d = 768, .ff = 3072, .ctx = 300, .out = 640 }, + .{ .in = 1280, .d = 1280, .ff = 5120, .ctx = 150, .out = 1024 }, +}; + +pub const Conv = struct { w: u64, b: u64 }; // w [out][kernel * in], the kernel's taps outermost +pub const Unit = struct { alpha0: u64, wide: Conv, alpha1: u64, point: Conv }; +pub const Block = struct { units: [3]Unit, alpha: u64, down: Conv }; + +pub const Weights = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(cuda.DeviceBuffer), + bytes: usize, + resampler: u64, // [resample_out][resample_taps] + first: Conv, // 1 -> 64, kernel 7 + blocks: [2]Block, + stages: [5]dec.Stage, + + pub fn deinit(w: *Weights) void { + for (w.bufs.items) |*b| b.free(); + w.bufs.deinit(w.gpa); + for (w.stages) |st| w.gpa.free(st.layers); + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + a: *const pth.Archive, + w: *Weights, + + fn device(l: *Loader, values: []const f32) !u64 { + const bytes = std.mem.sliceAsBytes(values); + var b = try cuda.DeviceBuffer.alloc(l.d, @max(bytes.len, 256)); + errdefer b.free(); + try b.upload(0, bytes); + try l.w.bufs.append(l.gpa, b); + l.w.bytes += bytes.len; + return b.ptr; + } + + fn one(l: *Loader, name: []const u8, shape: []const u64) !u64 { + const v = try l.a.readF32(l.gpa, name, shape); + defer l.gpa.free(v); + return l.device(v); + } + + /// A weight-normed convolution `prefix`conv: v * (g / |v|) over each output's inputs and taps, taps outermost. + fn conv(l: *Loader, prefix: []const u8, out: usize, in: usize, kernel: usize) !Conv { + var nb: [200]u8 = undefined; + const v = try l.a.readF32(l.gpa, try std.fmt.bufPrint(&nb, "{s}conv.parametrizations.weight.original1", .{prefix}), &.{ out, in, kernel }); + defer l.gpa.free(v); + const g = try l.a.readF32(l.gpa, try std.fmt.bufPrint(&nb, "{s}conv.parametrizations.weight.original0", .{prefix}), &.{ out, 1, 1 }); + defer l.gpa.free(g); + const w = try l.gpa.alloc(f32, v.len); + defer l.gpa.free(w); + for (0..out) |o| { + const row = v[o * in * kernel ..][0 .. in * kernel]; + var ss: f64 = 0; + for (row) |x| ss += @as(f64, x) * x; + const scale = g[o] / @as(f32, @floatCast(@sqrt(ss))); + for (0..in) |c| for (0..kernel) |j| { + w[(o * kernel + j) * in + c] = row[c * kernel + j] * scale; + }; + } + return .{ .w = try l.device(w), .b = try l.one(try std.fmt.bufPrint(&nb, "{s}conv.bias", .{prefix}), &.{out}) }; + } +}; + +fn fmt(buf: []u8, comptime f: []const u8, args: anytype) []const u8 { + return std.fmt.bufPrint(buf, f, args) catch unreachable; +} + +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, generator: []const u8) !*Weights { + var archive = try pth.Archive.openNested(gpa, io, generator); + defer archive.close(); + const w = try gpa.create(Weights); + errdefer gpa.destroy(w); + w.* = undefined; + w.gpa = gpa; + w.bufs = .empty; + w.bytes = 0; + for (&w.stages) |*st| st.layers = &.{}; + errdefer w.deinit(); + var l: Loader = .{ .gpa = gpa, .d = d, .a = &archive, .w = w }; + var nb: [160]u8 = undefined; + const e = "generator/encoder."; + w.resampler = try l.one("generator/to_internal.kernel", &.{ resample_out, 1, resample_taps }); + w.first = try l.conv(e ++ "0.", blocks[0].channels, 1, 7); + for (&w.blocks, blocks, 1..) |*b, shape, index| { + const c = shape.channels; + for (&b.units, 0..) |*u, ui| { + const p = e ++ "{d}.module.block.{d}.module.block."; + u.* = .{ + .alpha0 = try l.one(fmt(&nb, p ++ "0.alpha", .{ index, ui }), &.{ 1, c, 1 }), + .wide = try l.conv(fmt(&nb, p ++ "1.", .{ index, ui }), c, c, 7), + .alpha1 = try l.one(fmt(&nb, p ++ "2.alpha", .{ index, ui }), &.{ 1, c, 1 }), + .point = try l.conv(fmt(&nb, p ++ "3.", .{ index, ui }), c, c, 1), + }; + } + b.alpha = try l.one(fmt(&nb, e ++ "{d}.module.block.3.alpha", .{index}), &.{ 1, c, 1 }); + b.down = try l.conv(fmt(&nb, e ++ "{d}.module.block.4.", .{index}), 2 * c, c, 2 * shape.stride); + } + for (&w.stages, stages, 0..) |*st, shape, si| { + const s = 4 + 2 * si; + var count: usize = 0; + while (archive.tensors.contains(fmt(&nb, e ++ "{d}.layers.{d}.qkv.weight", .{ s, count }))) count += 1; + if (count == 0) return error.MissingTensor; + st.layers = try gpa.alloc(dec.Layer, count); + st.in_proj = try l.one(fmt(&nb, e ++ "{d}.input_proj.weight", .{s}), &.{ shape.d, shape.in }); + st.out_proj = try l.one(fmt(&nb, e ++ "{d}.output_proj.weight", .{s}), &.{ shape.out, shape.d }); + for (st.layers, 0..) |*L, li| { + const p = e ++ "{d}.layers.{d}."; + L.* = .{ + .n1w = try l.one(fmt(&nb, p ++ "norm1.weight", .{ s, li }), &.{shape.d}), + .n1b = try l.one(fmt(&nb, p ++ "norm1.bias", .{ s, li }), &.{shape.d}), + .n2w = try l.one(fmt(&nb, p ++ "norm2.weight", .{ s, li }), &.{shape.d}), + .n2b = try l.one(fmt(&nb, p ++ "norm2.bias", .{ s, li }), &.{shape.d}), + .qkv = try l.one(fmt(&nb, p ++ "qkv.weight", .{ s, li }), &.{ 3 * shape.d, shape.d }), + .attn_out = try l.one(fmt(&nb, p ++ "attention_out.weight", .{ s, li }), &.{ shape.d, shape.d }), + .ffn0 = try l.one(fmt(&nb, p ++ "ffn.0.weight", .{ s, li }), &.{ shape.ff, shape.d }), + .ffn1 = try l.one(fmt(&nb, p ++ "ffn.3.weight", .{ s, li }), &.{ shape.d, shape.ff }), + .attn_scale = try l.one(fmt(&nb, p ++ "attention_scale", .{ s, li }), &.{shape.d}), + .ffn_scale = try l.one(fmt(&nb, p ++ "ffn_scale", .{ s, li }), &.{shape.d}), + }; + } + } + return w; +} diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index 5849b950dd5..c79233e1c2f 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -12,6 +12,7 @@ const usage = \\usage: zonos3-generate --model LM_DIR --check DUMP_DIR [--max-rows 64] [--max-ctx 4096] \\ zonos3-generate --model LM_DIR --frames-check GEN_DIR [--max-frames 2000] \\ zonos3-generate --codec-check DUMP_DIR --generator GENERATOR.pt --head HEAD.pt + \\ zonos3-generate --encoder-check DUMP_DIR --generator GENERATOR.pt \\ zonos3-generate --checkpoint RELEASE_DIR --text "..." --wav OUT.wav [--voice-embedding E.npy | --voice-codes C.npy] \\ [--seed 0] [--temperature 0.75] [--top-k 80] [--top-p 0.69] [--max-frames 2000] [--decoder ID] \\ [--silence-frames 3] [--reference GEN_DIR] @@ -25,7 +26,9 @@ const usage = \\--text speaks the text as typed (line breaks collapsed, no number or date expansion) in the voice of a 192-d \\speaker embedding (float32 .npy) or of reference codes ([frames, 10] .npy); RELEASE_DIR is a snapshot of \\Zyphra/ZONOS3-Mini. With --reference the prompt rows, frames and audio are compared with GEN_DIR's (dump_rows.py). - \\The last stderr line is "RESULT zonos3 ...". + \\--encoder-check encodes DUMP_DIR/audio.npy (44.1 kHz, one lane) and compares the acoustic branch's captures with + \\the reference's (tools/dump_golden.py codec-encoder, a CUDA bf16 run, so the match is to bf16 rounding). + \\The last stderr line is "RESULT zonos3 ...". \\ ; @@ -41,6 +44,8 @@ const Check = struct { worst: f64 = 1.0, worst_rel: f64 = 0, audio_snr_db: f64 = 0, + prefix: bool = false, + floor: f64 = 0.9999, fn probe(ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void { const c: *Check = @ptrCast(@alignCast(ctx)); @@ -54,7 +59,8 @@ const Check = struct { }; defer c.gpa.free(bytes); const arr = try z3.npy.parse(bytes); - if (arr.numel() != rows * width) return error.ReferenceShape; + // a reference lane is padded to its full length: the rows this run has are its first + if (arr.numel() < rows * width or (!c.prefix and arr.numel() != rows * width)) return error.ReferenceShape; const ref = try arr.floats(c.gpa); defer c.gpa.free(ref); const mine = try c.gpa.alloc(f32, rows * width); @@ -82,7 +88,7 @@ const Check = struct { } } const rel = if (max_ref > 0) max_d / max_ref else max_d; - const ok = worst_row >= 0.9999; + const ok = worst_row >= c.floor; c.n += 1; c.fails += @intFromBool(!ok); c.worst = @min(c.worst, worst_row); @@ -355,6 +361,41 @@ fn speak(gpa: std.mem.Allocator, io: std.Io, a: Speak) !u8 { return if (std.mem.eql(u8, verdict, "FAIL")) 1 else 0; } +fn encoderCheck(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: []const u8) !u8 { + const path = try std.fs.path.join(gpa, &.{ dir, "audio.npy" }); + defer gpa.free(path); + const f = try readNpy(gpa, io, path); + defer gpa.free(f.bytes); + const audio = try f.arr.floats(gpa); + defer gpa.free(audio); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const t_load = nowNs(io); + const enc = try z3.encoder.Encoder.create(gpa, io, &driver, stream, generator); + defer enc.destroy(); + const Enc = struct { + fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { + try @as(*z3.encoder.Encoder, @ptrCast(@alignCast(c))).download(ptr, out); + } + }; + // the reference ran in bf16: a row's cosine against it, not fp32 rounding + var c: Check = .{ .gpa = gpa, .io = io, .ctx = enc, .get = Enc.get, .dir = dir, .prefix = true, .floor = 0.99 }; + std.debug.print("zonos3 encoder check: {d} samples, {d} MiB of weights, loaded in {d:.1} s\n", .{ audio.len, enc.w.bytes >> 20, @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9 }); + const lane = audio[0..@min(audio.len, z3.encoder.lane_frames * z3.encoder.frame_samples)]; + _ = try enc.acoustic(lane, .{ .ctx = &c, .f = Check.probe }); + const t0 = nowNs(io); + const frames = try enc.acoustic(lane, null); + try stream.synchronize(); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + const pass = c.fails == 0 and c.n > 0 and c.missing == 0; + std.debug.print("RESULT zonos3 encoder {s} probes={d} low={d} missing={d} worst_row_cos={d:.6} frames={d} encode_s={d:.3}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, frames, seconds }); + return if (pass) 0 else 1; +} + pub fn main(init: std.process.Init) !u8 { const arena = init.arena.allocator(); const gpa = std.heap.c_allocator; @@ -364,6 +405,7 @@ pub fn main(init: std.process.Init) !u8 { var check: ?[]const u8 = null; var frames_check: ?[]const u8 = null; var codec_check: ?[]const u8 = null; + var encoder_check: ?[]const u8 = null; var generator: []const u8 = ""; var head: []const u8 = ""; var sp: Speak = .{}; @@ -373,11 +415,18 @@ pub fn main(init: std.process.Init) !u8 { while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } } + if (encoder_check) |dir| { + if (i != argv.len or generator.len == 0) { + std.debug.print("{s}", .{usage}); + return 2; + } + return encoderCheck(gpa, io, dir, generator); + } if (codec_check) |dir| { if (i != argv.len or generator.len == 0 or head.len == 0) { std.debug.print("{s}", .{usage}); diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index 22eaae7122d..3dde9045d73 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -13,6 +13,7 @@ pub const kernels = @import("cuda/kernels.zig"); pub const engine = @import("cuda/engine.zig"); pub const codec = @import("cuda/codec.zig"); pub const codec_weights = @import("cuda/codec_weights.zig"); +pub const encoder = @import("cuda/encoder.zig"); pub const Engine = engine.Engine; pub const Options = engine.Options; From a5d476fb2e4f20612d080c36c24be510c49f10e0 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:51:34 +0000 Subject: [PATCH 316/361] zonos3: the SSL teacher on CUDA and its input features on the host, checked against the reference's fp32 run --- zig/build/cuda_kernels.zig | 1 + zig/kernels/cuda/zonos3_teacher.cu | 93 +++++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/zonos3/check_encoder.zig | 118 +++++++++ zig/src/families/zonos3/cuda/teacher.zig | 303 ++++++++++++++++++++++ zig/src/families/zonos3/features.zig | 204 +++++++++++++++ zig/src/families/zonos3/generate.zig | 58 ++--- zig/src/families/zonos3/zonos3.zig | 3 + 8 files changed, 739 insertions(+), 42 deletions(-) create mode 100644 zig/kernels/cuda/zonos3_teacher.cu create mode 100644 zig/src/families/zonos3/check_encoder.zig create mode 100644 zig/src/families/zonos3/cuda/teacher.zig create mode 100644 zig/src/families/zonos3/features.zig diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 57f9dc0d1d8..3d16874ab05 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -201,6 +201,7 @@ pub const kernels = [_]Kernel{ .{ .name = "zonos3", .flags = glue }, // ours: ZONOS3 Mini's fp32 row kernels over bf16 weights .{ .name = "zonos3_codec", .flags = glue }, // ours: ZONOS3's codec decoder in fp32 .{ .name = "zonos3_encoder", .flags = glue }, // ours: ZONOS3's codec encoder front end in fp32 + .{ .name = "zonos3_teacher", .flags = glue }, // ours: ZONOS3's SSL teacher's attention and convolution in fp32 }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. diff --git a/zig/kernels/cuda/zonos3_teacher.cu b/zig/kernels/cuda/zonos3_teacher.cu new file mode 100644 index 00000000000..11de94d0d53 --- /dev/null +++ b/zig/kernels/cuda/zonos3_teacher.cu @@ -0,0 +1,93 @@ +// ours: ZONOS3's SSL teacher (Wav2Vec2-BERT) on CUDA in fp32: relative-key attention, the conformer's convolution. +#include +#include +#include "common/reduce.cuh" +#include "common/act.cuh" + +namespace { + +using tf_common::block_max_tree; + +} // namespace + +// Swish in place: x * sigmoid(x). +extern "C" __global__ void zt_swish(float* __restrict__ x, long long n) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = tf_common::silu(x[i]); +} + +// GLU: out[r, c] = in[r, c] * sigmoid(in[r, C + c]). +extern "C" __global__ void zt_glu(const float* __restrict__ in, float* __restrict__ out, int C) { + const size_t r = blockIdx.y; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c < C) out[r * C + c] = in[r * 2 * C + c] * tf_common::sigmoidf_(in[r * 2 * C + C + c]); +} + +// Depthwise conv of K taps, the newest input last, zeros before row 0: out[t, c] = sum_j w[c][j] x[t - K + 1 + j, c]. +extern "C" __global__ void zt_dwconv(const float* __restrict__ x, const float* __restrict__ w, int K, int C, + float* __restrict__ out) { + const long long t = blockIdx.y; + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= C) return; + float a = 0.f; + for (int j = 0; j < K; ++j) { + const long long p = t - K + 1 + j; + if (p >= 0) a = fmaf(w[c * K + j], x[p * C + c], a); + } + out[t * C + c] = a; +} + +// Attention of (row l, head h) over all T rows: score(r) = (q . k_r + q . E[clamp(r - l, -64, 8) + 64]) / 8. +extern "C" __global__ void __launch_bounds__(128) zt_attention(const float* __restrict__ qkv, int D, int T, + const float* __restrict__ E, + float* __restrict__ out) { + __shared__ float part[32]; + __shared__ float pe[73]; + __shared__ float acc[128][65]; + const int l = blockIdx.x, h = blockIdx.y; + float qv[64]; + const float* qr = qkv + (size_t)l * 3 * D + h * 64; +#pragma unroll + for (int i = 0; i < 64; ++i) qv[i] = qr[i]; + if (threadIdx.x < 73) { + const float* e = E + threadIdx.x * 64; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 64; ++i) d = fmaf(qv[i], e[i], d); + pe[threadIdx.x] = d; + } + __syncthreads(); + float m = -INFINITY; + for (int r = threadIdx.x; r < T; r += blockDim.x) { + const float* k = qkv + (size_t)r * 3 * D + D + h * 64; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 64; ++i) d = fmaf(qv[i], k[i], d); + m = fmaxf(m, (d + pe[min(max(r - l, -64), 8) + 64]) * 0.125f); + } + m = block_max_tree(m, part, 4); + float a[65]; +#pragma unroll + for (int i = 0; i < 65; ++i) a[i] = 0.f; + for (int r = threadIdx.x; r < T; r += blockDim.x) { + const float* k = qkv + (size_t)r * 3 * D + D + h * 64; + const float* v = k + D; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 64; ++i) d = fmaf(qv[i], k[i], d); + const float e = expf((d + pe[min(max(r - l, -64), 8) + 64]) * 0.125f - m); + a[64] += e; +#pragma unroll + for (int i = 0; i < 64; ++i) a[i] = fmaf(e, v[i], a[i]); + } +#pragma unroll + for (int i = 0; i < 65; ++i) acc[threadIdx.x][i] = a[i]; + __syncthreads(); + if (threadIdx.x < 65) { + float s = 0.f; + for (int w = 0; w < 128; ++w) s += acc[w][threadIdx.x]; + acc[0][threadIdx.x] = s; + } + __syncthreads(); + if (threadIdx.x < 64) out[(size_t)l * D + h * 64 + threadIdx.x] = acc[0][threadIdx.x] / acc[0][64]; +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 843f9be7bcd..03585f6583c 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -208,6 +208,7 @@ pub const drama3_staged_gemv: []const u8 = if (available) &Blob("fatbin_drama3_s pub const zonos3: []const u8 = if (available) &Blob("fatbin_zonos3").bytes else &.{}; pub const zonos3_codec: []const u8 = if (available) &Blob("fatbin_zonos3_codec").bytes else &.{}; pub const zonos3_encoder: []const u8 = if (available) &Blob("fatbin_zonos3_encoder").bytes else &.{}; +pub const zonos3_teacher: []const u8 = if (available) &Blob("fatbin_zonos3_teacher").bytes else &.{}; pub const gdn_train: []const u8 = if (available) &Blob("fatbin_gdn_train").bytes else &.{}; pub const train_q4: []const u8 = if (available) &Blob("fatbin_train_q4").bytes else &.{}; pub const train_attn: []const u8 = if (available) &Blob("fatbin_train_attn").bytes else &.{}; diff --git a/zig/src/families/zonos3/check_encoder.zig b/zig/src/families/zonos3/check_encoder.zig new file mode 100644 index 00000000000..a8a600a162f --- /dev/null +++ b/zig/src/families/zonos3/check_encoder.zig @@ -0,0 +1,118 @@ +//! zonos3-generate's checks of the codec encoder against the reference's dumps: the acoustic branch, the SSL features. +const std = @import("std"); +const z3 = @import("zonos3"); +const cuda = @import("cuda"); +const gen = @import("generate.zig"); + +const Check = gen.Check; +const nowNs = gen.nowNs; +const readNpy = gen.readNpy; + +pub fn acoustic(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: []const u8) !u8 { + const path = try std.fs.path.join(gpa, &.{ dir, "audio.npy" }); + defer gpa.free(path); + const f = try readNpy(gpa, io, path); + defer gpa.free(f.bytes); + const audio = try f.arr.floats(gpa); + defer gpa.free(audio); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const t_load = nowNs(io); + const enc = try z3.encoder.Encoder.create(gpa, io, &driver, stream, generator); + defer enc.destroy(); + const Enc = struct { + fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { + try @as(*z3.encoder.Encoder, @ptrCast(@alignCast(c))).download(ptr, out); + } + }; + // the reference ran in bf16: a row's cosine against it, not fp32 rounding + var c: Check = .{ .gpa = gpa, .io = io, .ctx = enc, .get = Enc.get, .dir = dir, .prefix = true, .floor = 0.99 }; + std.debug.print("zonos3 encoder check: {d} samples, {d} MiB of weights, loaded in {d:.1} s\n", .{ audio.len, enc.w.bytes >> 20, @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9 }); + const lane = audio[0..@min(audio.len, z3.encoder.lane_frames * z3.encoder.frame_samples)]; + _ = try enc.acoustic(lane, .{ .ctx = &c, .f = Check.probe }); + const t0 = nowNs(io); + const frames = try enc.acoustic(lane, null); + try stream.synchronize(); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + const pass = c.fails == 0 and c.n > 0 and c.missing == 0; + std.debug.print("RESULT zonos3 encoder {s} probes={d} low={d} missing={d} worst_row_cos={d:.6} frames={d} encode_s={d:.3}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, frames, seconds }); + return if (pass) 0 else 1; +} + +/// The SSL teacher's features of a lane's 44.1 kHz audio, computed on the host, against the reference's. +pub fn features(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !u8 { + const audio_path = try std.fs.path.join(gpa, &.{ dir, "lane.0.teacher_audio.npy" }); + defer gpa.free(audio_path); + const a = try readNpy(gpa, io, audio_path); + defer gpa.free(a.bytes); + const audio = try a.arr.floats(gpa); + defer gpa.free(audio); + const want_path = try std.fs.path.join(gpa, &.{ dir, "lane.0.ssl.features.npy" }); + defer gpa.free(want_path); + const w = try readNpy(gpa, io, want_path); + defer gpa.free(w.bytes); + const want = try w.arr.floats(gpa); + defer gpa.free(want); + const t0 = nowNs(io); + const low = try z3.features.resample(gpa, audio); + defer gpa.free(low); + const got = try z3.features.rows(gpa, low); + defer gpa.free(got); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + var max_d: f64 = 0; + var worst: f64 = 1; + const width = z3.features.width; + const same_shape = got.len == want.len; + if (same_shape) for (0..got.len / width) |r| { + var d: f64 = 0; + var a2: f64 = 0; + var b2: f64 = 0; + for (got[r * width ..][0..width], want[r * width ..][0..width]) |x, y| { + d += @as(f64, x) * y; + a2 += @as(f64, x) * x; + b2 += @as(f64, y) * y; + max_d = @max(max_d, @abs(@as(f64, x) - y)); + } + worst = @min(worst, d / @sqrt(a2 * b2)); + }; + const pass = same_shape and worst >= 0.9999; + std.debug.print("RESULT zonos3 features {s} rows={d} reference_rows={d} worst_row_cos={d:.7} max_abs_diff={e:.3} seconds={d:.3}\n", .{ if (pass) "PASS" else "FAIL", got.len / width, want.len / width, worst, max_d, seconds }); + return if (pass) 0 else 1; +} + +/// The SSL teacher over the reference's feature rows, against its fp32 run's layers. +pub fn teacher(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, teacher_dir: []const u8) !u8 { + const path = try std.fs.path.join(gpa, &.{ dir, "lane.0.ssl.features.npy" }); + defer gpa.free(path); + const f = try readNpy(gpa, io, path); + defer gpa.free(f.bytes); + const feats = try f.arr.floats(gpa); + defer gpa.free(feats); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const t = try z3.teacher.Teacher.create(gpa, io, &driver, stream, teacher_dir); + defer t.destroy(); + const Get = struct { + fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { + try @as(*z3.teacher.Teacher, @ptrCast(@alignCast(c))).download(ptr, out); + } + }; + var c: Check = .{ .gpa = gpa, .io = io, .ctx = t, .get = Get.get, .dir = dir }; + std.debug.print("zonos3 teacher check: {d} rows, {d} MiB of weights\n", .{ feats.len / z3.teacher.feature_width, t.bytes >> 20 }); + _ = try t.run(feats, .{ .ctx = &c, .f = Check.probe }); + const t0 = nowNs(io); + _ = try t.run(feats, null); + try stream.synchronize(); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + const pass = c.fails == 0 and c.n > 0 and c.missing == 0; + std.debug.print("RESULT zonos3 teacher {s} probes={d} low={d} missing={d} worst_row_cos={d:.7} seconds={d:.3}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, seconds }); + return if (pass) 0 else 1; +} diff --git a/zig/src/families/zonos3/cuda/teacher.zig b/zig/src/families/zonos3/cuda/teacher.zig new file mode 100644 index 00000000000..46a6fd35fc0 --- /dev/null +++ b/zig/src/families/zonos3/cuda/teacher.zig @@ -0,0 +1,303 @@ +//! ZONOS3's SSL teacher on one GPU: Wav2Vec2-BERT's 16 conformer layers over a lane's rows, fp32 over bf16 weights. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const lm = @import("kernels.zig"); +const codec = @import("codec_kernels.zig"); + +const Buf = cuda.DeviceBuffer; + +pub const layers = 16; +pub const d = 1024; +pub const ffn = 4096; +pub const feature_width = 160; +pub const heads = 16; +pub const conv_taps = 31; +pub const distances = 73; // 64 to the left, the row itself, 8 to the right +pub const max_rows = 1000; // a 20 s lane is 999 rows +const eps: f32 = 1e-5; + +/// A capture under the reference's dump names: device fp32 rows [rows, width]. +pub const Probe = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void, +}; + +const Norm = struct { w: u64, b: u64 }; // fp32 +const Linear = struct { w: u64, b: u64 }; // bf16, b 0 without a bias +const Ffn = struct { in: Linear, out: Linear }; +const Layer = struct { + ffn1_norm: Norm, + ffn1: Ffn, + attn_norm: Norm, + q: Linear, + k: Linear, + v: Linear, + attn_out: Linear, + distance: u64, // fp32 [73][64] + conv_norm: Norm, + point1: Linear, + depthwise: u64, // fp32 [d][31] + depthwise_norm: Norm, + point2: Linear, + ffn2_norm: Norm, + ffn2: Ffn, + final_norm: Norm, +}; + +const names = .{ "zt_swish", "zt_glu", "zt_dwconv", "zt_attention" }; +const F = enum(u8) { swish, glu, dwconv, attention }; + +pub const Teacher = struct { + gpa: std.mem.Allocator, + dev: *const cuda.Driver, + stream: cuda.Stream, + lm: lm.Kernels, + codec: codec.Kernels, + mod: cuda.Module, + fns: [names.len]cuda.Function, + bufs: std.ArrayList(Buf), + bytes: usize, + in_norm: Norm, + projection: Linear, + layers: [layers]Layer, + half: u64, // fp32 [d] of 0.5 + feats: u64, // [rows][160] + x: u64, // [rows][d] + h: u64, + n: u64, + att: u64, + big: u64, // [rows][ffn] + qkv: u64, // [rows][3 d] + + /// The teacher on a context the caller made current; `dir` holds its model.safetensors. + pub fn create(gpa: std.mem.Allocator, io: std.Io, dev: *const cuda.Driver, stream: cuda.Stream, dir: []const u8) !*Teacher { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const t = try gpa.create(Teacher); + errdefer gpa.destroy(t); + t.* = undefined; + t.gpa = gpa; + t.dev = dev; + t.stream = stream; + t.bufs = .empty; + t.bytes = 0; + t.lm = try lm.Kernels.load(dev); + errdefer t.lm.unload(); + t.codec = try codec.Kernels.load(dev); + errdefer t.codec.unload(); + t.mod = try cuda.Module.load(dev, cuda.kernels.zonos3_teacher); + errdefer t.mod.unload(); + inline for (names, 0..) |name, j| t.fns[j] = try t.mod.function(name); + errdefer t.freeBuffers(); + try t.loadWeights(io, dir); + const half: [d]f32 = @splat(0.5); + t.half = try t.device(std.mem.sliceAsBytes(&half)); + t.feats = try t.alloc(max_rows * feature_width * 4); + t.x = try t.alloc(max_rows * d * 4); + t.h = try t.alloc(max_rows * d * 4); + t.n = try t.alloc(max_rows * d * 4); + t.att = try t.alloc(max_rows * d * 4); + t.big = try t.alloc(max_rows * ffn * 4); + t.qkv = try t.alloc(max_rows * 3 * d * 4); + return t; + } + + pub fn destroy(t: *Teacher) void { + t.stream.synchronize() catch {}; + t.freeBuffers(); + t.mod.unload(); + t.codec.unload(); + t.lm.unload(); + t.gpa.destroy(t); + } + + fn freeBuffers(t: *Teacher) void { + for (t.bufs.items) |*b| b.free(); + t.bufs.deinit(t.gpa); + } + + fn alloc(t: *Teacher, bytes: usize) !u64 { + var b = try Buf.alloc(t.dev, @max(bytes, 256)); + errdefer b.free(); + try t.bufs.append(t.gpa, b); + return b.ptr; + } + + fn device(t: *Teacher, bytes: []const u8) !u64 { + const ptr = try t.alloc(bytes.len); + try t.buf(ptr).upload(0, bytes); + t.bytes += bytes.len; + return ptr; + } + + fn buf(t: *Teacher, ptr: u64) Buf { + return .{ .d = t.dev, .ptr = ptr, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + pub fn download(t: *Teacher, src: u64, out: []u8) !void { + try t.buf(src).downloadAsync(0, out, t.stream.handle); + try t.stream.synchronize(); + } + + fn loadWeights(t: *Teacher, io: std.Io, dir: []const u8) !void { + const gpa = t.gpa; + const path = try std.fs.path.join(gpa, &.{ dir, "model.safetensors" }); + defer gpa.free(path); + var file = try core.safetensors.File.open(gpa, io, path); + defer file.close(io); + var l: Loader = .{ .t = t, .file = &file }; + t.in_norm = try l.norm("feature_projection.layer_norm", .{}, feature_width); + t.projection = try l.linear("feature_projection.projection", .{}, d, feature_width, true); + for (&t.layers, 0..) |*L, i| { + const p = "encoder.layers.{d}."; + L.* = .{ + .ffn1_norm = try l.norm(p ++ "ffn1_layer_norm", .{i}, d), + .ffn1 = .{ .in = try l.linear(p ++ "ffn1.intermediate_dense", .{i}, ffn, d, true), .out = try l.linear(p ++ "ffn1.output_dense", .{i}, d, ffn, true) }, + .attn_norm = try l.norm(p ++ "self_attn_layer_norm", .{i}, d), + .q = try l.linear(p ++ "self_attn.linear_q", .{i}, d, d, true), + .k = try l.linear(p ++ "self_attn.linear_k", .{i}, d, d, true), + .v = try l.linear(p ++ "self_attn.linear_v", .{i}, d, d, true), + .attn_out = try l.linear(p ++ "self_attn.linear_out", .{i}, d, d, true), + .distance = try l.floats(p ++ "self_attn.distance_embedding.weight", .{i}, &.{ distances, d / heads }), + .conv_norm = try l.norm(p ++ "conv_module.layer_norm", .{i}, d), + .point1 = try l.conv1(p ++ "conv_module.pointwise_conv1", .{i}, 2 * d, d), + .depthwise = try l.floats(p ++ "conv_module.depthwise_conv.weight", .{i}, &.{ d, 1, conv_taps }), + .depthwise_norm = try l.norm(p ++ "conv_module.depthwise_layer_norm", .{i}, d), + .point2 = try l.conv1(p ++ "conv_module.pointwise_conv2", .{i}, d, d), + .ffn2_norm = try l.norm(p ++ "ffn2_layer_norm", .{i}, d), + .ffn2 = .{ .in = try l.linear(p ++ "ffn2.intermediate_dense", .{i}, ffn, d, true), .out = try l.linear(p ++ "ffn2.output_dense", .{i}, d, ffn, true) }, + .final_norm = try l.norm(p ++ "final_layer_norm", .{i}, d), + }; + } + } + + const Loader = struct { + t: *Teacher, + file: *core.safetensors.File, + nb: [160]u8 = undefined, + + fn bytesOf(l: *Loader, comptime f: []const u8, args: anytype, shape: []const usize) ![]const u8 { + const name = try std.fmt.bufPrint(&l.nb, f, args); + const tensor = l.file.get(name) orelse return error.MissingTensor; + if (!tensor.is(.bf16, shape)) return error.ShapeMismatch; + return tensor.bytes; + } + + /// A bf16 tensor as stored. + fn raw(l: *Loader, comptime f: []const u8, args: anytype, shape: []const usize) !u64 { + return l.t.device(try l.bytesOf(f, args, shape)); + } + + /// A small bf16 tensor widened to fp32. + fn floats(l: *Loader, comptime f: []const u8, args: anytype, shape: []const usize) !u64 { + const bytes = try l.bytesOf(f, args, shape); + const out = try l.t.gpa.alloc(f32, bytes.len / 2); + defer l.t.gpa.free(out); + for (out, 0..) |*o, i| o.* = @bitCast(@as(u32, std.mem.readInt(u16, bytes[i * 2 ..][0..2], .little)) << 16); + return l.t.device(std.mem.sliceAsBytes(out)); + } + + fn norm(l: *Loader, comptime f: []const u8, args: anytype, n: usize) !Norm { + return .{ .w = try l.floats(f ++ ".weight", args, &.{n}), .b = try l.floats(f ++ ".bias", args, &.{n}) }; + } + + fn linear(l: *Loader, comptime f: []const u8, args: anytype, out: usize, in: usize, bias: bool) !Linear { + return .{ .w = try l.raw(f ++ ".weight", args, &.{ out, in }), .b = if (bias) try l.raw(f ++ ".bias", args, &.{out}) else 0 }; + } + + /// A pointwise convolution's weight [out][in][1], used as a linear without a bias. + fn conv1(l: *Loader, comptime f: []const u8, args: anytype, out: usize, in: usize) !Linear { + return .{ .w = try l.raw(f ++ ".weight", args, &.{ out, in, 1 }), .b = 0 }; + } + }; + + fn go(t: *Teacher, which: F, gx: usize, gy: usize, block: usize, a: *cuda.Args) !void { + try cuda.launch.launch(t.fns[@backingInt(which)], .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy), .z = 1 }, .block = .{ .x = @intCast(block) } }, t.stream, a); + } + + fn lin(t: *Teacher, w: Linear, x: u64, in: usize, out: usize, y: u64, ys: usize, rows: usize) !void { + try t.lm.linear(t.stream, w.w, x, in, in, out, y, ys, rows, .{ .bias = w.b }); + } + + fn layernorm(t: *Teacher, x: u64, w: Norm, y: u64, n: usize, rows: usize) !void { + try t.codec.layernorm(t.stream, x, w.w, w.b, y, n, eps, rows); + } + + fn swish(t: *Teacher, x: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(i64, @intCast(n))); + try t.go(.swish, (n + 255) / 256, 1, 256, &a); + } + + /// x += half of ffn(norm(x)). + fn feedForward(t: *Teacher, w: Norm, f: Ffn, rows: usize) !void { + try t.layernorm(t.x, w, t.n, d, rows); + try t.lin(f.in, t.n, d, ffn, t.big, ffn, rows); + try t.swish(t.big, rows * ffn); + try t.lin(f.out, t.big, ffn, d, t.h, d, rows); + try t.codec.addScaled(t.stream, t.x, t.h, t.half, d, rows); + } + + /// A lane's feature rows [rows][160] through the teacher; the device rows [rows][d] of its sixteenth layer. + pub fn run(t: *Teacher, feats: []const f32, probe: ?Probe) !u64 { + const rows = feats.len / feature_width; + if (rows == 0 or rows > max_rows or feats.len % feature_width != 0) return error.BadFeatureRows; + const s = t.stream; + try t.buf(t.feats).uploadAsync(0, std.mem.sliceAsBytes(feats), s.handle); + try t.layernorm(t.feats, t.in_norm, t.n, feature_width, rows); + try t.lin(t.projection, t.n, feature_width, d, t.x, d, rows); + if (probe) |p| try p.f(p.ctx, "lane.0.ssl.feature_projection", t.x, rows, d); + for (t.layers, 0..) |L, li| { + try t.feedForward(L.ffn1_norm, L.ffn1, rows); + // attention over the whole lane, with the relative-key term + try t.layernorm(t.x, L.attn_norm, t.n, d, rows); + try t.lin(L.q, t.n, d, d, t.qkv, 3 * d, rows); + try t.lin(L.k, t.n, d, d, t.qkv + d * 4, 3 * d, rows); + try t.lin(L.v, t.n, d, d, t.qkv + 2 * d * 4, 3 * d, rows); + { + var a: cuda.Args = .{}; + a.add(t.qkv); + a.add(@as(i32, d)); + a.add(@as(i32, @intCast(rows))); + a.add(L.distance); + a.add(t.att); + try t.go(.attention, rows, heads, 128, &a); + } + try t.lin(L.attn_out, t.att, d, d, t.h, d, rows); + try t.codec.addScaled(s, t.x, t.h, 0, d, rows); + // the convolution module + try t.layernorm(t.x, L.conv_norm, t.n, d, rows); + try t.lin(L.point1, t.n, d, 2 * d, t.big, 2 * d, rows); + { + var a: cuda.Args = .{}; + a.add(t.big); + a.add(t.h); + a.add(@as(i32, d)); + try t.go(.glu, (d + 255) / 256, rows, 256, &a); + } + { + var a: cuda.Args = .{}; + a.add(t.h); + a.add(L.depthwise); + a.add(@as(i32, conv_taps)); + a.add(@as(i32, d)); + a.add(t.n); + try t.go(.dwconv, (d + 255) / 256, rows, 256, &a); + } + try t.layernorm(t.n, L.depthwise_norm, t.h, d, rows); + try t.swish(t.h, rows * d); + try t.lin(L.point2, t.h, d, d, t.n, d, rows); + try t.codec.addScaled(s, t.x, t.n, 0, d, rows); + try t.feedForward(L.ffn2_norm, L.ffn2, rows); + try t.layernorm(t.x, L.final_norm, t.n, d, rows); + std.mem.swap(u64, &t.x, &t.n); + if (probe) |p| { + var nb: [40]u8 = undefined; + try p.f(p.ctx, try std.fmt.bufPrint(&nb, "lane.0.ssl.layer.{d}", .{li}), t.x, rows, d); + } + } + if (probe) |p| try p.f(p.ctx, "lane.0.ssl", t.x, rows, d); + return t.x; + } +}; diff --git a/zig/src/families/zonos3/features.zig b/zig/src/families/zonos3/features.zig new file mode 100644 index 00000000000..732fd2b853b --- /dev/null +++ b/zig/src/families/zonos3/features.zig @@ -0,0 +1,204 @@ +//! The SSL teacher's input features on the host: 16 kHz audio, 80 Kaldi log-mel bins a frame, normalised, in pairs. +const std = @import("std"); + +pub const source_rate = 44100; +pub const rate = 16000; +pub const mel_bins = 80; +pub const width = 2 * mel_bins; // a stacked row +const frame = 400; +const hop = 160; +const fft = 512; +const bins = fft / 2 + 1; +// the resampler: 441 samples in for 160 out +const in_step = 441; +const out_step = 160; +const lowpass = 6; +const taps_before = 17; // ceil(lowpass * in_step / (out_step * 0.99)) +const taps = 2 * taps_before + in_step; + +/// The sinc kernel of a phase, Hann-windowed over six zero crossings at 0.99 of the output's Nyquist rate. +fn kernel(phase: usize, out: *[taps]f32) void { + const base: f64 = @as(f64, out_step) * 0.99; + const shift: f64 = -@as(f32, @floatFromInt(phase)) / @as(f32, out_step); + for (out, 0..) |*k, j| { + const idx = (@as(f64, @floatFromInt(j)) - taps_before) / in_step; + var t = (shift + idx) * base; + t = @min(@max(t, -lowpass), lowpass); + const c = @cos(t * std.math.pi / lowpass / 2.0); + t *= std.math.pi; + const sinc = if (t == 0) 1.0 else @sin(t) / t; + k.* = @floatCast(sinc * c * c * (base / in_step)); + } +} + +/// 44.1 kHz samples to 16 kHz (caller frees): ceil(160 n / 441) samples. +pub fn resample(gpa: std.mem.Allocator, x: []const f32) ![]f32 { + const n = (x.len * out_step + in_step - 1) / in_step; + const out = try gpa.alloc(f32, n); + errdefer gpa.free(out); + const kernels = try gpa.alloc([taps]f32, out_step); + defer gpa.free(kernels); + for (kernels, 0..) |*k, phase| kernel(phase, k); + for (out, 0..) |*o, m| { + const q = m / out_step; + const k = &kernels[m % out_step]; + var acc: f32 = 0; + for (k, 0..) |w, j| { + const p = q * in_step + j; + if (p >= taps_before and p - taps_before < x.len) acc = @mulAdd(f32, w, x[p - taps_before], acc); + } + o.* = acc; + } + return out; +} + +fn mel(hz: f64) f64 { + return 1127.0 * @log(1.0 + hz / 700.0); +} + +/// Triangles in mel space from 20 Hz to Nyquist, over the FFT bins' mel frequencies: [bins][mel_bins]. +fn filters(out: *[bins][mel_bins]f64) void { + const lo = mel(20.0); + const hi = mel(rate / 2); + var centers: [mel_bins + 2]f64 = undefined; + for (¢ers, 0..) |*c, i| c.* = lo + (hi - lo) * @as(f64, @floatFromInt(i)) / (mel_bins + 1); + const bin_width: f64 = @as(f64, rate) / fft; + for (out, 0..) |*row, b| { + const f = mel(bin_width * @as(f64, @floatFromInt(b))); + for (row, 0..) |*v, m| { + const down = (f - centers[m]) / (centers[m + 1] - centers[m]); + const up = (centers[m + 2] - f) / (centers[m + 2] - centers[m + 1]); + v.* = @max(0.0, @min(down, up)); + } + } +} + +/// In-place radix-2 FFT of `fft` points. +fn transform(re: *[fft]f64, im: *[fft]f64) void { + var j: usize = 0; + for (1..fft) |i| { + var bit: usize = fft >> 1; + while (j & bit != 0) : (bit >>= 1) j ^= bit; + j ^= bit; + if (i < j) { + std.mem.swap(f64, &re[i], &re[j]); + std.mem.swap(f64, &im[i], &im[j]); + } + } + var len: usize = 2; + while (len <= fft) : (len <<= 1) { + const angle = -2.0 * std.math.pi / @as(f64, @floatFromInt(len)); + var start: usize = 0; + while (start < fft) : (start += len) { + for (0..len / 2) |k| { + const wr = @cos(angle * @as(f64, @floatFromInt(k))); + const wi = @sin(angle * @as(f64, @floatFromInt(k))); + const a = start + k; + const b = a + len / 2; + const tr = re[b] * wr - im[b] * wi; + const ti = re[b] * wi + im[b] * wr; + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + } + } + } +} + +/// Stacked feature rows [frames / 2][width] of 16 kHz audio (caller frees); at least two frames of audio. +pub fn rows(gpa: std.mem.Allocator, audio: []const f32) ![]f32 { + if (audio.len < frame + hop) return error.AudioTooShort; + const frames = (1 + (audio.len - frame) / hop) & ~@as(usize, 1); // an odd last frame has no pair + const bank = try gpa.create([bins][mel_bins]f64); + defer gpa.destroy(bank); + filters(bank); + var window: [frame]f64 = undefined; + for (&window, 0..) |*w, n| w.* = std.math.pow(f64, 0.5 - 0.5 * @cos(2.0 * std.math.pi * @as(f64, @floatFromInt(n)) / (frame - 1)), 0.85); + const logmel = try gpa.alloc(f32, frames * mel_bins); + defer gpa.free(logmel); + var re: [fft]f64 = undefined; + var im: [fft]f64 = undefined; + var power: [bins]f64 = undefined; + for (0..frames) |f| { + var mean: f64 = 0; + for (re[0..frame], audio[f * hop ..][0..frame]) |*r, x| { + r.* = x * @as(f32, 32768.0); + mean += r.*; + } + mean /= frame; + for (re[0..frame]) |*r| r.* -= mean; + var n: usize = frame - 1; + while (n > 0) : (n -= 1) re[n] -= 0.97 * re[n - 1]; + re[0] *= 1.0 - 0.97; + for (re[0..frame], window) |*r, w| r.* *= w; + @memset(re[frame..], 0); + @memset(&im, 0); + transform(&re, &im); + // the publisher's spectrogram holds single-precision complex values before the power + for (&power, re[0..bins], im[0..bins]) |*p, r, i| { + const mag = std.math.hypot(@as(f64, @as(f32, @floatCast(r))), @as(f64, @as(f32, @floatCast(i)))); + p.* = mag * mag; + } + for (0..mel_bins) |m| { + var acc: f64 = 0; + for (power, bank) |p, row| acc += row[m] * p; + logmel[f * mel_bins + m] = @floatCast(@log(@max(acc, 1.192092955078125e-07))); + } + } + // each bin to zero mean and unit variance over the frames (n - 1 in the variance) + for (0..mel_bins) |m| { + var mean: f64 = 0; + for (0..frames) |f| mean += logmel[f * mel_bins + m]; + mean /= @floatFromInt(frames); + var ss: f64 = 0; + for (0..frames) |f| { + const d = logmel[f * mel_bins + m] - mean; + ss += d * d; + } + const scale = 1.0 / @sqrt(ss / @as(f64, @floatFromInt(frames - 1)) + 1e-7); + for (0..frames) |f| logmel[f * mel_bins + m] = @floatCast((logmel[f * mel_bins + m] - mean) * scale); + } + // two frames a row: the buffer already holds them side by side + return gpa.dupe(f32, logmel); +} + +test "resample: a constant stays a constant away from the edges" { + const t = std.testing; + const x = try t.allocator.alloc(f32, 4410); + defer t.allocator.free(x); + @memset(x, 0.5); + const y = try resample(t.allocator, x); + defer t.allocator.free(y); + try t.expectEqual(@as(usize, 1600), y.len); + for (y[100..1500]) |v| try t.expectApproxEqAbs(@as(f32, 0.5), v, 2e-3); +} + +test "transform: a cosine lands in its own bin" { + const t = std.testing; + var re: [fft]f64 = undefined; + var im: [fft]f64 = @splat(0); + for (&re, 0..) |*r, n| r.* = @cos(2.0 * std.math.pi * 5.0 * @as(f64, @floatFromInt(n)) / fft); + transform(&re, &im); + try t.expectApproxEqAbs(@as(f64, fft / 2), re[5], 1e-9); + try t.expectApproxEqAbs(@as(f64, 0), re[6], 1e-9); + try t.expectApproxEqAbs(@as(f64, 0), im[5], 1e-9); +} + +test "rows: the frames pair up, and each bin of a noisy lane is normalised" { + const t = std.testing; + const x = try t.allocator.alloc(f32, rate); + defer t.allocator.free(x); + var seed: u32 = 1; + for (x) |*v| { + seed = seed *% 1664525 +% 1013904223; + v.* = (@as(f32, @floatFromInt(seed >> 8)) / 16777216.0 - 0.5) * 0.2; + } + const got = try rows(t.allocator, x); + defer t.allocator.free(got); + try t.expectEqual(@as(usize, 98 * mel_bins), got.len); // 98 frames, 49 rows + var mean: f64 = 0; + var i: usize = 3; + while (i < got.len) : (i += mel_bins) mean += got[i]; + try t.expectApproxEqAbs(@as(f64, 0), mean / 98.0, 1e-4); +} diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index c79233e1c2f..b342d03abaa 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -3,6 +3,7 @@ const std = @import("std"); const z3 = @import("zonos3"); const cuda = @import("cuda"); const core = @import("core"); +const encoder_checks = @import("check_encoder.zig"); const cfg = z3.config; const W = cfg.frame_width; @@ -13,6 +14,8 @@ const usage = \\ zonos3-generate --model LM_DIR --frames-check GEN_DIR [--max-frames 2000] \\ zonos3-generate --codec-check DUMP_DIR --generator GENERATOR.pt --head HEAD.pt \\ zonos3-generate --encoder-check DUMP_DIR --generator GENERATOR.pt + \\ zonos3-generate --features-check DUMP_DIR + \\ zonos3-generate --teacher-check DUMP_DIR --teacher TEACHER_DIR \\ zonos3-generate --checkpoint RELEASE_DIR --text "..." --wav OUT.wav [--voice-embedding E.npy | --voice-codes C.npy] \\ [--seed 0] [--temperature 0.75] [--top-k 80] [--top-p 0.69] [--max-frames 2000] [--decoder ID] \\ [--silence-frames 3] [--reference GEN_DIR] @@ -28,11 +31,12 @@ const usage = \\Zyphra/ZONOS3-Mini. With --reference the prompt rows, frames and audio are compared with GEN_DIR's (dump_rows.py). \\--encoder-check encodes DUMP_DIR/audio.npy (44.1 kHz, one lane) and compares the acoustic branch's captures with \\the reference's (tools/dump_golden.py codec-encoder, a CUDA bf16 run, so the match is to bf16 rounding). - \\The last stderr line is "RESULT zonos3 ...". + \\--features-check computes the SSL teacher's input features of DUMP_DIR/lane.0.teacher_audio.npy on the host and + \\compares them with DUMP_DIR/lane.0.ssl.features.npy. The last stderr line is "RESULT zonos3 ...". \\ ; -const Check = struct { +pub const Check = struct { gpa: std.mem.Allocator, io: std.Io, ctx: *anyopaque, @@ -47,7 +51,7 @@ const Check = struct { prefix: bool = false, floor: f64 = 0.9999, - fn probe(ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void { + pub fn probe(ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void { const c: *Check = @ptrCast(@alignCast(ctx)); var nb: [96]u8 = undefined; const path = try std.fs.path.join(c.gpa, &.{ c.dir, try std.fmt.bufPrint(&nb, "{s}.npy", .{name}) }); @@ -150,7 +154,7 @@ fn loadPrompt(gpa: std.mem.Allocator, io: std.Io, e: *z3.Engine, dir: []const u8 } } -fn nowNs(io: std.Io) i128 { +pub fn nowNs(io: std.Io) i128 { return @intCast(std.Io.Clock.awake.now(io).toNanoseconds()); } @@ -250,7 +254,7 @@ const Speak = struct { silence_frames: usize = 3, }; -fn readNpy(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !struct { bytes: []u8, arr: z3.npy.Array } { +pub fn readNpy(gpa: std.mem.Allocator, io: std.Io, path: []const u8) !struct { bytes: []u8, arr: z3.npy.Array } { const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 28)); return .{ .bytes = bytes, .arr = try z3.npy.parse(bytes) }; } @@ -361,41 +365,6 @@ fn speak(gpa: std.mem.Allocator, io: std.Io, a: Speak) !u8 { return if (std.mem.eql(u8, verdict, "FAIL")) 1 else 0; } -fn encoderCheck(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: []const u8) !u8 { - const path = try std.fs.path.join(gpa, &.{ dir, "audio.npy" }); - defer gpa.free(path); - const f = try readNpy(gpa, io, path); - defer gpa.free(f.bytes); - const audio = try f.arr.floats(gpa); - defer gpa.free(audio); - var driver = try cuda.Driver.open(); - defer driver.close(); - var ctx = try cuda.Context.init(&driver, 0); - defer ctx.deinit(); - var stream = try cuda.Stream.init(&driver, true); - defer stream.deinit(); - const t_load = nowNs(io); - const enc = try z3.encoder.Encoder.create(gpa, io, &driver, stream, generator); - defer enc.destroy(); - const Enc = struct { - fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { - try @as(*z3.encoder.Encoder, @ptrCast(@alignCast(c))).download(ptr, out); - } - }; - // the reference ran in bf16: a row's cosine against it, not fp32 rounding - var c: Check = .{ .gpa = gpa, .io = io, .ctx = enc, .get = Enc.get, .dir = dir, .prefix = true, .floor = 0.99 }; - std.debug.print("zonos3 encoder check: {d} samples, {d} MiB of weights, loaded in {d:.1} s\n", .{ audio.len, enc.w.bytes >> 20, @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9 }); - const lane = audio[0..@min(audio.len, z3.encoder.lane_frames * z3.encoder.frame_samples)]; - _ = try enc.acoustic(lane, .{ .ctx = &c, .f = Check.probe }); - const t0 = nowNs(io); - const frames = try enc.acoustic(lane, null); - try stream.synchronize(); - const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; - const pass = c.fails == 0 and c.n > 0 and c.missing == 0; - std.debug.print("RESULT zonos3 encoder {s} probes={d} low={d} missing={d} worst_row_cos={d:.6} frames={d} encode_s={d:.3}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, frames, seconds }); - return if (pass) 0 else 1; -} - pub fn main(init: std.process.Init) !u8 { const arena = init.arena.allocator(); const gpa = std.heap.c_allocator; @@ -406,6 +375,9 @@ pub fn main(init: std.process.Init) !u8 { var frames_check: ?[]const u8 = null; var codec_check: ?[]const u8 = null; var encoder_check: ?[]const u8 = null; + var features_check: ?[]const u8 = null; + var teacher_check: ?[]const u8 = null; + var teacher_dir: []const u8 = ""; var generator: []const u8 = ""; var head: []const u8 = ""; var sp: Speak = .{}; @@ -415,17 +387,19 @@ pub fn main(init: std.process.Init) !u8 { while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--features-check")) features_check = v else if (std.mem.eql(u8, k, "--teacher-check")) teacher_check = v else if (std.mem.eql(u8, k, "--teacher")) teacher_dir = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } } + if (teacher_check) |dir| return if (i == argv.len and teacher_dir.len > 0) encoder_checks.teacher(gpa, io, dir, teacher_dir) else 2; + if (features_check) |dir| return if (i == argv.len) encoder_checks.features(gpa, io, dir) else 2; if (encoder_check) |dir| { if (i != argv.len or generator.len == 0) { std.debug.print("{s}", .{usage}); return 2; } - return encoderCheck(gpa, io, dir, generator); + return encoder_checks.acoustic(gpa, io, dir, generator); } if (codec_check) |dir| { if (i != argv.len or generator.len == 0 or head.len == 0) { diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index 3dde9045d73..fd9515151e9 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -5,6 +5,7 @@ pub const sampler = @import("sampler.zig"); pub const generation = @import("generation.zig"); pub const prompt = @import("prompt.zig"); pub const speech = @import("speech.zig"); +pub const features = @import("features.zig"); pub const release = @import("release.zig"); pub const voices = @import("voices.zig"); pub const request = @import("request.zig"); @@ -14,6 +15,7 @@ pub const engine = @import("cuda/engine.zig"); pub const codec = @import("cuda/codec.zig"); pub const codec_weights = @import("cuda/codec_weights.zig"); pub const encoder = @import("cuda/encoder.zig"); +pub const teacher = @import("cuda/teacher.zig"); pub const Engine = engine.Engine; pub const Options = engine.Options; @@ -29,6 +31,7 @@ test { _ = generation; _ = prompt; _ = speech; + _ = features; _ = release; _ = voices; _ = codec_weights; From 10a617539265cbe57feb1bb52d1350e75f12e29e Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:01:59 +0000 Subject: [PATCH 317/361] zonos3: the recipe page (sources, pins, how each check was run and what it gave) and the reference-dump tool --- docs/recipes/zonos3-mini.md | 186 ++++++++++++++++++++++++++++ tools/zig/zonos3_reference.py | 227 ++++++++++++++++++++++++++++++++++ 2 files changed, 413 insertions(+) create mode 100644 docs/recipes/zonos3-mini.md create mode 100644 tools/zig/zonos3_reference.py diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md new file mode 100644 index 00000000000..81d62270171 --- /dev/null +++ b/docs/recipes/zonos3-mini.md @@ -0,0 +1,186 @@ +# ZONOS3 Mini on CUDA + +`zig/src/families/zonos3` runs Zyphra's ZONOS3 Mini text-to-speech model on the CUDA runtime, from the files the +publisher released, and serves it on `POST /v1/audio/speech`. This page records what is ported, where every source +came from, and how each part was checked, so the checks can be rerun. + +Status: a work in progress on one branch, proposed in #3615. The kernels are not registered with the kernel contract +yet, and the quality suite has not been run on this build. + +## Sources + +| What | Where | Pin | +| --- | --- | --- | +| Checkpoint | `huggingface.co/Zyphra/ZONOS3-Mini` (Apache-2.0) | revision `d2d142a86b1e6aeb4252679673c86ecd86177bf8` | +| Reference code | `github.com/Zyphra/ZONOS3-Mini` (MIT) | commit `96d9e0ec1e39083ed336ac78f24e3dbc93721c0f` | +| Reference environment | Python 3.12.3, torch 2.9.1+cu128, torchaudio 2.9.1+cu128, transformers 4.57.3 | the repo's `constraints.txt` | + +Nothing is converted: the server reads the release folder as published. + +| File in the release | Read by | sha256 | +| --- | --- | --- | +| `lm/zonos3_mini/model.pth` (bf16) | the backbone | `3b4ac0a6e3002bd575ad9a0761ae7524806a908f553042171dead8f3a2146caa` | +| `lm/zonos3_mini/params.json` | the geometry check | `28dc488d7142831d739f427e048c699b7ed12852d88da0a9123a137f15aa5a5b` | +| `lm/zonos3_mini/tokenizer/superbpe8192.json` | the text tokenizer | `90322f910600027dee7fe63d400d1d9dc1035c167d560aadf0871e3661d08bf3` | +| `autoencoder/generator.pt` (fp32) | the codec's quantizer, semantic head, resamplers, encoder | `75a587a3eda9ca3d345f0c305756a7ff8619b01685c261b08ae243c69c2caf9a` | +| `autoencoder/heads/keep2_plain/step_0050000.pt` (fp32) | the codec decoder's stages and iSTFT head | `7432e335e717417961267f2242547ce389a796cdc296a8b8d5289658e3c28936` | +| `autoencoder/teacher/model.safetensors` (bf16) | the encoder's SSL teacher | `a15182741d6ee3cd780b8b830f49fa6b7fcce383655d451970841b24114767a5` | +| `registries/codec_registry_keep2_plain.json`, `registries/silence_frame_*.json` | the decoder's files, the silence frame | `5437b4159b2bdbc33d3c1a27a316df7ae361b06f5ce3c9822f585402bcb4351a` (the registry) | +| `gguf/voices//*.codes.npy`, `*.embedding.npy` | the default voices | | + +The `.pth` files are torch.save archives; `zig/src/core/torch_pth.zig` reads them without Python (stored zip +members, a pickle VM limited to the tensor allow-list, nested state dicts named by their keys). + +## What runs + +- **Backbone** (`cuda/engine.zig`, `zonos3.cu`): 11 layers at width 1,024, nine Gated DeltaNet and two global + attention layers, Full AttnRes residuals, a dense feed-forward in layer 0 and a 64-expert top-2 latent mixture of + experts in the rest, one linear head for 10 codebooks of 4,098 logits a frame. +- **Sampler and generation** (`sampler.zig`, `generation.zig`, on the host): the release's masks, repetition + penalty, temperature, top-k, top-p and min-p, its end-of-audio countdown and cold-start padding. Draws come from a + counter-based generator keyed by the request's seed, the frame and the codebook. +- **Codec decoder** (`cuda/codec.zig`, `zonos3_codec.cu`): the `keep2_plain` decoder, the reference servers' + default: code tables, the semantic head, five causal transformer stages from 15 Hz to 240 Hz, the ConvNeXt head, + two centered iSTFTs, the FIR mixer and the 44,160 to 44,100 Hz resampler. It keeps its state between calls and + hands out the samples no later frame can change. +- **Prompt and output** (`prompt.zig`, `speech.zig`, `release.zig`, `voices.zig`): the training layout + `[reference prefix | speaker row] [condition rows] text [silence]`, the undelayed frames to decode, the decoder's + -3 dB headroom and the soft limiter above -1 dBFS. +- **Served route** (`native/zonos_host.zig`, `server/zonos_speech.zig`): one request at a time; the release's 27 + default voices by their reference codes; `speaker_reference_codes` for a caller's own voice; WAV or PCM, whole or + streamed in chunks of 1, 2, 4, 8 and then 15 frames. +- **Codec encoder, in progress** (`cuda/encoder.zig`, `cuda/teacher.zig`, `features.zig`): the acoustic branch and + the SSL teacher each run and are checked on their own. The quantizer that joins them, lanes for clips past 20 s + and an upload field on the route are not written, so the server cannot yet clone from an audio file. + +Refused or absent: cloning from an uploaded clip, text normalization (text is spoken as typed), speaker and control +guidance, LACI, steering, speech editing, accent adapters, phoneme, start and pause tokens, short-text prompts, +condition values (every condition row is its "unknown" bucket), the `full_mr` decoder, concurrency, Metal. + +## Precision + +- Weights stay as published: the backbone's and the teacher's in bf16, the codec's in fp32. +- Every activation, cache and state is fp32, and every sum is fp32. No int8, fp8 or bf16 activations. +- Each row kernel takes prompt rows and decode rows alike, with one fixed reduction order a row, so a row's bits do + not depend on how the rows before it were chunked. The codec's kernels are written the same way per row and per + sample. +- All four kernel images build with the glue flags (`--fmad=false`, IEEE division and square root). + +The reference's oracle (`zonos3.reference`, `tools/dump_golden.py lm`) runs the backbone in fp32 on the CPU, which +is what the port is compared with. The publisher's CUDA servers run parts in bf16; see "The reference's bf16 paths". + +## How it was checked + +All figures below were measured on one RTX 5090 (driver 615.71, nvcc 13.3, Zig 0.17.0, `-Dsm=120`) at branch commit +`141aefa97`, with every reference dump regenerated for that run. + +### The reference side + +`tools/zig/zonos3_reference.py` writes the dumps from the publisher's PyTorch code; `--help` lists the +subcommands. With `RELEASE` a snapshot of the checkpoint, `ZONOS` a checkout of the reference repo with its `model` +package installed, and `LM=RELEASE/lm/zonos3_mini`: + +```sh +python tools/zig/zonos3_reference.py requests RELEASE D/requests +python tools/zig/zonos3_reference.py rows LM D/requests/greedy_embedding.json D/gen_greedy_embedding --device cpu +python tools/zig/zonos3_reference.py rows LM D/requests/greedy_reference.json D/gen_greedy_reference --device cpu +python ZONOS/tools/dump_golden.py lm LM --input-ids D/gen_greedy_embedding/input_ids.npy --dtype f32 --mode full -o D/lm_embedding +python ZONOS/tools/dump_golden.py lm LM --input-ids D/gen_greedy_reference/input_ids.npy --dtype f32 --mode full -o D/lm_reference +python tools/zig/zonos3_reference.py codec RELEASE/gguf/voices/English/Savannah_en-American_F_1.codes.npy D/codec_savannah +python ZONOS/tools/dump_golden.py codec-encoder --generator RELEASE/autoencoder/generator.pt \ + --audio RELEASE/gguf/voices/English/Cillian_en-Irish_M_1.wav -o D/enc_cillian +python tools/zig/zonos3_reference.py encoder RELEASE/autoencoder/generator.pt D/enc_cillian/audio.npy D/enc_cillian_fp32 +python tools/zig/zonos3_reference.py teacher RELEASE/autoencoder/teacher D/enc_cillian/lane.0.ssl.features.npy D/teacher_cillian_fp32 +``` + +The test request is "The quick brown fox jumps over the lazy dog, and then it rests by the river." in the release's +Savannah voice, once by her speaker embedding (a 30-row prompt) and once by her reference codes (a 209-row prompt). +"Greedy" is the release's sampler at temperature 0: its masks and repetition penalty still apply. + +### The port's side + +`zig build zonos3-generate -Dnvcc=... -Dsm=120 -Doptimize=ReleaseFast` builds the tool. Each mode ends with one +`RESULT zonos3 ...` line; the table quotes them. + +| Check | Command (after `zonos3-generate`) | Compared with | Result | +| --- | --- | --- | --- | +| Backbone, embedding prompt | `--model LM --check D/lm_embedding` | the oracle's 109 sublayer captures, 30 rows | every row's cosine 1.0000000; worst relative difference 3.3e-6 | +| Backbone, reference prompt | `--model LM --check D/lm_reference --max-rows 256` | 109 captures, 209 rows | every row's cosine 1.0000000; worst relative difference 3.7e-6 | +| Greedy frames, embedding voice | `--model LM --frames-check D/gen_greedy_embedding --max-rows N` | the reference's 78 frames | 78 of 78 identical at N = 1, 7, 64 and 256 | +| Greedy frames, reference voice | `--model LM --frames-check D/gen_greedy_reference --max-rows N` | the reference's 80 frames | 80 of 80 identical at N = 1, 7, 64 and 256 | +| Codec decoder | `--codec-check D/codec_savannah --generator G --head H` | 13 captures and the audio of 171 frames, CPU fp32 | cosine 1.0000000; audio SNR 115.9 dB | +| Codec in chunks | the same run | frames fed 1, 3, 7, 15, ... at a time, the settled samples taken after each | bit-identical to one pass | +| Text to audio, embedding voice | `--checkpoint RELEASE --text "..." --voice-embedding E --temperature 0 --reference D/gen_greedy_embedding` | the reference's prompt rows, frames and CPU audio | rows equal, 78 of 78 frames, 205,800 of 205,800 samples, audio SNR 111.7 dB | +| Text to audio, reference voice | the same with `--voice-codes C` and `D/gen_greedy_reference` | as above | rows equal, 80 of 80 frames, 211,680 of 211,680 samples, audio SNR 117.5 dB | +| Teacher's features | `--features-check D/enc_cillian` | the reference's 999 feature rows of a 20 s lane | cosine 1.0000000; largest difference 2.4e-7 | +| Encoder, acoustic branch | `--encoder-check D/enc_cillian_fp32 --generator G` | 101 captures of the fp32 run, 145 frames | every row's cosine 1.000000 | +| SSL teacher | `--teacher-check D/teacher_cillian_fp32 --teacher RELEASE/autoencoder/teacher` | 18 captures of the fp32 run, 999 rows | worst row's cosine 0.9999252 | + +`G` is `RELEASE/autoencoder/generator.pt` and `H` the `keep2_plain` head checkpoint. A capture passes when its worst +row's cosine against the reference is at least 0.9999. The backbone's "equal prompt rows" also covers the tokenizer: +the port's SuperBPE ids for the test sentence equal the reference's. + +The teacher is the loosest match (its largest element difference is 0.09 against values up to 24). Its rows attend +to the whole 20 s lane, most of it the zero padding after this 9.7 s clip, and the difference grows from layer 8 on. +I have not yet found whether a reduction order or the padded rows explain it. + +### Sampled speech + +The reference draws with PyTorch's generator, so sampled frames cannot match it. Two indirect checks: + +- **Repeatability:** the served route returns the same bytes for the same seed, and a streamed reply's bytes equal + the whole reply's. +- **Transcription:** Whisper large-v3-turbo (resampled to 16 kHz) transcribed the greedy test sentence with no + errors, from the port and from the reference alike, and a 62-word sampled passage with word error rates of 0.033 + and 0.016 in two voices; each error was the word "TensorFold". + +### The served route + +`tensorfold-native serve RELEASE --parallel 1`, default context 4,096 and 2,000 frames a request: + +| Measure | Value | +| --- | --- | +| A 19.4 s sampled reply, whole | 1.28 s (15 times real time) | +| The same reply streamed | first response byte at 0.06 s, done at 1.29 s, bytes equal to the whole reply | +| Device memory in use after it | 3.57 GiB (2.36 GiB of it weights) | +| A second request while one runs | 503 | +| An unknown voice, `top_k` above 4,096, malformed `speaker_reference_codes` | 400 with the reason | + +The standalone tool measured the parts: 22.0 s of sampled audio took 1.15 s to generate and 0.27 s to decode; the +decoder alone turns 11.4 s of codes into audio in 0.13 s; the acoustic encoder takes 0.48 s for a 9.7 s clip and the +teacher 0.26 s for a 20 s lane. There are no CUDA graphs and the sampler runs on the host; none of this is tuned. + +### Repo checks + +`zig fmt --check build.zig zig`, `tools/zig/lean_check.py` (0 new over the base), `tools/zig/cuda_common_check.py` +(0 violations) and `zig build test-cuda-host` pass; the family's host tests run in it and alone as +`zig build test-zonos-host`. On a machine whose umask is 0002 one unrelated test in that suite +(`serve --config`, which refuses a group-writable file) fails; it passes under umask 022. + +Not run: `zig build test`, `test-kernel-contract`, `test-golden`, and any quality suite. + +## The reference's bf16 paths + +The publisher's CUDA code runs some parts under bf16 autocast, and those runs sit visibly away from the same code in +fp32. Measured with the reference alone, on the dumps above: + +| Part | bf16 run against fp32 run | +| --- | --- | +| Codec decoder audio (the CUDA server's decode against the CPU decode, same frames) | 35.4 dB SNR | +| Encoder latent, 145 frames | worst row's cosine 0.966, mean 0.998 | +| Teacher output, 999 rows | worst row's cosine 0.085, mean 0.984 | +| Codes re-encoded from a release clip against the codes the release ships for it | 97% equal in the semantic codebook, 56% to 87% in the residual ones | + +The port computes in fp32 and matches the fp32 runs. Two consequences: its audio is closer to the publisher's CPU +decode than the publisher's own CUDA server is, and a native encoder's codes will not be bit-equal to the +publisher's. The encoder's gate should therefore be code agreement and cloned-voice quality, not identity. + +## Shared code this touches + +- `drama3/codec_pth.zig` moved to `core/torch_pth.zig` (its zip half to `core/torch_zip.zig`) and gained nested + checkpoints and a raw reader; Drama 3's codec loads through the same code and its host tests pass. +- `core/speech_api.zig`: `SpeechRequest.speaker`, an optional speaker vector. +- `server/`: voices load through `speech_voices.zig`; the speech route, the sampling parser, the voices listing, + model detection and the tokenizer loader each gained a branch for a release folder, which has no `config.json` + and is recognised by `lm/zonos3_mini/params.json`. +- `native/`: `zonos3` in the CUDA open dispatch, the capabilities list and the rank refusals. diff --git a/tools/zig/zonos3_reference.py b/tools/zig/zonos3_reference.py new file mode 100644 index 00000000000..aa92bc2e87b --- /dev/null +++ b/tools/zig/zonos3_reference.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Reference dumps for the ZONOS3 Mini port from the publisher's PyTorch code: what zonos3-generate checks against.""" + +USAGE = """Run inside an environment that has the publisher's `zonos3` package (github.com/Zyphra/ZONOS3-Mini, `pip install -e +model`) and a local snapshot of huggingface.co/Zyphra/ZONOS3-Mini; docs/recipes/zonos3-mini.md pins both and gives +the commands. Every subcommand writes float32 / int32 .npy files under OUT, named as zonos3-generate reads them. + + requests RELEASE OUT the three GenerateRequest files (embedding voice, reference voice, each greedy) + rows LM_DIR REQUEST OUT one request generated by zonos3.reference: prompt rows, frames, audio + codec CODES.npy OUT the codec decoder (CPU fp32) on codes [frames, 10], with its capture points + encoder GENERATOR AUDIO.npy OUT the codec encoder's acoustic branch in fp32 on one lane of 44.1 kHz audio + teacher TEACHER_DIR FEATS.npy OUT the SSL teacher in fp32 on one lane's feature rows + +The backbone's per-layer dump and the encoder's bf16 production dump come from the publisher's tool unchanged: + tools/dump_golden.py lm LM_DIR --input-ids OUT/input_ids.npy --dtype f32 --mode full -o DIR + tools/dump_golden.py codec-encoder --generator GENERATOR --audio CLIP -o DIR +The release runs its encoder and teacher under bf16 autocast on CUDA; `encoder` and `teacher` here run the same +modules and weights in fp32, the precision the port computes in. +""" + +import argparse +import base64 +import json +from pathlib import Path + +import numpy as np +import torch + +CODEC = "opus_dual_3n_600k_sched600k_r4096_step600000" +TEXT = "The quick brown fox jumps over the lazy dog, and then it rests by the river." +VOICE = "gguf/voices/English/Savannah_en-American_F_1" + + +def save(out, taps): + for name, value in taps.items(): + np.save(out / f"{name}.npy", np.ascontiguousarray(value, dtype=np.float32)) + + +def requests(args): + """The checks' requests: one voice by its embedding and by its reference codes, sampled (seed 42) and greedy.""" + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + voice = Path(args.release) / VOICE + emb = base64.b64encode(Path(f"{voice}.embedding.npy").read_bytes()).decode() + codes = np.load(f"{voice}.codes.npy").tolist() + base = {"text": TEXT, "language": "en_us", "seed": 42, "stream": False} + by_embedding = {**base, "speaker_mode": "embedding", "speaker_embedding_base64": emb} + by_reference = {**base, "speaker_reference_codes": codes} + for name, request in (("embedding", by_embedding), ("reference", by_reference)): + (out / f"{name}.json").write_text(json.dumps(request)) + (out / f"greedy_{name}.json").write_text(json.dumps({**request, "temperature": 0.0})) + print(f"4 requests -> {out}") + + +def rows(args): + """zonos3.reference's generation of one request: input_ids.npy (+ .cond.json), rows.npy, audio.f32, meta.json.""" + from zonos3.reference.lm import Zonos3LM + from zonos3.reference.synth import ReferenceAssets, plan_prompt, synthesize + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + request = json.loads(Path(args.request).read_text()) + device = torch.device(args.device) + dtype = torch.float32 if args.dtype == "f32" else torch.bfloat16 + lm = Zonos3LM.load(args.lm, device=device, dtype=dtype) + assets = ReferenceAssets.load() + plan = plan_prompt(lm, request, assets=assets, device=device) + np.save(out / "input_ids.npy", plan.cond.input_ids.to(torch.float32).numpy()) + (out / "input_ids.cond.json").write_text(json.dumps(plan.cond_json()) + "\n") + result = synthesize(lm, request, assets=assets, device=device, dtype=dtype) + generated = torch.stack([r.to(torch.int32) for r in result.rows]).numpy() + np.save(out / "rows.npy", generated) + result.pcm.astype(" {out}") + + +def codec(args): + """The decoder on codes [frames, 10]: latent, stage_{0..8}, trunk, y0 / y1, s0 / s1, mixer, audio.""" + from zonos3.tokenizer import matched_codec + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + codes = np.load(args.codes).astype(np.int64) + np.save(out / "codes.npy", codes.astype(np.int32)) + model = matched_codec.load_model(CODEC, "cpu", decoder=args.decoder) + taps = {} + + def rows_of(name): + return lambda m, i, o: taps.__setitem__(name, o[0].float().T.contiguous().numpy()) + + for i in (0, 2, 4, 6, 8): + model.stages[i].register_forward_hook(rows_of(f"stage_{i}")) + model.head.norm.register_forward_hook(lambda m, i, o: taps.__setitem__("trunk", o[0].float().numpy())) + for i, linear in enumerate(model.head.outs): + linear.register_forward_hook(lambda m, inp, o, i=i: taps.__setitem__(f"y{i}", o[0].float().numpy())) + + def branches(m, inp): + for i in range(inp[0].shape[1]): + taps[f"s{i}"] = inp[0][0, i].float().numpy() + + model.head.mixer.register_forward_pre_hook(branches) + model.head.mixer.register_forward_hook(lambda m, i, o: taps.__setitem__("mixer", o[0, 0].float().numpy())) + packed = torch.from_numpy(codes).unsqueeze(0).permute(0, 2, 1) + with torch.inference_mode(): + taps["latent"] = model.latent(packed)[0].float().T.contiguous().numpy() + taps["audio"] = model(packed).float().reshape(-1).numpy() + save(out, taps) + print(f"{len(codes)} frames, {len(taps)} captures -> {out}") + + +def encoder(args): + """The acoustic branch in fp32: internal_audio, lane.0.enc.*, lane.0.stage.N(.in|.lK), lane.0.acoustic.""" + from torch.nn import functional as F + + from zonos3.codec.hybrid10_dual_encoding.model import MossCodec + from zonos3.codec.resample_exact import resample_exact + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + state = torch.load(args.generator, map_location="cpu", mmap=True, weights_only=True) + model = MossCodec(state["config"]["model"]) + model.load_state_dict(state["generator"], strict=True, assign=True) + model.eval().requires_grad_(False) + audio = np.load(args.audio).astype(np.float32).reshape(-1)[: 300 * 2940] + np.save(out / "audio.npy", audio) + wave = torch.from_numpy(audio)[None, None] + frames = (wave.shape[-1] + 2939) // 2940 + internal = resample_exact(wave, model.to_internal) + internal = F.pad(internal, (0, frames * 2944 - internal.shape[-1])) + enc = model.encoder.cuda().float() + taps = {} + + def channels_first(name): + return lambda m, i, o: taps.__setitem__(name, o[0].float().T.contiguous().cpu().numpy()) + + enc[0].register_forward_hook(channels_first("lane.0.enc.in")) + for b in (0, 1): + block = enc[1 + b].module.block + for u in range(3): + block[u].register_forward_hook(channels_first(f"lane.0.enc.b{b}.res{u}")) + enc[1 + b].register_forward_hook(channels_first(f"lane.0.enc.b{b}.conv")) + for si, index in enumerate((4, 6, 8, 10, 12)): + enc[index].register_forward_hook(channels_first(f"lane.0.stage.{si}")) + enc[index].input_proj.register_forward_hook( + lambda m, i, o, si=si: taps.__setitem__(f"lane.0.stage.{si}.in", o[0].float().contiguous().cpu().numpy()) + ) + for li, layer in enumerate(enc[index].layers): + # an eval stage calls layer.forward itself, past any hook + def forward(x, inner=layer.forward, name=f"lane.0.stage.{si}.l{li}"): + o = inner(x) + taps[name] = o[0].float().contiguous().cpu().numpy() + return o + + layer.forward = forward + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + with torch.inference_mode(): + latent = enc(internal.cuda()) + taps["lane.0.acoustic"] = latent[0].float().T.contiguous().cpu().numpy() + taps["internal_audio"] = internal[0].T.contiguous().numpy() + save(out, taps) + print(f"{frames} frames, {len(taps)} captures -> {out}") + + +def teacher(args): + """The teacher in fp32 on feature rows [rows, 160]: .feature_projection, .layer.N, and lane.0.ssl (layer 16).""" + from zonos3.codec.s1dac.losses import SemanticTeacher + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + feats = np.load(args.features).astype(np.float32) + model = SemanticTeacher(args.teacher, layer=16, dtype=torch.float32).cuda().eval() + taps = {"lane.0.ssl.features": feats} + inner = model.model + inner.feature_projection.register_forward_hook( + lambda m, i, o: taps.__setitem__("lane.0.ssl.feature_projection", o[0][0].float().cpu().numpy()) + ) + for li, layer in enumerate(inner.encoder.layers): + layer.register_forward_hook( + lambda m, i, o, li=li: taps.__setitem__(f"lane.0.ssl.layer.{li}", o[0][0].float().cpu().numpy()) + ) + torch.backends.cuda.matmul.allow_tf32 = False + with torch.inference_mode(): + x = torch.from_numpy(feats)[None].cuda() + mask = torch.ones(1, x.shape[1], dtype=torch.bool, device="cuda") + taps["lane.0.ssl"] = model(x, mask)[0].float().cpu().numpy() + save(out, taps) + print(f"{len(feats)} rows, {len(taps)} captures -> {out}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + p = commands.add_parser("requests") + p.add_argument("release") + p.add_argument("out") + p.set_defaults(run=requests) + p = commands.add_parser("rows") + p.add_argument("lm") + p.add_argument("request") + p.add_argument("out") + p.add_argument("--device", default="cpu") + p.add_argument("--dtype", choices=("f32", "bf16"), default="f32") + p.set_defaults(run=rows) + p = commands.add_parser("codec") + p.add_argument("codes") + p.add_argument("out") + p.add_argument("--decoder", default="keep2_plain") + p.set_defaults(run=codec) + p = commands.add_parser("encoder") + p.add_argument("generator") + p.add_argument("audio") + p.add_argument("out") + p.set_defaults(run=encoder) + p = commands.add_parser("teacher") + p.add_argument("teacher") + p.add_argument("features") + p.add_argument("out") + p.set_defaults(run=teacher) + args = parser.parse_args() + args.run(args) + + +if __name__ == "__main__": + main() From c0b2a4f067dc1d5769c84adc92321edc69d1402c Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:02:07 +0000 Subject: [PATCH 318/361] zonos3: the reference tool writes four requests --- tools/zig/zonos3_reference.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/zig/zonos3_reference.py b/tools/zig/zonos3_reference.py index aa92bc2e87b..469e60584cf 100644 --- a/tools/zig/zonos3_reference.py +++ b/tools/zig/zonos3_reference.py @@ -5,7 +5,7 @@ model`) and a local snapshot of huggingface.co/Zyphra/ZONOS3-Mini; docs/recipes/zonos3-mini.md pins both and gives the commands. Every subcommand writes float32 / int32 .npy files under OUT, named as zonos3-generate reads them. - requests RELEASE OUT the three GenerateRequest files (embedding voice, reference voice, each greedy) + requests RELEASE OUT four GenerateRequest files (embedding voice, reference voice; sampled, greedy) rows LM_DIR REQUEST OUT one request generated by zonos3.reference: prompt rows, frames, audio codec CODES.npy OUT the codec decoder (CPU fp32) on codes [frames, 10], with its capture points encoder GENERATOR AUDIO.npy OUT the codec encoder's acoustic branch in fp32 on one lane of 44.1 kHz audio From 0bfa07bcdc3fef2d9d37737279ee9c7afefe2e01 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:09:55 +0000 Subject: [PATCH 319/361] zonos3: the codec quantizer, and a clip's first lane encoded end to end: codes equal to the reference's fp32 run --- tools/zig/zonos3_reference.py | 52 +++++ zig/kernels/cuda/zonos3_encoder.cu | 44 ++++ zig/src/families/zonos3/check_encoder.zig | 80 +++++++ zig/src/families/zonos3/cuda/codec.zig | 9 +- zig/src/families/zonos3/cuda/codec_layers.zig | 10 + .../families/zonos3/cuda/codec_weights.zig | 64 ++++++ zig/src/families/zonos3/cuda/quantizer.zig | 212 ++++++++++++++++++ zig/src/families/zonos3/generate.zig | 6 +- zig/src/families/zonos3/release.zig | 2 + zig/src/families/zonos3/zonos3.zig | 2 + 10 files changed, 472 insertions(+), 9 deletions(-) create mode 100644 zig/src/families/zonos3/cuda/quantizer.zig diff --git a/tools/zig/zonos3_reference.py b/tools/zig/zonos3_reference.py index 469e60584cf..ddbfbd3752d 100644 --- a/tools/zig/zonos3_reference.py +++ b/tools/zig/zonos3_reference.py @@ -10,6 +10,7 @@ codec CODES.npy OUT the codec decoder (CPU fp32) on codes [frames, 10], with its capture points encoder GENERATOR AUDIO.npy OUT the codec encoder's acoustic branch in fp32 on one lane of 44.1 kHz audio teacher TEACHER_DIR FEATS.npy OUT the SSL teacher in fp32 on one lane's feature rows + quantize GENERATOR ACOUSTIC.npy SSL.npy OUT the quantizer in fp32 on those two runs' rows: the lane's codes The backbone's per-layer dump and the encoder's bf16 production dump come from the publisher's tool unchanged: tools/dump_golden.py lm LM_DIR --input-ids OUT/input_ids.npy --dtype f32 --mode full -o DIR @@ -190,6 +191,51 @@ def teacher(args): print(f"{len(feats)} rows, {len(taps)} captures -> {out}") +def quantize(args): + """The quantizer in fp32 on one lane's acoustic and teacher rows: pooled, semantic, rvq.N.*, codes.""" + from zonos3.codec.hybrid10_dual_encoding.model import MossCodec + from zonos3.codec.s1dac.losses import average_ssl_frames + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + state = torch.load(args.generator, map_location="cpu", mmap=True, weights_only=True) + cfg = state["config"]["model"] + model = MossCodec(cfg) + model.load_state_dict(state["generator"], strict=True, assign=True) + model.eval().requires_grad_(False).float() + acoustic = torch.from_numpy(np.load(args.acoustic).astype(np.float32)).T[None] # [1, 1024, frames] + ssl = torch.from_numpy(np.load(args.ssl).astype(np.float32))[None] # [1, rows, 1024] + frames = acoustic.shape[-1] + taps = {} + + def rows_of(name, value): + taps[name] = value[0].float().T.contiguous().numpy() + + with torch.inference_mode(): + # the teacher saw a full 20 s lane: its rows pool onto the lane's 300 frames, of which the clip has `frames` + pooled = average_ssl_frames(ssl, 300, cfg["dual_encoding"]["window_ratio"])[..., :frames] + rows_of("lane.0.pooled", pooled) + semantic = model.semantic_encoder(pooled) + rows_of("lane.0.semantic", semantic) + q1, c1, e1, _, _ = model.quantizer.semantic_quantizer(semantic) + rows_of("lane.0.rvq.0.projected", e1) + rows_of("lane.0.rvq.0.quantized", q1) + prediction = model.semantic_head(q1) + rows_of("lane.0.semantic_prediction", prediction) + residual = acoustic - prediction + rows_of("lane.0.residual", residual) + codes = [c1[0, 0]] + for i, quantizer in enumerate(model.quantizer.quantizer.quantizers, 1): + z_q, _, _, indices, z_e = quantizer(residual) + rows_of(f"lane.0.rvq.{i}.projected", z_e) + rows_of(f"lane.0.rvq.{i}.quantized", z_q) + residual = residual - z_q + codes.append(indices[0]) + np.save(out / "codes.npy", torch.stack(codes, 1).numpy().astype(np.int32)) + save(out, taps) + print(f"{frames} frames, {len(taps)} captures -> {out}") + + def main(): parser = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) commands = parser.add_subparsers(dest="command", required=True) @@ -219,6 +265,12 @@ def main(): p.add_argument("features") p.add_argument("out") p.set_defaults(run=teacher) + p = commands.add_parser("quantize") + p.add_argument("generator") + p.add_argument("acoustic") + p.add_argument("ssl") + p.add_argument("out") + p.set_defaults(run=quantize) args = parser.parse_args() args.run(args) diff --git a/zig/kernels/cuda/zonos3_encoder.cu b/zig/kernels/cuda/zonos3_encoder.cu index ebf1bdbd9b6..e364140c093 100644 --- a/zig/kernels/cuda/zonos3_encoder.cu +++ b/zig/kernels/cuda/zonos3_encoder.cu @@ -69,3 +69,47 @@ extern "C" __global__ void ze_patch_down(const float* __restrict__ in, float* __ const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < C * h) out[t * C * h + i] = in[(t * h + i % h) * C + i / h]; } + +// x -= y over n values. +extern "C" __global__ void ze_sub(float* __restrict__ x, const float* __restrict__ y, long long n) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] -= y[i]; +} + +// A row's nearest code by cosine: codes[row * 10 + col] = argmax_c e . C[c], C [4096][8] unit rows, ties to the lower. +extern "C" __global__ void __launch_bounds__(256) ze_nearest(const float* __restrict__ e, const float* __restrict__ C, + int* __restrict__ codes, int col) { + __shared__ float best[256]; + __shared__ int which[256]; + const float* x = e + (size_t)blockIdx.x * 8; + float bv = -INFINITY; + int bi = 0x7FFFFFFF; + for (int c = threadIdx.x; c < 4096; c += blockDim.x) { + const float* row = C + (size_t)c * 8; + float d = 0.f; +#pragma unroll + for (int i = 0; i < 8; ++i) d = fmaf(x[i], row[i], d); + if (d > bv) { + bv = d; + bi = c; + } + } + best[threadIdx.x] = bv; + which[threadIdx.x] = bi; + __syncthreads(); + if (threadIdx.x != 0) return; + for (int t = 1; t < 256; ++t) + if (best[t] > bv || (best[t] == bv && which[t] < bi)) { + bv = best[t]; + bi = which[t]; + } + codes[blockIdx.x * 10 + col] = bi; +} + +// residual[r] -= table[codes[r][col]] over D values a row. +extern "C" __global__ void ze_sub_code(float* __restrict__ residual, const float* __restrict__ table, + const int* __restrict__ codes, int col, int D) { + const size_t r = blockIdx.y; + const int d = blockIdx.x * blockDim.x + threadIdx.x; + if (d < D) residual[r * D + d] -= table[(size_t)codes[r * 10 + col] * D + d]; +} diff --git a/zig/src/families/zonos3/check_encoder.zig b/zig/src/families/zonos3/check_encoder.zig index a8a600a162f..bbd86e7499c 100644 --- a/zig/src/families/zonos3/check_encoder.zig +++ b/zig/src/families/zonos3/check_encoder.zig @@ -116,3 +116,83 @@ pub fn teacher(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, teacher_dir: std.debug.print("RESULT zonos3 teacher {s} probes={d} low={d} missing={d} worst_row_cos={d:.7} seconds={d:.3}\n", .{ if (pass) "PASS" else "FAIL", c.n, c.fails, c.missing, c.worst, seconds }); return if (pass) 0 else 1; } + +/// A clip's first lane end to end (acoustic branch, features, teacher, pooling, quantizer) against the fp32 codes. +pub fn encode(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, audio_path: []const u8, root: []const u8) !u8 { + var rel = try z3.release.open(gpa, io, root, null); + defer rel.deinit(); + const teacher_dir = try std.fs.path.join(gpa, &.{ root, z3.release.teacher_dir }); + defer gpa.free(teacher_dir); + const f = try readNpy(gpa, io, audio_path); + defer gpa.free(f.bytes); + const all = try f.arr.floats(gpa); + defer gpa.free(all); + const lane_samples = z3.encoder.lane_frames * z3.encoder.frame_samples; + const audio = all[0..@min(all.len, lane_samples)]; + const want_path = try std.fs.path.join(gpa, &.{ dir, "codes.npy" }); + defer gpa.free(want_path); + const w = try readNpy(gpa, io, want_path); + defer gpa.free(w.bytes); + const want = try w.arr.ints(gpa); + defer gpa.free(want); + + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const enc = try z3.encoder.Encoder.create(gpa, io, &driver, stream, rel.generator); + defer enc.destroy(); + const teach = try z3.teacher.Teacher.create(gpa, io, &driver, stream, teacher_dir); + defer teach.destroy(); + const dec = try z3.codec_weights.load(gpa, io, &driver, rel.generator, rel.head); + defer { + dec.deinit(); + gpa.destroy(dec); + } + const quant = try z3.quantizer.Quantizer.create(gpa, io, &driver, stream, rel.generator, dec); + defer quant.destroy(); + const Get = struct { + fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { + try @as(*z3.quantizer.Quantizer, @ptrCast(@alignCast(c))).download(ptr, out); + } + }; + var c: Check = .{ .gpa = gpa, .io = io, .ctx = quant, .get = Get.get, .dir = dir }; + + const t0 = nowNs(io); + const frames = try enc.acoustic(audio, null); + // the teacher hears the lane padded to its 20 s + const padded = try gpa.alloc(f32, lane_samples); + defer gpa.free(padded); + @memset(padded, 0); + @memcpy(padded[0..audio.len], audio); + const low = try z3.features.resample(gpa, padded); + defer gpa.free(low); + const feats = try z3.features.rows(gpa, low); + defer gpa.free(feats); + const rows = feats.len / z3.teacher.feature_width; + const ssl_ptr = try teach.run(feats, null); + const ssl = try gpa.alloc(f32, rows * z3.teacher.d); + defer gpa.free(ssl); + try teach.download(ssl_ptr, std.mem.sliceAsBytes(ssl)); + const pooled = try z3.quantizer.pool(gpa, ssl, frames); + defer gpa.free(pooled); + const codes = try gpa.alloc([z3.quantizer.codebooks]i32, frames); + defer gpa.free(codes); + try quant.run(enc.latent, pooled, codes, null); + const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; + try quant.run(enc.latent, pooled, codes, .{ .ctx = &c, .f = Check.probe }); + + const n = @min(frames, w.arr.shape[0]); + var same: [z3.quantizer.codebooks]usize = @splat(0); + for (codes[0..n], 0..) |row, r| for (row, 0..) |code, cb| { + same[cb] += @intFromBool(code == want[r * z3.quantizer.codebooks + cb]); + }; + var total: usize = 0; + for (same) |v| total += v; + const pass = c.fails == 0 and c.missing == 0 and frames == w.arr.shape[0] and same[0] == n; + std.debug.print("codes equal to the fp32 reference's, per codebook of {d} frames: {any}\n", .{ n, same }); + std.debug.print("RESULT zonos3 encode {s} frames={d} reference_frames={d} probes={d} low={d} worst_row_cos={d:.6} codes_equal={d}/{d} semantic_equal={d}/{d} seconds={d:.3}\n", .{ if (pass) "PASS" else "FAIL", frames, w.arr.shape[0], c.n, c.fails, c.worst, total, n * z3.quantizer.codebooks, same[0], n, seconds }); + return if (pass) 0 else 1; +} diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig index 7e2fcd11595..db8c3b248d5 100644 --- a/zig/src/families/zonos3/cuda/codec.zig +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -167,14 +167,7 @@ pub const Codec = struct { } fn convnext(c: *Codec, b: wts.Block, hist: u64, x: u64, rows: usize) !void { - const k = &c.k; - const s = c.stream; - try k.dwconv(s, x, rows, b.dw_w, b.dw_b, hist, c.o_, W); - try k.layernorm(s, c.o_, b.ln_w, b.ln_b, c.n, W, 1e-6, rows); - try k.linear(s, b.pw1_w, b.pw1_b, c.n, W, W, wts.hidden, c.big, wts.hidden, rows); - try k.gelu(s, c.big, rows * wts.hidden); - try k.linear(s, b.pw2_w, b.pw2_b, c.big, wts.hidden, wts.hidden, W, c.o_, W, rows); - try k.addScaled(s, x, c.o_, 0, W, rows); + try stage_layer.convnext(&c.k, c.stream, .{ .n = c.n, .o = c.o_, .att = c.att, .big = c.big }, b, hist, x, rows); } fn layer(c: *Codec, shape: wts.StageShape, L: wts.Layer, kv: [2]u64, x: u64, rows: usize, pos0: usize) !void { diff --git a/zig/src/families/zonos3/cuda/codec_layers.zig b/zig/src/families/zonos3/cuda/codec_layers.zig index f366906c06a..41570dbc13f 100644 --- a/zig/src/families/zonos3/cuda/codec_layers.zig +++ b/zig/src/families/zonos3/cuda/codec_layers.zig @@ -6,6 +6,16 @@ const wts = @import("codec_weights.zig"); /// A layer's scratch rows: the norm's output, a projection's output, attention's output, and the wide rows. pub const Scratch = struct { n: u64, o: u64, att: u64, big: u64 }; +/// A causal ConvNeXt block on x [rows][width]; hist [width][6] holds the six inputs before these rows. +pub fn convnext(k: *const kern.Kernels, s: cuda.Stream, sc: Scratch, b: wts.Block, hist: u64, x: u64, rows: usize) !void { + try k.dwconv(s, x, rows, b.dw_w, b.dw_b, hist, sc.o, wts.width); + try k.layernorm(s, sc.o, b.ln_w, b.ln_b, sc.n, wts.width, 1e-6, rows); + try k.linear(s, b.pw1_w, b.pw1_b, sc.n, wts.width, wts.width, wts.hidden, sc.big, wts.hidden, rows); + try k.gelu(s, sc.big, rows * wts.hidden); + try k.linear(s, b.pw2_w, b.pw2_b, sc.big, wts.hidden, wts.hidden, wts.width, sc.o, wts.width, rows); + try k.addScaled(s, x, sc.o, 0, wts.width, rows); +} + /// x [rows][d] at positions pos0 on: x += scale * attention(norm(x)), then x += scale * ffn(norm(x)). pub fn layer(k: *const kern.Kernels, s: cuda.Stream, sc: Scratch, shape: wts.StageShape, L: wts.Layer, kv: [2]u64, x: u64, rows: usize, pos0: usize) !void { const d = shape.d; diff --git a/zig/src/families/zonos3/cuda/codec_weights.zig b/zig/src/families/zonos3/cuda/codec_weights.zig index f0fe598b00f..0e1c4f0733f 100644 --- a/zig/src/families/zonos3/cuda/codec_weights.zig +++ b/zig/src/families/zonos3/cuda/codec_weights.zig @@ -228,6 +228,70 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, generator return w; } +/// What encoding adds to the decoder's tables: the semantic encoder, each quantizer's input projection and codes. +pub const Quantizer = struct { + gpa: std.mem.Allocator, + bufs: std.ArrayList(cuda.DeviceBuffer), + bytes: usize, + sem_in_w: u64, // [width][latent_dim] + sem_in_b: u64, + sem: [sem_blocks]Block, + in_w: [1 + residuals]u64, // [codebook_dim][width] for the semantic quantizer, [codebook_dim][latent_dim] for the rest + in_b: [1 + residuals]u64, + codes: [1 + residuals]u64, // [4096][codebook_dim], each row at unit length + + pub fn deinit(q: *Quantizer) void { + for (q.bufs.items) |*b| b.free(); + q.bufs.deinit(q.gpa); + } +}; + +pub fn loadQuantizer(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, generator: []const u8) !*Quantizer { + var g = try pth.Archive.openNested(gpa, io, generator); + defer g.close(); + const q = try gpa.create(Quantizer); + errdefer gpa.destroy(q); + q.* = undefined; + q.gpa = gpa; + q.bufs = .empty; + q.bytes = 0; + errdefer q.deinit(); + // the loader's helpers write through a Weights' buffer list: lend it this one's + var shell: Weights = undefined; + shell.gpa = gpa; + shell.bufs = .empty; + shell.bytes = 0; + defer { + q.bufs = shell.bufs; + q.bytes = shell.bytes; + } + var l: Loader = .{ .gpa = gpa, .d = d, .w = &shell }; + const first = try l.normed(&g, "generator/semantic_encoder.0.", width, latent_dim); + defer gpa.free(first); + q.sem_in_w = try l.device(first); + q.sem_in_b = try l.one(&g, "generator/semantic_encoder.0.bias", &.{width}); + for (&q.sem, 1..) |*b, i| b.* = try l.block(&g, "generator/semantic_encoder.{d}.", i); + inline for (0..1 + residuals) |i| { + const p = if (i == 0) "generator/quantizer.semantic_quantizer.quantizers.0." else std.fmt.comptimePrint("generator/quantizer.quantizer.quantizers.{d}.", .{i - 1}); + const in = if (i == 0) width else latent_dim; + const w = try l.normed(&g, p ++ "in_proj.", codebook_dim, in); + defer gpa.free(w); + q.in_w[i] = try l.device(w); + q.in_b[i] = try l.one(&g, p ++ "in_proj.bias", &.{codebook_dim}); + const codes = try g.readF32(gpa, p ++ "codebook.weight", &.{ codebook_size, codebook_dim }); + defer gpa.free(codes); + for (0..codebook_size) |c| { + const row = codes[c * codebook_dim ..][0..codebook_dim]; + var ss: f64 = 0; + for (row) |x| ss += @as(f64, x) * x; + const scale: f32 = @floatCast(1.0 / @max(@sqrt(ss), 1e-12)); + for (row) |*x| x.* *= scale; + } + q.codes[i] = try l.device(codes); + } + return q; +} + test "synthesis: a lone DC bin gives the window over n" { const t = std.testing; var win2: [8]f32 = undefined; diff --git a/zig/src/families/zonos3/cuda/quantizer.zig b/zig/src/families/zonos3/cuda/quantizer.zig new file mode 100644 index 00000000000..cd49aec5052 --- /dev/null +++ b/zig/src/families/zonos3/cuda/quantizer.zig @@ -0,0 +1,212 @@ +//! ZONOS3's codec quantizer on one GPU: a lane's acoustic rows and teacher rows in, ten codes a frame out. +const std = @import("std"); +const cuda = @import("cuda"); +const kern = @import("codec_kernels.zig"); +const layers = @import("codec_layers.zig"); +const wts = @import("codec_weights.zig"); + +const Buf = cuda.DeviceBuffer; +const W = wts.width; +const D = wts.latent_dim; + +pub const lane_frames = 300; // the frames a teacher lane's rows pool onto +pub const codebooks = 1 + wts.residuals; + +/// A capture under the reference's dump names: device fp32 rows [rows, width]. +pub const Probe = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, name: []const u8, ptr: u64, rows: usize, width: usize) anyerror!void, + + fn at(p: Probe, comptime f: []const u8, index: usize, ptr: u64, rows: usize, width: usize) !void { + var nb: [48]u8 = undefined; + try p.f(p.ctx, try std.fmt.bufPrint(&nb, f, .{index}), ptr, rows, width); + } +}; + +/// The teacher's rows averaged onto the lane's first `frames` frames: a window two frames wide each (caller frees). +pub fn pool(gpa: std.mem.Allocator, ssl: []const f32, frames: usize) ![]f32 { + const rows = ssl.len / D; + if (rows == 0 or ssl.len % D != 0 or frames == 0 or frames > lane_frames) return error.BadTeacherRows; + const out = try gpa.alloc(f32, frames * D); + errdefer gpa.free(out); + const ratio: f32 = @as(f32, @floatFromInt(rows)) / lane_frames; + const limit: f32 = @floatFromInt(rows); + const sum = try gpa.alloc(f64, D); + defer gpa.free(sum); + for (0..frames) |f| { + const centre = (@as(f32, @floatFromInt(f)) + 0.5) * ratio; + const left = @min(@max(centre - ratio, 0), limit); + const right = @min(@max(centre + ratio, 0), limit); + @memset(sum, 0); + var cell: usize = @intFromFloat(@floor(left)); + while (cell < rows and @as(f32, @floatFromInt(cell)) < right) : (cell += 1) { + const lo = @max(left, @as(f32, @floatFromInt(cell))); + const hi = @min(right, @as(f32, @floatFromInt(cell + 1))); + const part: f64 = hi - lo; + for (sum, ssl[cell * D ..][0..D]) |*s, v| s.* += part * v; + } + const span: f64 = right - left; + for (out[f * D ..][0..D], sum) |*o, s| o.* = @floatCast(s / span); + } + return out; +} + +const names = .{ "ze_sub", "ze_nearest", "ze_sub_code" }; +const F = enum(u8) { sub, nearest, sub_code }; + +pub const Quantizer = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + stream: cuda.Stream, + k: kern.Kernels, + mod: cuda.Module, + fns: [names.len]cuda.Function, + dec: *const wts.Weights, // the decoder's code tables and semantic head + w: *wts.Quantizer, + bufs: std.ArrayList(Buf), + hist: u64, // [8][W][6]: the semantic encoder's and head's ConvNeXt histories, zero at a lane's start + x: u64, // [frames][D] + y: u64, + residual: u64, + e: u64, // [frames][8] + codes: u64, // i32 [frames][10] + sc: layers.Scratch, + + /// `dec`: the decoder's weights of the same generator, which outlive this. + pub fn create(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, stream: cuda.Stream, generator: []const u8, dec: *const wts.Weights) !*Quantizer { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const q = try gpa.create(Quantizer); + errdefer gpa.destroy(q); + q.* = undefined; + q.gpa = gpa; + q.d = d; + q.stream = stream; + q.dec = dec; + q.bufs = .empty; + q.k = try kern.Kernels.load(d); + errdefer q.k.unload(); + q.mod = try cuda.Module.load(d, cuda.kernels.zonos3_encoder); + errdefer q.mod.unload(); + inline for (names, 0..) |name, j| q.fns[j] = try q.mod.function(name); + q.w = try wts.loadQuantizer(gpa, io, d, generator); + errdefer { + q.w.deinit(); + gpa.destroy(q.w); + } + errdefer q.freeState(); + const n = lane_frames; + q.hist = try q.alloc(2 * wts.sem_blocks * W * 6 * 4); + q.x = try q.alloc(n * D * 4); + q.y = try q.alloc(n * D * 4); + q.residual = try q.alloc(n * D * 4); + q.e = try q.alloc(n * wts.codebook_dim * 4); + q.codes = try q.alloc(n * 10 * 4); + q.sc = .{ .n = try q.alloc(n * W * 4), .o = try q.alloc(n * W * 4), .att = 0, .big = try q.alloc(n * wts.hidden * 4) }; + return q; + } + + pub fn destroy(q: *Quantizer) void { + q.stream.synchronize() catch {}; + q.freeState(); + q.w.deinit(); + q.gpa.destroy(q.w); + q.mod.unload(); + q.k.unload(); + q.gpa.destroy(q); + } + + fn freeState(q: *Quantizer) void { + for (q.bufs.items) |*b| b.free(); + q.bufs.deinit(q.gpa); + } + + fn alloc(q: *Quantizer, bytes: usize) !u64 { + var b = try Buf.alloc(q.d, @max(bytes, 256)); + errdefer b.free(); + try q.bufs.append(q.gpa, b); + return b.ptr; + } + + fn buf(q: *Quantizer, ptr: u64) Buf { + return .{ .d = q.d, .ptr = ptr, .len = std.math.maxInt(usize) / 2, .borrowed = true }; + } + + pub fn download(q: *Quantizer, src: u64, out: []u8) !void { + try q.buf(src).downloadAsync(0, out, q.stream.handle); + try q.stream.synchronize(); + } + + fn go(q: *Quantizer, which: F, gx: usize, gy: usize, a: *cuda.Args) !void { + try cuda.launch.launch(q.fns[@backingInt(which)], .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy), .z = 1 }, .block = .{ .x = 256 } }, q.stream, a); + } + + /// Codebook `col`'s codes of the rows in `from` [n][width], into the codes buffer's column. + fn nearest(q: *Quantizer, from: u64, width: usize, col: usize, n: usize) !void { + try q.k.linear(q.stream, q.w.in_w[col], q.w.in_b[col], from, width, width, wts.codebook_dim, q.e, wts.codebook_dim, n); + var a: cuda.Args = .{}; + a.add(q.e); + a.add(q.w.codes[col]); + a.add(q.codes); + a.add(@as(i32, @intCast(col))); + try q.go(.nearest, n, 1, &a); + } + + /// `acoustic`: device rows [n][D]; `pooled`: the teacher's rows on those frames (pool). The codes [n][10]. + pub fn run(q: *Quantizer, acoustic: u64, pooled: []const f32, out: [][codebooks]i32, probe: ?Probe) !void { + const n = out.len; + if (n == 0 or n > lane_frames or pooled.len != n * D) return error.BadLane; + const k = &q.k; + const s = q.stream; + var hist = q.buf(q.hist); + hist.len = 2 * wts.sem_blocks * W * 6 * 4; + try hist.fill8(0, s.handle); + // the semantic code: the pooled teacher rows through the semantic encoder + try q.buf(q.x).uploadAsync(0, std.mem.sliceAsBytes(pooled), s.handle); + if (probe) |p| try p.f(p.ctx, "lane.0.pooled", q.x, n, D); + try k.linear(s, q.w.sem_in_w, q.w.sem_in_b, q.x, D, D, W, q.y, W, n); + for (q.w.sem, 0..) |b, i| try layers.convnext(k, s, q.sc, b, q.hist + i * W * 6 * 4, q.y, n); + if (probe) |p| try p.f(p.ctx, "lane.0.semantic", q.y, n, W); + try q.nearest(q.y, W, 0, n); + if (probe) |p| try p.f(p.ctx, "lane.0.rvq.0.projected", q.e, n, wts.codebook_dim); + // its decoded prediction leaves the residual the nine other codebooks take + try k.gather(s, q.codes, 0, q.dec.sem_table, q.y, W, n); + if (probe) |p| try p.f(p.ctx, "lane.0.rvq.0.quantized", q.y, n, W); + for (q.dec.sem, 0..) |b, i| try layers.convnext(k, s, q.sc, b, q.hist + (wts.sem_blocks + i) * W * 6 * 4, q.y, n); + try k.linear(s, q.dec.sem_out_w, q.dec.sem_out_b, q.y, W, W, D, q.x, D, n); + if (probe) |p| try p.f(p.ctx, "lane.0.semantic_prediction", q.x, n, D); + try q.buf(q.residual).copyFrom(0, acoustic, n * D * 4, s.handle); + { + var a: cuda.Args = .{}; + a.add(q.residual); + a.add(q.x); + a.add(@as(i64, @intCast(n * D))); + try q.go(.sub, (n * D + 255) / 256, 1, &a); + } + if (probe) |p| try p.f(p.ctx, "lane.0.residual", q.residual, n, D); + for (1..codebooks) |col| { + try q.nearest(q.residual, D, col, n); + if (probe) |p| try p.at("lane.0.rvq.{d}.projected", col, q.e, n, wts.codebook_dim); + var a: cuda.Args = .{}; + a.add(q.residual); + a.add(q.dec.res_tables + (col - 1) * wts.codebook_size * D * 4); + a.add(q.codes); + a.add(@as(i32, @intCast(col))); + a.add(@as(i32, D)); + try q.go(.sub_code, (D + 255) / 256, n, &a); + } + try q.download(q.codes, std.mem.sliceAsBytes(out)); + } +}; + +test "pool: each frame averages a window two frames wide, clipped at the lane's ends" { + const t = std.testing; + // 600 teacher rows on 300 frames: two rows a frame, each window four rows + const ssl = try t.allocator.alloc(f32, 600 * D); + defer t.allocator.free(ssl); + for (0..600) |r| @memset(ssl[r * D ..][0..D], @floatFromInt(r)); + const got = try pool(t.allocator, ssl, 3); + defer t.allocator.free(got); + try t.expectApproxEqAbs(@as(f32, 1.0), got[0], 1e-6); // rows 0..2 (the window starts before the lane) + try t.expectApproxEqAbs(@as(f32, 2.5), got[D], 1e-6); // rows 1..4 + try t.expectApproxEqAbs(@as(f32, 4.5), got[2 * D], 1e-6); // rows 3..6 +} diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index b342d03abaa..cba8f812d93 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -16,6 +16,7 @@ const usage = \\ zonos3-generate --encoder-check DUMP_DIR --generator GENERATOR.pt \\ zonos3-generate --features-check DUMP_DIR \\ zonos3-generate --teacher-check DUMP_DIR --teacher TEACHER_DIR + \\ zonos3-generate --encode-check DUMP_DIR --audio AUDIO.npy --checkpoint RELEASE_DIR \\ zonos3-generate --checkpoint RELEASE_DIR --text "..." --wav OUT.wav [--voice-embedding E.npy | --voice-codes C.npy] \\ [--seed 0] [--temperature 0.75] [--top-k 80] [--top-p 0.69] [--max-frames 2000] [--decoder ID] \\ [--silence-frames 3] [--reference GEN_DIR] @@ -378,6 +379,8 @@ pub fn main(init: std.process.Init) !u8 { var features_check: ?[]const u8 = null; var teacher_check: ?[]const u8 = null; var teacher_dir: []const u8 = ""; + var encode_check: ?[]const u8 = null; + var clip: []const u8 = ""; var generator: []const u8 = ""; var head: []const u8 = ""; var sp: Speak = .{}; @@ -387,11 +390,12 @@ pub fn main(init: std.process.Init) !u8 { while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--features-check")) features_check = v else if (std.mem.eql(u8, k, "--teacher-check")) teacher_check = v else if (std.mem.eql(u8, k, "--teacher")) teacher_dir = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--features-check")) features_check = v else if (std.mem.eql(u8, k, "--teacher-check")) teacher_check = v else if (std.mem.eql(u8, k, "--teacher")) teacher_dir = v else if (std.mem.eql(u8, k, "--encode-check")) encode_check = v else if (std.mem.eql(u8, k, "--audio")) clip = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } } + if (encode_check) |dir| return if (i == argv.len and clip.len > 0 and sp.checkpoint.len > 0) encoder_checks.encode(gpa, io, dir, clip, sp.checkpoint) else 2; if (teacher_check) |dir| return if (i == argv.len and teacher_dir.len > 0) encoder_checks.teacher(gpa, io, dir, teacher_dir) else 2; if (features_check) |dir| return if (i == argv.len) encoder_checks.features(gpa, io, dir) else 2; if (encoder_check) |dir| { diff --git a/zig/src/families/zonos3/release.zig b/zig/src/families/zonos3/release.zig index 50a4ae45786..b4062eb6d25 100644 --- a/zig/src/families/zonos3/release.zig +++ b/zig/src/families/zonos3/release.zig @@ -5,6 +5,8 @@ const cfg = @import("config.zig"); pub const lm_dir = "lm/zonos3_mini"; /// The SuperBPE tokenizer params.json names, inside the language model's folder. pub const tokenizer_file = "tokenizer/superbpe8192.json"; +/// The codec encoder's SSL teacher, a folder with its model.safetensors. +pub const teacher_dir = "autoencoder/teacher"; /// The reference servers' default decoder: the pruned multi-resolution iSTFT head. pub const default_decoder = "keep2_plain"; /// A decoder's registry: codec_registry.json, or codec_registry_.json. diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index fd9515151e9..60f53fa3e42 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -16,6 +16,7 @@ pub const codec = @import("cuda/codec.zig"); pub const codec_weights = @import("cuda/codec_weights.zig"); pub const encoder = @import("cuda/encoder.zig"); pub const teacher = @import("cuda/teacher.zig"); +pub const quantizer = @import("cuda/quantizer.zig"); pub const Engine = engine.Engine; pub const Options = engine.Options; @@ -35,4 +36,5 @@ test { _ = release; _ = voices; _ = codec_weights; + _ = quantizer; } From f99c607e747893309153a9b7fc71f07379394782 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:15:13 +0000 Subject: [PATCH 320/361] zonos3: a whole reference clip encoded natively in lanes: codes equal to the reference's fp32 run at one and four lanes --- tools/zig/zonos3_reference.py | 67 ++++++++++++++++ zig/src/families/zonos3/check_encoder.zig | 76 ++++++------------ zig/src/families/zonos3/cuda/clip.zig | 94 +++++++++++++++++++++++ zig/src/families/zonos3/cuda/encoder.zig | 33 +++++--- zig/src/families/zonos3/generate.zig | 7 +- zig/src/families/zonos3/zonos3.zig | 1 + 6 files changed, 212 insertions(+), 66 deletions(-) create mode 100644 zig/src/families/zonos3/cuda/clip.zig diff --git a/tools/zig/zonos3_reference.py b/tools/zig/zonos3_reference.py index ddbfbd3752d..ec743f333d9 100644 --- a/tools/zig/zonos3_reference.py +++ b/tools/zig/zonos3_reference.py @@ -11,6 +11,7 @@ encoder GENERATOR AUDIO.npy OUT the codec encoder's acoustic branch in fp32 on one lane of 44.1 kHz audio teacher TEACHER_DIR FEATS.npy OUT the SSL teacher in fp32 on one lane's feature rows quantize GENERATOR ACOUSTIC.npy SSL.npy OUT the quantizer in fp32 on those two runs' rows: the lane's codes + clip GENERATOR TEACHER_DIR AUDIO.npy OUT [--seconds S] a whole clip's codes in fp32, lane by lane The backbone's per-layer dump and the encoder's bf16 production dump come from the publisher's tool unchanged: tools/dump_golden.py lm LM_DIR --input-ids OUT/input_ids.npy --dtype f32 --mode full -o DIR @@ -236,6 +237,65 @@ def rows_of(name, value): print(f"{frames} frames, {len(taps)} captures -> {out}") +def clip(args): + """A whole clip encoded in fp32 with the publisher's lanes (20 s, 10 s of left context): audio.npy and codes.npy.""" + from torch.nn import functional as F + + from zonos3.codec.hybrid10_dual_encoding.model import MossCodec + from zonos3.codec.resample_exact import resample_exact + from zonos3.codec.s1dac.losses import SemanticTeacher, average_ssl_frames + from zonos3.codec.s1dac.same_data.npy_ogg_dataset import Wav2Vec2BertFeaturePreprocessor + + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + state = torch.load(args.generator, map_location="cpu", mmap=True, weights_only=True) + cfg = state["config"]["model"] + model = MossCodec(cfg) + model.load_state_dict(state["generator"], strict=True, assign=True) + model.eval().requires_grad_(False).float().cuda() + teacher = SemanticTeacher(args.teacher, layer=16, dtype=torch.float32).cuda().eval() + audio = np.load(args.audio).astype(np.float32).reshape(-1) + if args.seconds: + count = int(args.seconds * 44100) + audio = np.tile(audio, (count + audio.size - 1) // audio.size)[:count].copy() + audio = audio[: 900 * 2940] + np.save(out / "audio.npy", audio) + wave = torch.from_numpy(audio)[None, None] + frames = (wave.shape[-1] + 2939) // 2940 + internal = resample_exact(wave, model.to_internal.cpu()) + internal = F.pad(internal, (0, frames * 2944 - internal.shape[-1])) + external = F.pad(wave, (0, frames * 2940 - wave.shape[-1])) + features = Wav2Vec2BertFeaturePreprocessor(44100) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + codes = np.zeros((frames, 10), dtype=np.int32) + start = 0 + with torch.inference_mode(): + while start < frames: + # the first lane starts the clip; a later one carries 150 frames of what came before + context = 0 if start == 0 else 150 + end = min(frames, start + 300 - context) + first, n = start - context, end - (start - context) + latent = model.encoder(internal[..., first * 2944 : end * 2944].cuda()) + lane = F.pad(external[0, :, first * 2940 : end * 2940], (0, (300 - n) * 2940)) + info = {} + features(lane, info) + feats = info["w2v_bert_input_features"][None].cuda() + ssl = teacher(feats, torch.ones(1, feats.shape[1], dtype=torch.bool, device="cuda")) + pooled = average_ssl_frames(ssl, 300, cfg["dual_encoding"]["window_ratio"])[..., :n] + q1, c1, _, _, _ = model.quantizer.semantic_quantizer(model.semantic_encoder(pooled)) + residual = latent - model.semantic_head(q1) + lane_codes = [c1[0, 0]] + for quantizer in model.quantizer.quantizer.quantizers: + z_q, _, _, indices, _ = quantizer(residual) + residual = residual - z_q + lane_codes.append(indices[0]) + codes[start:end] = torch.stack(lane_codes, 1)[context:].cpu().numpy() + start = end + np.save(out / "codes.npy", codes) + print(f"{frames} frames -> {out}") + + def main(): parser = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) commands = parser.add_subparsers(dest="command", required=True) @@ -271,6 +331,13 @@ def main(): p.add_argument("ssl") p.add_argument("out") p.set_defaults(run=quantize) + p = commands.add_parser("clip") + p.add_argument("generator") + p.add_argument("teacher") + p.add_argument("audio") + p.add_argument("out") + p.add_argument("--seconds", type=float, help="repeat the audio to this length") + p.set_defaults(run=clip) args = parser.parse_args() args.run(args) diff --git a/zig/src/families/zonos3/check_encoder.zig b/zig/src/families/zonos3/check_encoder.zig index bbd86e7499c..fedab07b5f0 100644 --- a/zig/src/families/zonos3/check_encoder.zig +++ b/zig/src/families/zonos3/check_encoder.zig @@ -33,9 +33,11 @@ pub fn acoustic(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, generator: var c: Check = .{ .gpa = gpa, .io = io, .ctx = enc, .get = Enc.get, .dir = dir, .prefix = true, .floor = 0.99 }; std.debug.print("zonos3 encoder check: {d} samples, {d} MiB of weights, loaded in {d:.1} s\n", .{ audio.len, enc.w.bytes >> 20, @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9 }); const lane = audio[0..@min(audio.len, z3.encoder.lane_frames * z3.encoder.frame_samples)]; - _ = try enc.acoustic(lane, .{ .ctx = &c, .f = Check.probe }); + const probe: z3.encoder.Probe = .{ .ctx = &c, .f = Check.probe }; + try enc.acoustic(0, try enc.load(lane, probe), probe); const t0 = nowNs(io); - const frames = try enc.acoustic(lane, null); + const frames = try enc.load(lane, null); + try enc.acoustic(0, frames, null); try stream.synchronize(); const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; const pass = c.fails == 0 and c.n > 0 and c.missing == 0; @@ -117,18 +119,14 @@ pub fn teacher(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, teacher_dir: return if (pass) 0 else 1; } -/// A clip's first lane end to end (acoustic branch, features, teacher, pooling, quantizer) against the fp32 codes. -pub fn encode(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, audio_path: []const u8, root: []const u8) !u8 { - var rel = try z3.release.open(gpa, io, root, null); - defer rel.deinit(); - const teacher_dir = try std.fs.path.join(gpa, &.{ root, z3.release.teacher_dir }); - defer gpa.free(teacher_dir); +/// A whole clip encoded natively (lanes of 20 s with 10 s of left context) against the reference's fp32 codes. +pub fn encode(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, root: []const u8) !u8 { + const audio_path = try std.fs.path.join(gpa, &.{ dir, "audio.npy" }); + defer gpa.free(audio_path); const f = try readNpy(gpa, io, audio_path); defer gpa.free(f.bytes); - const all = try f.arr.floats(gpa); - defer gpa.free(all); - const lane_samples = z3.encoder.lane_frames * z3.encoder.frame_samples; - const audio = all[0..@min(all.len, lane_samples)]; + const audio = try f.arr.floats(gpa); + defer gpa.free(audio); const want_path = try std.fs.path.join(gpa, &.{ dir, "codes.npy" }); defer gpa.free(want_path); const w = try readNpy(gpa, io, want_path); @@ -136,63 +134,39 @@ pub fn encode(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, audio_path: [ const want = try w.arr.ints(gpa); defer gpa.free(want); + var rel = try z3.release.open(gpa, io, root, null); + defer rel.deinit(); var driver = try cuda.Driver.open(); defer driver.close(); var ctx = try cuda.Context.init(&driver, 0); defer ctx.deinit(); var stream = try cuda.Stream.init(&driver, true); defer stream.deinit(); - const enc = try z3.encoder.Encoder.create(gpa, io, &driver, stream, rel.generator); - defer enc.destroy(); - const teach = try z3.teacher.Teacher.create(gpa, io, &driver, stream, teacher_dir); - defer teach.destroy(); const dec = try z3.codec_weights.load(gpa, io, &driver, rel.generator, rel.head); defer { dec.deinit(); gpa.destroy(dec); } - const quant = try z3.quantizer.Quantizer.create(gpa, io, &driver, stream, rel.generator, dec); - defer quant.destroy(); - const Get = struct { - fn get(c: *anyopaque, ptr: u64, out: []u8) anyerror!void { - try @as(*z3.quantizer.Quantizer, @ptrCast(@alignCast(c))).download(ptr, out); - } - }; - var c: Check = .{ .gpa = gpa, .io = io, .ctx = quant, .get = Get.get, .dir = dir }; - + const t_load = nowNs(io); + const clip = try z3.clip.Clip.create(gpa, io, &driver, stream, root, rel.generator, dec); + defer clip.destroy(); + const load_s = @as(f64, @floatFromInt(nowNs(io) - t_load)) / 1e9; + _ = try clip.encode(gpa, audio); const t0 = nowNs(io); - const frames = try enc.acoustic(audio, null); - // the teacher hears the lane padded to its 20 s - const padded = try gpa.alloc(f32, lane_samples); - defer gpa.free(padded); - @memset(padded, 0); - @memcpy(padded[0..audio.len], audio); - const low = try z3.features.resample(gpa, padded); - defer gpa.free(low); - const feats = try z3.features.rows(gpa, low); - defer gpa.free(feats); - const rows = feats.len / z3.teacher.feature_width; - const ssl_ptr = try teach.run(feats, null); - const ssl = try gpa.alloc(f32, rows * z3.teacher.d); - defer gpa.free(ssl); - try teach.download(ssl_ptr, std.mem.sliceAsBytes(ssl)); - const pooled = try z3.quantizer.pool(gpa, ssl, frames); - defer gpa.free(pooled); - const codes = try gpa.alloc([z3.quantizer.codebooks]i32, frames); + const codes = try clip.encode(gpa, audio); defer gpa.free(codes); - try quant.run(enc.latent, pooled, codes, null); const seconds = @as(f64, @floatFromInt(nowNs(io) - t0)) / 1e9; - try quant.run(enc.latent, pooled, codes, .{ .ctx = &c, .f = Check.probe }); - const n = @min(frames, w.arr.shape[0]); - var same: [z3.quantizer.codebooks]usize = @splat(0); - for (codes[0..n], 0..) |row, r| for (row, 0..) |code, cb| { - same[cb] += @intFromBool(code == want[r * z3.quantizer.codebooks + cb]); + const cb = z3.quantizer.codebooks; + const n = @min(codes.len, w.arr.shape[0]); + var same: [cb]usize = @splat(0); + for (codes[0..n], 0..) |row, r| for (row, 0..) |code, j| { + same[j] += @intFromBool(code == want[r * cb + j]); }; var total: usize = 0; for (same) |v| total += v; - const pass = c.fails == 0 and c.missing == 0 and frames == w.arr.shape[0] and same[0] == n; + const pass = codes.len == w.arr.shape[0] and total == n * cb; std.debug.print("codes equal to the fp32 reference's, per codebook of {d} frames: {any}\n", .{ n, same }); - std.debug.print("RESULT zonos3 encode {s} frames={d} reference_frames={d} probes={d} low={d} worst_row_cos={d:.6} codes_equal={d}/{d} semantic_equal={d}/{d} seconds={d:.3}\n", .{ if (pass) "PASS" else "FAIL", frames, w.arr.shape[0], c.n, c.fails, c.worst, total, n * z3.quantizer.codebooks, same[0], n, seconds }); + std.debug.print("RESULT zonos3 encode {s} frames={d} reference_frames={d} codes_equal={d}/{d} semantic_equal={d}/{d} audio_s={d:.2} encode_s={d:.3} load_s={d:.1} weights_mib={d}\n", .{ if (pass) "PASS" else "FAIL", codes.len, w.arr.shape[0], total, n * cb, same[0], n, @as(f64, @floatFromInt(audio.len)) / 44100.0, seconds, load_s, clip.bytes() >> 20 }); return if (pass) 0 else 1; } diff --git a/zig/src/families/zonos3/cuda/clip.zig b/zig/src/families/zonos3/cuda/clip.zig new file mode 100644 index 00000000000..db253a671f2 --- /dev/null +++ b/zig/src/families/zonos3/cuda/clip.zig @@ -0,0 +1,94 @@ +//! A reference clip to its codes on one GPU: the codec encoder's acoustic branch, the SSL teacher and the quantizer. +const std = @import("std"); +const cuda = @import("cuda"); +const enc = @import("encoder.zig"); +const teach = @import("teacher.zig"); +const quant = @import("quantizer.zig"); +const features = @import("../features.zig"); +const release = @import("../release.zig"); +const dec = @import("codec_weights.zig"); + +pub const codebooks = quant.codebooks; +pub const rate = 44100; +/// The shortest clip the release clones from, and the longest it keeps. +pub const min_samples = rate / 2; +pub const max_frames = enc.clip_frames; +/// Frames of what came before that a lane after the first carries: 10 s. +const context = enc.lane_frames / 2; + +pub const Clip = struct { + gpa: std.mem.Allocator, + encoder: *enc.Encoder, + teacher: *teach.Teacher, + quantizer: *quant.Quantizer, + + /// On a context the caller made current; `root` is the release folder, `decoder` its decoder's weights. + pub fn create(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, stream: cuda.Stream, root: []const u8, generator: []const u8, decoder: *const dec.Weights) !*Clip { + const c = try gpa.create(Clip); + errdefer gpa.destroy(c); + const teacher_dir = try std.fs.path.join(gpa, &.{ root, release.teacher_dir }); + defer gpa.free(teacher_dir); + c.gpa = gpa; + c.encoder = try enc.Encoder.create(gpa, io, d, stream, generator); + errdefer c.encoder.destroy(); + c.teacher = try teach.Teacher.create(gpa, io, d, stream, teacher_dir); + errdefer c.teacher.destroy(); + c.quantizer = try quant.Quantizer.create(gpa, io, d, stream, generator, decoder); + return c; + } + + pub fn destroy(c: *Clip) void { + c.quantizer.destroy(); + c.teacher.destroy(); + c.encoder.destroy(); + c.gpa.destroy(c); + } + + /// Device bytes of weights this holds. + pub fn bytes(c: *const Clip) usize { + return c.encoder.w.bytes + c.teacher.bytes + c.quantizer.w.bytes; + } + + /// A clip's codes [frames][10] (caller frees): 44.1 kHz mono, at least half a second; past 60 s is not read. + pub fn encode(c: *Clip, gpa: std.mem.Allocator, clip: []const f32) ![][codebooks]i32 { + if (clip.len < min_samples) return error.ClipTooShort; + const audio = clip[0..@min(clip.len, max_frames * enc.frame_samples)]; + const frames = try c.encoder.load(audio, null); + const out = try gpa.alloc([codebooks]i32, frames); + errdefer gpa.free(out); + const lane_samples = enc.lane_frames * enc.frame_samples; + const padded = try gpa.alloc(f32, lane_samples); + defer gpa.free(padded); + const lane = try gpa.alloc([codebooks]i32, enc.lane_frames); + defer gpa.free(lane); + const ssl = try gpa.alloc(f32, teach.max_rows * teach.d); + defer gpa.free(ssl); + var start: usize = 0; + while (start < frames) { + // the first lane starts the clip; a later one begins `context` frames back and keeps what follows them + const carried: usize = if (start == 0) 0 else context; + const end = @min(frames, start + enc.lane_frames - carried); + const first = start - carried; + const n = end - first; + try c.encoder.acoustic(first, n, null); + // the teacher hears the lane's own samples, zero to its 20 s + const from = first * enc.frame_samples; + const have = @min(audio.len, end * enc.frame_samples) - from; + @memset(padded, 0); + @memcpy(padded[0..have], audio[from..][0..have]); + const low = try features.resample(gpa, padded); + defer gpa.free(low); + const feats = try features.rows(gpa, low); + defer gpa.free(feats); + const rows = feats.len / teach.feature_width; + const ptr = try c.teacher.run(feats, null); + try c.teacher.download(ptr, std.mem.sliceAsBytes(ssl[0 .. rows * teach.d])); + const pooled = try quant.pool(gpa, ssl[0 .. rows * teach.d], n); + defer gpa.free(pooled); + try c.quantizer.run(c.encoder.latent, pooled, lane[0..n], null); + @memcpy(out[start..end], lane[carried..n]); + start = end; + } + return out; + } +}; diff --git a/zig/src/families/zonos3/cuda/encoder.zig b/zig/src/families/zonos3/cuda/encoder.zig index 35149215dff..90224e9f767 100644 --- a/zig/src/families/zonos3/cuda/encoder.zig +++ b/zig/src/families/zonos3/cuda/encoder.zig @@ -10,6 +10,7 @@ const Buf = cuda.DeviceBuffer; pub const frame_samples = 2940; // 44.1 kHz samples a code frame pub const internal_frame = 2944; // 44.16 kHz samples a code frame pub const lane_frames = 300; // a lane is at most 20 s; a longer clip continues in lanes with 10 s of left context +pub const clip_frames = 900; // a reference clip is at most 60 s pub const latent_dim = 1024; const head_rows = 16; // 240 Hz rows a code frame @@ -36,8 +37,9 @@ pub const Encoder = struct { fns: [names.len]cuda.Function, w: *wts.Weights, bufs: std.ArrayList(Buf), - audio: u64, // the lane's 44.1 kHz samples + audio: u64, // the clip's 44.1 kHz samples wave: u64, // its 44.16 kHz samples, whole frames + frames: usize = 0, // the loaded clip's frames p: u64, // front-end rows, three buffers a block's steps rotate through q: u64, r: u64, @@ -69,8 +71,9 @@ pub const Encoder = struct { const samples = lane_frames * internal_frame; const rows = lane_frames * head_rows; const front = samples * wts.blocks[0].channels * 4; - e.audio = try e.alloc(lane_frames * frame_samples * 4); - e.wave = try e.alloc(samples * 4); + e.frames = 0; + e.audio = try e.alloc(clip_frames * frame_samples * 4); + e.wave = try e.alloc(clip_frames * internal_frame * 4); e.p = try e.alloc(front); e.q = try e.alloc(front); e.r = try e.alloc(front); @@ -168,15 +171,13 @@ pub const Encoder = struct { try e.go(.patch_down, (c * h + 255) / 256, rows, 0, &a); } - /// A lane's audio (44.1 kHz, at most 20 s, from the lane's start) to `latent`; the frames it covers. - pub fn acoustic(e: *Encoder, audio: []const f32, probe: ?Probe) !usize { + /// A clip (44.1 kHz, at most 60 s) resampled whole to 44.16 kHz, zero to the end of its last frame; its frames. + pub fn load(e: *Encoder, audio: []const f32, probe: ?Probe) !usize { const frames = (audio.len + frame_samples - 1) / frame_samples; - if (frames == 0 or frames > lane_frames) return error.BadLane; + if (frames == 0 or frames > clip_frames) return error.BadClip; const s = e.stream; - const k = &e.k; const w = e.w; - var t = frames * internal_frame; - // 44.16 kHz, zero to the end of the last frame + const t = frames * internal_frame; try e.buf(e.audio).uploadAsync(0, std.mem.sliceAsBytes(audio), s.handle); var wave = e.buf(e.wave); wave.len = t * 4; @@ -192,11 +193,22 @@ pub const Encoder = struct { try e.go(.resample_in, (count + 255) / 256, 1, 0, &a); } if (probe) |p| try p.f(p.ctx, "internal_audio", e.wave, t, 1); + e.frames = frames; + return frames; + } + + /// A lane of the loaded clip, `frames` frames from frame `first` (at most 20 s), to `latent`. + pub fn acoustic(e: *Encoder, first: usize, frames: usize, probe: ?Probe) !void { + if (frames == 0 or frames > lane_frames or first + frames > e.frames) return error.BadLane; + const s = e.stream; + const k = &e.k; + const w = e.w; + var t = frames * internal_frame; // the front end: x holds the block's rows, y and z are scratch var x = e.p; var y = e.q; var z = e.r; - try e.conv(e.wave, 1, t, w.first, 7, 1, 1, 6, x, wts.blocks[0].channels); + try e.conv(e.wave + first * internal_frame * 4, 1, t, w.first, 7, 1, 1, 6, x, wts.blocks[0].channels); if (probe) |p| try p.f(p.ctx, "lane.0.enc.in", x, t, wts.blocks[0].channels); for (w.blocks, wts.blocks, 0..) |b, shape, bi| { const c = shape.channels; @@ -234,6 +246,5 @@ pub const Encoder = struct { } try e.buf(e.latent).copyFrom(0, x, frames * latent_dim * 4, s.handle); if (probe) |p| try p.f(p.ctx, "lane.0.acoustic", e.latent, frames, latent_dim); - return frames; } }; diff --git a/zig/src/families/zonos3/generate.zig b/zig/src/families/zonos3/generate.zig index cba8f812d93..b02e1a4113e 100644 --- a/zig/src/families/zonos3/generate.zig +++ b/zig/src/families/zonos3/generate.zig @@ -16,7 +16,7 @@ const usage = \\ zonos3-generate --encoder-check DUMP_DIR --generator GENERATOR.pt \\ zonos3-generate --features-check DUMP_DIR \\ zonos3-generate --teacher-check DUMP_DIR --teacher TEACHER_DIR - \\ zonos3-generate --encode-check DUMP_DIR --audio AUDIO.npy --checkpoint RELEASE_DIR + \\ zonos3-generate --encode-check DUMP_DIR --checkpoint RELEASE_DIR \\ zonos3-generate --checkpoint RELEASE_DIR --text "..." --wav OUT.wav [--voice-embedding E.npy | --voice-codes C.npy] \\ [--seed 0] [--temperature 0.75] [--top-k 80] [--top-p 0.69] [--max-frames 2000] [--decoder ID] \\ [--silence-frames 3] [--reference GEN_DIR] @@ -380,7 +380,6 @@ pub fn main(init: std.process.Init) !u8 { var teacher_check: ?[]const u8 = null; var teacher_dir: []const u8 = ""; var encode_check: ?[]const u8 = null; - var clip: []const u8 = ""; var generator: []const u8 = ""; var head: []const u8 = ""; var sp: Speak = .{}; @@ -390,12 +389,12 @@ pub fn main(init: std.process.Init) !u8 { while (i + 1 < argv.len) : (i += 2) { const k = argv[i]; const v = argv[i + 1]; - if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--features-check")) features_check = v else if (std.mem.eql(u8, k, "--teacher-check")) teacher_check = v else if (std.mem.eql(u8, k, "--teacher")) teacher_dir = v else if (std.mem.eql(u8, k, "--encode-check")) encode_check = v else if (std.mem.eql(u8, k, "--audio")) clip = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { + if (std.mem.eql(u8, k, "--model")) model = v else if (std.mem.eql(u8, k, "--check")) check = v else if (std.mem.eql(u8, k, "--frames-check")) frames_check = v else if (std.mem.eql(u8, k, "--codec-check")) codec_check = v else if (std.mem.eql(u8, k, "--encoder-check")) encoder_check = v else if (std.mem.eql(u8, k, "--features-check")) features_check = v else if (std.mem.eql(u8, k, "--teacher-check")) teacher_check = v else if (std.mem.eql(u8, k, "--teacher")) teacher_dir = v else if (std.mem.eql(u8, k, "--encode-check")) encode_check = v else if (std.mem.eql(u8, k, "--generator")) generator = v else if (std.mem.eql(u8, k, "--checkpoint")) sp.checkpoint = v else if (std.mem.eql(u8, k, "--text")) sp.text = v else if (std.mem.eql(u8, k, "--wav")) sp.wav = v else if (std.mem.eql(u8, k, "--voice-embedding")) sp.embedding = v else if (std.mem.eql(u8, k, "--voice-codes")) sp.codes = v else if (std.mem.eql(u8, k, "--decoder")) sp.decoder = v else if (std.mem.eql(u8, k, "--reference")) sp.reference = v else if (std.mem.eql(u8, k, "--seed")) sp.sampling.seed = try std.fmt.parseInt(u64, v, 10) else if (std.mem.eql(u8, k, "--temperature")) sp.sampling.temperature = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--top-k")) sp.sampling.top_k = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--top-p")) sp.sampling.top_p = try std.fmt.parseFloat(f32, v) else if (std.mem.eql(u8, k, "--silence-frames")) sp.silence_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--head")) head = v else if (std.mem.eql(u8, k, "--max-frames")) max_frames = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-rows")) opts.max_rows = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--max-ctx")) opts.max_ctx = try std.fmt.parseInt(usize, v, 10) else { std.debug.print("unknown flag {s}\n{s}", .{ k, usage }); return 2; } } - if (encode_check) |dir| return if (i == argv.len and clip.len > 0 and sp.checkpoint.len > 0) encoder_checks.encode(gpa, io, dir, clip, sp.checkpoint) else 2; + if (encode_check) |dir| return if (i == argv.len and sp.checkpoint.len > 0) encoder_checks.encode(gpa, io, dir, sp.checkpoint) else 2; if (teacher_check) |dir| return if (i == argv.len and teacher_dir.len > 0) encoder_checks.teacher(gpa, io, dir, teacher_dir) else 2; if (features_check) |dir| return if (i == argv.len) encoder_checks.features(gpa, io, dir) else 2; if (encoder_check) |dir| { diff --git a/zig/src/families/zonos3/zonos3.zig b/zig/src/families/zonos3/zonos3.zig index 60f53fa3e42..5377fe35046 100644 --- a/zig/src/families/zonos3/zonos3.zig +++ b/zig/src/families/zonos3/zonos3.zig @@ -17,6 +17,7 @@ pub const codec_weights = @import("cuda/codec_weights.zig"); pub const encoder = @import("cuda/encoder.zig"); pub const teacher = @import("cuda/teacher.zig"); pub const quantizer = @import("cuda/quantizer.zig"); +pub const clip = @import("cuda/clip.zig"); pub const Engine = engine.Engine; pub const Options = engine.Options; From d02c00d61799aef8458b6514cc726f173377294e Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:22:46 +0000 Subject: [PATCH 321/361] zonos3: voice cloning from an uploaded clip (ref_audio), encoded by the engine on first use A clip is read by core's WAV reader and resampler. The speech request gains reference_audio. --- zig/src/core/speech_api.zig | 2 ++ zig/src/families/zonos3/prompt.zig | 16 +++++++--- zig/src/native/zonos_host.zig | 37 ++++++++++++++++++++-- zig/src/server/speech.zig | 17 +++++++--- zig/src/server/zonos_speech.zig | 51 ++++++++++++++++++++++++++---- 5 files changed, 104 insertions(+), 19 deletions(-) diff --git a/zig/src/core/speech_api.zig b/zig/src/core/speech_api.zig index e4443eeb1e4..46b35e9f000 100644 --- a/zig/src/core/speech_api.zig +++ b/zig/src/core/speech_api.zig @@ -21,6 +21,8 @@ pub const SpeechRequest = struct { cfg_gamma: f32 = 1, /// A speaker embedding for the family's speaker row; empty: the prompt rows carry the voice, or there is none. speaker: []const f32 = &.{}, + /// A reference clip to clone the voice from: mono samples at the family's rate; empty: none. + reference_audio: []const f32 = &.{}, }; pub const SpeechInfo = struct { diff --git a/zig/src/families/zonos3/prompt.zig b/zig/src/families/zonos3/prompt.zig index e2233d85675..9dd2eff0395 100644 --- a/zig/src/families/zonos3/prompt.zig +++ b/zig/src/families/zonos3/prompt.zig @@ -43,6 +43,15 @@ fn delayed(codes: []const [C]i32, i: usize) [W]i32 { return r; } +/// A reference clip's codes as a prompt's first rows: delayed a row a codebook, then their flushed tail (caller frees). +pub fn referenceRows(gpa: std.mem.Allocator, codes: []const [C]i32) ![][W]i32 { + if (codes.len == 0) return error.EmptyReference; + for (codes) |row| for (row) |code| if (code < 0 or code >= cfg.codebook_size) return error.BadReferenceCode; + const rows = try gpa.alloc([W]i32, codes.len + C - 1); + for (rows, 0..) |*row, i| row.* = delayed(codes, i); + return rows; +} + /// `ids`: the text's SuperBPE ids. `silence`: the codec's silence frame, `silence_frames` of it prefilled (0: none). pub fn build(gpa: std.mem.Allocator, ids: []const u32, speaker: Speaker, silence: [C]i32, silence_frames: usize) !Prompt { if (ids.len == 0) return error.EmptyText; @@ -56,10 +65,9 @@ pub fn build(gpa: std.mem.Allocator, ids: []const u32, speaker: Speaker, silence try rows.append(gpa, blank()); }, .reference => |codes| { - if (codes.len == 0) return error.EmptyReference; - for (codes) |row| for (row) |code| if (code < 0 or code >= cfg.codebook_size) return error.BadReferenceCode; - // the delayed codes and their flushed tail - for (0..codes.len + C - 1) |i| try rows.append(gpa, delayed(codes, i)); + const prefix = try referenceRows(gpa, codes); + defer gpa.free(prefix); + try rows.appendSlice(gpa, prefix); }, } const condition_row = rows.items.len; diff --git a/zig/src/native/zonos_host.zig b/zig/src/native/zonos_host.zig index 1ff590543f7..a812197e9f8 100644 --- a/zig/src/native/zonos_host.zig +++ b/zig/src/native/zonos_host.zig @@ -102,6 +102,8 @@ const Host = struct { rel: z3.release.Release, e: *z3.Engine, codec: *z3.Codec, + clip: ?*z3.clip.Clip = null, // the clip encoder, loaded by the first request that brings a clip + dir: []const u8, info_: api.Info, mutex: std.Io.Mutex = .init, wake: std.Io.Condition = .init, @@ -143,6 +145,13 @@ const Host = struct { if (r.pcm.len < @as(usize, r.max_frames) * sp.frame_length) return false; if (r.speaker.len != 0 and r.speaker.len != cfg.speaker_dim) return false; for (r.speaker) |x| if (!std.math.isFinite(x)) return false; + if (r.reference_audio.len != 0) { + // a clip becomes a reference prefix: a row a frame and nine more, ahead of the request's rows + const clip_frames = (r.reference_audio.len + z3.codec.frame_samples - 1) / z3.codec.frame_samples; + if (r.speaker.len != 0 or r.reference_audio.len < z3.clip.min_samples or clip_frames > z3.clip.max_frames) return false; + if (r.frames.len + clip_frames + C - 1 > sp.max_prompt_tokens) return false; + for (r.reference_audio) |x| if (!std.math.isFinite(x)) return false; + } if (!std.math.isFinite(r.temperature) or r.temperature < 0) return false; if (!std.math.isFinite(r.top_p) or r.top_p <= 0 or r.top_p > 1 or r.top_k == 0) return false; if (r.unconditioned.len != 0 or r.cfg_gamma != 1) return false; @@ -228,7 +237,24 @@ const Host = struct { fn serve(h: *Host, job: Job, samples: *usize) !api.Reason { const r = job.request; const gpa = h.gpa; - const layout = try Layout.of(r.frames); + var rows = r.frames; + var cloned: [][W]i32 = &.{}; + defer gpa.free(cloned); + if (r.reference_audio.len != 0) { + if (h.clip == null) { + h.clip = try z3.clip.Clip.create(gpa, h.io, &h.e.driver, h.e.stream, h.dir, h.rel.generator, h.codec.w); + std.log.info("zonos3: clip encoder loaded, {d} MiB of weights", .{h.clip.?.bytes() >> 20}); + } + const codes = try h.clip.?.encode(gpa, r.reference_audio); + defer gpa.free(codes); + const prefix = try z3.prompt.referenceRows(gpa, codes); + defer gpa.free(prefix); + cloned = try gpa.alloc([W]i32, prefix.len + r.frames.len); + @memcpy(cloned[0..prefix.len], prefix); + @memcpy(cloned[prefix.len..], r.frames); + rows = cloned; + } + const layout = try Layout.of(rows); var replaced: [1 + cfg.conditions]z3.Replace = undefined; var n: usize = 0; if (r.speaker.len != 0) { @@ -245,8 +271,8 @@ const Host = struct { const sampling: z3.Sampling = .{ .temperature = r.temperature, .top_k = r.top_k, .top_p = r.top_p, .seed = r.seed }; try h.e.reset(); try h.codec.reset(); - var audio: Audio = .{ .h = h, .job = job, .prefill = r.frames[r.frames.len - layout.prefill ..] }; - const made = try z3.generation.generateWatched(gpa, Guarded{ .h = h }, r.frames, @as([]const z3.Replace, replaced[0..n]), sampling, r.max_frames, &audio); + var audio: Audio = .{ .h = h, .job = job, .prefill = rows[rows.len - layout.prefill ..] }; + const made = try z3.generation.generateWatched(gpa, Guarded{ .h = h }, rows, @as([]const z3.Replace, replaced[0..n]), sampling, r.max_frames, &audio); defer gpa.free(made.rows); samples.* = audio.samples; return if (made.eos_frame != null) .stop else .length; @@ -275,9 +301,11 @@ const Host = struct { const h = self(p); drain(h); h.e.ctx.makeCurrent() catch {}; + if (h.clip) |c| c.destroy(); h.codec.destroy(); h.e.destroy(); h.rel.deinit(); + h.gpa.free(h.dir); h.gpa.destroy(h); } }; @@ -293,9 +321,12 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !ap errdefer e.destroy(); const codec = try z3.Codec.create(gpa, io, &e.driver, e.stream, rel.generator, rel.head, .{ .max_frames = b.frames }); errdefer codec.destroy(); + const kept = try gpa.dupe(u8, dir); + errdefer gpa.free(kept); h.* = .{ .gpa = gpa, .io = io, + .dir = kept, .rel = rel, .e = e, .codec = codec, diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index 91682b3e567..eb4226889a0 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -35,6 +35,8 @@ const served_fields = [_][]const u8{ "model", "input", "voice", "speaker", "resp /// A voice as codes the caller encoded: frames of ten codec codes, a ZONOS3 reference prefix in place of `voice`. const zonos_codes = "speaker_reference_codes"; +/// A voice as a clip: a WAV file in base64, which a ZONOS3 engine encodes; other models refuse it. +const zonos_clip = "ref_audio"; /// The rest of the speech protocol's fields: synthesis modifiers and references this route does not honor. const modifier_fields = [_][]const u8{ "speed", "task_type", "language", "instructions", "ref_audio", "ref_text", "references", "x_vector_only_mode", "stream_codec_output", "suppress_bootstrap_silence", "token_count", "duration_tokens", "initial_codec_chunk_frames", "max_new_tokens", "repetition_penalty", "stage_params" }; @@ -42,7 +44,7 @@ const modifier_fields = [_][]const u8{ "speed", "task_type", "language", "instru pub const Format = audio_out.Format; /// `rate` and `channels` are the reply's: the model's own rate and mono unless the request asked otherwise. -pub const Plan = struct { input: []const u8, prompt: []const u32, frames: ?[]const [11]i32 = null, speaker: []const f32 = &.{}, refs: []const @import("drama_prompt").Reference = &.{}, reference_rows: u32 = 0, sampling: speech_sampling.Options, format: Format, stream: bool, rate: u32 = 0, channels: u8 = 1, budget_s: ?f64 = null }; +pub const Plan = struct { input: []const u8, prompt: []const u32, frames: ?[]const [11]i32 = null, speaker: []const f32 = &.{}, reference_audio: []const f32 = &.{}, refs: []const @import("drama_prompt").Reference = &.{}, reference_rows: u32 = 0, sampling: speech_sampling.Options, format: Format, stream: bool, rate: u32 = 0, channels: u8 = 1, budget_s: ?f64 = null }; /// One whole take: its audio, why it ended, and whether it ended in a mid-utterance silence. const Take = struct { pcm: []f32, reason: api.Reason, silence_mid: bool = false, trip: bool = false, jump: ?f64 = null }; @@ -91,7 +93,7 @@ fn checkFields(cx: *Cx, body: Value, inline_voices: bool) errors.Refused!void { return cx.refuse("stream_format must be one of: audio, sse"); } else if (std.mem.eql(u8, key, "sample_rate") or std.mem.eql(u8, key, "channels")) { continue; // checked with the format and stream in prepare - } else if (speech_sampling.isField(key) or std.mem.eql(u8, key, zonos_codes)) { + } else if (speech_sampling.isField(key) or std.mem.eql(u8, key, zonos_codes) or std.mem.eql(u8, key, zonos_clip)) { continue; // validated together before building the prompt } else if (listed(&modifier_fields, key)) { if (value != .null) return cx.fail(.request, "{s} is not supported by this model", .{key}); @@ -150,12 +152,16 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused const format = try responseFormat(cx, raw.strField("response_format") orelse "wav"); const stream = if (raw.get("stream")) |s| s == .bool and s.bool else false; if (stream and format != .pcm) return cx.refuse("stream=true requires response_format='pcm'"); + const voice = raw.strField("voice") orelse raw.strField("speaker") orelse "default"; const codes = raw.field(zonos_codes); - if (codes != null and srv.zonos == null) return cx.fail(.request, "{s} is not supported by this model", .{zonos_codes}); + const clip = raw.field(zonos_clip); + if (srv.zonos == null) for ([_]struct { ?Value, []const u8 }{ .{ codes, zonos_codes }, .{ clip, zonos_clip } }) |f| { + if (f[0] != null) return cx.fail(.request, "{s} is not supported by this model", .{f[1]}); + }; if (srv.zonos) |state| { - const made = try zonos.plan(state, cx, srv.text, sp, input, raw.strField("voice") orelse raw.strField("speaker") orelse "default", codes); + const made = try zonos.plan(state, cx, srv.text, sp, input, voice, codes, clip); const rate, const channels = try output(cx, raw, sp, stream); - return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .sampling = sampling, .format = format, .stream = stream, .rate = rate, .channels = channels }; + return .{ .input = input, .prompt = made.prompt, .frames = made.frames, .reference_audio = made.reference_audio, .sampling = sampling, .format = format, .stream = stream, .rate = rate, .channels = channels }; } const refs = try voiceRefs(srv, cx, raw); const rate, const channels = try output(cx, raw, sp, stream); @@ -257,6 +263,7 @@ fn synthesize(srv: *Server, c: *Conn, cx: *Cx, id: []const u8, sp: api.SpeechInf .unconditioned = guided.rows, .cfg_gamma = guided.gamma, .speaker = plan.speaker, + .reference_audio = plan.reference_audio, }; var box: Mailbox = .{ .io = srv.io, .gpa = srv.gpa }; defer box.deinit(); diff --git a/zig/src/server/zonos_speech.zig b/zig/src/server/zonos_speech.zig index 94a9755a0bf..40ce3c31599 100644 --- a/zig/src/server/zonos_speech.zig +++ b/zig/src/server/zonos_speech.zig @@ -21,7 +21,12 @@ pub const State = struct { default: ?*const req.voices.Voice, }; -pub const Made = struct { prompt: []const u32, frames: []const [11]i32 }; +pub const Made = struct { prompt: []const u32, frames: []const [11]i32, reference_audio: []const f32 = &.{} }; + +const rate = 44100; +/// A reference clip: at least half a second, and the first 60 s of it in whole frames of 2940 samples. +const min_clip = rate / 2; +const max_clip = req.reference_frames * 2940; /// The state for a ZONOS3 Mini release at `dir` (from the arena `a`), or null for any other checkpoint. pub fn load(a: Allocator, io: std.Io, dir: []const u8, default_voice: []const u8) !?*State { @@ -57,9 +62,38 @@ fn referenceCodes(cx: *errors.Cx, value: json.Value) errors.Refused![]const [req return out; } +/// `ref_audio` (a base64 WAV, or a data: URL of one) to mono 44.1 kHz as the release prepares a clip, cut to 60 s. +fn referenceAudio(cx: *errors.Cx, value: json.Value) errors.Refused![]const f32 { + const text = value.str() orelse return cx.refuse(error_prefix ++ " ref_audio must be a base64 string holding a WAV file"); + const payload = if (std.mem.startsWith(u8, text, "data:")) text[(std.mem.indexOfScalar(u8, text, ',') orelse return cx.refuse(error_prefix ++ " ref_audio is a data URL without a payload")) + 1 ..] else text; + const decoder = std.base64.standard.Decoder; + const size = decoder.calcSizeForSlice(payload) catch return cx.refuse(error_prefix ++ " ref_audio is not valid base64"); + const bytes = try cx.a.alloc(u8, size); + decoder.decode(bytes, payload) catch return cx.refuse(error_prefix ++ " ref_audio is not valid base64"); + const wav = @import("core").wav; + const clip = wav.parse(cx.a, bytes) catch |e| return switch (e) { + error.OutOfMemory => error.OutOfMemory, + else => cx.refuse(error_prefix ++ " ref_audio must be a WAV file: PCM of 8, 16, 24 or 32 bits, or 32-bit float"), + }; + if (clip.rate < 8000 or clip.rate > 192000 or clip.rate % 50 != 0) return cx.refuse(error_prefix ++ " ref_audio's sample rate must be a multiple of 50 Hz from 8000 to 192000"); + const audio = try wav.resample(cx.a, clip.samples, clip.rate, rate); + if (audio.len < min_clip) return cx.refuse(error_prefix ++ " ref_audio must be at least half a second long"); + var peak: f32 = 0; + for (audio) |x| { + if (!std.math.isFinite(x)) return cx.refuse(error_prefix ++ " ref_audio holds samples that are not finite"); + peak = @max(peak, @abs(x)); + } + if (peak > 1) for (audio) |*x| { + x.* /= peak; + }; + return audio[0..@min(audio.len, max_clip)]; +} + /// The request's prompt: the voice's reference codes as a delayed prefix, the condition rows, the text, the silence. -pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.SpeechInfo, input: []const u8, voice: []const u8, own: ?json.Value) errors.Refused!Made { - const reference = if (own) |value| try referenceCodes(cx, value) else blk: { +pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.SpeechInfo, input: []const u8, voice: []const u8, own: ?json.Value, clip: ?json.Value) errors.Refused!Made { + if (own != null and clip != null) return cx.refuse(error_prefix ++ " send ref_audio or speaker_reference_codes, not both"); + const audio: []const f32 = if (clip) |value| try referenceAudio(cx, value) else &.{}; + const reference: []const [req.config.codebooks]i32 = if (clip != null) &.{} else if (own) |value| try referenceCodes(cx, value) else blk: { const chosen = if (voice.len == 0 or std.ascii.eqlIgnoreCase(voice, "default")) st.default else req.voices.find(st.voices, voice); const v = chosen orelse { if (st.voices.len == 0) return cx.refuse(error_prefix ++ " this release folder has no voices under gguf/voices"); @@ -75,13 +109,16 @@ pub fn plan(st: *const State, cx: *errors.Cx, text: text_mod.Text, sp: api.Speec error.OutOfMemory => error.OutOfMemory, else => cx.other("the tokenizer cannot encode this prompt"), }; - const built = req.prompt.build(cx.a, ids, .{ .reference = reference }, st.silence, req.silence_frames) catch |e| return switch (e) { + const speaker: req.prompt.Speaker = if (clip != null) .none else .{ .reference = reference }; + const built = req.prompt.build(cx.a, ids, speaker, st.silence, req.silence_frames) catch |e| return switch (e) { error.OutOfMemory => error.OutOfMemory, else => cx.refuse(error_prefix ++ " the text has nothing to speak"), }; - if (built.rows.len > sp.max_prompt_tokens) - return cx.fail(.request, error_prefix ++ " a prompt of {d} rows exceeds the maximum allowed length of {d} rows", .{ built.rows.len, sp.max_prompt_tokens }); - return .{ .prompt = ids, .frames = built.rows }; + // a clip's prefix is made by the engine: a row a frame and nine more + const rows = built.rows.len + if (audio.len > 0) (audio.len + 2939) / 2940 + req.config.codebooks - 1 else 0; + if (rows > sp.max_prompt_tokens) + return cx.fail(.request, error_prefix ++ " a prompt of {d} rows exceeds the maximum allowed length of {d} rows", .{ rows, sp.max_prompt_tokens }); + return .{ .prompt = ids, .frames = built.rows, .reference_audio = audio }; } pub fn listing(a: Allocator, st: *const State) !json.Value { From a1292326776d39ac9e6d3b20d86493f23e113496 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:25:17 +0000 Subject: [PATCH 322/361] zonos3: the recipe page covers the codec encoder and cloning from a clip --- docs/recipes/zonos3-mini.md | 59 ++++++++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 81d62270171..d437b070d67 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -5,7 +5,7 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records came from, and how each part was checked, so the checks can be rerun. Status: a work in progress on one branch, proposed in #3615. The kernels are not registered with the kernel contract -yet, and the quality suite has not been run on this build. +yet, memory admission is not written, and the quality suite has not been run on this build. ## Sources @@ -46,14 +46,18 @@ members, a pickle VM limited to the tensor allow-list, nested state dicts named - **Prompt and output** (`prompt.zig`, `speech.zig`, `release.zig`, `voices.zig`): the training layout `[reference prefix | speaker row] [condition rows] text [silence]`, the undelayed frames to decode, the decoder's -3 dB headroom and the soft limiter above -1 dBFS. +- **Codec encoder** (`cuda/clip.zig` over `cuda/encoder.zig`, `cuda/teacher.zig`, `cuda/quantizer.zig`, + `features.zig`): a reference clip to its codes. The acoustic branch (the 44,100 to 44,160 Hz resampler, a + convolutional front end, five causal transformer stages down to 15 Hz), the SSL teacher (Wav2Vec2-BERT's first 16 + conformer layers over log-mel features computed on the host), then the quantizer: the teacher's rows pooled onto + the frames give the semantic code, and nine residual codebooks take what its decoded prediction leaves. A clip + runs in the publisher's lanes: 20 s each, a later lane carrying 10 s of what came before. - **Served route** (`native/zonos_host.zig`, `server/zonos_speech.zig`): one request at a time; the release's 27 - default voices by their reference codes; `speaker_reference_codes` for a caller's own voice; WAV or PCM, whole or - streamed in chunks of 1, 2, 4, 8 and then 15 frames. -- **Codec encoder, in progress** (`cuda/encoder.zig`, `cuda/teacher.zig`, `features.zig`): the acoustic branch and - the SSL teacher each run and are checked on their own. The quantizer that joins them, lanes for clips past 20 s - and an upload field on the route are not written, so the server cannot yet clone from an audio file. + default voices by their reference codes; a caller's own voice as `ref_audio` (a WAV file in base64, encoded by the + engine) or as `speaker_reference_codes`; WAV or PCM, whole or streamed in chunks of 1, 2, 4, 8 and then 15 frames. + The clip encoder's weights load on the first request that brings a clip. -Refused or absent: cloning from an uploaded clip, text normalization (text is spoken as typed), speaker and control +Refused or absent: clips in formats other than WAV, text normalization (text is spoken as typed), speaker and control guidance, LACI, steering, speech editing, accent adapters, phoneme, start and pause tokens, short-text prompts, condition values (every condition row is its "unknown" bucket), the `full_mr` decoder, concurrency, Metal. @@ -72,7 +76,7 @@ is what the port is compared with. The publisher's CUDA servers run parts in bf1 ## How it was checked All figures below were measured on one RTX 5090 (driver 615.71, nvcc 13.3, Zig 0.17.0, `-Dsm=120`) at branch commit -`141aefa97`, with every reference dump regenerated for that run. +`39a2864ef`, with every reference dump regenerated for that run. ### The reference side @@ -91,8 +95,14 @@ python ZONOS/tools/dump_golden.py codec-encoder --generator RELEASE/autoencoder/ --audio RELEASE/gguf/voices/English/Cillian_en-Irish_M_1.wav -o D/enc_cillian python tools/zig/zonos3_reference.py encoder RELEASE/autoencoder/generator.pt D/enc_cillian/audio.npy D/enc_cillian_fp32 python tools/zig/zonos3_reference.py teacher RELEASE/autoencoder/teacher D/enc_cillian/lane.0.ssl.features.npy D/teacher_cillian_fp32 +python tools/zig/zonos3_reference.py clip RELEASE/autoencoder/generator.pt RELEASE/autoencoder/teacher D/enc_cillian/audio.npy D/clip_cillian +python tools/zig/zonos3_reference.py clip RELEASE/autoencoder/generator.pt RELEASE/autoencoder/teacher D/enc_cillian/audio.npy D/clip_cillian_47s --seconds 47.3 ``` +The encoder's clip is the release's own `Cillian_en-Irish_M_1.wav` (9.67 s, one lane); the 47.3 s clip is that +audio repeated, which takes four lanes. `clip` follows the publisher's lane layout; its production tool reports the +same four pieces for the 47.3 s clip (300 frames, then 150, 150 and 110 after 150 of context each). + The test request is "The quick brown fox jumps over the lazy dog, and then it rests by the river." in the release's Savannah voice, once by her speaker embedding (a 30-row prompt) and once by her reference codes (a 209-row prompt). "Greedy" is the release's sampler at temperature 0: its masks and repetition penalty still apply. @@ -115,6 +125,8 @@ Savannah voice, once by her speaker embedding (a 30-row prompt) and once by her | Teacher's features | `--features-check D/enc_cillian` | the reference's 999 feature rows of a 20 s lane | cosine 1.0000000; largest difference 2.4e-7 | | Encoder, acoustic branch | `--encoder-check D/enc_cillian_fp32 --generator G` | 101 captures of the fp32 run, 145 frames | every row's cosine 1.000000 | | SSL teacher | `--teacher-check D/teacher_cillian_fp32 --teacher RELEASE/autoencoder/teacher` | 18 captures of the fp32 run, 999 rows | worst row's cosine 0.9999252 | +| Clip to codes, one lane | `--encode-check D/clip_cillian --checkpoint RELEASE` | the fp32 run's codes, 145 frames | 1,450 of 1,450 codes equal | +| Clip to codes, four lanes | `--encode-check D/clip_cillian_47s --checkpoint RELEASE` | the fp32 run's codes, 710 frames | 7,100 of 7,100 codes equal | `G` is `RELEASE/autoencoder/generator.pt` and `H` the `keep2_plain` head checkpoint. A capture passes when its worst row's cosine against the reference is at least 0.9999. The backbone's "equal prompt rows" also covers the tokenizer: @@ -130,6 +142,9 @@ The reference draws with PyTorch's generator, so sampled frames cannot match it. - **Repeatability:** the served route returns the same bytes for the same seed, and a streamed reply's bytes equal the whole reply's. +- **Cloned voices:** two clips sent as `ref_audio` (the release's Cillian clip, and its Thaddeus clip as 48 kHz + stereo) each gave speech that Whisper transcribed with no errors. By the release's speaker encoder, each output's + cosine to its own source clip was 0.78 and 0.83, against 0.21 and 0.17 to the other clip. - **Transcription:** Whisper large-v3-turbo (resampled to 16 kHz) transcribed the greedy test sentence with no errors, from the port and from the reference alike, and a 62-word sampled passage with word error rates of 0.033 and 0.016 in two voices; each error was the word "TensorFold". @@ -143,12 +158,15 @@ The reference draws with PyTorch's generator, so sampled frames cannot match it. | A 19.4 s sampled reply, whole | 1.28 s (15 times real time) | | The same reply streamed | first response byte at 0.06 s, done at 1.29 s, bytes equal to the whole reply | | Device memory in use after it | 3.57 GiB (2.36 GiB of it weights) | +| Device memory once a clip has been cloned | 8.82 GiB (the clip encoder adds 4.43 GiB of weights) | +| The first request with a clip (9.7 s), which loads the encoder | 9.0 s | +| Later requests with a clip: a 9.7 s mono clip, a 15.4 s stereo 48 kHz clip | 1.07 s, 1.53 s | | A second request while one runs | 503 | -| An unknown voice, `top_k` above 4,096, malformed `speaker_reference_codes` | 400 with the reason | +| An unknown voice, `top_k` above 4,096, malformed `speaker_reference_codes`, a `ref_audio` that is no WAV or is under half a second | 400 with the reason | The standalone tool measured the parts: 22.0 s of sampled audio took 1.15 s to generate and 0.27 s to decode; the -decoder alone turns 11.4 s of codes into audio in 0.13 s; the acoustic encoder takes 0.48 s for a 9.7 s clip and the -teacher 0.26 s for a 20 s lane. There are no CUDA graphs and the sampler runs on the host; none of this is tuned. +decoder alone turns 11.4 s of codes into audio in 0.13 s; a 9.7 s clip encodes in 0.75 s and a 47.3 s clip in 5.1 s +(the acoustic branch 0.48 s and the teacher 0.26 s a lane). There are no CUDA graphs and the sampler runs on the host; none of this is tuned. ### Repo checks @@ -170,16 +188,29 @@ fp32. Measured with the reference alone, on the dumps above: | Encoder latent, 145 frames | worst row's cosine 0.966, mean 0.998 | | Teacher output, 999 rows | worst row's cosine 0.085, mean 0.984 | | Codes re-encoded from a release clip against the codes the release ships for it | 97% equal in the semantic codebook, 56% to 87% in the residual ones | +| Codes of the 47.3 s clip, the fp32 run against the bf16 production run | 96% equal in the semantic codebook, 40% to 75% in the residual ones | The port computes in fp32 and matches the fp32 runs. Two consequences: its audio is closer to the publisher's CPU -decode than the publisher's own CUDA server is, and a native encoder's codes will not be bit-equal to the -publisher's. The encoder's gate should therefore be code agreement and cloned-voice quality, not identity. +decode than the publisher's own CUDA server is, and the native encoder's codes are not the publisher's production +codes. Residual quantization amplifies small differences, so the codes diverge while describing the same audio. +Decoding the 9.67 s clip's three sets of codes with the reference decoder and comparing each with the clip: + +| Codes | Log-mel distance to the clip (L1) | Speaker cosine to the clip | +| --- | --- | --- | +| Shipped with the release | 0.574 | 0.946 | +| The reference's bf16 run | 0.576 | 0.944 | +| The fp32 run (what the port produces) | 0.620 | 0.947 | + +That is one clip: the fp32 codes keep the speaker as well and sit about 8% further in log-mel distance. Whether +that gap is real across clips, and whether the backbone (trained on bf16-encoded references) clones as well from +fp32 codes, needs a proper listening or scoring pass before the encoder's gate is agreed. ## Shared code this touches - `drama3/codec_pth.zig` moved to `core/torch_pth.zig` (its zip half to `core/torch_zip.zig`) and gained nested checkpoints and a raw reader; Drama 3's codec loads through the same code and its host tests pass. -- `core/speech_api.zig`: `SpeechRequest.speaker`, an optional speaker vector. +- `drama3/wav.zig` moved to `core/wav.zig`: both families read WAV files and resample with it. +- `core/speech_api.zig`: `SpeechRequest.speaker`, an optional speaker vector, and `reference_audio`, an optional clip. - `server/`: voices load through `speech_voices.zig`; the speech route, the sampling parser, the voices listing, model detection and the tokenizer loader each gained a branch for a release folder, which has no `config.json` and is recognised by `lm/zonos3_mini/params.json`. From fc1098633be457e21f94cb7a8d0c254ef9f2c6f6 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:34:33 +0000 Subject: [PATCH 323/361] zonos3: the speech field check keeps refusing ref_audio and reference codes for other models --- zig/src/server/speech.zig | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/zig/src/server/speech.zig b/zig/src/server/speech.zig index eb4226889a0..5725465c711 100644 --- a/zig/src/server/speech.zig +++ b/zig/src/server/speech.zig @@ -79,11 +79,13 @@ fn listed(names: []const []const u8, key: []const u8) bool { return false; } +const Takes = struct { inline_voices: bool = false, zonos: bool = false }; + /// Refuses what this route would drop: unknown fields, set modifiers, non-strings, a bad ``stream``/``stream_format``. -fn checkFields(cx: *Cx, body: Value, inline_voices: bool) errors.Refused!void { +fn checkFields(cx: *Cx, body: Value, takes: Takes) errors.Refused!void { for (body.object.keys(), body.object.values()) |key, value| { if (listed(&served_fields, key)) { - if (value == .object and inline_voices and std.mem.eql(u8, key, "voice")) continue; // an attested voice object + if (value == .object and takes.inline_voices and std.mem.eql(u8, key, "voice")) continue; // an attested voice object if (value != .string) return cx.fail(.request, "{s} must be a string", .{key}); } else if (std.mem.eql(u8, key, "stream")) { if (value != .bool and value != .null) return cx.refuse("stream must be a boolean"); @@ -93,7 +95,7 @@ fn checkFields(cx: *Cx, body: Value, inline_voices: bool) errors.Refused!void { return cx.refuse("stream_format must be one of: audio, sse"); } else if (std.mem.eql(u8, key, "sample_rate") or std.mem.eql(u8, key, "channels")) { continue; // checked with the format and stream in prepare - } else if (speech_sampling.isField(key) or std.mem.eql(u8, key, zonos_codes) or std.mem.eql(u8, key, zonos_clip)) { + } else if (speech_sampling.isField(key) or (takes.zonos and (std.mem.eql(u8, key, zonos_codes) or std.mem.eql(u8, key, zonos_clip)))) { continue; // validated together before building the prompt } else if (listed(&modifier_fields, key)) { if (value != .null) return cx.fail(.request, "{s} is not supported by this model", .{key}); @@ -138,7 +140,7 @@ const rate_list = list: { /// Every check that can refuse the request, then its prompt ids, before anything reaches the engine. fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused!Plan { if (raw != .object) return cx.refuse("speech request body must be a JSON object"); - try checkFields(cx, raw, srv.config.voice.inline_voices); + try checkFields(cx, raw, .{ .inline_voices = srv.config.voice.inline_voices, .zonos = srv.zonos != null }); const zonos = @import("zonos_speech.zig"); const sampling = if (srv.zonos != null) try speech_sampling.parseFrom(cx, raw, .{ .temperature = zonos.temperature, .top_p = zonos.top_p, .top_k = zonos.top_k }, zonos.max_top_k) else try speech_sampling.parse(cx, raw); const model = raw.strField("model") orelse return cx.fail(.request, "model is required: send {s}", .{srv.config.served_name}); @@ -155,9 +157,6 @@ fn prepare(srv: *Server, cx: *Cx, sp: api.SpeechInfo, raw: Value) errors.Refused const voice = raw.strField("voice") orelse raw.strField("speaker") orelse "default"; const codes = raw.field(zonos_codes); const clip = raw.field(zonos_clip); - if (srv.zonos == null) for ([_]struct { ?Value, []const u8 }{ .{ codes, zonos_codes }, .{ clip, zonos_clip } }) |f| { - if (f[0] != null) return cx.fail(.request, "{s} is not supported by this model", .{f[1]}); - }; if (srv.zonos) |state| { const made = try zonos.plan(state, cx, srv.text, sp, input, voice, codes, clip); const rate, const channels = try output(cx, raw, sp, stream); @@ -491,6 +490,20 @@ pub fn quantizeInPlace(pcm: []f32) error{NonFinite}![]u8 { return bytes[0 .. 2 * pcm.len]; } +test "fields: a ZONOS3 server takes a clip and reference codes, any other refuses both as before" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const body = (try json.parse(a, "{\"model\": \"m\", \"input\": \"hi\", \"ref_audio\": \"UklGRg==\", \"speaker_reference_codes\": [[1]]}")).ok; + var cx: Cx = .{ .a = a }; + try checkFields(&cx, body, .{ .zonos = true }); + try std.testing.expectError(error.Refused, checkFields(&cx, body, .{})); + try std.testing.expectEqualStrings("ref_audio is not supported by this model", cx.message); + const codes = (try json.parse(a, "{\"model\": \"m\", \"input\": \"hi\", \"speaker_reference_codes\": [[1]]}")).ok; + try std.testing.expectError(error.Refused, checkFields(&cx, codes, .{})); + try std.testing.expectEqualStrings("unknown speech request field: speaker_reference_codes", cx.message); +} + test "fields: unknown ones are refused even when null, modifiers when set" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); @@ -513,9 +526,9 @@ test "fields: unknown ones are refused even when null, modifiers when set" { var cx: Cx = .{ .a = a }; const body = (try json.parse(a, case[0])).ok; if (case[1].len == 0) { - try checkFields(&cx, body, false); + try checkFields(&cx, body, .{}); } else { - try std.testing.expectError(error.Refused, checkFields(&cx, body, false)); + try std.testing.expectError(error.Refused, checkFields(&cx, body, .{})); try std.testing.expectEqualStrings(case[1], cx.message); } } From 1cab5f70be825911cb66bf89dcabfbb3e3ec3bf7 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:35:15 +0000 Subject: [PATCH 324/361] zonos3: a browser test page and its pass-through server, and how to run them --- docs/recipes/zonos3-mini.md | 18 ++++ tools/zig/zonos3_test_page.html | 161 ++++++++++++++++++++++++++++++++ tools/zig/zonos3_test_page.py | 76 +++++++++++++++ 3 files changed, 255 insertions(+) create mode 100644 tools/zig/zonos3_test_page.html create mode 100644 tools/zig/zonos3_test_page.py diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index d437b070d67..e6b585716eb 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -168,6 +168,24 @@ The standalone tool measured the parts: 22.0 s of sampled audio took 1.15 s to g decoder alone turns 11.4 s of codes into audio in 0.13 s; a 9.7 s clip encodes in 0.75 s and a 47.3 s clip in 5.1 s (the acoustic branch 0.48 s and the teacher 0.26 s a lane). There are no CUDA graphs and the sampler runs on the host; none of this is tuned. +### A test page + +`tools/zig/zonos3_test_page.py` serves a small browser page (`zonos3_test_page.html`) and passes its three routes +(`/v1/voices`, `/v1/models`, `/v1/audio/speech`) through to the model's port, so the page and the API share an +origin. It uses the standard library only. + +```sh +tensorfold-native serve RELEASE --parallel 1 --port 8080 +python3 tools/zig/zonos3_test_page.py --upstream 127.0.0.1:8080 --port 8081 +``` + +The page lists the server's voices, speaks text with the seed and sampling fields, keeps each take with its player +and timing, and clones a voice from an audio file: the browser decodes the file, makes a 16-bit mono WAV of its +first 60 s and sends it as `ref_audio` with each request. It adds no authentication; it binds 127.0.0.1 unless +`--bind` says otherwise. Checked with curl through the pass-through (the page, the voice list, a spoken reply, a +cloned reply, a refusal's message passed back, other paths 404); the page's script was parsed but not driven in a +browser by an automated test. + ### Repo checks `zig fmt --check build.zig zig`, `tools/zig/lean_check.py` (0 new over the base), `tools/zig/cuda_common_check.py` diff --git a/tools/zig/zonos3_test_page.html b/tools/zig/zonos3_test_page.html new file mode 100644 index 00000000000..837b395629b --- /dev/null +++ b/tools/zig/zonos3_test_page.html @@ -0,0 +1,161 @@ + + + + + +ZONOS3 Mini test page + + + +

+

ZONOS3 Mini on TensorFold

+

Text is spoken as typed: write numbers and dates out in words. One request at a time. + Cloned voices stay in this browser tab only; clone only voices you have the right to use.

+ + + + +
+
+
+
+
+
+
+
+
+
+
+
+ + +
+
+
+ + + diff --git a/tools/zig/zonos3_test_page.py b/tools/zig/zonos3_test_page.py new file mode 100644 index 00000000000..17c9e72ea72 --- /dev/null +++ b/tools/zig/zonos3_test_page.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""A browser test page for a ZONOS3 Mini server: serves the page and passes its three /v1 routes to tensorfold serve.""" + +import argparse +import http.client +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +USAGE = """Start the model, then this page beside it: + + tensorfold-native serve RELEASE --parallel 1 --port 8080 + python3 tools/zig/zonos3_test_page.py --upstream 127.0.0.1:8080 --port 8081 + +Open http://127.0.0.1:8081/. The page lists the server's voices, speaks text with the sampling fields, and clones a +voice from an audio file: the browser turns the file into a WAV and sends it as ref_audio with each request. The +pass-through exists so the page and the API share an origin; it adds no authentication, so bind it only where the +model's own port may be reached (--bind, 127.0.0.1 by default). Standard library only.""" + +PAGE = Path(__file__).with_name("zonos3_test_page.html") +ROUTES = {"GET": ("/v1/voices", "/v1/models"), "POST": ("/v1/audio/speech",)} + + +def handler(upstream): + host, _, port = upstream.rpartition(":") + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def reply(self, status, content_type, data): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def forward(self, method): + size = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(size) if method == "POST" else None + if self.path not in ROUTES[method]: + return self.reply(404, "application/json", b'{"error": {"message": "not a route of this page"}}') + try: + conn = http.client.HTTPConnection(host, int(port), timeout=600) + conn.request(method, self.path, body, {"Content-Type": "application/json"}) + response = conn.getresponse() + data = response.read() + conn.close() + self.reply(response.status, response.getheader("Content-Type", "application/octet-stream"), data) + except OSError as e: + message = '{"error": {"message": "the speech server is not reachable: %s"}}' % str(e).replace('"', "'") + self.reply(502, "application/json", message.encode()) + + def do_GET(self): + if self.path in ("/", "/index.html"): + return self.reply(200, "text/html; charset=utf-8", PAGE.read_bytes()) + self.forward("GET") + + def do_POST(self): + self.forward("POST") + + return Handler + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, epilog=USAGE, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--upstream", default="127.0.0.1:8080", help="the tensorfold server's host:port") + parser.add_argument("--bind", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8081) + args = parser.parse_args() + ThreadingHTTPServer((args.bind, args.port), handler(args.upstream)).serve_forever() + + +if __name__ == "__main__": + main() From 63ced502bf092320b1c028fa44adeabbe6d33efc Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:04:57 +0000 Subject: [PATCH 325/361] zonos3: draw sampled codes with the lane core's keyed sampler The frame sampler keeps the release's masks and repetition penalty and hands each codebook's unmasked logits to core/lanes/sampling.zig at position frame * 10 + codebook, in place of the family's own seeded generator. Greedy frames are unchanged: 78 of 78 and 80 of 80 identical to the reference at prompt chunks of 7 and 256 rows. --- docs/recipes/zonos3-mini.md | 12 ++- zig/build/cuda.zig | 4 +- zig/build/cuda_engines.zig | 2 +- zig/build/zonos3.zig | 14 +-- zig/src/families/zonos3/generation.zig | 2 +- zig/src/families/zonos3/sampler.zig | 128 ++++++++----------------- 6 files changed, 60 insertions(+), 102 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index e6b585716eb..3913a19c9de 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -37,8 +37,10 @@ members, a pickle VM limited to the tensor allow-list, nested state dicts named attention layers, Full AttnRes residuals, a dense feed-forward in layer 0 and a 64-expert top-2 latent mixture of experts in the rest, one linear head for 10 codebooks of 4,098 logits a frame. - **Sampler and generation** (`sampler.zig`, `generation.zig`, on the host): the release's masks, repetition - penalty, temperature, top-k, top-p and min-p, its end-of-audio countdown and cold-start padding. Draws come from a - counter-based generator keyed by the request's seed, the frame and the codebook. + penalty, its end-of-audio countdown and cold-start padding, on fp32 logits. Each codebook's code is then drawn + by TensorFold's keyed sampler (`core/lanes/sampling.zig`: temperature, top-k, top-p and min-p in float64) among + the ids left unmasked, at position `frame * 10 + codebook` under the request's seed. Temperature 0 is its greedy + rule: the first maximum, ties to the lower id. - **Codec decoder** (`cuda/codec.zig`, `zonos3_codec.cu`): the `keep2_plain` decoder, the reference servers' default: code tables, the semantic head, five causal transformer stages from 15 Hz to 240 Hz, the ConvNeXt head, two centered iSTFTs, the FIR mixer and the 44,160 to 44,100 Hz resampler. It keeps its state between calls and @@ -138,7 +140,11 @@ I have not yet found whether a reduction order or the padded rows explain it. ### Sampled speech -The reference draws with PyTorch's generator, so sampled frames cannot match it. Two indirect checks: +The reference draws with PyTorch's generator, so sampled frames cannot match it; a seeded draw is defined by +TensorFold's keyed sampler instead. With it, the standalone tool gave byte-identical WAV files for one seeded +request run twice, and Whisper transcribed that 4.9 s reply with no errors. The figures in the rest of this section +and in the serving table below were measured before the sampler moved to the keyed one (commit 39a2864ef, the +family's own seeded generator) and have not been repeated since. Two indirect checks: - **Repeatability:** the served route returns the same bytes for the same seed, and a streamed reply's bytes equal the whole reply's. diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 14d279efcb5..f5d89980734 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -175,7 +175,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const d3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, mods.core) } } }); const d3_exe = b.addExecutable(.{ .name = "drama3-generate", .root_module = d3_tool }); b.step("drama3-generate", "Drama generation and replay controls on CUDA").dependOn(&b.addInstallArtifact(d3_exe, .{}).step); - @import("zonos3.zig").install(b, target, optimize, cuda, mods.core); + @import("zonos3.zig").install(b, target, optimize, cuda, mods.core, mods.lanes); } /// The Kolibri-1 CUDA family over the runtime, the core and the lane core. const kolibri1Module = @import("kolibri.zig").module; @@ -318,7 +318,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st } const drama3 = @import("drama3_host.zig").hostTests(b, step, cuda, mods.core); const native_modules = engines(b, host, .debug, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision); - @import("zonos3.zig").hostTests(b, step, cuda, mods.core, native_modules.api); + @import("zonos3.zig").hostTests(b, step, cuda, mods.core, mods.lanes, native_modules.api); b.step("test-qwen-grants-host", "Qwen MTP head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"shared head costs:"} })).step); b.step("test-nemotron-grants-host", "Nemotron shared head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"Nemotron shared prices:"} })).step); b.step("test-nemotron-cuda-steps-host", "Nemotron CUDA's stepped prompt pass on the lanes, stopped before GPU work").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"nemotron cuda steps:"} })).step); diff --git a/zig/build/cuda_engines.zig b/zig/build/cuda_engines.zig index f0974d84f2f..3e433462ced 100644 --- a/zig/build/cuda_engines.zig +++ b/zig/build/cuda_engines.zig @@ -76,7 +76,7 @@ pub fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu .{ .name = "lanes", .module = lanes }, .{ .name = "nemotron", .module = nemotron }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, core) }, - .{ .name = "zonos3", .module = @import("zonos3.zig").module(b, target, optimize, cuda, core) }, + .{ .name = "zonos3", .module = @import("zonos3.zig").module(b, target, optimize, cuda, core, lanes) }, .{ .name = "lfm2", .module = lfm2Module(b, target, optimize, cuda, core) }, .{ .name = "core", .module = core }, .{ .name = "flashnext", .module = flashnextModule(b, target, optimize, cuda, core, lanes, qwen_vision, api) }, diff --git a/zig/build/zonos3.zig b/zig/build/zonos3.zig index 92409c26c72..91e8a46f0e9 100644 --- a/zig/build/zonos3.zig +++ b/zig/build/zonos3.zig @@ -1,14 +1,14 @@ //! ZONOS3 Mini's CUDA family module and its zonos3-generate tool. const std = @import("std"); -/// The family over a runtime and the core. -pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) *std.Build.Module { - return b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/zonos3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); +/// The family over a runtime, the core and the lane core (its keyed sampler). +pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/zonos3.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "lanes", .module = lanes } } }); } /// The family's host tests (config, prompt, sampler, generation, output stage, release layout) and its host's. -pub fn hostTests(b: *std.Build, step: *std.Build.Step, cuda: *std.Build.Module, core: *std.Build.Module, api: *std.Build.Module) void { - const family = module(b, b.graph.host, .debug, cuda, core); +pub fn hostTests(b: *std.Build, step: *std.Build.Step, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, api: *std.Build.Module) void { + const family = module(b, b.graph.host, .debug, cuda, core, lanes); const run = b.addRunArtifact(b.addTest(.{ .root_module = family })); const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/zonos_host.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "zonos3", .module = family }, .{ .name = "engine_api", .module = api }, .{ .name = "cuda", .module = cuda } } }); const run_host = b.addRunArtifact(b.addTest(.{ .root_module = host })); @@ -19,8 +19,8 @@ pub fn hostTests(b: *std.Build, step: *std.Build.Step, cuda: *std.Build.Module, } } -pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module) void { - const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "cuda", .module = cuda }, .{ .name = "zonos3", .module = module(b, target, optimize, cuda, core) } } }); +pub fn install(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module) void { + const tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "cuda", .module = cuda }, .{ .name = "zonos3", .module = module(b, target, optimize, cuda, core, lanes) } } }); const exe = b.addExecutable(.{ .name = "zonos3-generate", .root_module = tool }); b.step("zonos3-generate", "ZONOS3 Mini's backbone on CUDA against the reference's dumps").dependOn(&b.addInstallArtifact(exe, .{}).step); } diff --git a/zig/src/families/zonos3/generation.zig b/zig/src/families/zonos3/generation.zig index c6d0f3a1d09..a4efded753a 100644 --- a/zig/src/families/zonos3/generation.zig +++ b/zig/src/families/zonos3/generation.zig @@ -41,7 +41,7 @@ pub fn generateWatched(gpa: std.mem.Allocator, engine: anytype, prompt: []const while (true) { try engine.lastLogits(@ptrCast(logits)); const generated = rows.items.len; - var row = sampler.sample(logits, codes.items, generated, cfg.eoa_id, sampling); + var row = try sampler.sample(gpa, logits, codes.items, generated, cfg.eoa_id, sampling); coldStart(&row, generated, has_audio_prefix); try codes.append(gpa, row); var full: [W]i32 = undefined; diff --git a/zig/src/families/zonos3/sampler.zig b/zig/src/families/zonos3/sampler.zig index 29c1e55c3aa..bc10f488253 100644 --- a/zig/src/families/zonos3/sampler.zig +++ b/zig/src/families/zonos3/sampler.zig @@ -1,6 +1,7 @@ -//! ZONOS3's frame sampler on the host: specials masked, repetition penalty, temperature, top-k, top-p, min-p, one draw. +//! ZONOS3's frame sampler on the host: specials masked, the repetition penalty, then the keyed sampler a codebook. const std = @import("std"); const cfg = @import("config.zig"); +const keyed_sampler = @import("lanes").sampling; const V = cfg.audio_vocab; const C = cfg.codebooks; @@ -15,42 +16,34 @@ pub const Sampling = struct { repetition_codebooks: i32 = 6, seed: u64 = 0, - /// The settings as every sampler applies them: top_k < 1 is the whole codebook, a negative count every codebook. + /// The settings as every sampler applies them: a penalty of at least 1, a negative count every codebook. pub fn clamped(s: Sampling) Sampling { var c = s; - c.temperature = @max(s.temperature, 1e-6); - c.top_k = if (s.top_k >= 1) s.top_k else cfg.codebook_size; - c.top_p = @min(@max(s.top_p, 0.0), 1.0); - c.min_p = @max(s.min_p, 0.0); c.repetition_penalty = @max(s.repetition_penalty, 1.0); c.repetition_codebooks = if (s.repetition_codebooks < 0) C else @min(s.repetition_codebooks, C); return c; } -}; -/// A draw in [0, 1) that depends only on the request's seed, the frame and the codebook. -pub fn uniform(seed: u64, frame: u64, codebook: u64) f32 { - var z = seed +% 0x9E3779B97F4A7C15 *% (frame *% C + codebook + 1); - z = (z ^ (z >> 30)) *% 0xBF58476D1CE4E5B9; - z = (z ^ (z >> 27)) *% 0x94D049BB133111EB; - z ^= z >> 31; - return @as(f32, @floatFromInt(z >> 40)) * (1.0 / 16777216.0); -} + /// The keyed sampler's rule: top_k < 1 or past the codebook keeps every candidate, temperature 0 is greedy. + pub fn keyed(s: Sampling) keyed_sampler.Sampling { + const k: u32 = if (s.top_k >= 1 and s.top_k < cfg.codebook_size) s.top_k else 0; + return .{ .seed = s.seed, .temperature = s.temperature, .top_k = k, .top_p = s.top_p, .min_p = @max(s.min_p, 0.0) }; + } +}; -fn argmax(x: []const f32) usize { - var best: usize = 0; - for (x, 0..) |v, i| if (v > x[best]) { - best = i; - }; - return best; +/// The keyed sampler's position of a frame's codebook: every draw of a reply has its own. +pub fn position(frame: u64, codebook: u64) u64 { + return frame * C + codebook; } /// Frame `frame`'s codes from its logits (overwritten); `recent`: generated rows, oldest first; `stop`: the end id. -pub fn sample(logits: *[C][V]f32, recent: []const [C]i32, frame: u64, stop: i32, sampling: Sampling) [C]i32 { +pub fn sample(gpa: std.mem.Allocator, logits: *[C][V]f32, recent: []const [C]i32, frame: u64, stop: i32, sampling: Sampling) ![C]i32 { const s = sampling.clamped(); + const rule = s.keyed(); const window: usize = if (s.repetition_window > 0 and s.repetition_penalty > 1.0 and s.repetition_codebooks > 0) @min(s.repetition_window, recent.len) else 0; var out: [C]i32 = undefined; - var order: [V]u16 = undefined; + var values: [V]f64 = undefined; + var ids: [V]u64 = undefined; for (logits, 0..) |*l, cb| { for (l[cfg.codebook_size..], cfg.codebook_size..) |*v, id| { if (id == cfg.audio_pad_id or id != stop) v.* = -std.math.inf(f32); @@ -65,66 +58,15 @@ pub fn sample(logits: *[C][V]f32, recent: []const [C]i32, frame: u64, stop: i32, v.* = if (v.* > 0) v.* / s.repetition_penalty else v.* * s.repetition_penalty; } } - for (l) |*v| v.* /= s.temperature; - const greedy = argmax(l); - for (&order, 0..) |*o, i| o.* = @intCast(i); - const Desc = struct { - fn lt(x: *const [V]f32, a: u16, b: u16) bool { - return x[a] > x[b] or (x[a] == x[b] and a < b); - } - }; - std.mem.sort(u16, &order, l, Desc.lt); - if (s.top_k < V) { - const kth = l[order[s.top_k - 1]]; - for (l) |*v| if (v.* < kth) { - v.* = -std.math.inf(f32); - }; - } - // softmax, in descending order so the nucleus cut reads the running sum - const top = l[order[0]]; - var total: f32 = 0; - for (l) |*v| { - v.* = @exp(v.* - top); - total += v.*; - } - for (l) |*v| v.* /= total; - if (s.top_p > 0 and s.top_p < 1) { - var before: f32 = 0; - var kept: f32 = 0; - for (order) |id| { - const p = l[id]; - if (before > s.top_p) l[id] = 0 else kept += p; - before += p; - } - const norm = @max(kept, 1e-8); - for (l) |*v| v.* /= norm; + // the masked ids are no candidates: the keyed sampler draws among the rest, in float64 + var n: usize = 0; + for (l, 0..) |v, id| { + if (v == -std.math.inf(f32)) continue; + values[n] = v; + ids[n] = id; + n += 1; } - if (s.min_p > 0) { - const floor = s.min_p * l[order[0]]; - var kept: f32 = 0; - for (l) |*v| { - if (v.* < floor) v.* = 0; - kept += v.*; - } - const norm = @max(kept, 1e-8); - for (l) |*v| v.* /= norm; - } - var sum: f32 = 0; - for (l) |v| sum += v; - if (!(sum > 0)) { - out[cb] = @intCast(greedy); - continue; - } - const target = uniform(s.seed, frame, cb) * sum; - var run: f32 = 0; - var pick: usize = greedy; - for (l, 0..) |p, id| { - if (p <= 0) continue; - run += p; - pick = id; - if (run > target) break; - } - out[cb] = @intCast(pick); + out[cb] = @intCast(try keyed_sampler.choose(gpa, values[0..n], ids[0..n], position(frame, cb), rule)); } return out; } @@ -138,7 +80,7 @@ test "sampler: specials other than the stop id are never drawn, and a zero tempe l[cfg.audio_pad_id] = 50; l[100 + cb] = 9; } - const got = sample(logits, &.{}, 0, cfg.eoa_id, .{ .temperature = 0 }); + const got = try sample(t.allocator, logits, &.{}, 0, cfg.eoa_id, .{ .temperature = 0 }); for (got, 0..) |code, cb| try t.expectEqual(@as(i32, @intCast(100 + cb)), code); } @@ -152,13 +94,23 @@ test "sampler: a repeated code is penalised in the first codebooks only" { l[6] = 1.5; } const recent = [_][C]i32{@splat(5)}; - const got = sample(logits, &recent, 1, cfg.eoa_id, .{ .temperature = 0 }); + const got = try sample(t.allocator, logits, &recent, 1, cfg.eoa_id, .{ .temperature = 0 }); for (got, 0..) |code, cb| try t.expectEqual(@as(i32, if (cb < 6) 6 else 5), code); } -test "sampler: the same seed, frame and codebook give the same draw" { +test "sampler: a seeded draw depends on the seed, the frame and the codebook alone" { const t = std.testing; - try t.expectEqual(uniform(42, 3, 1), uniform(42, 3, 1)); - try t.expect(uniform(42, 3, 1) != uniform(42, 3, 2)); - try t.expect(uniform(42, 3, 1) < 1.0 and uniform(42, 3, 1) >= 0.0); + const logits = try t.allocator.create([C][V]f32); + defer t.allocator.destroy(logits); + var got: [3][C]i32 = undefined; + for (&got, [_]u64{ 42, 42, 43 }) |*g, seed| { + for (logits, 0..) |*l, cb| for (l, 0..) |*v, i| { + v.* = @as(f32, @floatFromInt((i * 13 + cb * 5) % 101)) * 0.05; + }; + g.* = try sample(t.allocator, logits, &.{}, 7, cfg.eoa_id, .{ .seed = seed, .temperature = 1.0, .top_k = 0, .top_p = 1.0 }); + } + try t.expectEqual(got[0], got[1]); + try t.expect(!std.mem.eql(i32, &got[0], &got[2])); + for (got[0]) |code| try t.expect(code < cfg.codebook_size or code == cfg.eoa_id); + try t.expect(position(3, 1) != position(3, 2) and position(3, 9) + 1 == position(4, 0)); } From fc080c64b54010ec6b5bead4dbf8d145c97710a6 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:25:25 +0000 Subject: [PATCH 326/361] zonos3: launch records for all 40 kernels, contract tests for the norms and linears Gate 5: each launch's registers and shared memory on sm_80 to sm_121, measured with nvcc 13.0, and a 13.2 set for the seven launches later releases compile differently. Gates 1 to 4: z3_rmsnorm, zc_layernorm, z3_linear and zc_linear through the row and dense input families. --- docs/recipes/zonos3-mini.md | 41 ++- zig/src/core/contract/registry_cuda_sets.zig | 2 +- zig/src/core/contract/registry_joins.zig | 2 + zig/src/core/contract/zonos3_cuda_records.zig | 67 +++++ zig/tests/cuda/contract_family_sets.zig | 6 +- zig/tests/cuda/contract_limits.zig | 1 + zig/tests/cuda/contract_zonos3.zig | 280 ++++++++++++++++++ 7 files changed, 394 insertions(+), 5 deletions(-) create mode 100644 zig/src/core/contract/zonos3_cuda_records.zig create mode 100644 zig/tests/cuda/contract_zonos3.zig diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 3913a19c9de..2ff3e7e764d 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -4,8 +4,9 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records what is ported, where every source came from, and how each part was checked, so the checks can be rerun. -Status: a work in progress on one branch, proposed in #3615. The kernels are not registered with the kernel contract -yet, memory admission is not written, and the quality suite has not been run on this build. +Status: a work in progress on one branch, proposed in #3615. Every kernel launch has its limits record, but only four +of the 40 kernels have numeric contract tests and none has a planted control of its own; memory admission is not +written, and the quality suite has not been run on this build. ## Sources @@ -199,7 +200,41 @@ browser by an automated test. `zig build test-zonos-host`. On a machine whose umask is 0002 one unrelated test in that suite (`serve --config`, which refuses a group-writable file) fails; it passes under umask 022. -Not run: `zig build test`, `test-kernel-contract`, `test-golden`, and any quality suite. +`zig build test-kernel-contract` passes with the family's records joined. + +Not run: `zig build test`, `test-golden`, and any quality suite. + +### Kernel contract + +**Launch limits (gate 5).** The four images hold 40 kernels, each registered as one launch in +`zig/src/core/contract/zonos3_cuda_records.zig` with the thread count and the largest dynamic shared memory the +engine asks for. The records were measured, not written by hand: every image was built for sm_80, sm_86, sm_89, +sm_120 and sm_121 and audited with + + zig build fatbins kernel-contract-fatbins compile-cuda-tests -Dnvcc=NVCC -Dsm=80,86,89,120,121 --prefix OUT + tf-cuda-test kernel-contract-limits OUT/fatbin + +and the `RECORD` lines it prints were copied into the file. With nvcc 13.0.88 all 200 launch and chip pairs pass +with their record current, and the same records are current for images built by nvcc 13.0.48. nvcc 13.2.86 compiles +seven of the launches with other register counts (`z3_attention`, `z3_conv_silu`, `z3_embed`, `zc_dwconv`, +`zc_resample`, `ze_resample_in`, `zt_attention`); those are the file's `cuda_132` set, joined into the registry's +13.2 set, and nvcc 13.3.73 compiles all 40 as 13.2 does. With the set in place all 200 pairs are current under each +of the four compilers. The audit also reports 18 stale records for launches of other families +(`exl3_experts tf_exl3_prompt_down` and `tf_exl3_prompt_gu`, `flashnext_mtp fn_row_topk`, `qwen35 tf_q35_gdn_slots_1`, +`_2` and `_4`); this branch does not change those kernels, and the same audit was not run on the base to compare. + +**Numeric gates (1 to 4).** `zig/tests/cuda/contract_zonos3.zig` registers four kernels, the ones that sum: +`z3_rmsnorm`, `zc_layernorm`, `z3_linear` and `zc_linear`, through the contract's row and dense input families with +the bf16 inputs widened to the fp32 rows these kernels read. On an RTX 5090 (driver 615.71.09, images from nvcc +13.0.88), `tf-cuda-test kernel-contract zonos3` ended with + + (filtered) SUMMARY 4 kernels: 4 pass gates 1-4, 0 fail, 0 known findings; 0 controls: 0 red as planted, 0 missed; 0 limit problems + +The layer norm's test adds a term to its bound: the kernel scales in fp32 and then adds the bias, so the roundings +before the bias are a fraction of the scaled value and not of the sum, which gate 4's rows make cancel. + +Not done: numeric tests for the other 36 kernels, and a planted control for any of them. The four tests above rely +on the gates' shared controls only. ## The reference's bf16 paths diff --git a/zig/src/core/contract/registry_cuda_sets.zig b/zig/src/core/contract/registry_cuda_sets.zig index fcfc5d1ac1b..45a89dde696 100644 --- a/zig/src/core/contract/registry_cuda_sets.zig +++ b/zig/src/core/contract/registry_cuda_sets.zig @@ -6,7 +6,7 @@ const CudaSet = registry.CudaSet; /// The later releases' sets, rising by release; a tree's images are checked against the newest at or below their own. pub const cuda_sets = [_]CudaSet{ - .{ .release = .{ .major = 13, .minor = 2 }, .usage = &(@import("registry_shared_attention.zig").nvcc132(Override) ++ [_]Override{ + .{ .release = .{ .major = 13, .minor = 2 }, .usage = &(@import("registry_shared_attention.zig").nvcc132(Override) ++ @import("zonos3_cuda_records.zig").cuda_132 ++ [_]Override{ .{ .name = "window_pages tf_wrows_merge_512_pg", .usage = .{ .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } }, .{ .name = "moe tf_moe_topk_sigmoid_score_warp", .usage = .{ .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 } } }, .{ .name = "norms tf_rms_rows", .usage = .{ .{ .regs = 32, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 } } }, diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 1ebc696fe43..7f78b593a5c 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -23,6 +23,7 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("nemo_audio_cuda_records.zig").cuda ++ @import("idol_cuda_sets.zig").cuda ++ @import("qwen3_asr_cuda_records.zig").cuda ++ + @import("zonos3_cuda_records.zig").cuda ++ @import("exl3_dense_records.zig").cuda ++ @import("exl3_finish_records.zig").cuda ++ @import("lfm2_moe_cuda_records.zig").cuda ++ @@ -165,4 +166,5 @@ test { _ = @import("inkling2_dspark_metal_records.zig"); _ = @import("h3_image_cuda_records.zig"); _ = @import("inkling2_vision_metal_records.zig"); + _ = @import("zonos3_cuda_records.zig"); } diff --git a/zig/src/core/contract/zonos3_cuda_records.zig b/zig/src/core/contract/zonos3_cuda_records.zig new file mode 100644 index 00000000000..b332c859b66 --- /dev/null +++ b/zig/src/core/contract/zonos3_cuda_records.zig @@ -0,0 +1,67 @@ +//! ZONOS3 Mini's CUDA launches: the backbone (zonos3.cu), the codec decoder, the codec encoder and its SSL teacher. +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage, the compiler of the release fatbins. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "zonos3 z3_embed", .symbol = "z3_embed", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3 z3_rmsnorm", .symbol = "z3_rmsnorm", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 128, .bound = 256 }, .{ .regs = 15, .static = 128, .bound = 256 }, .{ .regs = 15, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3 z3_attnres", .symbol = "z3_attnres", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 384, .bound = 256 }, .{ .regs = 40, .static = 384, .bound = 256 }, .{ .regs = 40, .static = 384, .bound = 256 }, .{ .regs = 40, .static = 384, .bound = 256 }, .{ .regs = 40, .static = 384, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3 z3_linear", .symbol = "z3_linear", .image = "zonos3", .threads = 256, .dynamic = 16384 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3 z3_conv_silu", .symbol = "z3_conv_silu", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 35, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3 z3_gdn_prep", .symbol = "z3_gdn_prep", .image = "zonos3", .threads = 128 }, .usage = .{ .{ .regs = 20, .static = 128, .bound = 128 }, .{ .regs = 20, .static = 128, .bound = 128 }, .{ .regs = 20, .static = 128, .bound = 128 }, .{ .regs = 21, .static = 128, .bound = 128 }, .{ .regs = 21, .static = 128, .bound = 128 } } }, + .{ .launch = .{ .name = "zonos3 z3_gdn", .symbol = "z3_gdn", .image = "zonos3", .threads = 128 }, .usage = .{ .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 }, .{ .regs = 255, .static = 0, .bound = 128 } } }, + .{ .launch = .{ .name = "zonos3 z3_gated_norm", .symbol = "z3_gated_norm", .image = "zonos3", .threads = 128 }, .usage = .{ .{ .regs = 22, .static = 128, .bound = 128 }, .{ .regs = 23, .static = 128, .bound = 128 }, .{ .regs = 23, .static = 128, .bound = 128 }, .{ .regs = 21, .static = 128, .bound = 128 }, .{ .regs = 21, .static = 128, .bound = 128 } } }, + .{ .launch = .{ .name = "zonos3 z3_attn_prep", .symbol = "z3_attn_prep", .image = "zonos3", .threads = 512 }, .usage = .{ .{ .regs = 28, .static = 0, .bound = 512 }, .{ .regs = 28, .static = 0, .bound = 512 }, .{ .regs = 28, .static = 0, .bound = 512 }, .{ .regs = 26, .static = 0, .bound = 512 }, .{ .regs = 26, .static = 0, .bound = 512 } } }, + .{ .launch = .{ .name = "zonos3 z3_attention", .symbol = "z3_attention", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 126, .static = 33920, .bound = 256 }, .{ .regs = 128, .static = 33920, .bound = 256 }, .{ .regs = 128, .static = 33920, .bound = 256 }, .{ .regs = 127, .static = 33920, .bound = 256 }, .{ .regs = 127, .static = 33920, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3 z3_mul_silu", .symbol = "z3_mul_silu", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3 z3_route", .symbol = "z3_route", .image = "zonos3", .threads = 32 }, .usage = .{ .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 26, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 }, .{ .regs = 36, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3 z3_combine", .symbol = "z3_combine", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3 z3_softcap", .symbol = "z3_softcap", .image = "zonos3", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_linear", .symbol = "zc_linear", .image = "zonos3_codec", .threads = 256, .dynamic = 23552 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_layernorm", .symbol = "zc_layernorm", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 17, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 19, .static = 128, .bound = 256 }, .{ .regs = 23, .static = 128, .bound = 256 }, .{ .regs = 23, .static = 128, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_attn_prep", .symbol = "zc_attn_prep", .image = "zonos3_codec", .threads = 32 }, .usage = .{ .{ .regs = 21, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 }, .{ .regs = 22, .static = 0, .bound = 32 }, .{ .regs = 23, .static = 0, .bound = 32 }, .{ .regs = 23, .static = 0, .bound = 32 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_attention", .symbol = "zc_attention", .image = "zonos3_codec", .threads = 128 }, .usage = .{ .{ .regs = 163, .static = 33408, .bound = 128 }, .{ .regs = 254, .static = 33408, .bound = 128 }, .{ .regs = 254, .static = 33408, .bound = 128 }, .{ .regs = 254, .static = 33408, .bound = 128 }, .{ .regs = 254, .static = 33408, .bound = 128 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_add_scaled", .symbol = "zc_add_scaled", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_gelu", .symbol = "zc_gelu", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_patch_up", .symbol = "zc_patch_up", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_dwconv", .symbol = "zc_dwconv", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_gather", .symbol = "zc_gather", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_latent", .symbol = "zc_latent", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 32, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_spec", .symbol = "zc_spec", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 29, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_ola", .symbol = "zc_ola", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 34, .static = 0, .bound = 0 }, .{ .regs = 72, .static = 0, .bound = 0 }, .{ .regs = 72, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_mix", .symbol = "zc_mix", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 23, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_codec zc_resample", .symbol = "zc_resample", .image = "zonos3_codec", .threads = 256 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_resample_in", .symbol = "ze_resample_in", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 19, .static = 0, .bound = 0 }, .{ .regs = 19, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_conv", .symbol = "ze_conv", .image = "zonos3_encoder", .threads = 256, .dynamic = 4096 }, .usage = .{ .{ .regs = 31, .static = 0, .bound = 256 }, .{ .regs = 37, .static = 0, .bound = 256 }, .{ .regs = 37, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_snake", .symbol = "ze_snake", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 0 }, .{ .regs = 19, .static = 0, .bound = 0 }, .{ .regs = 19, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_add", .symbol = "ze_add", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_patch_down", .symbol = "ze_patch_down", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 13, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_sub", .symbol = "ze_sub", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 }, .{ .regs = 10, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_nearest", .symbol = "ze_nearest", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 27, .static = 2048, .bound = 256 }, .{ .regs = 27, .static = 2048, .bound = 256 }, .{ .regs = 27, .static = 2048, .bound = 256 }, .{ .regs = 40, .static = 2048, .bound = 256 }, .{ .regs = 40, .static = 2048, .bound = 256 } } }, + .{ .launch = .{ .name = "zonos3_encoder ze_sub_code", .symbol = "ze_sub_code", .image = "zonos3_encoder", .threads = 256 }, .usage = .{ .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 }, .{ .regs = 14, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_teacher zt_swish", .symbol = "zt_swish", .image = "zonos3_teacher", .threads = 256 }, .usage = .{ .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 }, .{ .regs = 16, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_teacher zt_glu", .symbol = "zt_glu", .image = "zonos3_teacher", .threads = 256 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_teacher zt_dwconv", .symbol = "zt_dwconv", .image = "zonos3_teacher", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .launch = .{ .name = "zonos3_teacher zt_attention", .symbol = "zt_attention", .image = "zonos3_teacher", .threads = 128 }, .usage = .{ .{ .regs = 166, .static = 33700, .bound = 128 }, .{ .regs = 252, .static = 33700, .bound = 128 }, .{ .regs = 252, .static = 33700, .bound = 128 }, .{ .regs = 254, .static = 33700, .bound = 128 }, .{ .regs = 254, .static = 33700, .bound = 128 } } }, +}; + +/// What nvcc 13.2 compiles differently (13.3 the same): the registry's 13.2 set takes these. +pub const cuda_132 = [_]registry.Override{ + .{ .name = "zonos3 z3_attention", .usage = .{ .{ .regs = 126, .static = 33920, .bound = 256 }, .{ .regs = 128, .static = 33920, .bound = 256 }, .{ .regs = 128, .static = 33920, .bound = 256 }, .{ .regs = 128, .static = 33920, .bound = 256 }, .{ .regs = 128, .static = 33920, .bound = 256 } } }, + .{ .name = "zonos3 z3_conv_silu", .usage = .{ .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 39, .static = 0, .bound = 0 }, .{ .regs = 37, .static = 0, .bound = 0 }, .{ .regs = 37, .static = 0, .bound = 0 } } }, + .{ .name = "zonos3 z3_embed", .usage = .{ .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .name = "zonos3_codec zc_dwconv", .usage = .{ .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, + .{ .name = "zonos3_codec zc_resample", .usage = .{ .{ .regs = 19, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 0 } } }, + .{ .name = "zonos3_encoder ze_resample_in", .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 }, .{ .regs = 20, .static = 0, .bound = 0 } } }, + .{ .name = "zonos3_teacher zt_attention", .usage = .{ .{ .regs = 166, .static = 33700, .bound = 128 }, .{ .regs = 252, .static = 33700, .bound = 128 }, .{ .regs = 252, .static = 33700, .bound = 128 }, .{ .regs = 253, .static = 33700, .bound = 128 }, .{ .regs = 253, .static = 33700, .bound = 128 } } }, +}; + +test "ZONOS3 CUDA: every launch is in the live registry and fits every SM" { + const t = @import("std").testing; + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(@import("std").mem.eql(u8, active.launch.name, r.launch.name)); + try t.expectEqual(@as(usize, 1), found); + try t.expectEqual(@as(usize, 0), try registry.checkCuda(t.allocator, &.{r}, true)); + } +} diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 23c0f21bba0..cf72d3803af 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -1,4 +1,4 @@ -//! The CUDA contract's family sets and Clef's joint schema head. +//! The CUDA contract's family sets, Clef's joint schema head and ZONOS3's kernels. const std = @import("std"); const cuda = @import("cuda"); const check = @import("check.zig"); @@ -30,6 +30,7 @@ pub const Sets = struct { idol: *@import("contract_idol.zig").Set, idol_decoder: *@import("contract_idol_decoder.zig").Set, glm_moe: *@import("contract_glm_moe_direct.zig").Set, + zonos3: *@import("contract_zonos3.zig").Set, /// Each set's kernels appended to `list`, in this order. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel), affine4: *cuda.qlinear.Affine4Kernels, cap: u32) !Sets { @@ -82,6 +83,7 @@ pub const Sets = struct { errdefer idol.deinit(); const idol_decoder = try @import("contract_idol_decoder.zig").Set.init(gpu, s, a, list); const glm_moe = try @import("contract_glm_moe_direct.zig").Set.init(gpu, s, a, list); + const zonos3 = try @import("contract_zonos3.zig").Set.init(gpu, s, a, list); return .{ .gpa = gpu.gpa, .bf16_experts = bf16_experts, @@ -104,10 +106,12 @@ pub const Sets = struct { .a = a, .idol_decoder = idol_decoder, .glm_moe = glm_moe, + .zonos3 = zonos3, }; } pub fn deinit(sets: Sets) void { + sets.zonos3.deinit(); sets.glm_moe.deinit(); sets.idol_decoder.deinit(); sets.idol.deinit(); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index fe54dc36ba8..93c9c931dae 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -44,6 +44,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "glm_vision", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "zonos3", "zonos3_codec", "zonos3_encoder", "zonos3_teacher" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; return error.UnknownContractImage; } diff --git a/zig/tests/cuda/contract_zonos3.zig b/zig/tests/cuda/contract_zonos3.zig new file mode 100644 index 00000000000..0f95cf428c6 --- /dev/null +++ b/zig/tests/cuda/contract_zonos3.zig @@ -0,0 +1,280 @@ +//! ZONOS3 Mini's summing kernels under the contract on CUDA: the two norms and the two linears, all fp32 rows. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const rows = contract.rows; +const Dense = contract.dense.Dense; + +/// bf16 bit patterns widened to the fp32 values a kernel's rows hold. +fn widen(a: std.mem.Allocator, bits: []const u16) ![]f32 { + const out = try a.alloc(f32, bits.len); + for (out, bits) |*o, b| o.* = c.fromBf16(b); + return out; +} + +/// ceil(k / 256) squares a thread, then a warp's butterfly and the block's butterfly over 8 warps. +fn normDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 10; +} + +pub const Which = enum { rmsnorm, layernorm }; + +pub fn normSpec(which: Which) c.Spec { + return switch (which) { + // the backbone's norms at its width, the prompt's rows a pass + .rmsnorm => .{ .name = "cuda zonos3 z3_rmsnorm (fp32 rows, bf16 gamma)", .accum = .f32, .depth = normDepth, .ops = 8, .out = .f32, .tiles = .{ .{}, .{}, .{ .size = 256 } }, .served = &.{ .{ .rows = 1, .n = 1024, .k = 1024 }, .{ .rows = 64, .n = 1024, .k = 1024 } } }, + // the codec's stages (768, 1280), the teacher (1024) and its features (160) + .layernorm => .{ .name = "cuda zonos3_codec zc_layernorm (fp32 rows)", .accum = .f32, .depth = normDepth, .ops = 10, .out = .f32, .tiles = .{ .{}, .{}, .{ .size = 256, .step = 32, .min = 32 } }, .served = &.{ .{ .rows = 300, .n = 1280, .k = 1280 }, .{ .rows = 999, .n = 1024, .k = 1024 }, .{ .rows = 999, .n = 160, .k = 160 }, .{ .rows = 1024, .n = 768, .k = 768 } } }, + }; +} + +/// A norm over fp32 rows: z3_rmsnorm with its bf16 weight, or zc_layernorm with fp32 weight and bias. +pub const Norm = struct { + rig: rig_.Rig, + which: Which, + f: cuda.Function, + r: ?rows.Rows = null, + x: u64 = 0, + w: u64 = 0, + b: u64 = 0, + out: u64 = 0, + + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, which: Which) !Norm { + return .{ .rig = .{ .gpu = gpu, .s = s }, .which = which, .f = try mod.function(if (which == .rmsnorm) "z3_rmsnorm" else "zc_layernorm") }; + } + + pub fn deinit(self: *Norm) void { + if (self.r) |r| r.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Norm) g.Kernel { + return .{ .spec = normSpec(self.which), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Norm); + + pub fn prepare(self: *Norm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != shape.k or shape.k % 32 != 0) return false; + if (self.r) |r| r.deinit(); + self.r = null; + self.rig.reset(); + const a = self.rig.gpu.gpa; + const r = try rows.Rows.init(a, if (self.which == .rmsnorm) .rms else .layer_norm, shape); + self.r = r; + r.fill(fill, seed); + const x = try widen(a, r.x); + defer a.free(x); + self.x = try self.rig.input(std.mem.sliceAsBytes(x)); + if (self.which == .rmsnorm) { + self.w = try self.rig.input(std.mem.sliceAsBytes(r.w)); + } else { + const w = try widen(a, r.w); + defer a.free(w); + const b = try widen(a, r.b); + defer a.free(b); + self.w = try self.rig.input(std.mem.sliceAsBytes(w)); + self.b = try self.rig.input(std.mem.sliceAsBytes(b)); + } + self.out = try self.rig.output(r.outputs() * 4); + return true; + } + + pub fn run(self: *Norm) !void { + const r = self.r.?; + const k: c_int = @intCast(r.shape.k); + var a: cuda.Args = .{}; + a.add(self.x); + if (self.which == .rmsnorm) { + a.add(k); + a.add(self.w); + a.add(self.out); + a.add(k); + } else { + a.add(self.w); + a.add(self.b); + a.add(self.out); + } + a.add(k); + a.add(r.eps); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(r.shape.rows), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Norm) usize { + return self.r.?.outputs(); + } + + pub fn reference(self: *Norm, want: []f64, mag: []f64) !void { + return self.r.?.reference(want, mag); + } + + pub fn simulate(self: *Norm, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(acc, order, out); + } + + /// The layer norm's scaled value rounds in fp32 before the bias joins it: those roundings are of it, not the sum. + pub fn bounds(self: *Norm, want: []const f64, _: []const f64, allow: []f64) !void { + if (self.which != .layernorm) return; + const r = self.r.?; + const k = r.shape.k; + for (allow, want, 0..) |*l, w, i| l.* += normSpec(.layernorm).ops * 0x1p-24 * @abs(w - c.fromBf16(r.b[i % k])); + } +}; + +/// A lane's chain of fused multiply-adds over every 32nd input, then the warp's butterfly. +fn linearDepth(s: c.Shape) usize { + return (s.k + 31) / 32 + 5; +} + +pub const Weights = enum { bf16, f32 }; + +pub fn linearSpec(weights: Weights) c.Spec { + return switch (weights) { + // the backbone's projections: a GDN layer's, the dense feed-forward's two, an expert's, the head's + .bf16 => .{ .name = "cuda zonos3 z3_linear (fp32 rows, bf16 weights)", .accum = .f32, .depth = linearDepth, .out = .f32, .tiles = .{ .{}, .{ .size = 8 }, .{ .size = 256, .step = 8, .min = 8 } }, .served = &.{ .{ .rows = 1, .n = 2056, .k = 1024 }, .{ .rows = 64, .n = 1024, .k = 2048 }, .{ .rows = 2, .n = 3072, .k = 256 }, .{ .rows = 1, .n = 40980, .k = 1024 }, .{ .rows = 16, .n = 1024, .k = 4096 } } }, + // the codec's: a stage's attention and feed-forward, the encoder's first projection, an iSTFT branch + .f32 => .{ .name = "cuda zonos3_codec zc_linear (fp32 rows and weights)", .accum = .f32, .depth = linearDepth, .out = .f32, .tiles = .{ .{}, .{ .size = 8 }, .{ .size = 32 } }, .served = &.{ .{ .rows = 16, .n = 2304, .k = 768 }, .{ .rows = 8, .n = 1280, .k = 5120 }, .{ .rows = 8, .n = 768, .k = 5888 }, .{ .rows = 8, .n = 2208, .k = 2210 } } }, + }; +} + +/// y [rows, n] = x [rows, k] W^T with fp32 sums: z3_linear over bf16 weights, or zc_linear over fp32 ones. +pub const Linear = struct { + rig: rig_.Rig, + weights: Weights, + f: cuda.Function, + d: ?Dense = null, + x: u64 = 0, + w: u64 = 0, + out: u64 = 0, + + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, weights: Weights) !Linear { + const f = try mod.function(if (weights == .bf16) "z3_linear" else "zc_linear"); + return .{ .rig = .{ .gpu = gpu, .s = s }, .weights = weights, .f = f }; + } + + pub fn deinit(self: *Linear) void { + if (self.d) |d| d.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Linear) g.Kernel { + return .{ .spec = linearSpec(self.weights), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Linear); + + pub fn prepare(self: *Linear, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + // the bf16 kernel reads eight weights a load; both stage a row in at most 6 KiB of floats + if (shape.k == 0 or shape.n == 0 or shape.rows == 0 or shape.k > 6144 or shape.k % 2 != 0) return false; + if (self.weights == .bf16 and shape.k % 8 != 0) return false; + if (self.d) |d| d.deinit(); + self.d = null; + self.rig.reset(); + const a = self.rig.gpu.gpa; + const d = try Dense.init(a, shape, 1); + self.d = d; + d.fillX(fill, seed, 1); + const bits = try a.alloc(u16, d.w.len); + defer a.free(bits); + var prng = std.Random.DefaultPrng.init(seed ^ 0x5a); + const rng = prng.random(); + const k = shape.k; + for (bits) |*b| b.* = c.toBf16(if (fill == .stress) 0 else rng.float(f32) * 2 - 1); + if (fill == .stress) for (0..shape.n) |j| for (0..k / 2) |i| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 7)); + bits[j * k + i] = c.toBf16(v); + bits[j * k + k / 2 + i] = c.toBf16(-v); + }; + for (d.w, bits) |*w, b| w.* = c.fromBf16(b); + const x = try widen(a, d.x); + defer a.free(x); + self.x = try self.rig.input(std.mem.sliceAsBytes(x)); + if (self.weights == .bf16) { + self.w = try self.rig.input(std.mem.sliceAsBytes(bits)); + } else { + const w = try widen(a, bits); + defer a.free(w); + self.w = try self.rig.input(std.mem.sliceAsBytes(w)); + } + self.out = try self.rig.output(d.outputs() * 4); + return true; + } + + pub fn run(self: *Linear) !void { + const d = self.d.?; + const k: c_int = @intCast(d.shape.k); + const n: c_int = @intCast(d.shape.n); + var a: cuda.Args = .{}; + a.add(self.w); + a.add(self.x); + a.add(k); + if (self.weights == .bf16) a.add(@as(c_int, 1)); + a.add(k); + a.add(n); + a.add(self.out); + a.add(n); + a.add(@as(u64, 0)); + if (self.weights == .bf16) { + a.add(@as(u64, 0)); + a.add(@as(i64, 0)); + } + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast((d.shape.n + 7) / 8), .y = @intCast(d.shape.rows), .z = 1 }, .block = .{ .x = 256 }, .shared = @intCast(d.shape.k * 4) }, self.rig.s, &a); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Linear) usize { + return self.d.?.outputs(); + } + + pub fn reference(self: *Linear, want: []f64, mag: []f64) !void { + return self.d.?.reference(want, mag); + } + + pub fn simulate(self: *Linear, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.d.?.simulate(acc, order, out); + } +}; + +/// The family's registered kernels: the backbone's image and the codec's. +pub const Set = struct { + gpa: std.mem.Allocator, + backbone: cuda.Module, + codec: cuda.Module, + norms: [2]Norm, + linears: [2]Linear, + + /// The set, its kernels appended to `list`. + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var backbone = try cuda.Module.load(gpu.d, cuda.kernels.zonos3); + errdefer backbone.unload(); + var codec = try cuda.Module.load(gpu.d, cuda.kernels.zonos3_codec); + errdefer codec.unload(); + set.* = .{ + .gpa = gpu.gpa, + .backbone = backbone, + .codec = codec, + .norms = .{ try Norm.init(gpu, s, backbone, .rmsnorm), try Norm.init(gpu, s, codec, .layernorm) }, + .linears = .{ try Linear.init(gpu, s, backbone, .bf16), try Linear.init(gpu, s, codec, .f32) }, + }; + for (&set.norms) |*x| try list.append(a, x.kernel()); + for (&set.linears) |*x| try list.append(a, x.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.linears) |*x| x.deinit(); + for (&set.norms) |*x| x.deinit(); + set.codec.unload(); + set.backbone.unload(); + set.gpa.destroy(set); + } +}; From ca081af1222ada1437cbcb2ee5c2f928680a5c00 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:30:14 +0000 Subject: [PATCH 327/361] zonos3 docs: seeded replies from the served build repeat, streamed or whole --- docs/recipes/zonos3-mini.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 2ff3e7e764d..ec558f01c38 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -145,7 +145,15 @@ The reference draws with PyTorch's generator, so sampled frames cannot match it; TensorFold's keyed sampler instead. With it, the standalone tool gave byte-identical WAV files for one seeded request run twice, and Whisper transcribed that 4.9 s reply with no errors. The figures in the rest of this section and in the serving table below were measured before the sampler moved to the keyed one (commit 39a2864ef, the -family's own seeded generator) and have not been repeated since. Two indirect checks: +family's own seeded generator) and have not been repeated since. + +The served build with the keyed sampler, one seeded request of 746,760 PCM bytes (373,380 samples, 8.5 s at +44.1 kHz): sent again, sent streamed, and sent while two other requests +arrived, it returned the same bytes each time. The server runs one lane and does not queue: the two requests that +arrived while it spoke were refused with 503 `engine_busy` ("speech output capacity is full"), so there is no +concurrent decoding to compare a solo reply with yet. + +Two indirect checks: - **Repeatability:** the served route returns the same bytes for the same seed, and a streamed reply's bytes equal the whole reply's. From ba1a70759e40a7f2856d0dcf9aae31620153b199 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:58:34 +0000 Subject: [PATCH 328/361] zonos3: memory admission for the load and for the clip encoder The host counts a load's device bytes before allocating (the release's weights, then the backbone's and decoder's own count of their state) and asks the CUDA families' pool; a load or a clip that does not fit is refused, and a refused clip leaves the engine serving. --- docs/recipes/zonos3-mini.md | 25 +++++++- zig/src/families/zonos3/cuda/codec.zig | 21 ++++++- .../families/zonos3/cuda/codec_weights.zig | 14 ++--- .../families/zonos3/cuda/encoder_weights.zig | 12 ++-- zig/src/families/zonos3/cuda/engine.zig | 20 ++++++ zig/src/native/zonos_host.zig | 61 ++++++++++++++++++- zig/src/native/zonos_open.zig | 27 +++++++- 7 files changed, 160 insertions(+), 20 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index ec558f01c38..b12bfb7aeee 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -5,8 +5,8 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records came from, and how each part was checked, so the checks can be rerun. Status: a work in progress on one branch, proposed in #3615. Every kernel launch has its limits record, but only four -of the 40 kernels have numeric contract tests and none has a planted control of its own; memory admission is not -written, and the quality suite has not been run on this build. +of the 40 kernels have numeric contract tests and none has a planted control of its own; the quality suite has not +been run on this build. ## Sources @@ -212,6 +212,27 @@ browser by an automated test. Not run: `zig build test`, `test-golden`, and any quality suite. +### Memory admission + +The host works out what a load takes before it allocates anything and asks the pool every CUDA family reads +(`native/cuda_family_memory.zig`: the card's free memory less the reserve, and `TENSORFOLD_CUDA_MEMORY_LIMIT_GB`). + +- **The load:** the pinned release's weights as the device holds them (2,531,483,136 bytes: the backbone's bf16 and + the `keep2_plain` decoder's fp32), plus the backbone's and the decoder's state and workspaces, which their own + allocation code counts without allocating (`Engine.stateBytes`, `Codec.stateBytes`). At the default + `--context 4096` and 2,000 frames that is 3,828,406,528 bytes (3.57 GiB), and the server's log shows the same + number admitted and held after the load. A load that holds more than it was admitted for is an error. +- **The clip encoder** loads with the first request that brings a clip and takes 5,643,510,688 bytes (5.26 GiB) of + weights, state and workspaces, all of fixed size; the log again shows that number admitted and held. + +Checked on the served build with `TENSORFOLD_CUDA_MEMORY_LIMIT_GB`: at 3 the server refuses to start ("ZONOS3 Mini +needs 3.57 GiB of device memory at --context 4096; 3.00 GiB is free for it after the reserve"); at 5 it starts, a +cloning request is refused (HTTP 500, "cloning from a clip needs 5.26 GiB of device memory for its encoder, and less +than that is free"), and the same seeded request before and after that refusal returns the same bytes. The two +weight sizes are constants for this release and are not derived from the files; another checkpoint would need its +own. These counts are the engine's buffers: `nvidia-smi` showed the process at 4,264 MiB after the load, the CUDA +context and kernel images included. + ### Kernel contract **Launch limits (gate 5).** The four images hold 40 kernels, each registered as one launch in diff --git a/zig/src/families/zonos3/cuda/codec.zig b/zig/src/families/zonos3/cuda/codec.zig index db8c3b248d5..f6a366ea4fb 100644 --- a/zig/src/families/zonos3/cuda/codec.zig +++ b/zig/src/families/zonos3/cuda/codec.zig @@ -37,6 +37,7 @@ pub const Codec = struct { k: kern.Kernels, w: *wts.Weights, bufs: std.ArrayList(Buf), + counted: ?usize, // set: allocations are counted, not made frames: usize = 0, // code frames decoded emitted: usize = 0, // samples handed out // state @@ -72,6 +73,7 @@ pub const Codec = struct { c.frames = 0; c.emitted = 0; c.bufs = .empty; + c.counted = null; for (&c.kv) |*layers| layers.* = &.{}; c.k = try kern.Kernels.load(d); errdefer c.k.unload(); @@ -102,12 +104,25 @@ pub const Codec = struct { } fn alloc(c: *Codec, bytes: usize) !u64 { + if (c.counted) |*n| { + n.* += @max(bytes, 256); + return 0; + } var b = try Buf.alloc(c.d, @max(bytes, 256)); errdefer b.free(); try c.bufs.append(c.gpa, b); return b.ptr; } + /// Device bytes of the state and workspaces `o` allocates: the allocation code itself, counting. + pub fn stateBytes(o: Options) usize { + var c: Codec = undefined; + c.o = o; + c.counted = 0; + c.allocState() catch unreachable; + return c.counted.?; + } + fn allocState(c: *Codec) !void { const T = c.o.max_frames; const R = head_rate * c.o.pass_frames; @@ -117,8 +132,12 @@ pub const Codec = struct { for (&c.sem_hist, 0..) |*h, i| h.* = c.hist + i * one; for (&c.head_hist, 0..) |*h, i| h.* = c.hist + (wts.sem_blocks + i) * one; for (&c.kv, wts.stages, 0..) |*layers, shape, si| { - layers.* = try c.gpa.alloc([2]u64, c.w.stages[si].layers.len); const bytes = (T << @intCast(si)) * shape.d * 4; + if (c.counted != null) { + for (0..2 * shape.layers) |_| _ = try c.alloc(bytes); + continue; + } + layers.* = try c.gpa.alloc([2]u64, shape.layers); for (layers.*) |*pair| pair.* = .{ try c.alloc(bytes), try c.alloc(bytes) }; } for (&c.spec_frames, wts.n_ffts) |*f, n| f.* = try c.alloc(head_rate * T * n * 4); diff --git a/zig/src/families/zonos3/cuda/codec_weights.zig b/zig/src/families/zonos3/cuda/codec_weights.zig index 0e1c4f0733f..85034505afc 100644 --- a/zig/src/families/zonos3/cuda/codec_weights.zig +++ b/zig/src/families/zonos3/cuda/codec_weights.zig @@ -18,15 +18,15 @@ pub const resample_in = 736; pub const resample_out = 735; pub const resample_taps = 770; -pub const StageShape = struct { in: usize, d: usize, ff: usize, ctx: usize, out: usize }; +pub const StageShape = struct { in: usize, d: usize, ff: usize, ctx: usize, out: usize, layers: usize }; /// The five transformer stages, 15 Hz to 240 Hz; out 0: the last stage's features feed the head as they are. pub const stages = [5]StageShape{ - .{ .in = 1024, .d = 1280, .ff = 5120, .ctx = 150, .out = 1280 }, - .{ .in = 640, .d = 768, .ff = 3072, .ctx = 300, .out = 768 }, - .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 768 }, - .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 768 }, - .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 0 }, + .{ .in = 1024, .d = 1280, .ff = 5120, .ctx = 150, .out = 1280, .layers = 2 }, + .{ .in = 640, .d = 768, .ff = 3072, .ctx = 300, .out = 768, .layers = 2 }, + .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 768, .layers = 2 }, + .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 768, .layers = 2 }, + .{ .in = 384, .d = 768, .ff = 3072, .ctx = 480, .out = 0, .layers = 2 }, }; pub const Layer = struct { n1w: u64, n1b: u64, n2w: u64, n2b: u64, qkv: u64, attn_out: u64, ffn0: u64, ffn1: u64, attn_scale: u64, ffn_scale: u64 }; @@ -191,7 +191,7 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, generator const s = 2 * si; var count: usize = 0; while (h.tensors.contains(fmt(&nb, "trainable/stages.{d}.layers.{d}.qkv.weight", .{ s, count }))) count += 1; - if (count == 0) return error.MissingTensor; + if (count != shape.layers) return error.MissingTensor; st.layers = try gpa.alloc(Layer, count); st.in_proj = try l.one(&h, fmt(&nb, "trainable/stages.{d}.input_proj.weight", .{s}), &.{ shape.d, shape.in }); st.out_proj = if (shape.out == 0) 0 else try l.one(&h, fmt(&nb, "trainable/stages.{d}.output_proj.weight", .{s}), &.{ shape.out, shape.d }); diff --git a/zig/src/families/zonos3/cuda/encoder_weights.zig b/zig/src/families/zonos3/cuda/encoder_weights.zig index eed102cffeb..d95281d65be 100644 --- a/zig/src/families/zonos3/cuda/encoder_weights.zig +++ b/zig/src/families/zonos3/cuda/encoder_weights.zig @@ -17,11 +17,11 @@ pub const front_width = 256; /// The stages after the patch: 240, 120, 60, 30 and 15 Hz; each but the last is followed by a patch down by 2. pub const stages = [5]dec.StageShape{ - .{ .in = front_width * patch, .d = 768, .ff = 3072, .ctx = 480, .out = 384 }, - .{ .in = 768, .d = 768, .ff = 3072, .ctx = 480, .out = 384 }, - .{ .in = 768, .d = 768, .ff = 3072, .ctx = 480, .out = 384 }, - .{ .in = 768, .d = 768, .ff = 3072, .ctx = 300, .out = 640 }, - .{ .in = 1280, .d = 1280, .ff = 5120, .ctx = 150, .out = 1024 }, + .{ .in = front_width * patch, .d = 768, .ff = 3072, .ctx = 480, .out = 384, .layers = 12 }, + .{ .in = 768, .d = 768, .ff = 3072, .ctx = 480, .out = 384, .layers = 12 }, + .{ .in = 768, .d = 768, .ff = 3072, .ctx = 480, .out = 384, .layers = 12 }, + .{ .in = 768, .d = 768, .ff = 3072, .ctx = 300, .out = 640, .layers = 12 }, + .{ .in = 1280, .d = 1280, .ff = 5120, .ctx = 150, .out = 1024, .layers = 32 }, }; pub const Conv = struct { w: u64, b: u64 }; // w [out][kernel * in], the kernel's taps outermost @@ -126,7 +126,7 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, generator const s = 4 + 2 * si; var count: usize = 0; while (archive.tensors.contains(fmt(&nb, e ++ "{d}.layers.{d}.qkv.weight", .{ s, count }))) count += 1; - if (count == 0) return error.MissingTensor; + if (count != shape.layers) return error.MissingTensor; st.layers = try gpa.alloc(dec.Layer, count); st.in_proj = try l.one(fmt(&nb, e ++ "{d}.input_proj.weight", .{s}), &.{ shape.d, shape.in }); st.out_proj = try l.one(fmt(&nb, e ++ "{d}.output_proj.weight", .{s}), &.{ shape.out, shape.d }); diff --git a/zig/src/families/zonos3/cuda/engine.zig b/zig/src/families/zonos3/cuda/engine.zig index fa44709a48e..cbd21bba419 100644 --- a/zig/src/families/zonos3/cuda/engine.zig +++ b/zig/src/families/zonos3/cuda/engine.zig @@ -9,10 +9,14 @@ const D = cfg.dim; const W = cfg.frame_width; const Buf = cuda.DeviceBuffer; +/// A host's say on a load: an error refuses it. +pub const Gate = struct { ptr: *anyopaque, check: *const fn (*anyopaque, *const cuda.Context) anyerror!void }; + pub const Options = struct { device: u32 = 0, max_ctx: usize = 4096, // positions (prompt rows + frames), at most the model's 32768 max_rows: usize = 64, // rows a pass + gate: ?Gate = null, // asked once the context is current, before anything is allocated on it pub fn validate(o: Options) !void { if (o.max_ctx < 2 or o.max_ctx > cfg.max_seqlen) return error.BadContext; @@ -44,6 +48,7 @@ pub const Engine = struct { k: kern.Kernels, w: *wts.Weights, bufs: std.ArrayList(Buf), + counted: ?usize, // set: allocations are counted, not made position: usize = 0, // state kv: [cfg.layers][2]u64, // attention layers: K, V fp32 [max_ctx][4][32] @@ -86,11 +91,13 @@ pub const Engine = struct { e.o = o; e.position = 0; e.bufs = .empty; + e.counted = null; e.c = try cfg.Config.load(gpa, io, model_dir); e.driver = try cuda.Driver.open(); errdefer e.driver.close(); e.ctx = try cuda.Context.init(&e.driver, std.math.cast(c_int, o.device) orelse return error.NoSuchCudaDevice); errdefer e.ctx.deinit(); + if (o.gate) |g| try g.check(g.ptr, &e.ctx); e.stream = try cuda.Stream.init(&e.driver, true); errdefer e.stream.deinit(); e.k = try kern.Kernels.load(&e.driver); @@ -124,12 +131,25 @@ pub const Engine = struct { } fn alloc(e: *Engine, bytes: usize) !u64 { + if (e.counted) |*n| { + n.* += @max(bytes, 256); + return 0; + } var b = try Buf.alloc(&e.driver, @max(bytes, 256)); errdefer b.free(); try e.bufs.append(e.gpa, b); return b.ptr; } + /// Device bytes of the state and workspaces `o` allocates: the allocation code itself, counting. + pub fn stateBytes(o: Options) usize { + var e: Engine = undefined; + e.o = o; + e.counted = 0; + e.allocState() catch unreachable; + return e.counted.?; + } + fn allocState(e: *Engine) !void { const R = e.o.max_rows; const kvb = e.o.max_ctx * cfg.kv_width * 4; diff --git a/zig/src/native/zonos_host.zig b/zig/src/native/zonos_host.zig index a812197e9f8..1a765921236 100644 --- a/zig/src/native/zonos_host.zig +++ b/zig/src/native/zonos_host.zig @@ -14,6 +14,38 @@ pub const Options = struct { context: u32 = 4096, device: u32 = 0, max_frames: ?u32 = null, + admit: ?Admit = null, // null: nothing is asked, as the tool and tests load + refusal: ?*Refusal = null, +}; + +/// Who knows the pool: the device bytes a load may still take, on the context given. +pub const Admit = struct { ptr: *anyopaque, room: *const fn (*anyopaque, *const cuda.Context) anyerror!u64 }; + +/// A refused load's sizes, in bytes. +pub const Refusal = struct { need: u64 = 0, room: u64 = 0 }; + +/// The pinned release's weights as the device holds them: the backbone's bf16 and the keep2_plain decoder's fp32. +pub const weight_bytes: u64 = 2_531_483_136; +/// The clip encoder's weights, state and workspaces: the acoustic encoder, the SSL teacher and the quantizers. +pub const clip_bytes: u64 = 5_643_510_688; + +/// Device bytes a load takes at a context and frame budget: the weights, then each part's own count of its state. +pub fn need(context: u32, frames: u32) u64 { + return weight_bytes + z3.Engine.stateBytes(.{ .max_ctx = context }) + z3.Codec.stateBytes(.{ .max_frames = frames }); +} + +const Door = struct { + o: Options, + need: u64, + + fn check(p: *anyopaque, ctx: *const cuda.Context) anyerror!void { + const d: *Door = @ptrCast(@alignCast(p)); + const a = d.o.admit orelse return; + const room = try a.room(a.ptr, ctx); + if (d.need <= room) return; + if (d.o.refusal) |r| r.* = .{ .need = d.need, .room = room }; + return error.InsufficientDeviceMemory; + } }; /// The frame budget and the prompt rows a context leaves. @@ -103,6 +135,7 @@ const Host = struct { e: *z3.Engine, codec: *z3.Codec, clip: ?*z3.clip.Clip = null, // the clip encoder, loaded by the first request that brings a clip + admit: ?Admit = null, dir: []const u8, info_: api.Info, mutex: std.Io.Mutex = .init, @@ -220,6 +253,11 @@ const Host = struct { var samples: usize = 0; const reason = h.serve(job, &samples) catch |err| switch (err) { error.Cancelled => api.Reason.cancelled, + // refused before anything ran on the device: the engine is as it was + error.ClipEncoderNeedsMoreDeviceMemory => { + h.finish(job, .failed, 0, "cloning from a clip needs 5.26 GiB of device memory for its encoder, and less than that is free"); + continue; + }, else => { h.lock(); h.failed = true; @@ -242,8 +280,12 @@ const Host = struct { defer gpa.free(cloned); if (r.reference_audio.len != 0) { if (h.clip == null) { + if (h.admit) |a| if (clip_bytes > try a.room(a.ptr, &h.e.ctx)) return error.ClipEncoderNeedsMoreDeviceMemory; + const before = cuda.usage(false).device; h.clip = try z3.clip.Clip.create(gpa, h.io, &h.e.driver, h.e.stream, h.dir, h.rel.generator, h.codec.w); - std.log.info("zonos3: clip encoder loaded, {d} MiB of weights", .{h.clip.?.bytes() >> 20}); + const took = cuda.usage(false).device - before; + std.log.info("zonos3: clip encoder loaded, {d} bytes on the device ({d} admitted)", .{ took, clip_bytes }); + if (took > clip_bytes) return error.ClipEncoderOverItsAdmission; } const codes = try h.clip.?.encode(gpa, r.reference_audio); defer gpa.free(codes); @@ -317,10 +359,12 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !ap errdefer gpa.destroy(h); var rel = try z3.release.open(gpa, io, dir, null); errdefer rel.deinit(); - const e = try z3.Engine.create(gpa, io, rel.lm, .{ .device = o.device, .max_ctx = o.context }); + var door: Door = .{ .o = o, .need = need(o.context, b.frames) }; + const e = try z3.Engine.create(gpa, io, rel.lm, .{ .device = o.device, .max_ctx = o.context, .gate = .{ .ptr = &door, .check = Door.check } }); errdefer e.destroy(); const codec = try z3.Codec.create(gpa, io, &e.driver, e.stream, rel.generator, rel.head, .{ .max_frames = b.frames }); errdefer codec.destroy(); + if (cuda.usage(false).device > door.need) return error.LoadOverItsAdmission; const kept = try gpa.dupe(u8, dir); errdefer gpa.free(kept); h.* = .{ @@ -330,6 +374,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !ap .rel = rel, .e = e, .codec = codec, + .admit = o.admit, .info_ = .{ .name = "ZONOS3 Mini", .text_generation = false, @@ -341,10 +386,20 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !ap }, }; h.worker = try std.Thread.spawn(.{}, Host.run, .{h}); - std.log.info("zonos3: decoder {s}, {d} MiB of weights, {d} frames a request", .{ h.rel.decoder, (e.w.bytes + codec.w.bytes) >> 20, b.frames }); + const held = cuda.usage(false).device; + std.log.info("zonos3: decoder {s}, {d} frames a request, {d} bytes on the device ({d} admitted)", .{ h.rel.decoder, b.frames, held, door.need }); return .{ .engine = .{ .ctx = h, .vtable = &Host.vtable }, .ctx = h, .close = Host.close }; } +test "need: the weights, then state that grows with the context and with the frame budget" { + const t = std.testing; + const base = need(4096, 2000); + try t.expectEqual(@as(u64, 3_828_406_528), base); + try t.expect(need(8192, 2000) > base and need(4096, 1000) < base); + // two attention layers keep a key row and a value row a position + try t.expectEqual(@as(u64, 2 * 2 * 4096 * cfg.kv_width * 4), need(8192, 2000) - base); +} + test "budget: the release's frame budget where the context holds it, the rest for the prompt" { const t = std.testing; const d = try budget(4096, null); diff --git a/zig/src/native/zonos_open.zig b/zig/src/native/zonos_open.zig index d49e92de4ef..235191d1613 100644 --- a/zig/src/native/zonos_open.zig +++ b/zig/src/native/zonos_open.zig @@ -4,6 +4,22 @@ const api = @import("engine_api"); const zonos_host = @import("zonos_host.zig"); const Allocator = std.mem.Allocator; const setting = @import("cuda_device.zig").setting; +const memory = @import("cuda_family_memory.zig"); +const cuda = @import("cuda"); + +/// The pool as every CUDA family reads it (the reserve, TENSORFOLD_CUDA_MEMORY_LIMIT_GB), less what this process holds. +const Room = struct { + var gpa: Allocator = undefined; + var io: std.Io = undefined; + + fn room(_: *anyopaque, ctx: *const cuda.Context) anyerror!u64 { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + var problem: []const u8 = ""; + const pool = try memory.pool(arena.allocator(), io, ctx, &problem) orelse return error.UnreadableMemoryPool; + return pool.room(cuda.usage(false).device); + } +}; pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { const settings = @import("sys").environment; @@ -49,7 +65,16 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c problem.* = "ZONOS3 Mini uses one prompt segment at a time: use --segments 1"; return null; } - return zonos_host.open(gpa, io, o.dir, .{ .context = @intCast(window), .device = device, .max_frames = o.max_frames }) catch |e| { + Room.gpa = gpa; + Room.io = io; + var refusal: zonos_host.Refusal = .{}; + const admit: zonos_host.Admit = .{ .ptr = &Room.gpa, .room = Room.room }; + return zonos_host.open(gpa, io, o.dir, .{ .context = @intCast(window), .device = device, .max_frames = o.max_frames, .admit = admit, .refusal = &refusal }) catch |e| { + if (e == error.InsufficientDeviceMemory) { + const text = "ZONOS3 Mini needs {d:.2} GiB of device memory at --context {d}; {d:.2} GiB is free for it after the reserve"; + problem.* = try std.fmt.allocPrint(a, text, .{ memory.toGib(refusal.need), window, memory.toGib(refusal.room) }); + return null; + } problem.* = try std.fmt.allocPrint(a, "the native ZONOS3 Mini CUDA engine could not load the checkpoint ({s})", .{@errorName(e)}); return null; }; From 9a8eb837d86c1be4615b0ca6441f07d83322254d Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:12:04 +0000 Subject: [PATCH 329/361] zonos3 docs: the whole kernel-contract run's summary --- docs/recipes/zonos3-mini.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index b12bfb7aeee..58fdd7df7c9 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -259,6 +259,15 @@ the bf16 inputs widened to the fp32 rows these kernels read. On an RTX 5090 (dri (filtered) SUMMARY 4 kernels: 4 pass gates 1-4, 0 fail, 0 known findings; 0 controls: 0 red as planted, 0 missed; 0 limit problems +The whole run on the same card and images (`tf-cuda-test kernel-contract`, 83 minutes of gates) ended with + + SUMMARY 647 kernels: 647 pass gates 1-4, 0 fail, 8 known findings; 418 controls: 418 red as planted, 0 missed; 186 limit problems + +and exit code 1 for the limit problems. None of the 186 names a ZONOS3 launch: all 40 of the family's live launch +checks pass, and the three live failures are `flashnext_mtp fn_row_topk` and `exl3_experts tf_exl3_prompt_gu` and +`tf_exl3_prompt_down`, whose records read 0. The same run was not made on the base, so this page does not claim the +186 are the base's. + The layer norm's test adds a term to its bound: the kernel scales in fp32 and then adds the bias, so the roundings before the bias are a fraction of the scaled value and not of the sum, which gate 4's rows make cancel. From 8bb233d0af26305a2194b13f55222c6e57485581 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:46:59 +0000 Subject: [PATCH 330/361] zonos3 docs: the arithmetic reference is the publisher's code in fp32, with exact gates --- docs/recipes/zonos3-mini.md | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 58fdd7df7c9..57c72eaee96 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -73,8 +73,20 @@ condition values (every condition row is its "unknown" bucket), the `full_mr` de sample. - All four kernel images build with the glue flags (`--fmad=false`, IEEE division and square root). -The reference's oracle (`zonos3.reference`, `tools/dump_golden.py lm`) runs the backbone in fp32 on the CPU, which -is what the port is compared with. The publisher's CUDA servers run parts in bf16; see "The reference's bf16 paths". +### The arithmetic reference + +One reference, fixed for every part of the model: the publisher's PyTorch code (the pinned reference repo) run in +fp32 on the CPU over the published weights, with no autocast. The backbone's oracle (`zonos3.reference`, +`tools/dump_golden.py lm`) already runs that way; for the codec decoder, the encoder and the teacher, +`tools/zig/zonos3_reference.py` runs the publisher's modules in fp32 where its servers would use bf16 autocast. + +The gates against it are exact: greedy frames equal frame for frame, a clip's codes equal code for code, streamed +bytes equal whole ones. Cosines, SNR figures and voice scores on this page describe how close intermediate values +are; none of them is a gate. + +What this choice costs: the publisher's CUDA servers run the codec and the teacher in bf16, so the codes this port +encodes from a clip are not the codes the publisher's server encodes from it. "The reference's bf16 paths" measures +the difference. The port has no bf16 path and none is planned as an option. ## How it was checked @@ -298,9 +310,10 @@ Decoding the 9.67 s clip's three sets of codes with the reference decoder and co | The reference's bf16 run | 0.576 | 0.944 | | The fp32 run (what the port produces) | 0.620 | 0.947 | -That is one clip: the fp32 codes keep the speaker as well and sit about 8% further in log-mel distance. Whether -that gap is real across clips, and whether the backbone (trained on bf16-encoded references) clones as well from -fp32 codes, needs a proper listening or scoring pass before the encoder's gate is agreed. +That is one clip: the fp32 codes keep the speaker as well and sit about 8% further in log-mel distance. These +scores are context, not a gate: the encoder's gate is code equality with the fp32 reference ("The arithmetic +reference"). Not measured: whether that gap holds across clips, and whether the backbone, which was trained on +bf16-encoded references, clones as well from fp32 codes. ## Shared code this touches From 7bbc1eec27c62f9967d18160f5b7ca4b0acebb73 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:48:07 +0000 Subject: [PATCH 331/361] zonos3: contract tests for the other 36 kernels and a planted control for all 40 zc_spec and ze_nearest now keep a NaN: the spectrum's clamp is a comparison, and a NaN dot is never the nearest code. --- zig/kernels/cuda/zonos3_codec.cu | 3 +- zig/kernels/cuda/zonos3_encoder.cu | 4 +- zig/tests/cuda/contract_zonos3.zig | 142 +++++- zig/tests/cuda/contract_zonos3_attn.zig | 441 ++++++++++++++++++ zig/tests/cuda/contract_zonos3_backbone.zig | 324 +++++++++++++ zig/tests/cuda/contract_zonos3_conv.zig | 139 ++++++ zig/tests/cuda/contract_zonos3_gdn.zig | 319 +++++++++++++ zig/tests/cuda/contract_zonos3_pick.zig | 226 ++++++++++ zig/tests/cuda/contract_zonos3_point.zig | 338 ++++++++++++++ zig/tests/cuda/contract_zonos3_ref.zig | 163 +++++++ zig/tests/cuda/contract_zonos3_windows.zig | 476 ++++++++++++++++++++ 11 files changed, 2547 insertions(+), 28 deletions(-) create mode 100644 zig/tests/cuda/contract_zonos3_attn.zig create mode 100644 zig/tests/cuda/contract_zonos3_backbone.zig create mode 100644 zig/tests/cuda/contract_zonos3_conv.zig create mode 100644 zig/tests/cuda/contract_zonos3_gdn.zig create mode 100644 zig/tests/cuda/contract_zonos3_pick.zig create mode 100644 zig/tests/cuda/contract_zonos3_point.zig create mode 100644 zig/tests/cuda/contract_zonos3_ref.zig create mode 100644 zig/tests/cuda/contract_zonos3_windows.zig diff --git a/zig/kernels/cuda/zonos3_codec.cu b/zig/kernels/cuda/zonos3_codec.cu index cdfe14a7cd9..102d9a850ea 100644 --- a/zig/kernels/cuda/zonos3_codec.cu +++ b/zig/kernels/cuda/zonos3_codec.cu @@ -184,7 +184,8 @@ extern "C" __global__ void zc_spec(float* __restrict__ y, int half) { float* r = y + (size_t)blockIdx.y * 2 * half; const int i = blockIdx.x * blockDim.x + threadIdx.x; if (i >= half) return; - const float mag = expf(fminf(r[i], 4.605170185988092f)); + const float lm = r[i]; + const float mag = expf(lm > 4.605170185988092f ? 4.605170185988092f : lm); // a comparison: a NaN stays NaN const float ph = r[half + i]; r[i] = mag * cosf(ph); r[half + i] = mag * sinf(ph); diff --git a/zig/kernels/cuda/zonos3_encoder.cu b/zig/kernels/cuda/zonos3_encoder.cu index e364140c093..ebeca51a74c 100644 --- a/zig/kernels/cuda/zonos3_encoder.cu +++ b/zig/kernels/cuda/zonos3_encoder.cu @@ -76,14 +76,14 @@ extern "C" __global__ void ze_sub(float* __restrict__ x, const float* __restrict if (i < n) x[i] -= y[i]; } -// A row's nearest code by cosine: codes[row * 10 + col] = argmax_c e . C[c], C [4096][8] unit rows, ties to the lower. +// codes[row * 10 + col] = argmax_c e . C[c], C [4096][8]: ties to the lower, a NaN dot never wins, none finite: 0. extern "C" __global__ void __launch_bounds__(256) ze_nearest(const float* __restrict__ e, const float* __restrict__ C, int* __restrict__ codes, int col) { __shared__ float best[256]; __shared__ int which[256]; const float* x = e + (size_t)blockIdx.x * 8; float bv = -INFINITY; - int bi = 0x7FFFFFFF; + int bi = threadIdx.x; for (int c = threadIdx.x; c < 4096; c += blockDim.x) { const float* row = C + (size_t)c * 8; float d = 0.f; diff --git a/zig/tests/cuda/contract_zonos3.zig b/zig/tests/cuda/contract_zonos3.zig index 0f95cf428c6..c318241961a 100644 --- a/zig/tests/cuda/contract_zonos3.zig +++ b/zig/tests/cuda/contract_zonos3.zig @@ -39,14 +39,16 @@ pub const Norm = struct { rig: rig_.Rig, which: Which, f: cuda.Function, + /// control: the launch's epsilon is one more than the reference's + fault: bool = false, r: ?rows.Rows = null, x: u64 = 0, w: u64 = 0, b: u64 = 0, out: u64 = 0, - pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, which: Which) !Norm { - return .{ .rig = .{ .gpu = gpu, .s = s }, .which = which, .f = try mod.function(if (which == .rmsnorm) "z3_rmsnorm" else "zc_layernorm") }; + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, which: Which, fault: bool) !Norm { + return .{ .rig = .{ .gpu = gpu, .s = s }, .which = which, .f = try mod.function(if (which == .rmsnorm) "z3_rmsnorm" else "zc_layernorm"), .fault = fault }; } pub fn deinit(self: *Norm) void { @@ -55,7 +57,9 @@ pub const Norm = struct { } pub fn kernel(self: *Norm) g.Kernel { - return .{ .spec = normSpec(self.which), .ctx = self, .vt = &vt }; + var spec = normSpec(self.which); + if (self.fault) spec.name = if (self.which == .rmsnorm) "control: zonos3 z3_rmsnorm with its epsilon one too large" else "control: zonos3 zc_layernorm with its epsilon one too large"; + return .{ .spec = spec, .ctx = self, .vt = &vt, .control = if (self.fault) .shapes else null }; } const vt = g.hooks(Norm); @@ -102,7 +106,7 @@ pub const Norm = struct { a.add(self.out); } a.add(k); - a.add(r.eps); + a.add(if (self.fault) r.eps + 1 else r.eps); try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast(r.shape.rows), .y = 1, .z = 1 }, .block = .{ .x = 256 } }, self.rig.s, &a); try self.rig.s.synchronize(); } @@ -149,14 +153,16 @@ pub const Linear = struct { rig: rig_.Rig, weights: Weights, f: cuda.Function, + /// control: the launch is one block of eight outputs short + fault: bool = false, d: ?Dense = null, x: u64 = 0, w: u64 = 0, out: u64 = 0, - pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, weights: Weights) !Linear { + pub fn init(gpu: check.Gpu, s: cuda.Stream, mod: cuda.Module, weights: Weights, fault: bool) !Linear { const f = try mod.function(if (weights == .bf16) "z3_linear" else "zc_linear"); - return .{ .rig = .{ .gpu = gpu, .s = s }, .weights = weights, .f = f }; + return .{ .rig = .{ .gpu = gpu, .s = s }, .weights = weights, .f = f, .fault = fault }; } pub fn deinit(self: *Linear) void { @@ -165,7 +171,9 @@ pub const Linear = struct { } pub fn kernel(self: *Linear) g.Kernel { - return .{ .spec = linearSpec(self.weights), .ctx = self, .vt = &vt }; + var spec = linearSpec(self.weights); + if (self.fault) spec.name = if (self.weights == .bf16) "control: zonos3 z3_linear launched one block short" else "control: zonos3 zc_linear launched one block short"; + return .{ .spec = spec, .ctx = self, .vt = &vt, .control = if (self.fault) .shapes else null }; } const vt = g.hooks(Linear); @@ -225,7 +233,7 @@ pub const Linear = struct { a.add(@as(u64, 0)); a.add(@as(i64, 0)); } - try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast((d.shape.n + 7) / 8), .y = @intCast(d.shape.rows), .z = 1 }, .block = .{ .x = 256 }, .shared = @intCast(d.shape.k * 4) }, self.rig.s, &a); + try cuda.launch.launch(self.f, .{ .grid = .{ .x = @intCast((d.shape.n + 7) / 8 - ref.one(self.fault)), .y = @intCast(d.shape.rows), .z = 1 }, .block = .{ .x = 256 }, .shared = @intCast(d.shape.k * 4) }, self.rig.s, &a); try self.rig.s.synchronize(); } @@ -242,39 +250,123 @@ pub const Linear = struct { } }; -/// The family's registered kernels: the backbone's image and the codec's. +const ref = @import("contract_zonos3_ref.zig"); +const point = @import("contract_zonos3_point.zig"); +const pick = @import("contract_zonos3_pick.zig"); +const backbone = @import("contract_zonos3_backbone.zig"); +const gdn = @import("contract_zonos3_gdn.zig"); +const attn = @import("contract_zonos3_attn.zig"); +const windows = @import("contract_zonos3_windows.zig"); +const conv = @import("contract_zonos3_conv.zig"); + +fn Pair(comptime K: type) type { + return [2]ref.Gated(K); +} + +/// The family's registered kernels over its four images: each kernel, then the control planted for it. pub const Set = struct { gpa: std.mem.Allocator, - backbone: cuda.Module, - codec: cuda.Module, - norms: [2]Norm, - linears: [2]Linear, + mods: ref.Mods, + norms: [4]Norm, + linears: [4]Linear, + points: [2 * point.kinds.len]ref.Gated(point.Point), + route: [2]ref.Checked(pick.Route), + nearest: [2]ref.Checked(pick.Nearest), + embed: Pair(backbone.Embed), + attnres: Pair(backbone.AttnRes), + conv_silu: Pair(backbone.ConvSilu), + gdn_prep: Pair(gdn.GdnPrep), + gdn: Pair(gdn.Gdn), + gated_norm: Pair(gdn.GatedNorm), + attn_prep: Pair(attn.Prep), + attention: [3]Pair(attn.Attention), + codec_prep: Pair(attn.CodecPrep), + dwconv: [2]Pair(windows.DwConv), + latent: Pair(windows.Latent), + ola: Pair(windows.Ola), + fir: [3]Pair(windows.Fir), + conv: Pair(conv.Conv), + + /// The fields that hold a kernel and its control side by side, in the order they register. + const pairs = .{ "embed", "attnres", "conv_silu", "gdn_prep", "gdn", "gated_norm", "attn_prep", "codec_prep", "latent", "ola", "conv" }; + const groups = .{ "attention", "dwconv", "fir" }; /// The set, its kernels appended to `list`. pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { const set = try gpu.gpa.create(Set); errdefer gpu.gpa.destroy(set); - var backbone = try cuda.Module.load(gpu.d, cuda.kernels.zonos3); - errdefer backbone.unload(); - var codec = try cuda.Module.load(gpu.d, cuda.kernels.zonos3_codec); - errdefer codec.unload(); - set.* = .{ - .gpa = gpu.gpa, - .backbone = backbone, - .codec = codec, - .norms = .{ try Norm.init(gpu, s, backbone, .rmsnorm), try Norm.init(gpu, s, codec, .layernorm) }, - .linears = .{ try Linear.init(gpu, s, backbone, .bf16), try Linear.init(gpu, s, codec, .f32) }, + var m: ref.Mods = undefined; + m.backbone = try cuda.Module.load(gpu.d, cuda.kernels.zonos3); + errdefer m.backbone.unload(); + m.codec = try cuda.Module.load(gpu.d, cuda.kernels.zonos3_codec); + errdefer m.codec.unload(); + m.encoder = try cuda.Module.load(gpu.d, cuda.kernels.zonos3_encoder); + errdefer m.encoder.unload(); + m.teacher = try cuda.Module.load(gpu.d, cuda.kernels.zonos3_teacher); + errdefer m.teacher.unload(); + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + set.gpa = gpu.gpa; + set.mods = m; + for (0..4) |i| { + const codec = i >= 2; + const fault = i % 2 == 1; + set.norms[i] = try Norm.init(gpu, s, if (codec) m.codec else m.backbone, if (codec) .layernorm else .rmsnorm, fault); + set.linears[i] = try Linear.init(gpu, s, if (codec) m.codec else m.backbone, if (codec) .f32 else .bf16, fault); + } + for (point.kinds, 0..) |kind, i| for (0..2) |j| { + set.points[2 * i + j] = .{ .rig = rig, .k = try point.Point.init(m, kind, j == 1) }; }; + const f = struct { + fn of(mod: cuda.Module, comptime symbol: [:0]const u8) !cuda.Function { + return mod.function(symbol); + } + }.of; + for (0..2) |j| { + const fault = j == 1; + set.route[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_route"), .fault = fault } }; + set.nearest[j] = .{ .rig = rig, .k = .{ .f = try f(m.encoder, "ze_nearest"), .fault = fault } }; + set.embed[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_embed"), .fault = fault } }; + set.attnres[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_attnres"), .fault = fault } }; + set.conv_silu[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_conv_silu"), .fault = fault } }; + set.gdn_prep[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_gdn_prep"), .fault = fault } }; + set.gdn[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_gdn"), .fault = fault } }; + set.gated_norm[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_gated_norm"), .fault = fault } }; + set.attn_prep[j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_attn_prep"), .fault = fault } }; + set.attention[0][j] = .{ .rig = rig, .k = .{ .f = try f(m.backbone, "z3_attention"), .which = .backbone, .fault = fault } }; + set.attention[1][j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_attention"), .which = .codec, .fault = fault } }; + set.attention[2][j] = .{ .rig = rig, .k = .{ .f = try f(m.teacher, "zt_attention"), .which = .teacher, .fault = fault } }; + set.codec_prep[j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_attn_prep"), .fault = fault } }; + set.dwconv[0][j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_dwconv"), .which = .codec, .fault = fault } }; + set.dwconv[1][j] = .{ .rig = rig, .k = .{ .f = try f(m.teacher, "zt_dwconv"), .which = .teacher, .fault = fault } }; + set.latent[j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_latent"), .fault = fault } }; + set.ola[j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_ola"), .fault = fault } }; + set.fir[0][j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_mix"), .which = .mix, .fault = fault } }; + set.fir[1][j] = .{ .rig = rig, .k = .{ .f = try f(m.codec, "zc_resample"), .which = .resample, .fault = fault } }; + set.fir[2][j] = .{ .rig = rig, .k = .{ .f = try f(m.encoder, "ze_resample_in"), .which = .resample_in, .fault = fault } }; + set.conv[j] = .{ .rig = rig, .k = .{ .f = try f(m.encoder, "ze_conv"), .fault = fault } }; + } for (&set.norms) |*x| try list.append(a, x.kernel()); for (&set.linears) |*x| try list.append(a, x.kernel()); + for (&set.points) |*x| try list.append(a, x.kernel()); + for (&set.route) |*x| try list.append(a, x.kernel()); + for (&set.nearest) |*x| try list.append(a, x.kernel()); + inline for (pairs) |field| for (&@field(set, field)) |*x| try list.append(a, x.kernel()); + inline for (groups) |field| for (&@field(set, field)) |*pair| for (pair) |*x| try list.append(a, x.kernel()); return set; } pub fn deinit(set: *Set) void { + inline for (groups) |field| for (&@field(set, field)) |*pair| for (pair) |*x| x.deinit(); + inline for (pairs) |field| for (&@field(set, field)) |*x| x.deinit(); + for (&set.nearest) |*x| x.deinit(); + for (&set.route) |*x| x.deinit(); + for (&set.points) |*x| x.deinit(); for (&set.linears) |*x| x.deinit(); for (&set.norms) |*x| x.deinit(); - set.codec.unload(); - set.backbone.unload(); + set.mods.teacher.unload(); + set.mods.encoder.unload(); + set.mods.codec.unload(); + set.mods.backbone.unload(); set.gpa.destroy(set); } }; diff --git a/zig/tests/cuda/contract_zonos3_attn.zig b/zig/tests/cuda/contract_zonos3_attn.zig new file mode 100644 index 00000000000..f614f1b1545 --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_attn.zig @@ -0,0 +1,441 @@ +//! ZONOS3's attention under the contract: the backbone's, the codec's and the teacher's, and the two that rotate. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +pub const Which = enum { backbone, codec, teacher }; + +/// A thread's chain over every 256th (backbone) or 128th key, then the threads' partials in order. +fn backboneDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 256; +} + +fn codecDepth(s: c.Shape) usize { + return (s.k + 127) / 128 + 128; +} + +fn teacherDepth(s: c.Shape) usize { + return (s.rows + 127) / 128 + 128; +} + +/// Backbone: rows x 512 x the last row's keys. Codec: rows x a stage's width x its context. Teacher: k is 64. +pub fn attentionSpec(which: Which, fault: bool) c.Spec { + return switch (which) { + .backbone => .{ .name = if (fault) "control: zonos3 z3_attention seeing one key fewer" else "cuda zonos3 z3_attention", .accum = .f32, .depth = backboneDepth, .out = .f32, .served = &.{ .{ .rows = 64, .n = 512, .k = 256 }, .{ .rows = 1, .n = 512, .k = 4096 }, .{ .rows = 1, .n = 512, .k = 1 }, .{ .rows = 7, .n = 512, .k = 300 } } }, + .codec => .{ .name = if (fault) "control: zonos3 zc_attention seeing one key fewer" else "cuda zonos3_codec zc_attention", .accum = .f32, .depth = codecDepth, .out = .f32, .served = &.{ .{ .rows = 16, .n = 768, .k = 300 }, .{ .rows = 8, .n = 1280, .k = 150 }, .{ .rows = 1, .n = 768, .k = 480 } } }, + .teacher => .{ .name = if (fault) "control: zonos3 zt_attention seeing one key fewer" else "cuda zonos3_teacher zt_attention", .accum = .f32, .depth = teacherDepth, .out = .f32, .served = &.{ .{ .rows = 64, .n = 1024, .k = 64 }, .{ .rows = 1, .n = 1024, .k = 64 }, .{ .rows = 200, .n = 1024, .k = 64 } } }, + }; +} + +const distances = 73; + +/// Softmax attention of a (row, head): fma-chain scores, then values and weights summed by thread, then across. +pub const Attention = struct { + f: cuda.Function, + which: Which, + /// control: the device sees one key fewer than the reference + fault: bool = false, + shape: c.Shape = undefined, + pos0: usize = 0, + /// backbone: q [T][512]; codec and teacher: qkv [T][3 n] + q: []f32 = &.{}, + /// the key and value caches (backbone [L][128], codec [L][n]); the teacher's keys and values are qkv's + kc: []f32 = &.{}, + vc: []f32 = &.{}, + /// backbone: a gate a (row, head); teacher: the distance table [73][64] + extra: []f32 = &.{}, + dev: [4]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Attention) c.Spec { + return attentionSpec(self.which, self.fault); + } + + pub fn control(self: *const Attention) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Attention, a: std.mem.Allocator) void { + for ([_]*[]f32{ &self.q, &self.kc, &self.vc, &self.extra }) |x| { + a.free(x.*); + x.* = &.{}; + } + } + + fn headDim(self: *const Attention) usize { + return if (self.which == .backbone) 32 else 64; + } + + /// The width of a cache row, and of the values a key head holds. + fn cacheWidth(self: *const Attention) usize { + return if (self.which == .backbone) 128 else self.shape.n; + } + + /// Rows of keys the launch can reach. + fn keys(self: *const Attention) usize { + return if (self.which == .teacher) self.shape.rows else self.pos0 + self.shape.rows; + } + + pub fn prepare(self: *Attention, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const T = shape.rows; + if (T == 0 or shape.k == 0) return false; + switch (self.which) { + .backbone => if (shape.n != 512 or shape.k < T) return false, + .codec => if (shape.n % 64 != 0) return false, + .teacher => if (shape.n != 1024 or shape.k != 64) return false, + } + self.free(a); + self.shape = shape; + const n = shape.n; + self.pos0 = switch (self.which) { + .backbone => shape.k - T, + // gate 4: the first row sees the first `ctx` keys; else the last row's window is full or sliding + .codec => if (fill == .stress) shape.k - 1 else (shape.k -| T) + rng.uintLessThan(usize, shape.k), + .teacher => 0, + }; + const L = self.keys(); + const cw = self.cacheWidth(); + const qw: usize = if (self.which == .backbone) n else 3 * n; + self.q = try ref.values(a, rng, T * qw, .random, 1); + if (self.which != .teacher) { + self.kc = try ref.values(a, rng, L * cw, .random, 1); + self.vc = try ref.values(a, rng, L * cw, .random, 2); + } + if (self.which == .backbone) self.extra = try ref.values(a, rng, T * 16, .random, 3); + if (self.which == .teacher) self.extra = try ref.values(a, rng, distances * 64, .random, 1); + const vals = if (self.which == .teacher) self.q else self.vc; + const vstride: usize = if (self.which == .teacher) 3 * n else cw; + const vfirst: usize = if (self.which == .teacher) 2 * n else 0; + if (fill == .stress) { + // zero queries: every score is 0 and every weight 1; the values carry gate 4's terms along the keys + if (self.which == .backbone) @memset(self.q, 0) else for (0..T) |t| @memset(self.q[t * 3 * n ..][0..n], 0); + for (0..cw) |i| ref.stressAxis(vals, vfirst + i, vstride, L, rng); + if (self.which == .backbone) @memset(self.extra, 100); + } + if (fill == .nonfinite) { + const hd = self.headDim(); + self.q[5] = ref.nan; // row 0, head 0 + const keys_ = if (self.which == .teacher) self.q else self.kc; + const kfirst: usize = if (self.which == .teacher) n else 0; + if (T > 2) keys_[(self.pos0 + 2) * vstride + kfirst + hd + 3] = ref.inf; // key head 1, from row 2 on + if (T > 4) vals[(self.pos0 + 4) * vstride + vfirst + 2 * hd + 1] = -ref.inf; // key head 2, from row 4 on + } + self.dev[0] = try ref.input(rig, self.q); + if (self.kc.len > 0) self.dev[1] = try ref.input(rig, self.kc); + if (self.vc.len > 0) self.dev[2] = try ref.input(rig, self.vc); + if (self.extra.len > 0) self.dev[3] = try ref.input(rig, self.extra); + self.out = try rig.output(T * n * 4); + return true; + } + + pub fn run(self: *Attention, rig: *rig_.Rig) !void { + const T = self.shape.rows; + const n = self.shape.n; + const less = ref.one(self.fault); + var a: cuda.Args = .{}; + switch (self.which) { + .backbone => { + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(self.dev[2]); + a.add(self.dev[3]); + a.add(ref.int(self.pos0 -| less)); + a.add(self.out); + try ref.go(self.f, rig.s, T, 16, 256, 0, &a); + }, + .codec => { + a.add(self.dev[0]); + a.add(ref.int(n)); + a.add(self.dev[1]); + a.add(self.dev[2]); + a.add(ref.int(self.pos0)); + a.add(ref.int(self.shape.k - less)); + a.add(self.out); + try ref.go(self.f, rig.s, T, n / 64, 128, 0, &a); + }, + .teacher => { + a.add(self.dev[0]); + a.add(ref.int(n)); + a.add(ref.int(T - less)); + a.add(self.dev[3]); + a.add(self.out); + try ref.go(self.f, rig.s, T, 16, 128, 0, &a); + }, + } + } + + pub fn count(self: *const Attention) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Attention, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const T = self.shape.rows; + const n = self.shape.n; + const hd = self.headDim(); + const L = self.keys(); + const depth = self.spec().depth(self.shape); + const e = try a.alloc(Iv, 2 * L); + defer a.free(e); + const scratch = try a.alloc(f64, @max(L, 64)); + defer a.free(scratch); + const terms = e[L..]; + var dot: [64]Iv = undefined; + var pe: [distances]Iv = undefined; + for (0..T * n / hd) |at| { + const t = at / (n / hd); + const h = at % (n / hd); + const kh = if (self.which == .backbone) h >> 2 else h; + const p = self.pos0 + t; + const lo = if (self.which == .codec) (p + 1) -| self.shape.k else 0; + const hi = if (self.which == .teacher) T else p + 1; + const q = switch (self.which) { + .backbone => self.q[t * n + h * hd ..][0..hd], + else => self.q[t * 3 * n + h * hd ..][0..hd], + }; + if (self.which == .teacher and !s.exact) for (&pe, 0..) |*v, d| { + for (dot[0..hd], q, self.extra[d * 64 ..][0..64]) |*term, x, y| term.* = Iv.of(x).mul(Iv.of(y)); + v.* = s.sum(dot[0..hd], hd, scratch); + }; + const w = e[0 .. hi - lo]; + if (!s.exact) for (w, lo..) |*score, j| { + const k = switch (self.which) { + .teacher => self.q[j * 3 * n + n + kh * hd ..][0..hd], + else => self.kc[j * self.cacheWidth() + kh * hd ..][0..hd], + }; + for (dot[0..hd], q, k) |*term, x, y| term.* = Iv.of(x).mul(Iv.of(y)); + const d = s.sum(dot[0..hd], hd, scratch); + score.* = switch (self.which) { + .backbone => d.mul(Iv.of(@as(f32, 0.17677669529663688))), + .codec => d.mul(Iv.of(0.125)), + .teacher => blk: { + const rel = @as(i64, @intCast(j)) - @as(i64, @intCast(t)); + break :blk d.add(pe[@intCast(std.math.clamp(rel, -64, 8) + 64)]).mul(Iv.of(0.125)); + }, + }; + }; + const den = ref.softmaxParts(s, w, depth, scratch); + const gate = if (self.which == .backbone) Iv.of(self.extra[t * 16 + h]).sigmoid() else Iv.of(1); + for (0..hd) |i| { + for (terms[0 .. hi - lo], w, lo..) |*term, weight, j| { + const v = switch (self.which) { + .teacher => self.q[j * 3 * n + 2 * n + kh * hd + i], + else => self.vc[j * self.cacheWidth() + kh * hd + i], + }; + term.* = weight.mul(Iv.of(v)); + } + const r = s.sum(terms[0 .. hi - lo], depth, scratch).div(den); + out[t * n + h * hd + i] = if (self.which == .backbone) r.mul(gate) else r; + } + } + } +}; + +const theta: f32 = 10000; + +/// Rows x the queries' 512 x a head's 32. +pub fn prepSpec(fault: bool) c.Spec { + return .{ .name = if (fault) "control: zonos3 z3_attn_prep rotating its rows one position late" else "cuda zonos3 z3_attn_prep (q in place)", .accum = .f32, .depth = warpDeep, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 64, .n = 512, .k = 32 }, .{ .rows = 1, .n = 512, .k = 32 }, .{ .rows = 7, .n = 512, .k = 32 } } }; +} + +fn warpDeep(_: c.Shape) usize { + return 5; +} + +/// The backbone's q and k rms-normed per head of 32 (q times |temp|) and rotated; k and v land in their cache rows. +pub const Prep = struct { + f: cuda.Function, + /// control: the device takes the rows one position late + fault: bool = false, + T: usize = 0, + pos0: usize = 0, + q: []f32 = &.{}, + kv: []f32 = &.{}, + temp: [16]u16 = undefined, + dev: [2]u64 = @splat(0), + out: [3]u64 = @splat(0), + + pub const sums = {}; + + pub fn spec(self: *const Prep) c.Spec { + return prepSpec(self.fault); + } + + pub fn control(self: *const Prep) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Prep, a: std.mem.Allocator) void { + a.free(self.q); + a.free(self.kv); + self.q = &.{}; + self.kv = &.{}; + } + + pub fn prepare(self: *Prep, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != 512 or shape.k != 32) return false; + self.free(a); + const T = shape.rows; + self.T = T; + // gate 4: row 0 at position 0, where the rotation is by 1 and 0 + self.pos0 = if (fill == .stress) 0 else rng.uintLessThan(usize, 4096); + self.q = try ref.values(a, rng, T * 512, fill, 2); + self.kv = try ref.values(a, rng, T * 256, fill, 2); + for (&self.temp) |*v| v.* = c.toBf16(if (fill == .stress) 1 else rng.float(f32) * 4 - 2); + if (fill == .nonfinite) { + ref.plant(self.q, T, 512); + self.kv[40] = ref.nan; // row 0, key head 1 + } + self.dev = .{ try ref.input(rig, self.kv), try ref.input(rig, &self.temp) }; + // the control's rows land a cache row late: a row more keeps them inside the buffers + const cache = (T + ref.one(self.fault)) * 128 * 4; + self.out = .{ try rig.output(T * 512 * 4), try rig.output(cache), try rig.output(cache) }; + return true; + } + + pub fn run(self: *Prep, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out[0], std.mem.sliceAsBytes(self.q)); + var a: cuda.Args = .{}; + a.add(self.out[0]); + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(self.pos0 + ref.one(self.fault))); + a.add(ref.before(self.out[1], self.pos0 * 128)); + a.add(ref.before(self.out[2], self.pos0 * 128)); + a.add(theta); + try ref.go(self.f, rig.s, self.T, 1, 512, 0, &a); + } + + pub fn count(self: *const Prep) usize { + return self.T * 512 + 2 * self.T * 128; + } + + /// A head's 32 values `x` scaled by `scale` over their rms and rotated in adjacent pairs at `pos`. + fn rotate(s: Sums, x: []const f32, scale: ?Iv, pos: usize, out: []Iv) void { + var scratch: [32]f64 = undefined; + var sq: [32]Iv = undefined; + for (&sq, x) |*v, y| v.* = ref.square(Iv.of(y)); + const inv = ref.rmsScale(s.sum(&sq, 5, &scratch), 32, 1e-6); + var y: [32]Iv = undefined; + for (&y, x) |*v, raw| { + v.* = Iv.of(raw).mul(inv); + if (scale) |m| v.* = v.mul(m); + } + for (0..16) |pair| { + const exponent = -@as(f64, @floatFromInt(2 * pair)) / 32; + const freq = std.math.pow(f64, theta, exponent); + // powf within 8 ulps + const ang = Iv.of(@floatFromInt(pos)).mul(ref.wide(freq, freq, freq, 0x1p-20)); + const cs = ang.trig(false); + const sn = ang.trig(true); + out[2 * pair] = y[2 * pair].mul(cs).sub(y[2 * pair + 1].mul(sn)); + out[2 * pair + 1] = y[2 * pair].mul(sn).add(y[2 * pair + 1].mul(cs)); + } + } + + pub fn solve(self: *const Prep, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const T = self.T; + const kc = out[T * 512 ..]; + const vc = out[T * 512 + T * 128 ..]; + for (0..T) |t| { + for (0..16) |h| { + const scale = Iv.of(@abs(ref.bf(self.temp[h]))); + rotate(s, self.q[t * 512 + h * 32 ..][0..32], scale, self.pos0 + t, out[t * 512 + h * 32 ..][0..32]); + } + for (0..4) |h| rotate(s, self.kv[t * 256 + h * 32 ..][0..32], null, self.pos0 + t, kc[t * 128 + h * 32 ..][0..32]); + for (self.kv[t * 256 + 128 ..][0..128], 0..) |v, i| vc[t * 128 + i] = Iv.of(v); + } + } +}; + +/// Rows x [q | k | v] of a stage's width. +pub fn codecPrepSpec(fault: bool) c.Spec { + return .{ .name = if (fault) "control: zonos3 zc_attn_prep rotating its rows one position late" else "cuda zonos3_codec zc_attn_prep (q in place)", .accum = .none, .depth = ref.noSums, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 16, .n = 2304, .k = 1 }, .{ .rows = 8, .n = 3840, .k = 1 }, .{ .rows = 1, .n = 2304, .k = 1 } } }; +} + +/// The codec's attention inputs: q and k rotated in adjacent pairs by position; k and v land in their cache rows. +pub const CodecPrep = struct { + f: cuda.Function, + /// control: the device takes the rows one position late + fault: bool = false, + T: usize = 0, + d: usize = 0, + pos0: usize = 0, + qkv: []f32 = &.{}, + out: [3]u64 = @splat(0), + + const rate: f32 = -9.210340371976184 * 2.0 / 64.0; + + pub fn spec(self: *const CodecPrep) c.Spec { + return codecPrepSpec(self.fault); + } + + pub fn control(self: *const CodecPrep) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *CodecPrep, a: std.mem.Allocator) void { + a.free(self.qkv); + self.qkv = &.{}; + } + + pub fn prepare(self: *CodecPrep, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 192 != 0) return false; + self.free(a); + self.T = shape.rows; + self.d = shape.n / 3; + self.pos0 = rng.uintLessThan(usize, 2048); + self.qkv = try ref.values(a, rng, self.T * shape.n, fill, 2); + if (fill == .nonfinite) ref.plant(self.qkv, self.T, shape.n); + const cache = (self.T + ref.one(self.fault)) * self.d * 4; + self.out = .{ try rig.output(self.qkv.len * 4), try rig.output(cache), try rig.output(cache) }; + return true; + } + + pub fn run(self: *CodecPrep, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out[0], std.mem.sliceAsBytes(self.qkv)); + var a: cuda.Args = .{}; + a.add(self.out[0]); + a.add(ref.int(self.d)); + a.add(ref.int(self.pos0 + ref.one(self.fault))); + a.add(ref.before(self.out[1], self.pos0 * self.d)); + a.add(ref.before(self.out[2], self.pos0 * self.d)); + try ref.go(self.f, rig.s, self.T, self.d / 64, 32, 0, &a); + } + + pub fn count(self: *const CodecPrep) usize { + return self.T * 5 * self.d; + } + + pub fn solve(self: *const CodecPrep, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + const T = self.T; + const d = self.d; + const kc = out[T * 3 * d ..]; + const vc = out[T * 4 * d ..]; + for (0..T) |t| { + const row = self.qkv[t * 3 * d ..][0 .. 3 * d]; + for (0..d / 2) |pair| { + const m: f64 = @floatFromInt(pair % 32); + const phase = Iv.of(@floatFromInt(self.pos0 + t)).mul(Iv.of(m).mul(Iv.of(rate)).exp()); + const cs = phase.trig(false); + const sn = phase.trig(true); + for ([_][]Iv{ out[t * 3 * d ..], kc[t * d ..] }, [_]usize{ 0, d }) |dst, from| { + const re = Iv.of(row[from + 2 * pair]); + const im = Iv.of(row[from + 2 * pair + 1]); + dst[2 * pair] = re.mul(cs).sub(im.mul(sn)); + dst[2 * pair + 1] = re.mul(sn).add(im.mul(cs)); + } + } + for (row[d..], 0..) |v, i| out[t * 3 * d + d + i] = Iv.of(v); + for (row[2 * d ..], 0..) |v, i| vc[t * d + i] = Iv.of(v); + } + } +}; diff --git a/zig/tests/cuda/contract_zonos3_backbone.zig b/zig/tests/cuda/contract_zonos3_backbone.zig new file mode 100644 index 00000000000..fae17eac7cd --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_backbone.zig @@ -0,0 +1,324 @@ +//! ZONOS3's summing backbone kernels under the contract: the embedding, AttnRes and the GDN's convolution. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const D = 1024; +const columns = 11; + +fn name(comptime plain: []const u8, comptime broken: []const u8, fault: bool) []const u8 { + return if (fault) "control: zonos3 " ++ broken else "cuda zonos3 " ++ plain; +} + +fn elevenDeep(_: c.Shape) usize { + return columns; +} + +/// Frames x width x the frame's eleven columns. +pub fn embedSpec(fault: bool) c.Spec { + return .{ .name = name("z3_embed", "z3_embed reading its tables one row late", fault), .accum = .f32, .depth = elevenDeep, .out = .f32, .served = &.{ .{ .rows = 64, .n = D, .k = columns }, .{ .rows = 1, .n = D, .k = columns }, .{ .rows = 256, .n = D, .k = columns } } }; +} + +/// A frame row's eleven embeddings summed in column order: bf16 tables, an fp32 chain. +pub const Embed = struct { + f: cuda.Function, + /// control: the device takes each column's table to start one row late + fault: bool = false, + shape: c.Shape = undefined, + ids: []i32 = &.{}, + tables: []u16 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + const table_rows = 16; + + pub fn spec(self: *const Embed) c.Spec { + return embedSpec(self.fault); + } + + pub fn control(self: *const Embed) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Embed, a: std.mem.Allocator) void { + a.free(self.ids); + a.free(self.tables); + self.ids = &.{}; + self.tables = &.{}; + } + + pub fn prepare(self: *Embed, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != columns) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + self.ids = try a.alloc(i32, shape.rows * columns); + for (self.ids, 0..) |*v, i| v.* = if (fill == .stress) @intCast(i % columns) else @intCast(rng.uintLessThan(u32, table_rows)); + // a row more than the columns read, for the control's shifted tables + self.tables = try ref.bfs(a, rng, (columns * table_rows + columns) * n, -1, 1); + if (fill == .stress) for (0..n) |i| { + var terms: [columns]f32 = undefined; + ref.stress(&terms, rng); + for (terms, 0..) |t, col| self.tables[(col * table_rows + col) * n + i] = c.toBf16(t); + }; + if (fill == .nonfinite) { + const put = [_]f32{ ref.nan, ref.inf, -ref.inf }; + for (put, 0..) |v, r| if (r < shape.rows) { + const row: usize = @intCast(self.ids[r * columns + r]); + self.tables[((r * table_rows) + row) * n + (r + 1) * n / 5] = c.toBf16(v); + }; + } + self.dev = .{ try ref.input(rig, self.ids), try ref.input(rig, self.tables) }; + self.out = try rig.output(shape.rows * n * 4); + return true; + } + + pub fn run(self: *Embed, rig: *rig_.Rig) !void { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(table_rows + ref.one(self.fault))); + a.add(self.out); + a.add(ref.int(self.shape.n)); + try ref.go(self.f, rig.s, self.shape.rows, 1, 256, 0, &a); + } + + pub fn count(self: *const Embed) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Embed, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + var scratch: [columns]f64 = undefined; + for (out, 0..) |*o, at| { + var terms: [columns]Iv = undefined; + for (&terms, 0..) |*t, col| { + const row: usize = @intCast(self.ids[at / n * columns + col]); + t.* = Iv.of(ref.bf(self.tables[(col * table_rows + row) * n + at % n])); + } + o.* = s.sum(&terms, columns, &scratch); + } + } +}; + +const eps: f32 = 1e-5; + +/// A thread's fma chain over the width, the warp's and the block's butterflies; then the sources in order. +fn attnresDepth(s: c.Shape) usize { + return @max((s.n + 255) / 256 + 10, s.k); +} + +/// Rows x width x sources: the embedding alone, a layer's bank so far, the whole bank before the head. +pub fn attnresSpec(fault: bool) c.Spec { + return .{ .name = name("z3_attnres", "z3_attnres mixing one source fewer", fault), .accum = .f32, .depth = attnresDepth, .out = .f32, .served = &.{ .{ .rows = 16, .n = D, .k = 16 }, .{ .rows = 1, .n = D, .k = 1 }, .{ .rows = 1, .n = D, .k = 23 }, .{ .rows = 64, .n = D, .k = 5 } } }; +} + +/// A row's sources mixed by the softmax of each source's rms-normed dot with the query. +pub const AttnRes = struct { + f: cuda.Function, + /// control: the device mixes the first k - 1 sources + fault: bool = false, + shape: c.Shape = undefined, + bank: []f32 = &.{}, + query: []u16 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const AttnRes) c.Spec { + return attnresSpec(self.fault); + } + + pub fn control(self: *const AttnRes) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *AttnRes, a: std.mem.Allocator) void { + a.free(self.bank); + a.free(self.query); + self.bank = &.{}; + self.query = &.{}; + } + + pub fn prepare(self: *AttnRes, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 32 != 0 or shape.k == 0 or shape.k > 64) return false; + self.free(a); + self.shape = shape; + // gate 4: sixteen sources and a zero query, so every weight is 1/16 and the mix sums whole numbers + if (fill == .stress) self.shape.k = 16; + const S = self.shape.k; + const rows = shape.rows; + const n = shape.n; + self.bank = try ref.values(a, rng, S * rows * n, .random, 2); + self.query = try ref.bfs(a, rng, n, -1, 1); + if (fill == .stress) { + @memset(self.query, 0); + for (0..rows * n) |at| ref.stressAxis(self.bank, at, rows * n, S, rng); + for (self.bank) |*v| v.* *= 16; + } + if (fill == .nonfinite) ref.plant(self.bank[0 .. rows * n], rows, n); + self.dev = .{ try ref.input(rig, self.bank), try ref.input(rig, self.query) }; + self.out = try rig.output(rows * n * 4); + return true; + } + + pub fn run(self: *AttnRes, rig: *rig_.Rig) !void { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(ref.int(self.shape.k - ref.one(self.fault))); + a.add(ref.int(self.shape.rows)); + a.add(self.dev[1]); + a.add(self.out); + a.add(ref.int(self.shape.n)); + a.add(eps); + try ref.go(self.f, rig.s, self.shape.rows, 1, 256, 0, &a); + } + + pub fn count(self: *const AttnRes) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const AttnRes, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const S = self.shape.k; + const rows = self.shape.rows; + const n = self.shape.n; + const depth = attnresDepth(self.shape); + const terms = try a.alloc(Iv, n); + defer a.free(terms); + const scratch = try a.alloc(f64, @max(n, S)); + defer a.free(scratch); + var w: [64]Iv = undefined; + var mix: [64]Iv = undefined; + for (0..rows) |r| { + for (w[0..S], 0..) |*score, src| { + const x = self.bank[(src * rows + r) * n ..][0..n]; + for (terms, x) |*t, v| t.* = ref.square(Iv.of(v)); + const inv = ref.rmsScale(s.sum(terms, depth, scratch), n, eps); + for (terms, x, self.query) |*t, v, q| t.* = Iv.of(v).mul(inv).mul(Iv.of(ref.bf(q))); + score.* = s.sum(terms, depth, scratch); + } + const total = ref.softmaxParts(s, w[0..S], S, scratch); + for (w[0..S]) |*v| v.* = v.div(total); + for (0..n) |i| { + for (mix[0..S], w[0..S], 0..) |*t, weight, src| t.* = Iv.of(self.bank[(src * rows + r) * n + i]).mul(weight); + out[r * n + i] = s.sum(mix[0..S], S, scratch); + } + } + } +}; + +const conv_width = 1536; +const taps = 4; + +fn tapsDeep(_: c.Shape) usize { + return taps; +} + +/// Rows x the GDN's q | k | v channels x the kernel's four taps. +pub fn convSpec(fault: bool) c.Spec { + return .{ .name = name("z3_conv_silu (state in place)", "z3_conv_silu launched one row short", fault), .accum = .f32, .depth = tapsDeep, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 64, .n = conv_width, .k = taps }, .{ .rows = 1, .n = conv_width, .k = taps }, .{ .rows = 7, .n = conv_width, .k = taps } } }; +} + +/// The GDN's causal depthwise convolution and SiLU; the state keeps a channel's last three inputs. +pub const ConvSilu = struct { + f: cuda.Function, + /// control: the device runs rows - 1 rows + fault: bool = false, + shape: c.Shape = undefined, + proj: []f32 = &.{}, + state: []f32 = &.{}, + w: []u16 = &.{}, + dev: [2]u64 = @splat(0), + out: [2]u64 = @splat(0), + + pub const sums = {}; + const pad = 8; + + pub fn spec(self: *const ConvSilu) c.Spec { + return convSpec(self.fault); + } + + pub fn control(self: *const ConvSilu) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *ConvSilu, a: std.mem.Allocator) void { + a.free(self.proj); + a.free(self.state); + a.free(self.w); + self.proj = &.{}; + self.state = &.{}; + self.w = &.{}; + } + + pub fn prepare(self: *ConvSilu, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != taps) return false; + self.free(a); + self.shape = shape; + const T = shape.rows; + const C = shape.n; + const ps = C + pad; + self.proj = try ref.values(a, rng, T * ps, .random, 2); + self.state = try ref.values(a, rng, C * 3, .random, 2); + self.w = try ref.bfs(a, rng, C * taps, -1, 1); + if (fill == .stress) { + for (self.w) |*v| v.* = c.toBf16(1); + var line: [3 + 4]f32 = undefined; + for (0..C) |ch| { + ref.stress(line[0 .. 3 + @min(T, 4)], rng); + @memcpy(self.state[ch * 3 ..][0..3], line[0..3]); + for (0..T) |t| self.proj[t * ps + ch] = if (t < 4) line[3 + t] else 1; + } + } + if (fill == .nonfinite) ref.plant(self.proj, T, ps); + self.dev = .{ try ref.input(rig, self.proj), try ref.input(rig, self.w) }; + self.out = .{ try rig.output(T * C * 4), try rig.output(C * 3 * 4) }; + return true; + } + + pub fn run(self: *ConvSilu, rig: *rig_.Rig) !void { + const C = self.shape.n; + try ref.restore(rig, self.out[1], std.mem.sliceAsBytes(self.state)); + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(ref.int(C + pad)); + a.add(ref.int(self.shape.rows - ref.one(self.fault))); + a.add(self.dev[1]); + a.add(self.out[1]); + a.add(self.out[0]); + a.add(ref.int(C)); + try ref.go(self.f, rig.s, (C + 255) / 256, 1, 256, 0, &a); + } + + pub fn count(self: *const ConvSilu) usize { + return self.shape.rows * self.shape.n + self.shape.n * 3; + } + + /// Channel `ch`'s input `i` rows after the state's first: the three the state holds, then the rows. + fn at(self: *const ConvSilu, ch: usize, i: usize) f32 { + return if (i < 3) self.state[ch * 3 + i] else self.proj[(i - 3) * (self.shape.n + pad) + ch]; + } + + pub fn solve(self: *const ConvSilu, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const T = self.shape.rows; + const C = self.shape.n; + var scratch: [taps]f64 = undefined; + for (0..C) |ch| { + for (0..T) |t| { + var terms: [taps]Iv = undefined; + for (&terms, 0..) |*term, j| term.* = Iv.of(self.at(ch, t + j)).mul(Iv.of(ref.bf(self.w[ch * taps + j]))); + out[t * C + ch] = ref.silu(s.sum(&terms, taps, &scratch)); + } + for (0..3) |j| out[T * C + ch * 3 + j] = Iv.of(self.at(ch, T + j)); + } + } +}; diff --git a/zig/tests/cuda/contract_zonos3_conv.zig b/zig/tests/cuda/contract_zonos3_conv.zig new file mode 100644 index 00000000000..249decd57f4 --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_conv.zig @@ -0,0 +1,139 @@ +//! ZONOS3's encoder convolution under the contract: every layout the front end launches it at. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const Layout = struct { cout: usize, k: usize, cin: usize, taps: usize, stride: usize, pad: usize, dilated: bool = false }; + +/// The front end's convolutions: the first, a unit's dilated and pointwise ones at 64 and 128, the two strided. +const layouts = [_]Layout{ + .{ .cout = 64, .k = 448, .cin = 64, .taps = 7, .stride = 1, .pad = 6, .dilated = true }, + .{ .cout = 64, .k = 7, .cin = 1, .taps = 7, .stride = 1, .pad = 6 }, + .{ .cout = 64, .k = 64, .cin = 64, .taps = 1, .stride = 1, .pad = 0 }, + .{ .cout = 128, .k = 256, .cin = 64, .taps = 4, .stride = 2, .pad = 2 }, + .{ .cout = 128, .k = 896, .cin = 128, .taps = 7, .stride = 1, .pad = 6, .dilated = true }, + .{ .cout = 128, .k = 128, .cin = 128, .taps = 1, .stride = 1, .pad = 0 }, + .{ .cout = 256, .k = 1024, .cin = 128, .taps = 8, .stride = 4, .pad = 4 }, +}; + +/// A lane's fma chain over every 32nd input, the warp's butterfly, then the bias. +fn convDepth(s: c.Shape) usize { + return (s.k + 31) / 32 + 6; +} + +/// Output rows x output channels x (taps x input channels). +pub fn convSpec(fault: bool) c.Spec { + const served = comptime blk: { + var list: [layouts.len]c.Shape = undefined; + for (&list, layouts) |*x, l| x.* = .{ .rows = if (l.k > 512) 8 else 16, .n = l.cout, .k = l.k }; + const final = list; + break :blk &final; + }; + return .{ .name = if (fault) "control: zonos3 ze_conv launched with a pad one short" else "cuda zonos3_encoder ze_conv", .accum = .f32, .depth = convDepth, .out = .f32, .served = served }; +} + +/// The encoder's strided, dilated convolution over rows of channels, zero outside the rows. +pub const Conv = struct { + f: cuda.Function, + /// control: the device's pad is one less + fault: bool = false, + l: Layout = undefined, + dilation: usize = 1, + T: usize = 0, + x: []f32 = &.{}, + w: []f32 = &.{}, + b: []f32 = &.{}, + dev: [3]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Conv) c.Spec { + return convSpec(self.fault); + } + + pub fn control(self: *const Conv) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Conv, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.w); + a.free(self.b); + self.x = &.{}; + self.w = &.{}; + self.b = &.{}; + } + + pub fn prepare(self: *Conv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0) return false; + const l = for (layouts) |x| { + if (x.cout == shape.n and x.k == shape.k) break x; + } else return false; + self.free(a); + self.l = l; + self.T = shape.rows; + // the units' dilations are 1, 3 and 9; gate 1 takes 9, where each of the first rows feeds one output row + self.dilation = if (!l.dilated) 1 else if (fill == .nonfinite) 9 else ([_]usize{ 1, 3, 9 })[rng.uintLessThan(usize, 3)]; + const rows = self.T * l.stride; + self.x = try ref.values(a, rng, rows * l.cin, .random, 1); + self.w = try ref.values(a, rng, l.cout * l.k, .random, 1); + self.b = try ref.values(a, rng, l.cout, .random, 1); + if (fill == .stress) { + @memset(self.w, 1); + @memset(self.b, 0); + for (self.x) |*v| v.* = @floatFromInt(1 + 2 * rng.uintLessThan(u32, 128)); + ref.stress(self.x[0..@min(64, self.x.len)], rng); + } + if (fill == .nonfinite) ref.plant(self.x, rows, l.cin); + self.dev = .{ try ref.input(rig, self.x), try ref.input(rig, self.w), try ref.input(rig, self.b) }; + self.out = try rig.output(self.T * l.cout * 4); + return true; + } + + pub fn run(self: *Conv, rig: *rig_.Rig) !void { + const l = self.l; + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(ref.int(l.cin)); + a.add(ref.int(self.T * l.stride)); + a.add(self.dev[1]); + a.add(self.dev[2]); + a.add(ref.int(l.taps)); + a.add(ref.int(self.dilation)); + a.add(ref.int(l.stride)); + a.add(ref.int(l.pad * self.dilation - ref.one(self.fault and l.pad > 0))); + a.add(self.out); + a.add(ref.int(l.cout)); + try ref.go(self.f, rig.s, self.T, (l.cout + 7) / 8, 256, l.k * 4, &a); + } + + pub fn count(self: *const Conv) usize { + return self.T * self.l.cout; + } + + pub fn solve(self: *const Conv, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const l = self.l; + const rows: i64 = @intCast(self.T * l.stride); + const terms = try a.alloc(Iv, l.k); + defer a.free(terms); + const scratch = try a.alloc(f64, l.k); + defer a.free(scratch); + for (out, 0..) |*o, at| { + const t = at / l.cout; + const w = self.w[at % l.cout * l.k ..][0..l.k]; + for (terms, w, 0..) |*term, weight, i| { + const p = @as(i64, @intCast(t * l.stride + i / l.cin * self.dilation)) - @as(i64, @intCast(l.pad * self.dilation)); + term.* = if (p < 0 or p >= rows) Iv.of(0) else Iv.of(weight).mul(Iv.of(self.x[@as(usize, @intCast(p)) * l.cin + i % l.cin])); + } + o.* = s.sum(terms, convDepth(.{ .rows = 1, .n = l.cout, .k = l.k }), scratch).add(Iv.of(self.b[at % l.cout])); + } + } +}; diff --git a/zig/tests/cuda/contract_zonos3_gdn.zig b/zig/tests/cuda/contract_zonos3_gdn.zig new file mode 100644 index 00000000000..46770754801 --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_gdn.zig @@ -0,0 +1,319 @@ +//! ZONOS3's GDN layer under the contract: its inputs' norms and gates, the recurrence, and the gated norm after it. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const conv_width = 1536; + +fn name(comptime plain: []const u8, comptime broken: []const u8, fault: bool) []const u8 { + return if (fault) "control: zonos3 " ++ broken else "cuda zonos3 " ++ plain; +} + +const heads = 4; +const head = 128; +const inner = heads * head; + +/// A warp's butterfly, then the four warps'. +fn headDeep(_: c.Shape) usize { + return 7; +} + +/// Rows x the q | k | v channels x a head's 128. +pub fn prepSpec(fault: bool) c.Spec { + return .{ .name = name("z3_gdn_prep (q and k in place)", "z3_gdn_prep reading its gates' inputs one value late", fault), .accum = .f32, .depth = headDeep, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 64, .n = conv_width, .k = head }, .{ .rows = 1, .n = conv_width, .k = head }, .{ .rows = 7, .n = conv_width, .k = head } } }; +} + +/// The GDN's inputs: q and k l2-normed per head in place (q times 128^-1/2), and each (row, head)'s decay and beta. +pub const GdnPrep = struct { + f: cuda.Function, + /// control: the device reads a and b one value late in the projection row + fault: bool = false, + T: usize = 0, + conv: []f32 = &.{}, + proj: []f32 = &.{}, + a_log: [heads]u16 = undefined, + dt_bias: [heads]u16 = undefined, + dev: [3]u64 = @splat(0), + out: [2]u64 = @splat(0), + + pub const sums = {}; + const ps = 2 * heads + 4; + const a_off = 3; + const q_scale: f32 = 0.088388347648318447; + + pub fn spec(self: *const GdnPrep) c.Spec { + return prepSpec(self.fault); + } + + pub fn control(self: *const GdnPrep) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *GdnPrep, a: std.mem.Allocator) void { + a.free(self.conv); + a.free(self.proj); + self.conv = &.{}; + self.proj = &.{}; + } + + pub fn prepare(self: *GdnPrep, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != conv_width or shape.k != head) return false; + self.free(a); + self.T = shape.rows; + self.conv = try ref.values(a, rng, self.T * conv_width, fill, 2); + self.proj = try ref.values(a, rng, self.T * ps, .random, 3); + for (&self.a_log, &self.dt_bias) |*x, *y| { + x.* = c.toBf16(rng.float(f32) * 2 - 2); + y.* = c.toBf16(rng.float(f32) * 2 - 1); + } + if (fill == .nonfinite) ref.plant(self.conv, self.T, conv_width); + self.dev = .{ try ref.input(rig, self.proj), try ref.input(rig, &self.a_log), try ref.input(rig, &self.dt_bias) }; + self.out = .{ try rig.output(self.conv.len * 4), try rig.output(self.T * heads * 2 * 4) }; + return true; + } + + pub fn run(self: *GdnPrep, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out[0], std.mem.sliceAsBytes(self.conv)); + var a: cuda.Args = .{}; + a.add(self.out[0]); + a.add(self.dev[0]); + a.add(ref.int(ps)); + a.add(ref.int(a_off + ref.one(self.fault))); + a.add(self.dev[1]); + a.add(self.dev[2]); + a.add(self.out[1]); + try ref.go(self.f, rig.s, self.T, heads, head, 0, &a); + } + + pub fn count(self: *const GdnPrep) usize { + return self.T * conv_width + self.T * heads * 2; + } + + pub fn solve(self: *const GdnPrep, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var scratch: [head]f64 = undefined; + var sq: [head]Iv = undefined; + const gates = out[self.T * conv_width ..]; + for (0..self.T) |t| { + const row = self.conv[t * conv_width ..][0..conv_width]; + for (0..2 * heads) |part| { + const x = row[part * head ..][0..head]; + for (&sq, x) |*q, v| q.* = ref.square(Iv.of(v)); + const inv = s.sum(&sq, 7, &scratch).add(Iv.of(@as(f32, 1e-6))).rsqrt(); + for (x, 0..) |v, i| { + const y = Iv.of(v).mul(inv); + out[t * conv_width + part * head + i] = if (part < heads) y.mul(Iv.of(q_scale)) else y; + } + } + for (row[2 * inner ..], 0..) |v, i| out[t * conv_width + 2 * inner + i] = Iv.of(v); + const p = self.proj[t * ps + a_off ..][0 .. 2 * heads]; + for (0..heads) |h| { + const rate = Iv.of(ref.bf(self.a_log[h])).exp().neg(); + gates[(t * heads + h) * 2] = rate.mul(ref.softplus(Iv.of(p[h]).add(Iv.of(ref.bf(self.dt_bias[h]))))).exp(); + gates[(t * heads + h) * 2 + 1] = Iv.of(p[heads + h]).sigmoid(); + } + } + } +}; + +fn chainDeep(_: c.Shape) usize { + return head; +} + +/// Rows x the heads' outputs x a state row's 128. +pub fn gdnSpec(fault: bool) c.Spec { + return .{ .name = name("z3_gdn (state in place)", "z3_gdn launched one row short", fault), .accum = .f32, .depth = chainDeep, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 8, .n = inner, .k = head }, .{ .rows = 1, .n = inner, .k = head }, .{ .rows = 64, .n = inner, .k = head } } }; +} + +/// The GDN recurrence by token: a state row decays, predicts, takes the gated error along k, reads out along q. +pub const Gdn = struct { + f: cuda.Function, + /// control: the device runs rows - 1 rows + fault: bool = false, + T: usize = 0, + conv: []f32 = &.{}, + gates: []f32 = &.{}, + state: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: [2]u64 = @splat(0), + + pub const sums = {}; + const state_len = heads * head * head; + + pub fn spec(self: *const Gdn) c.Spec { + return gdnSpec(self.fault); + } + + pub fn control(self: *const Gdn) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Gdn, a: std.mem.Allocator) void { + a.free(self.conv); + a.free(self.gates); + a.free(self.state); + self.conv = &.{}; + self.gates = &.{}; + self.state = &.{}; + } + + pub fn prepare(self: *Gdn, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != inner or shape.k != head) return false; + self.free(a); + const T = shape.rows; + self.T = T; + // keys far below unit length keep the recurrence's float64 ranges from widening a step + self.conv = try ref.values(a, rng, T * conv_width, .random, 0.02); + self.gates = try a.alloc(f32, T * heads * 2); + for (self.gates, 0..) |*v, i| v.* = if (i % 2 == 0) 0.9 + 0.1 * rng.float(f32) else rng.float(f32); + self.state = try ref.values(a, rng, state_len, .random, 1); + for (0..T) |t| for (self.conv[t * conv_width + 2 * inner ..][0..inner]) |*v| { + v.* = rng.float(f32) * 2 - 1; + }; + if (fill == .stress) { + // q and k all ones, no decay, values zero; the first row takes its whole error, the later rows none + for (0..T) |t| { + @memset(self.conv[t * conv_width ..][0 .. 2 * inner], 1); + @memset(self.conv[t * conv_width + 2 * inner ..][0..inner], 0); + } + for (self.gates, 0..) |*v, i| v.* = if (i % 2 == 0 or i < heads * 2) 1 else 0; + for (0..heads * head) |row| ref.stress(self.state[row * head ..][0..head], rng); + } + if (fill == .nonfinite) { + self.state[5 * head + 3] = ref.nan; // head 0, value row 5 + if (T > 1) self.conv[conv_width + head + 7] = ref.nan; // row 1, head 1's q + if (T > 2) self.conv[2 * conv_width + 2 * head + 9] = ref.inf; // row 2, head 2's q + } + self.dev = .{ try ref.input(rig, self.conv), try ref.input(rig, self.gates) }; + self.out = .{ try rig.output(T * inner * 4), try rig.output(state_len * 4) }; + return true; + } + + pub fn run(self: *Gdn, rig: *rig_.Rig) !void { + try ref.restore(rig, self.out[1], std.mem.sliceAsBytes(self.state)); + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(self.T - ref.one(self.fault))); + a.add(self.out[1]); + a.add(self.out[0]); + try ref.go(self.f, rig.s, heads, 1, head, 0, &a); + } + + pub fn count(self: *const Gdn) usize { + return self.T * inner + state_len; + } + + pub fn solve(self: *const Gdn, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var scratch: [head]f64 = undefined; + var row: [head]Iv = undefined; + var terms: [head]Iv = undefined; + for (0..heads * head) |at| { + const h = at / head; + for (&row, self.state[at * head ..][0..head]) |*r, v| r.* = Iv.of(v); + for (0..self.T) |t| { + const q = self.conv[t * conv_width + h * head ..][0..head]; + const k = self.conv[t * conv_width + inner + h * head ..][0..head]; + const val = Iv.of(self.conv[t * conv_width + 2 * inner + at]); + const decay = Iv.of(self.gates[(t * heads + h) * 2]); + const beta = Iv.of(self.gates[(t * heads + h) * 2 + 1]); + for (&row, &terms, k) |*r, *term, kv| { + r.* = r.mul(decay); + term.* = r.mul(Iv.of(kv)); + } + const delta = beta.mul(val.sub(s.sum(&terms, head, &scratch))); + for (&row, &terms, k, q) |*r, *term, kv, qv| { + r.* = r.add(delta.mul(Iv.of(kv))); + term.* = r.mul(Iv.of(qv)); + } + out[t * inner + at] = s.sum(&terms, head, &scratch); + } + for (row, 0..) |r, j| out[self.T * inner + at * head + j] = r; + } + } +}; + +/// Rows x the heads' outputs x a head's 128. +pub fn gatedSpec(fault: bool) c.Spec { + return .{ .name = name("z3_gated_norm", "z3_gated_norm reading its gate one value late", fault), .accum = .f32, .depth = headDeep, .out = .f32, .served = &.{ .{ .rows = 64, .n = inner, .k = head }, .{ .rows = 1, .n = inner, .k = head }, .{ .rows = 7, .n = inner, .k = head } } }; +} + +/// y = rms_norm(o, w, 1e-5) silu(z) per head of 128. +pub const GatedNorm = struct { + f: cuda.Function, + /// control: the device reads z one value late in the projection row + fault: bool = false, + T: usize = 0, + o: []f32 = &.{}, + proj: []f32 = &.{}, + w: []u16 = &.{}, + dev: [3]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + const z_off = 5; + const ps = inner + z_off + 1; + + pub fn spec(self: *const GatedNorm) c.Spec { + return gatedSpec(self.fault); + } + + pub fn control(self: *const GatedNorm) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *GatedNorm, a: std.mem.Allocator) void { + a.free(self.o); + a.free(self.proj); + a.free(self.w); + self.o = &.{}; + self.proj = &.{}; + self.w = &.{}; + } + + pub fn prepare(self: *GatedNorm, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != inner or shape.k != head) return false; + self.free(a); + self.T = shape.rows; + self.o = try ref.values(a, rng, self.T * inner, fill, 2); + self.proj = try ref.values(a, rng, self.T * ps, .random, 3); + self.w = try ref.bfs(a, rng, head, -1, 3); + if (fill == .nonfinite) ref.plant(self.o, self.T, inner); + self.dev = .{ try ref.input(rig, self.o), try ref.input(rig, self.proj), try ref.input(rig, self.w) }; + self.out = try rig.output(self.T * inner * 4); + return true; + } + + pub fn run(self: *GatedNorm, rig: *rig_.Rig) !void { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(ps)); + a.add(ref.int(z_off + ref.one(self.fault))); + a.add(self.dev[2]); + a.add(self.out); + try ref.go(self.f, rig.s, self.T, heads, head, 0, &a); + } + + pub fn count(self: *const GatedNorm) usize { + return self.T * inner; + } + + pub fn solve(self: *const GatedNorm, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var scratch: [head]f64 = undefined; + var sq: [head]Iv = undefined; + for (0..self.T * heads) |at| { + const x = self.o[at * head ..][0..head]; + for (&sq, x) |*q, v| q.* = ref.square(Iv.of(v)); + const inv = ref.rmsScale(s.sum(&sq, 7, &scratch), head, 1e-5); + const z = self.proj[at / heads * ps + z_off + at % heads * head ..][0..head]; + for (x, z, self.w, 0..) |v, gate, w, i| out[at * head + i] = Iv.of(v).mul(inv).mul(Iv.of(ref.bf(w))).mul(ref.silu(Iv.of(gate))); + } + } +}; diff --git a/zig/tests/cuda/contract_zonos3_pick.zig b/zig/tests/cuda/contract_zonos3_pick.zig new file mode 100644 index 00000000000..f8c5daa66fe --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_pick.zig @@ -0,0 +1,226 @@ +//! ZONOS3's picking kernels under the contract: the MoE router and the quantizer's nearest code, by their own rules. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const experts = 64; + +/// Rows x experts: a prompt chunk's rows and the decode row. +pub fn routeSpec(fault: bool) c.Spec { + return .{ + .name = if (fault) "control: zonos3 z3_route with its bias one expert late" else "cuda zonos3 z3_route", + .accum = .none, + .depth = ref.noSums, + .out = .raw, + .nan = .{ .stated = "a NaN score never displaces a held pick; a picked NaN or +Inf logit makes both weights NaN" }, + .served = &.{ .{ .rows = 64, .n = experts, .k = 1 }, .{ .rows = 1, .n = experts, .k = 1 }, .{ .rows = 7, .n = experts, .k = 1 } }, + }; +} + +/// The top two of logits - bias by strict comparison in index order, weighted by the softmax of their raw logits. +pub const Route = struct { + f: cuda.Function, + /// control: the device's bias is rotated by one expert + fault: bool = false, + rows: usize = 0, + logits: []f32 = &.{}, + bias: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: [2]u64 = @splat(0), + + pub fn spec(self: *const Route) c.Spec { + return routeSpec(self.fault); + } + + pub fn control(self: *const Route) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Route, a: std.mem.Allocator) void { + a.free(self.logits); + a.free(self.bias); + self.logits = &.{}; + self.bias = &.{}; + } + + pub fn prepare(self: *Route, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != experts) return false; + self.free(a); + self.rows = shape.rows; + self.logits = try ref.values(a, rng, shape.rows * experts, fill, 4); + self.bias = try ref.values(a, rng, experts, fill, 2); + // ties: two experts of a row share a logit and a bias + for (0..shape.rows) |r| self.logits[r * experts + 11] = self.logits[r * experts + 40]; + self.bias[11] = self.bias[40]; + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, 0 }, .{ 1, 5 }, .{ 2, 7 }, .{ 3, 9 } }; + const put = [_]f32{ ref.nan, ref.nan, ref.inf, -ref.inf }; + for (at, put) |p, v| if (p[0] < shape.rows) { + self.logits[p[0] * experts + p[1]] = v; + }; + } + const seen = try a.dupe(f32, self.bias); + defer a.free(seen); + if (self.fault) std.mem.rotate(f32, seen, 1); + self.dev = .{ try ref.input(rig, self.logits), try ref.input(rig, seen) }; + self.out = .{ try rig.output(shape.rows * 2 * 4), try rig.output(shape.rows * 2 * 4) }; + return true; + } + + pub fn run(self: *Route, rig: *rig_.Rig) !void { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(experts)); + a.add(self.out[0]); + a.add(self.out[1]); + try ref.go(self.f, rig.s, self.rows, 1, 32, 0, &a); + } + + pub fn count(self: *const Route) usize { + return self.rows * 16; + } + + pub fn check(self: *const Route, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + const weights = got[self.rows * 8 ..]; + for (0..self.rows) |r| { + const l = self.logits[r * experts ..][0..experts]; + var b: [2]i32 = .{ -1, -1 }; + var v: [2]f32 = .{ -ref.inf, -ref.inf }; + for (l, self.bias, 0..) |x, bias, e| { + const s = x - bias; + if (b[0] < 0 or s > v[0]) { + b[1] = b[0]; + v[1] = v[0]; + b[0] = @intCast(e); + v[0] = s; + } else if (b[1] < 0 or s > v[1]) { + b[1] = @intCast(e); + v[1] = s; + } + } + const pick = [2]f32{ l[@intCast(b[0])], l[@intCast(b[1])] }; + // fmaxf: a NaN gives way to the other logit + const m: f32 = if (std.math.isNan(pick[0])) pick[1] else if (std.math.isNan(pick[1])) pick[0] else @max(pick[0], pick[1]); + const e0 = @exp(@as(f64, pick[0] - m)); + const e1 = @exp(@as(f64, pick[1] - m)); + const want = [2]f64{ e0 / (e0 + e1), e1 / (e0 + e1) }; + for (0..2) |j| { + const have = ref.readI32(got, r * 2 + j); + if (have != b[j]) return try std.fmt.bufPrint(msg, "row {d} pick {d}: expert {d} where {d} is due", .{ r, j, have, b[j] }); + const w: f64 = ref.readF32(weights, r * 2 + j); + const same = if (std.math.isNan(want[j])) std.math.isNan(w) else @abs(w - want[j]) <= 1e-6 * want[j] + 0x1p-140; + if (!same) return try std.fmt.bufPrint(msg, "row {d} weight {d}: {e} where float64 gives {e}", .{ r, j, w, want[j] }); + } + } + return null; + } +}; + +const codes = 4096; +const code_dim = 8; +const columns = 10; +const column = 3; + +/// Rows x 8 against the codebook's 4,096 unit rows. +pub fn nearestSpec(fault: bool) c.Spec { + return .{ + .name = if (fault) "control: zonos3 ze_nearest writing the next codebook's column" else "cuda zonos3_encoder ze_nearest", + .accum = .none, + .depth = ref.noSums, + .out = .raw, + .nan = .{ .stated = "a NaN dot is never the nearest; a row whose every dot is NaN or -Inf gives code 0" }, + .served = &.{ .{ .rows = 64, .n = code_dim, .k = codes }, .{ .rows = 1, .n = code_dim, .k = codes }, .{ .rows = 300, .n = code_dim, .k = codes } }, + }; +} + +/// The code whose row has the largest dot with a row's 8 values (an fma chain in index order), ties to the lower. +pub const Nearest = struct { + f: cuda.Function, + /// control: the device writes column 4 + fault: bool = false, + rows: usize = 0, + e: []f32 = &.{}, + book: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub fn spec(self: *const Nearest) c.Spec { + return nearestSpec(self.fault); + } + + pub fn control(self: *const Nearest) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Nearest, a: std.mem.Allocator) void { + a.free(self.e); + a.free(self.book); + self.e = &.{}; + self.book = &.{}; + } + + pub fn prepare(self: *Nearest, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != code_dim or shape.k != codes) return false; + self.free(a); + self.rows = shape.rows; + self.e = try ref.values(a, rng, shape.rows * code_dim, fill, 1); + self.book = try ref.values(a, rng, codes * code_dim, .random, 1); + for (0..codes / 2) |r| { + const row = self.book[r * code_dim ..][0..code_dim]; + var ss: f32 = 0; + for (row) |v| ss += v * v; + for (row) |*v| v.* /= @sqrt(ss); + // every code has a twin in the upper half: each row's best dot is a tie + @memcpy(self.book[(codes / 2 + r) * code_dim ..][0..code_dim], row); + } + if (fill == .nonfinite) { + self.e[1] = ref.nan; + if (shape.rows > 1) self.e[code_dim + 2] = ref.inf; + if (shape.rows > 2) self.e[2 * code_dim + 5] = -ref.inf; + } + self.dev = .{ try ref.input(rig, self.e), try ref.input(rig, self.book) }; + self.out = try rig.output(shape.rows * columns * 4); + return true; + } + + pub fn run(self: *Nearest, rig: *rig_.Rig) !void { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(self.out); + a.add(ref.int(column + ref.one(self.fault))); + try ref.go(self.f, rig.s, self.rows, 1, 256, 0, &a); + } + + pub fn count(self: *const Nearest) usize { + return self.rows * columns * 4; + } + + pub fn check(self: *const Nearest, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + for (0..self.rows) |r| { + const x = self.e[r * code_dim ..][0..code_dim]; + var best: f32 = -ref.inf; + var want: i32 = 0; + for (0..codes) |code| { + var d: f32 = 0; + for (x, self.book[code * code_dim ..][0..code_dim]) |p, q| d = @mulAdd(f32, p, q, d); + if (d > best) { + best = d; + want = @intCast(code); + } + } + for (0..columns) |col| { + const have = ref.readI32(got, r * columns + col); + const due: i32 = if (col == column) want else -1; + if (have != due) return try std.fmt.bufPrint(msg, "row {d} column {d}: {d} where {d} is due", .{ r, col, have, due }); + } + } + return null; + } +}; diff --git a/zig/tests/cuda/contract_zonos3_point.zig b/zig/tests/cuda/contract_zonos3_point.zig new file mode 100644 index 00000000000..8f56001c487 --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_point.zig @@ -0,0 +1,338 @@ +//! ZONOS3's pointwise and moving kernels under the contract: no sums, each output a few fp32 steps from its inputs. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +pub const Kind = enum { mul_silu, combine, softcap, add_scaled, add_plain, gelu, patch_up, gather, spec, snake, add, sub, patch_down, sub_code, swish, glu }; + +const Image = enum { backbone, codec, encoder, teacher }; + +const Info = struct { + symbol: [:0]const u8, + image: Image, + name: []const u8, + /// What the control's launch gets wrong. + fault: []const u8, + in_place: bool = false, + out: c.Elem = .f32, + served: []const c.Shape, +}; + +fn sh(rows: usize, n: usize) c.Shape { + return .{ .rows = rows, .n = n, .k = 1 }; +} + +/// Each kind's facts, built at compile time so the served lists outlive the call. +fn info(kind: Kind) Info { + return switch (kind) { + inline else => |k| comptime infoOf(k), + }; +} + +fn infoOf(comptime kind: Kind) Info { + return switch (kind) { + // the dense feed-forward's hidden rows, and an expert's for each of a row's two picks + .mul_silu => .{ .symbol = "z3_mul_silu", .image = .backbone, .name = "cuda zonos3 z3_mul_silu", .fault = "reads its gate one value late", .served = &.{ sh(64, 2048), sh(1, 2048), sh(2, 1536), sh(128, 1536) } }, + .combine => .{ .symbol = "z3_combine", .image = .backbone, .name = "cuda zonos3 z3_combine", .fault = "weighs each pick with the other pick's weight", .served = &.{ sh(64, 256), sh(1, 256) } }, + .softcap => .{ .symbol = "z3_softcap", .image = .backbone, .name = "cuda zonos3 z3_softcap (in place)", .fault = "launched one value short", .in_place = true, .served = &.{ sh(8, 40980), sh(1, 40980), sh(64, 40980) } }, + // a stage's attention and feed-forward residuals with their layer scale, and the ConvNeXt block's plain one + .add_scaled => .{ .symbol = "zc_add_scaled", .image = .codec, .name = "cuda zonos3_codec zc_add_scaled (in place, layer scale)", .fault = "launched without its scale", .in_place = true, .served = &.{ sh(16, 768), sh(300, 1280), sh(1, 768) } }, + .add_plain => .{ .symbol = "zc_add_scaled", .image = .codec, .name = "cuda zonos3_codec zc_add_scaled (in place, no scale)", .fault = "launched one column short", .in_place = true, .served = &.{ sh(16, 768), sh(300, 768) } }, + .gelu => .{ .symbol = "zc_gelu", .image = .codec, .name = "cuda zonos3_codec zc_gelu (in place)", .fault = "launched one value short", .in_place = true, .served = &.{ sh(16, 2048), sh(300, 5120), sh(1, 3072) } }, + // rows are the doubled ones, n half the stage's output width + .patch_up => .{ .symbol = "zc_patch_up", .image = .codec, .name = "cuda zonos3_codec zc_patch_up", .fault = "launched one row short", .served = &.{ sh(16, 384), sh(600, 640), sh(2, 384) } }, + .gather => .{ .symbol = "zc_gather", .image = .codec, .name = "cuda zonos3_codec zc_gather", .fault = "reads the next codebook's column", .served = &.{ sh(16, 768), sh(1, 768), sh(300, 768) } }, + // n is both halves: 369 and 1,105 bins + .spec => .{ .symbol = "zc_spec", .image = .codec, .name = "cuda zonos3_codec zc_spec (in place)", .fault = "launched one row short", .in_place = true, .served = &.{ sh(16, 738), sh(16, 2210), sh(1, 738) } }, + .snake => .{ .symbol = "ze_snake", .image = .encoder, .name = "cuda zonos3_encoder ze_snake", .fault = "launched one value short", .served = &.{ sh(64, 64), sh(2944, 64), sh(368, 128), sh(1, 256) } }, + .add => .{ .symbol = "ze_add", .image = .encoder, .name = "cuda zonos3_encoder ze_add (in place)", .fault = "launched one value short", .in_place = true, .served = &.{ sh(64, 64), sh(2944, 64), sh(368, 128) } }, + .sub => .{ .symbol = "ze_sub", .image = .encoder, .name = "cuda zonos3_encoder ze_sub (in place)", .fault = "launched one value short", .in_place = true, .served = &.{ sh(16, 1024), sh(300, 1024), sh(1, 1024) } }, + // k is the patch: 23 front-end frames a row, then 2 a stage + .patch_down => .{ .symbol = "ze_patch_down", .image = .encoder, .name = "cuda zonos3_encoder ze_patch_down", .fault = "launched one row short", .served = &.{ .{ .rows = 16, .n = 5888, .k = 23 }, .{ .rows = 8, .n = 768, .k = 2 }, .{ .rows = 150, .n = 1280, .k = 2 }, .{ .rows = 1, .n = 768, .k = 2 } } }, + .sub_code => .{ .symbol = "ze_sub_code", .image = .encoder, .name = "cuda zonos3_encoder ze_sub_code (in place)", .fault = "reads the next codebook's column", .in_place = true, .served = &.{ sh(16, 1024), sh(300, 1024), sh(1, 1024) } }, + .swish => .{ .symbol = "zt_swish", .image = .teacher, .name = "cuda zonos3_teacher zt_swish (in place)", .fault = "launched one value short", .in_place = true, .served = &.{ sh(16, 4096), sh(999, 1024), sh(1, 4096) } }, + .glu => .{ .symbol = "zt_glu", .image = .teacher, .name = "cuda zonos3_teacher zt_glu", .fault = "launched one row short", .served = &.{ sh(16, 1024), sh(999, 1024), sh(2, 1024) } }, + }; +} + +const table_rows = 64; +const column = 3; +const cap: f32 = 15; +const sqrt_half: f32 = 0.70710678118654752; +const log_100: f32 = 4.605170185988092; + +pub const Point = struct { + f: cuda.Function, + kind: Kind, + /// control: the launch differs from the reference as `Info.fault` says + fault: bool = false, + shape: c.Shape = undefined, + x: []f32 = &.{}, + y: []f32 = &.{}, + z: []f32 = &.{}, + ids: []i32 = &.{}, + dev: [3]u64 = @splat(0), + out: u64 = 0, + label: [120]u8 = undefined, + + pub fn init(mods: ref.Mods, kind: Kind, fault: bool) !Point { + const i = info(kind); + const mod = switch (i.image) { + .backbone => mods.backbone, + .codec => mods.codec, + .encoder => mods.encoder, + .teacher => mods.teacher, + }; + return .{ .f = try mod.function(i.symbol), .kind = kind, .fault = fault }; + } + + pub fn spec(self: *Point) c.Spec { + const i = info(self.kind); + const name = if (self.fault) std.fmt.bufPrint(&self.label, "control: zonos3 {s} {s}", .{ i.symbol, i.fault }) catch unreachable else i.name; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = i.out, .in_place = i.in_place, .tiles = .{ .{}, .{ .size = 256 }, .{} }, .served = i.served }; + } + + pub fn control(self: *const Point) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Point, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.y); + a.free(self.z); + a.free(self.ids); + self.x = &.{}; + self.y = &.{}; + self.z = &.{}; + self.ids = &.{}; + } + + /// The width of a row of `x`. + fn width(self: *const Point) usize { + const n = self.shape.n; + return switch (self.kind) { + .mul_silu => 2 * n + 1, + .glu, .patch_up => 2 * n, + .patch_down => n / self.shape.k, + else => n, + }; + } + + fn xRows(self: *const Point) usize { + const rows = self.shape.rows; + return switch (self.kind) { + .combine => 2 * rows, + .patch_up => rows / 2, + .gather => table_rows, + .patch_down => rows * self.shape.k, + else => rows, + }; + } + + pub fn prepare(self: *Point, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + switch (self.kind) { + .patch_up => if (shape.rows % 2 != 0) return false, + .spec => if (shape.n % 2 != 0) return false, + .patch_down => if (shape.k == 0 or shape.n % shape.k != 0) return false, + else => {}, + } + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + const xr = self.xRows(); + const xw = self.width(); + self.x = try ref.values(a, rng, xr * xw, fill, 4); + if (fill == .nonfinite) ref.plant(self.x, xr, xw); + switch (self.kind) { + .combine => { + self.y = try a.alloc(f32, 2 * rows); + for (self.y) |*v| v.* = rng.float(f32); + }, + .add_scaled => { + self.y = try ref.values(a, rng, rows * n, fill, 4); + self.z = try ref.values(a, rng, n, fill, 1); + }, + .add_plain, .add, .sub => self.y = try ref.values(a, rng, rows * n, fill, 4), + .snake => { + self.y = try a.alloc(f32, n); + for (self.y) |*v| v.* = 0.5 + 1.5 * rng.float(f32); // the checkpoint's alphas are positive + }, + .sub_code => self.y = try ref.values(a, rng, table_rows * n, fill, 4), + else => {}, + } + if (self.kind == .gather or self.kind == .sub_code) { + self.ids = try a.alloc(i32, rows * 10); + for (self.ids, 0..) |*v, i| v.* = if (fill == .nonfinite and i % 10 == column) @intCast(i / 10 % table_rows) else @intCast(rng.uintLessThan(u32, table_rows)); + } + if (info(self.kind).in_place) { + self.out = try rig.output(self.x.len * 4); + } else { + self.dev[0] = try ref.input(rig, self.x); + self.out = try rig.output(self.count() * 4); + } + if (self.y.len > 0) { + if (self.kind == .combine and self.fault) { + const swapped = try a.dupe(f32, self.y); + defer a.free(swapped); + for (0..rows) |r| std.mem.swap(f32, &swapped[2 * r], &swapped[2 * r + 1]); + self.dev[1] = try ref.input(rig, swapped); + } else self.dev[1] = try ref.input(rig, self.y); + } + if (self.z.len > 0) self.dev[2] = try ref.input(rig, self.z); + if (self.ids.len > 0) self.dev[2] = try ref.input(rig, self.ids); + return true; + } + + pub fn run(self: *Point, rig: *rig_.Rig) !void { + const rows = self.shape.rows; + const n = self.shape.n; + const total = rows * n; + const short = ref.one(self.fault); + if (info(self.kind).in_place) try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.x)); + var a: cuda.Args = .{}; + switch (self.kind) { + .mul_silu => { + a.add(self.dev[0]); + a.add(ref.int(2 * n + 1)); + a.add(ref.int(0)); + a.add(ref.int(n + short)); + a.add(ref.int(n)); + a.add(self.out); + try ref.go(self.f, rig.s, (n + 255) / 256, rows, 256, 0, &a); + }, + .combine => { + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(n)); + a.add(self.out); + try ref.go(self.f, rig.s, (n + 255) / 256, rows, 256, 0, &a); + }, + .softcap => { + a.add(self.out); + a.add(ref.long(total - short)); + a.add(cap); + try ref.go(self.f, rig.s, (total + 255) / 256, 1, 256, 0, &a); + }, + .add_scaled, .add_plain => { + a.add(self.out); + a.add(self.dev[1]); + a.add(if (self.kind == .add_scaled and !self.fault) self.dev[2] else @as(u64, 0)); + a.add(ref.int(if (self.kind == .add_plain) n - short else n)); + try ref.go(self.f, rig.s, (n + 255) / 256, rows, 256, 0, &a); + }, + .gelu, .swish => { + a.add(self.out); + a.add(ref.long(total - short)); + try ref.go(self.f, rig.s, (total + 255) / 256, 1, 256, 0, &a); + }, + .patch_up => { + a.add(self.dev[0]); + a.add(self.out); + a.add(ref.int(2 * n)); + try ref.go(self.f, rig.s, (n + 255) / 256, rows - short, 256, 0, &a); + }, + .gather => { + a.add(self.dev[2]); + a.add(ref.int(column + short)); + a.add(self.dev[0]); + a.add(self.out); + a.add(ref.int(n)); + try ref.go(self.f, rig.s, (n + 255) / 256, rows, 256, 0, &a); + }, + .spec => { + a.add(self.out); + a.add(ref.int(n / 2)); + try ref.go(self.f, rig.s, (n / 2 + 255) / 256, rows - short, 256, 0, &a); + }, + .snake => { + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(n)); + a.add(ref.long(total - short)); + a.add(self.out); + try ref.go(self.f, rig.s, (total + 255) / 256, 1, 256, 0, &a); + }, + .add, .sub => { + a.add(self.out); + a.add(self.dev[1]); + a.add(ref.long(total - short)); + try ref.go(self.f, rig.s, (total + 255) / 256, 1, 256, 0, &a); + }, + .patch_down => { + a.add(self.dev[0]); + a.add(self.out); + a.add(ref.int(n / self.shape.k)); + a.add(ref.int(self.shape.k)); + try ref.go(self.f, rig.s, (n + 255) / 256, rows - short, 256, 0, &a); + }, + .sub_code => { + a.add(self.out); + a.add(self.dev[1]); + a.add(self.dev[2]); + a.add(ref.int(column + short)); + a.add(ref.int(n)); + try ref.go(self.f, rig.s, (n + 255) / 256, rows, 256, 0, &a); + }, + .glu => { + a.add(self.dev[0]); + a.add(self.out); + a.add(ref.int(n)); + try ref.go(self.f, rig.s, (n + 255) / 256, rows - short, 256, 0, &a); + }, + } + } + + pub fn count(self: *const Point) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Point, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + const n = self.shape.n; + const x = self.x; + for (out, 0..) |*o, at| { + const r = at / n; + const i = at % n; + o.* = switch (self.kind) { + .mul_silu => Iv.of(x[r * (2 * n + 1) + i]).mul(ref.silu(Iv.of(x[r * (2 * n + 1) + n + i]))), + .combine => Iv.of(x[2 * r * n + i]).mul(Iv.of(self.y[2 * r])).add(Iv.of(x[(2 * r + 1) * n + i]).mul(Iv.of(self.y[2 * r + 1]))), + .softcap => Iv.of(cap).mul(ref.tanh(Iv.of(x[at]).div(Iv.of(cap)))), + .add_scaled => Iv.of(x[at]).add(Iv.of(self.z[i]).mul(Iv.of(self.y[at]))), + .add_plain, .add => Iv.of(x[at]).add(Iv.of(self.y[at])), + .sub => Iv.of(x[at]).sub(Iv.of(self.y[at])), + .gelu => Iv.of(0.5).mul(Iv.of(x[at])).mul(Iv.of(1).add(ref.erf(Iv.of(x[at]).mul(Iv.of(sqrt_half))))), + .patch_up => Iv.of(x[(r >> 1) * 2 * n + 2 * i + (r & 1)]), + .gather => Iv.of(x[@as(usize, @intCast(self.ids[r * 10 + column])) * n + i]), + .spec => blk: { + const half = n / 2; + const bin = i % half; + const mag = Iv.of(x[r * n + bin]).atMost(log_100).exp(); + break :blk mag.mul(Iv.of(x[r * n + half + bin]).trig(i >= half)); + }, + .snake => blk: { + const alpha = Iv.of(self.y[i]); + const s = alpha.mul(Iv.of(x[at])).trig(true); + break :blk Iv.of(x[at]).add(ref.square(s).div(alpha.add(Iv.of(@as(f32, 1e-9))))); + }, + .patch_down => blk: { + const h = self.shape.k; + break :blk Iv.of(x[(r * h + i % h) * (n / h) + i / h]); + }, + .sub_code => Iv.of(x[at]).sub(Iv.of(self.y[@as(usize, @intCast(self.ids[r * 10 + column])) * n + i])), + .swish => ref.silu(Iv.of(x[at])), + .glu => Iv.of(x[r * 2 * n + i]).mul(Iv.of(x[r * 2 * n + n + i]).sigmoid()), + }; + } + } +}; + +/// The kernels a control is planted for: every kind. +pub const kinds = std.enums.values(Kind); diff --git a/zig/tests/cuda/contract_zonos3_ref.zig b/zig/tests/cuda/contract_zonos3_ref.zig new file mode 100644 index 00000000000..d27b893968e --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_ref.zig @@ -0,0 +1,163 @@ +//! ZONOS3's kernels under the contract: launches by symbol, the gates' fills, and fp32 functions as float64 ranges. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); + +pub const base = @import("contract_minimax_glue_ref.zig"); +pub const Iv = base.Iv; +pub const Sums = base.Sums; +pub const Gated = base.Gated; +pub const Checked = base.Checked; +pub const noSums = base.noSums; +pub const input = base.input; +pub const restore = base.restore; +pub const nan = base.nan; +pub const inf = base.inf; + +const c = core.contract.spec; +const g = core.contract.gates; + +/// The four images' modules, loaded once for every registration. +pub const Mods = struct { backbone: cuda.Module, codec: cuda.Module, encoder: cuda.Module, teacher: cuda.Module }; + +pub fn go(f: cuda.Function, s: cuda.Stream, gx: usize, gy: usize, block: usize, shared: usize, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy), .z = 1 }, .block = .{ .x = @intCast(block) }, .shared = @intCast(shared) }, s, a); +} + +pub fn int(x: usize) c_int { + return @intCast(x); +} + +pub fn long(x: usize) i64 { + return @intCast(x); +} + +/// A device address `back` fp32 values before `ptr`: a cache whose first `back` values the launch never touches. +pub fn before(ptr: u64, back: usize) u64 { + return ptr -% 4 * @as(u64, back); +} + +/// The value m with the range [lo, hi] widened by `rel` of each end. +pub fn wide(m: f64, lo: f64, hi: f64, rel: f64) Iv { + return .{ .m = m, .lo = lo - @abs(lo) * rel - 0x1p-149, .hi = hi + @abs(hi) * rel + 0x1p-149 }; +} + +/// An increasing single-precision libm function of a range, within `ulps` of its value. +pub fn rising(comptime f: fn (f64) f64, a: Iv, ulps: f64) Iv { + return wide(f(a.m), f(a.lo), f(a.hi), ulps * 0x1p-23); +} + +fn tanh64(x: f64) f64 { + return std.math.tanh(x); +} + +fn log1p64(x: f64) f64 { + return std.math.log1p(x); +} + +/// tanhf, within 4 ulps. +pub fn tanh(a: Iv) Iv { + return rising(tanh64, a, 4); +} + +/// erff, within 4 ulps. +pub fn erf(a: Iv) Iv { + return rising(core.act_ref.erf, a, 4); +} + +/// act.cuh's softplusf_: x past 20, else log1pf(expf(x)). +pub fn softplus(a: Iv) Iv { + if (a.m > 20) return a; + return rising(log1p64, a.exp(), 4); +} + +/// act.cuh's silu: v / (1 + expf(-v)). +pub fn silu(v: Iv) Iv { + return v.div(Iv.of(1).add(v.neg().exp())); +} + +/// The square of a range: never below zero. +pub fn square(v: Iv) Iv { + const lo = @min(@abs(v.lo), @abs(v.hi)); + const hi = @max(@abs(v.lo), @abs(v.hi)); + return wide(v.m * v.m, if (v.lo <= 0 and v.hi >= 0) 0 else lo * lo, hi * hi, 0x1p-24); +} + +/// reduce.cuh's rms_scale: 1 / sqrt(ss / width + eps), each step IEEE. +pub fn rmsScale(ss: Iv, width: usize, eps: f32) Iv { + return ss.div(Iv.of(@floatFromInt(width))).add(Iv.of(eps)).rsqrt(); +} + +/// `n` fp32 values: uniform in [-span, span), or gate 4's whole numbers in [-32, 32]. +pub fn values(a: std.mem.Allocator, rng: std.Random, n: usize, fill: g.Fill, span: f32) ![]f32 { + const x = try a.alloc(f32, n); + for (x) |*v| v.* = if (fill == .stress) base.int(rng, -32, 32) else (rng.float(f32) * 2 - 1) * span; + return x; +} + +/// `n` bf16 values uniform in [lo, hi). +pub fn bfs(a: std.mem.Allocator, rng: std.Random, n: usize, lo: f32, hi: f32) ![]u16 { + return base.bfs(a, rng, n, lo, hi); +} + +pub fn bf(h: u16) f64 { + return c.fromBf16(h); +} + +/// NaN, +Inf and -Inf at known places of rows [rows][n]: a row each, row 3 holding both infinities. +pub fn plant(x: []f32, rows: usize, n: usize) void { + const at = [_][2]usize{ .{ 0, n / 3 }, .{ 1, n / 2 }, .{ 2, n - 1 }, .{ 3, 0 }, .{ 3, n - 1 } }; + const put = [_]f32{ nan, inf, -inf, inf, -inf }; + for (at, put) |p, v| if (p[0] < rows) { + x[p[0] * n + p[1]] = v; + }; +} + +/// The magnitude gate 4's sums pass through: past fp16's range, and where bf16 steps by 1,024. +pub const big: f32 = 0x1p17; + +/// Gate 4's terms: odd numbers to 255 and up to 16 of +-2^17 summing to zero; fp32 sums of 32,768 stay exact. +pub fn stress(x: []f32, rng: std.Random) void { + for (x) |*v| v.* = @floatFromInt(1 + 2 * rng.uintLessThan(u32, 128)); + const pairs = @min(16, (x.len / 2) & ~@as(usize, 1)); + for (0..pairs) |j| x[2 * j] = if (j % 2 == 0) big else -big; +} + +/// `stress` along every `stride`-th value from `first`: a strided axis of a larger buffer. +pub fn stressAxis(x: []f32, first: usize, stride: usize, count: usize, rng: std.Random) void { + var tmp: [64]f32 = undefined; + const head = @min(count, tmp.len); + stress(tmp[0..head], rng); + for (0..count) |i| x[first + i * stride] = if (i < head) tmp[i] else @floatFromInt(1 + 2 * rng.uintLessThan(u32, 128)); +} + +pub fn readF32(bytes: []const u8, i: usize) f32 { + return base.readF32(bytes, i); +} + +pub fn readI32(bytes: []const u8, i: usize) i32 { + return base.readI32(bytes, i); +} + +/// `scores` to softmax weights in place, expf(score - max), and their fp32 sum; gate 4's zero scores give 1s. +pub fn softmaxParts(s: Sums, scores: []Iv, depth: usize, scratch: []f64) Iv { + if (s.exact) { + for (scores) |*e| e.* = Iv.of(1); + } else { + var top = scores[0]; + for (scores[1..]) |v| { + // fmaxf: a NaN gives way + if (std.math.isNan(top.m) or v.m > top.m) top.m = v.m; + top.lo = @max(top.lo, v.lo); + top.hi = @max(top.hi, v.hi); + } + for (scores) |*e| e.* = e.sub(top).exp(); + } + return s.sum(scores, depth, scratch); +} + +/// 1 when a control's fault is on. +pub fn one(on: bool) usize { + return @intFromBool(on); +} diff --git a/zig/tests/cuda/contract_zonos3_windows.zig b/zig/tests/cuda/contract_zonos3_windows.zig new file mode 100644 index 00000000000..8347bf93480 --- /dev/null +++ b/zig/tests/cuda/contract_zonos3_windows.zig @@ -0,0 +1,476 @@ +//! ZONOS3's windowed sums under the contract: the codec's five, the encoder's resampler, the teacher's convolution. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_zonos3_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +fn kDeep(s: c.Shape) usize { + return s.k; +} + +pub const Depthwise = enum { codec, teacher }; + +/// Rows x channels x taps: the codec's (7 taps, a bias, history in place), the teacher's (31, zeros before row 0). +pub fn depthwiseSpec(which: Depthwise, fault: bool) c.Spec { + return switch (which) { + .codec => .{ .name = if (fault) "control: zonos3 zc_dwconv launched one row short" else "cuda zonos3_codec zc_dwconv (history in place)", .accum = .f32, .depth = kDeep, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 16, .n = 768, .k = 8 }, .{ .rows = 1, .n = 768, .k = 8 }, .{ .rows = 300, .n = 768, .k = 8 } } }, + .teacher => .{ .name = if (fault) "control: zonos3 zt_dwconv launched one tap short" else "cuda zonos3_teacher zt_dwconv", .accum = .f32, .depth = kDeep, .out = .f32, .served = &.{ .{ .rows = 64, .n = 1024, .k = 31 }, .{ .rows = 1, .n = 1024, .k = 31 }, .{ .rows = 999, .n = 1024, .k = 31 } } }, + }; +} + +/// A channel's causal convolution over the rows before and at each row, an fma chain from the oldest tap. +pub const DwConv = struct { + f: cuda.Function, + which: Depthwise, + /// control: a row (codec) or a tap (teacher) fewer than the reference + fault: bool = false, + T: usize = 0, + C: usize = 0, + /// the rows before row 0 ([taps - 1][C]: the codec's history, the teacher's zeros), then the rows + x: []f32 = &.{}, + w: []f32 = &.{}, + b: []f32 = &.{}, + dev: [3]u64 = @splat(0), + out: [2]u64 = @splat(0), + + pub const sums = {}; + + fn taps(self: *const DwConv) usize { + return if (self.which == .codec) 7 else 31; + } + + pub fn spec(self: *const DwConv) c.Spec { + return depthwiseSpec(self.which, self.fault); + } + + pub fn control(self: *const DwConv) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *DwConv, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.w); + a.free(self.b); + self.x = &.{}; + self.w = &.{}; + self.b = &.{}; + } + + pub fn prepare(self: *DwConv, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const K = self.taps(); + if (shape.rows == 0 or shape.n == 0 or shape.k != (if (self.which == .codec) K + 1 else K)) return false; + self.free(a); + const T = shape.rows; + const C = shape.n; + self.T = T; + self.C = C; + const past = K - 1; + self.x = try ref.values(a, rng, (past + T) * C, .random, 2); + self.w = try ref.values(a, rng, C * K, .random, 1); + self.b = try ref.values(a, rng, C, .random, 1); + if (self.which == .teacher) @memset(self.x[0 .. past * C], 0); + if (fill == .stress) { + @memset(self.w, 1); + @memset(self.b, 0); + const from: usize = if (self.which == .codec) 0 else past; + for (0..C) |ch| ref.stressAxis(self.x, from * C + ch, C, past + T - from, rng); + } + if (fill == .nonfinite) ref.plant(self.x[past * C ..], T, C); + self.dev = .{ try ref.input(rig, self.x[past * C ..]), try ref.input(rig, self.w), try ref.input(rig, self.b) }; + self.out[0] = try rig.output(T * C * 4); + if (self.which == .codec) self.out[1] = try rig.output(C * 6 * 4); + return true; + } + + pub fn run(self: *DwConv, rig: *rig_.Rig) !void { + const T = self.T; + const C = self.C; + const less = ref.one(self.fault); + var a: cuda.Args = .{}; + if (self.which == .codec) { + // hist [C][6]: a channel's six inputs before row 0, oldest first + const hist = try rig.gpu.gpa.alloc(f32, C * 6); + defer rig.gpu.gpa.free(hist); + for (hist, 0..) |*v, i| v.* = self.x[(i % 6) * C + i / 6]; + try ref.restore(rig, self.out[1], std.mem.sliceAsBytes(hist)); + a.add(self.dev[0]); + a.add(ref.int(T - less)); + a.add(self.dev[1]); + a.add(self.dev[2]); + a.add(self.out[1]); + a.add(self.out[0]); + a.add(ref.int(C)); + try ref.go(self.f, rig.s, (C + 255) / 256, 1, 256, 0, &a); + } else { + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(31 - less)); + a.add(ref.int(C)); + a.add(self.out[0]); + try ref.go(self.f, rig.s, (C + 255) / 256, T, 256, 0, &a); + } + } + + pub fn count(self: *const DwConv) usize { + return self.T * self.C + (if (self.which == .codec) self.C * 6 else 0); + } + + pub fn solve(self: *const DwConv, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const T = self.T; + const C = self.C; + const K = self.taps(); + var scratch: [32]f64 = undefined; + var terms: [32]Iv = undefined; + for (0..C) |ch| { + for (0..T) |t| { + var n: usize = 0; + if (self.which == .codec) { + terms[0] = Iv.of(self.b[ch]); + n = 1; + } + for (0..K) |j| { + // the teacher's kernel skips the rows before row 0 + if (self.which == .teacher and t + j < K - 1) continue; + terms[n] = Iv.of(self.w[ch * K + j]).mul(Iv.of(self.x[(t + j) * C + ch])); + n += 1; + } + out[t * C + ch] = s.sum(terms[0..n], n, &scratch); + } + if (self.which == .codec) for (0..6) |j| { + out[T * C + ch * 6 + j] = Iv.of(self.x[(T + j) * C + ch]); + }; + } + } +}; + +const book_rows = 4096; +const used_rows = 16; +const residuals = 9; + +/// Frames x the latent's width x its ten terms. +pub fn latentSpec(fault: bool) c.Spec { + return .{ .name = if (fault) "control: zonos3 zc_latent launched one row short" else "cuda zonos3_codec zc_latent (in place)", .accum = .f32, .depth = kDeep, .out = .f32, .in_place = true, .served = &.{ .{ .rows = 16, .n = 1024, .k = 10 }, .{ .rows = 1, .n = 1024, .k = 10 }, .{ .rows = 300, .n = 1024, .k = 10 } } }; +} + +/// z plus the nine residual codebooks' rows of a frame's codes, in codebook order. +pub const Latent = struct { + f: cuda.Function, + /// control: the launch covers rows - 1 rows + fault: bool = false, + shape: c.Shape = undefined, + z: []f32 = &.{}, + /// [9][4096][n] as the kernel strides it; the codes stay below `used_rows` + tables: []f32 = &.{}, + ids: []i32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Latent) c.Spec { + return latentSpec(self.fault); + } + + pub fn control(self: *const Latent) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Latent, a: std.mem.Allocator) void { + a.free(self.z); + a.free(self.tables); + a.free(self.ids); + self.z = &.{}; + self.tables = &.{}; + self.ids = &.{}; + } + + fn row(self: *const Latent, book: usize, code: usize) []f32 { + return self.tables[(book * book_rows + code) * self.shape.n ..][0..self.shape.n]; + } + + pub fn prepare(self: *Latent, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != residuals + 1) return false; + self.free(a); + self.shape = shape; + const T = shape.rows; + const n = shape.n; + self.z = try ref.values(a, rng, T * n, .random, 2); + self.tables = try a.alloc(f32, ((residuals - 1) * book_rows + used_rows) * n); + @memset(self.tables, 0); + for (0..residuals) |book| for (0..used_rows) |code| for (self.row(book, code)) |*v| { + v.* = rng.float(f32) * 2 - 1; + }; + self.ids = try a.alloc(i32, T * 10); + for (self.ids, 0..) |*v, i| v.* = if (fill == .stress) @intCast(i % 10) else @intCast(rng.uintLessThan(u32, used_rows)); + if (fill == .stress) for (0..n) |d| { + var line: [residuals + 1]f32 = undefined; + ref.stress(&line, rng); + for (0..T) |t| self.z[t * n + d] = line[0]; + for (0..residuals) |book| self.row(book, book + 1)[d] = line[1 + book]; + }; + if (fill == .nonfinite) ref.plant(self.z, T, n); + self.dev = .{ try ref.input(rig, self.ids), try ref.input(rig, self.tables) }; + self.out = try rig.output(T * n * 4); + return true; + } + + pub fn run(self: *Latent, rig: *rig_.Rig) !void { + const n = self.shape.n; + try ref.restore(rig, self.out, std.mem.sliceAsBytes(self.z)); + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(self.out); + a.add(ref.int(n)); + try ref.go(self.f, rig.s, (n + 255) / 256, self.shape.rows - ref.one(self.fault), 256, 0, &a); + } + + pub fn count(self: *const Latent) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Latent, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + var scratch: [residuals + 1]f64 = undefined; + for (out, 0..) |*o, at| { + var terms: [residuals + 1]Iv = undefined; + terms[0] = Iv.of(self.z[at]); + for (0..residuals) |book| terms[1 + book] = Iv.of(self.row(book, @intCast(self.ids[at / n * 10 + 1 + book]))[at % n]); + o.* = s.sum(&terms, residuals + 1, &scratch); + } + } +}; + +const hop = 184; + +/// Head frames x the branch's FFT size x the frames a sample overlaps (736 / 184 and 2,208 / 184). +pub fn olaSpec(fault: bool) c.Spec { + return .{ .name = if (fault) "control: zonos3 zc_ola with its hop one sample long" else "cuda zonos3_codec zc_ola", .accum = .f32, .depth = kDeep, .out = .f32, .served = &.{ .{ .rows = 16, .n = 736, .k = 4 }, .{ .rows = 16, .n = 2208, .k = 12 }, .{ .rows = 2, .n = 736, .k = 4 }, .{ .rows = 64, .n = 2208, .k = 12 } } }; +} + +/// A sample's overlapping windowed frames summed in frame order, over the same frames' squared windows. +pub const Ola = struct { + f: cuda.Function, + /// control: the device's hop is 185 + fault: bool = false, + F: usize = 0, + N: usize = 0, + n0: usize = 0, + samples: usize = 0, + frames: []f32 = &.{}, + win2: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Ola) c.Spec { + return olaSpec(self.fault); + } + + pub fn control(self: *const Ola) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Ola, a: std.mem.Allocator) void { + a.free(self.frames); + a.free(self.win2); + self.frames = &.{}; + self.win2 = &.{}; + } + + /// The frames whose window covers centered sample `i` of the launch: first and one past the last. + fn span(self: *const Ola, i: usize) [2]usize { + const p = self.n0 + i + self.N / 2; + return .{ if (p < self.N) 0 else (p - self.N) / hop + 1, @min(p / hop, self.F - 1) + 1 }; + } + + pub fn prepare(self: *Ola, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n < 2 * hop or shape.n % hop != 0 or shape.k != shape.n / hop) return false; + self.free(a); + self.F = shape.rows; + self.N = shape.n; + const all = if (self.F > 1) (self.F - 1) * hop else self.N / 2; + self.n0 = if (fill == .stress) 0 else rng.uintLessThan(usize, all / 2); + self.samples = all - self.n0; + self.frames = try ref.values(a, rng, self.F * self.N, .random, 2); + self.win2 = try a.alloc(f32, self.N); + for (self.win2) |*v| v.* = if (fill == .stress) 1 else 0.1 + rng.float(f32); + if (fill == .stress) for (0..self.samples) |i| { + const fs = self.span(i); + var line: [16]f32 = undefined; + ref.stress(line[0 .. fs[1] - fs[0]], rng); + for (fs[0]..fs[1]) |fr| self.frames[fr * self.N + (i + self.N / 2 - fr * hop)] = line[fr - fs[0]]; + }; + if (fill == .nonfinite) ref.plant(self.frames, self.F, self.N); + self.dev = .{ try ref.input(rig, self.frames), try ref.input(rig, self.win2) }; + self.out = try rig.output(self.samples * 4); + return true; + } + + pub fn run(self: *Ola, rig: *rig_.Rig) !void { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + a.add(ref.int(self.F)); + a.add(ref.int(self.N)); + a.add(ref.int(hop + ref.one(self.fault))); + a.add(ref.long(self.n0)); + a.add(ref.long(self.samples)); + a.add(self.out); + try ref.go(self.f, rig.s, (self.samples + 255) / 256, 1, 256, 0, &a); + } + + pub fn count(self: *const Ola) usize { + return self.samples; + } + + pub fn solve(self: *const Ola, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var scratch: [16]f64 = undefined; + for (out, 0..) |*o, i| { + const fs = self.span(i); + const p = self.n0 + i + self.N / 2; + var top: [16]Iv = undefined; + var env: [16]Iv = undefined; + for (fs[0]..fs[1]) |fr| { + top[fr - fs[0]] = Iv.of(self.frames[fr * self.N + p - fr * hop]); + env[fr - fs[0]] = Iv.of(self.win2[p - fr * hop]); + } + const n = fs[1] - fs[0]; + o.* = s.sum(top[0..n], n, &scratch).div(s.sum(env[0..n], n, &scratch)); + } + } +}; + +pub const Taps = enum { mix, resample, resample_in }; + +const frame = 2944; + +/// Frames x a frame's samples x taps: the mixer's 2 x 127, the resamplers' 770 (736 to 735) and 769 (735 to 736). +pub fn tapsSpec(which: Taps, fault: bool) c.Spec { + return switch (which) { + .mix => .{ .name = if (fault) "control: zonos3 zc_mix reading its branches one sample early" else "cuda zonos3_codec zc_mix", .accum = .f32, .depth = kDeep, .out = .f32, .served = &.{ .{ .rows = 4, .n = frame, .k = 254 }, .{ .rows = 1, .n = frame, .k = 254 }, .{ .rows = 16, .n = frame, .k = 254 } } }, + .resample => .{ .name = if (fault) "control: zonos3 zc_resample reading its input one sample early" else "cuda zonos3_codec zc_resample", .accum = .f32, .depth = kDeep, .out = .f32, .served = &.{ .{ .rows = 4, .n = 2940, .k = 770 }, .{ .rows = 1, .n = 2940, .k = 770 }, .{ .rows = 16, .n = 2940, .k = 770 } } }, + .resample_in => .{ .name = if (fault) "control: zonos3 ze_resample_in reading its input one sample early" else "cuda zonos3_encoder ze_resample_in", .accum = .f32, .depth = kDeep, .out = .f32, .served = &.{ .{ .rows = 4, .n = frame, .k = 769 }, .{ .rows = 1, .n = frame, .k = 769 }, .{ .rows = 16, .n = frame, .k = 769 } } }, + }; +} + +/// An fma chain over a sample's taps in tap order, the input zero outside its length. +pub const Fir = struct { + f: cuda.Function, + which: Taps, + /// control: the device's input starts one sample early + fault: bool = false, + first: usize = 0, + samples: usize = 0, + total: usize = 0, + /// the mixer's two branches are `total` apart + x: []f32 = &.{}, + w: []f32 = &.{}, + dev: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Fir) c.Spec { + return tapsSpec(self.which, self.fault); + } + + pub fn control(self: *const Fir) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Fir, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.w); + self.x = &.{}; + self.w = &.{}; + } + + /// Phases x taps of the kernel, and the input and output steps of a phase cycle. + fn geometry(self: *const Fir) [4]usize { + return switch (self.which) { + .mix => .{ 2, 127, 1, 1 }, + .resample => .{ 735, 770, 736, 735 }, + .resample_in => .{ 736, 769, 735, 736 }, + }; + } + + pub fn prepare(self: *Fir, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + const geo = self.geometry(); + self.samples = shape.rows * shape.n; + self.first = if (fill == .stress or self.which == .resample_in) 0 else rng.uintLessThan(usize, 2000); + // the input ends inside the last outputs' taps + self.total = (self.first + self.samples) * geo[2] / geo[3] + rng.uintLessThan(usize, 60); + const branches: usize = if (self.which == .mix) 2 else 1; + self.x = try ref.values(a, rng, branches * self.total, .random, 1); + self.w = try ref.values(a, rng, geo[0] * geo[1], .random, 1); + if (fill == .stress) { + @memset(self.w, 1); + for (self.x) |*v| v.* = @floatFromInt(1 + 2 * rng.uintLessThan(u32, 128)); + ref.stress(self.x[0..@min(64, self.total)], rng); + } + if (fill == .nonfinite) { + self.x[5] = ref.nan; + self.x[self.total / 2] = ref.inf; + self.x[self.x.len - 3] = -ref.inf; + } + self.dev = .{ try ref.input(rig, self.x), try ref.input(rig, self.w) }; + self.out = try rig.output(self.samples * 4); + return true; + } + + pub fn run(self: *Fir, rig: *rig_.Rig) !void { + const x = ref.before(self.dev[0], ref.one(self.fault)); + var a: cuda.Args = .{}; + a.add(x); + if (self.which == .mix) a.add(ref.long(self.total)); + a.add(ref.long(self.total)); + a.add(self.dev[1]); + if (self.which != .resample_in) a.add(ref.long(self.first)); + a.add(ref.long(self.samples)); + a.add(self.out); + try ref.go(self.f, rig.s, (self.samples + 255) / 256, 1, 256, 0, &a); + } + + pub fn count(self: *const Fir) usize { + return self.samples; + } + + pub fn solve(self: *const Fir, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const geo = self.geometry(); + const terms = try a.alloc(Iv, 800); + defer a.free(terms); + var scratch: [800]f64 = undefined; + const total: i64 = @intCast(self.total); + for (out, 0..) |*o, i| { + const m = self.first + i; + var n: usize = 0; + if (self.which == .mix) { + for (0..2) |b| for (0..127) |j| { + const p = @as(i64, @intCast(m + j)) - 63; + if (p < 0 or p >= total) continue; + terms[n] = Iv.of(self.w[b * 127 + j]).mul(Iv.of(self.x[b * self.total + @as(usize, @intCast(p))])); + n += 1; + }; + } else { + const phase = m % geo[0]; + for (0..geo[1]) |j| { + const p = @as(i64, @intCast(geo[2] * (m / geo[0]) + j)) - 17; + if (p < 0 or p >= total) continue; + terms[n] = Iv.of(self.w[phase * geo[1] + j]).mul(Iv.of(self.x[@intCast(p)])); + n += 1; + } + } + o.* = s.sum(terms[0..n], @max(n, 1), &scratch); + } + } +}; From fcbd993588819294b56ce678528599e8aa77d47e Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:44:43 +0000 Subject: [PATCH 332/361] zonos3 docs: the contract tests and controls for all 40 kernels --- docs/recipes/zonos3-mini.md | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 57c72eaee96..73afc6fb6bc 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -4,9 +4,8 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records what is ported, where every source came from, and how each part was checked, so the checks can be rerun. -Status: a work in progress on one branch, proposed in #3615. Every kernel launch has its limits record, but only four -of the 40 kernels have numeric contract tests and none has a planted control of its own; the quality suite has not -been run on this build. +Status: a work in progress on one branch, proposed in #3615. All 40 kernels have their limits records, numeric +contract tests and a planted control each; the quality suite has not been run on this build. ## Sources @@ -264,12 +263,30 @@ of the four compilers. The audit also reports 18 stale records for launches of o (`exl3_experts tf_exl3_prompt_down` and `tf_exl3_prompt_gu`, `flashnext_mtp fn_row_topk`, `qwen35 tf_q35_gdn_slots_1`, `_2` and `_4`); this branch does not change those kernels, and the same audit was not run on the base to compare. -**Numeric gates (1 to 4).** `zig/tests/cuda/contract_zonos3.zig` registers four kernels, the ones that sum: -`z3_rmsnorm`, `zc_layernorm`, `z3_linear` and `zc_linear`, through the contract's row and dense input families with -the bf16 inputs widened to the fp32 rows these kernels read. On an RTX 5090 (driver 615.71.09, images from nvcc -13.0.88), `tf-cuda-test kernel-contract zonos3` ended with +**Numeric gates (1 to 4).** `zig/tests/cuda/contract_zonos3.zig` and the `contract_zonos3_*.zig` files beside it +register all 40 kernels, 41 registrations in all because `zc_add_scaled` is tested with and without its layer scale: - (filtered) SUMMARY 4 kernels: 4 pass gates 1-4, 0 fail, 0 known findings; 0 controls: 0 red as planted, 0 missed; 0 limit problems +- the two norms and the two linears through the contract's row and dense input families, with the bf16 inputs + widened to the fp32 rows these kernels read; +- the 15 pointwise and moving kernels (`contract_zonos3_point.zig`), which have no sums: each output is checked + against the range fp32 allows around its float64 value; +- the router and the quantizer's nearest code (`contract_zonos3_pick.zig`), exact by their own stated rules; +- the other 19 kernels (`_backbone`, `_gdn`, `_attn`, `_windows`, `_conv`), each against a float64 reference that + follows the kernel's own order of sums; 18 of them sum, and for those gate 4's inputs are built so fp32 sums are + exact in any order. + +Every registration has a planted control, 41 in all: the same kernel launched wrong in one stated way (a row, a +value, a key or a block short, an input read one place late, a wrong epsilon), which gate 3 must turn red. + +Two kernels changed to pass gate 1: `zc_spec` clamped its log-magnitude with `fminf`, which drops a NaN, and now +compares; `ze_nearest` wrote an out-of-range code for a row whose every dot is NaN and now writes code 0. Neither +changes a finite input's result: every check in the table above was rerun after the change and gave the same +frames, codes and audio figures. + +On an RTX 5090 (driver 615.71.09, images from nvcc 13.0.88, the runner built for sm_80, 86, 89, 120 and 121), +`tf-cuda-test kernel-contract zonos3` ended with + + (filtered) SUMMARY 41 kernels: 41 pass gates 1-4, 0 fail, 0 known findings; 41 controls: 41 red as planted, 0 missed; 0 limit problems; gates 6450 ms, limits 9 ms The whole run on the same card and images (`tf-cuda-test kernel-contract`, 83 minutes of gates) ended with @@ -283,9 +300,6 @@ checks pass, and the three live failures are `flashnext_mtp fn_row_topk` and `ex The layer norm's test adds a term to its bound: the kernel scales in fp32 and then adds the bias, so the roundings before the bias are a fraction of the scaled value and not of the sum, which gate 4's rows make cancel. -Not done: numeric tests for the other 36 kernels, and a planted control for any of them. The four tests above rely -on the gates' shared controls only. - ## The reference's bf16 paths The publisher's CUDA code runs some parts under bf16 autocast, and those runs sit visibly away from the same code in From ab95f98b769ef70535d4a47b3f71275cb3eb9251 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:27:16 +0000 Subject: [PATCH 333/361] zonos3: the DeepSeek server build gets the request module; kernels.zig re-pinned for the four images --- zig/build/dsv41_draft.zig | 2 ++ zig/tests/fixtures/gradient-serving.tsv | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/zig/build/dsv41_draft.zig b/zig/build/dsv41_draft.zig index 17a6189d52e..e7e1b36f9b8 100644 --- a/zig/build/dsv41_draft.zig +++ b/zig/build/dsv41_draft.zig @@ -81,6 +81,8 @@ pub fn serverOn(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b m.addImport("uocr_chat", b.createModule(.{ .root_source_file = b.path("zig/src/families/uocr/chat.zig"), .target = target, .optimize = optimize })); // the server's Drama voice catalog reads the prompt builder; this engine set has no drama3 family to share m.addImport("drama_prompt", b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/prompt.zig"), .target = target, .optimize = optimize })); + // likewise ZONOS3's request side, which tells its release folder by its files + m.addImport("zonos_request", b.createModule(.{ .root_source_file = b.path("zig/src/families/zonos3/request.zig"), .target = target, .optimize = optimize })); const exe = b.addExecutable(.{ .name = name, .root_module = m }); _ = exe.getEmittedBin(); return exe; diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 07552991029..c94898230ca 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 0ada89c63783a53d138cdf33b3f3e2f961535e91448c82eeb5ca99a zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 43a403bbac618bafc5417a38f35712d14cc9de7bf7a4d45fd1a2d24d0b8eb801 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered +zig/src/cuda/kernels.zig e03c679cefb56c882767e3f02fd3404eef29662697b7b7f602b413cbcc58dc1d raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered); #4125: the inkling2_attn and inkling2_pattn images registered; the hy4_engram image registered (#4004); #4126: the inkling2_ops and inkling2_rows images registered; #4127: the inkling2_experts and inkling2_vision images registered; Mini ModelOpt and loop-math images registered; #1858: the idol_decoder image registered; #2302: the ricursive and ricursive_prep images registered; #3615: the four zonos3 images registered zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw From 6891c21c991d3516759d54d28513a7cfde1dfc50 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:47:45 +0000 Subject: [PATCH 334/361] zonos3 docs: the repo's checks, the whole contract run and the served figures on the rebased branch --- docs/recipes/zonos3-mini.md | 87 ++++++++++++++++++++----------------- 1 file changed, 47 insertions(+), 40 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 73afc6fb6bc..c2b6a9036fc 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -4,8 +4,8 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records what is ported, where every source came from, and how each part was checked, so the checks can be rerun. -Status: a work in progress on one branch, proposed in #3615. All 40 kernels have their limits records, numeric -contract tests and a planted control each; the quality suite has not been run on this build. +Status: one branch, proposed in #3615 and not yet opened as a pull request. All 40 kernels have their limits +records, numeric contract tests and a planted control each; the quality suite has not been run on this build. ## Sources @@ -89,8 +89,9 @@ the difference. The port has no bf16 path and none is planned as an option. ## How it was checked -All figures below were measured on one RTX 5090 (driver 615.71, nvcc 13.3, Zig 0.17.0, `-Dsm=120`) at branch commit -`39a2864ef`, with every reference dump regenerated for that run. +All figures below were measured on one RTX 5090 (driver 615.71, nvcc 13.3, Zig 0.17.0, `-Dsm=120`). The table of +port-side checks was last run in full on the branch rebased onto main `9489c3817`, with the contract tests and the +two kernel changes they brought in; the reference dumps are one set, regenerated before the first full run. ### The reference side @@ -153,46 +154,42 @@ I have not yet found whether a reduction order or the padded rows explain it. ### Sampled speech The reference draws with PyTorch's generator, so sampled frames cannot match it; a seeded draw is defined by -TensorFold's keyed sampler instead. With it, the standalone tool gave byte-identical WAV files for one seeded -request run twice, and Whisper transcribed that 4.9 s reply with no errors. The figures in the rest of this section -and in the serving table below were measured before the sampler moved to the keyed one (commit 39a2864ef, the -family's own seeded generator) and have not been repeated since. - -The served build with the keyed sampler, one seeded request of 746,760 PCM bytes (373,380 samples, 8.5 s at -44.1 kHz): sent again, sent streamed, and sent while two other requests -arrived, it returned the same bytes each time. The server runs one lane and does not queue: the two requests that -arrived while it spoke were refused with 503 `engine_busy` ("speech output capacity is full"), so there is no -concurrent decoding to compare a solo reply with yet. - -Two indirect checks: - -- **Repeatability:** the served route returns the same bytes for the same seed, and a streamed reply's bytes equal - the whole reply's. +TensorFold's keyed sampler instead. The checks of it are on the served build, at the default sampling settings: + +- **Repeatability:** one seeded request of 1,569,960 PCM bytes (784,980 samples, 17.8 s at 44.1 kHz) returned the + same bytes sent whole three times, streamed three times, and once while two other requests arrived. +- **No concurrent decoding to compare:** the server runs one lane and does not queue. The two requests that arrived + while it spoke were refused with 503 `engine_busy`, so there is no solo against concurrent comparison yet. +- **Transcription:** Whisper large-v3-turbo (resampled to 16 kHz) transcribed that 17.8 s reply, 49 words in the + Rupert voice, with no errors. - **Cloned voices:** two clips sent as `ref_audio` (the release's Cillian clip, and its Thaddeus clip as 48 kHz - stereo) each gave speech that Whisper transcribed with no errors. By the release's speaker encoder, each output's - cosine to its own source clip was 0.78 and 0.83, against 0.21 and 0.17 to the other clip. -- **Transcription:** Whisper large-v3-turbo (resampled to 16 kHz) transcribed the greedy test sentence with no - errors, from the port and from the reference alike, and a 62-word sampled passage with word error rates of 0.033 - and 0.016 in two voices; each error was the word "TensorFold". + stereo) each gave speech that Whisper transcribed with no errors. + +Measured earlier, with the family's own seeded generator before the sampler moved to the keyed one, and not +repeated since: by the release's speaker encoder each cloned output's cosine to its own source clip was 0.78 and +0.83, against 0.21 and 0.17 to the other clip; and Whisper's word error rates on a 62-word sampled passage were +0.033 and 0.016 in two voices, each error the word "TensorFold". It also transcribed the greedy test sentence with +no errors, from the port and from the reference alike. None of these is a gate. ### The served route -`tensorfold-native serve RELEASE --parallel 1`, default context 4,096 and 2,000 frames a request: +`tensorfold-native serve RELEASE --parallel 1`, default context 4,096 and 2,000 frames a request, after one short +warm-up request: | Measure | Value | | --- | --- | -| A 19.4 s sampled reply, whole | 1.28 s (15 times real time) | -| The same reply streamed | first response byte at 0.06 s, done at 1.29 s, bytes equal to the whole reply | +| The 17.8 s sampled reply, whole (three runs) | 0.61 to 0.62 s (29 times real time) | +| The same reply streamed (three runs) | first response byte at 0.04 s, done at 0.62 s, bytes equal to the whole reply | | Device memory in use after it | 3.57 GiB (2.36 GiB of it weights) | | Device memory once a clip has been cloned | 8.82 GiB (the clip encoder adds 4.43 GiB of weights) | | The first request with a clip (9.7 s), which loads the encoder | 9.0 s | -| Later requests with a clip: a 9.7 s mono clip, a 15.4 s stereo 48 kHz clip | 1.07 s, 1.53 s | -| A second request while one runs | 503 | +| Later requests with a clip: a 9.7 s mono clip, a 15.4 s stereo 48 kHz clip | 0.93 s, 1.32 s | +| A second and a third request while one runs | 503 each | | An unknown voice, `top_k` above 4,096, malformed `speaker_reference_codes`, a `ref_audio` that is no WAV or is under half a second | 400 with the reason | -The standalone tool measured the parts: 22.0 s of sampled audio took 1.15 s to generate and 0.27 s to decode; the -decoder alone turns 11.4 s of codes into audio in 0.13 s; a 9.7 s clip encodes in 0.75 s and a 47.3 s clip in 5.1 s -(the acoustic branch 0.48 s and the teacher 0.26 s a lane). There are no CUDA graphs and the sampler runs on the host; none of this is tuned. +The standalone tool measured the parts: the decoder alone turns 11.4 s of codes into audio in 0.13 s; a 9.7 s clip +encodes in 0.75 s and a 47.3 s clip in 5.1 s (the acoustic branch 0.48 s and the teacher 0.26 s a lane). There are +no CUDA graphs and the sampler runs on the host; none of this is tuned. ### A test page @@ -214,14 +211,23 @@ browser by an automated test. ### Repo checks -`zig fmt --check build.zig zig`, `tools/zig/lean_check.py` (0 new over the base), `tools/zig/cuda_common_check.py` -(0 violations) and `zig build test-cuda-host` pass; the family's host tests run in it and alone as -`zig build test-zonos-host`. On a machine whose umask is 0002 one unrelated test in that suite -(`serve --config`, which refuses a group-writable file) fails; it passes under umask 022. +On the branch rebased onto main `9489c3817`, the no-GPU workflow's steps were run on one Linux machine as the +workflow runs them (`-Dfixed-cpu`, its test timeouts) and all passed: + +- `zig fmt --check build.zig zig`; `tools/zig/lean_check.py` against the base with `lean_new.py` (221 problems on + both, 0 new); `tools/zig/cuda_common_check.py` (0 violations), `cuda_fragment_check.py` (0 misses) and their unit + tests; `host_tests_test.py`. +- `zig build test-host-a`, `test-host-b`, `test-kernel-contract`, `test-golden`, + `test-gradient-serving test-qwen-serving-host`, `test-server-security test-pull-security`, `fuzz-cortheon`, `test` + and `check-release-paths`. +- The family's host tests alone (`zig build test-zonos-host`), with Drama's and the CUDA host suite + (`test-drama-host test-cuda-host`). -`zig build test-kernel-contract` passes with the family's records joined. +They ran under umask 022: with 0002 one unrelated test (`serve --config`, which refuses a group-writable file) +fails. The macOS and Metal jobs were not run, and neither was any quality suite. -Not run: `zig build test`, `test-golden`, and any quality suite. +The family registers four kernel images, so `zig/tests/fixtures/gradient-serving.tsv` re-pins +`zig/src/cuda/kernels.zig`, as earlier image registrations did. ### Memory admission @@ -288,9 +294,10 @@ On an RTX 5090 (driver 615.71.09, images from nvcc 13.0.88, the runner built for (filtered) SUMMARY 41 kernels: 41 pass gates 1-4, 0 fail, 0 known findings; 41 controls: 41 red as planted, 0 missed; 0 limit problems; gates 6450 ms, limits 9 ms -The whole run on the same card and images (`tf-cuda-test kernel-contract`, 83 minutes of gates) ended with +The whole run on the same card and images (`tf-cuda-test kernel-contract`, 83 minutes of gates and 15 of limits, +while other builds shared the machine's CPU) ended with - SUMMARY 647 kernels: 647 pass gates 1-4, 0 fail, 8 known findings; 418 controls: 418 red as planted, 0 missed; 186 limit problems + SUMMARY 684 kernels: 684 pass gates 1-4, 0 fail, 8 known findings; 459 controls: 459 red as planted, 0 missed; 186 limit problems; gates 4966609 ms, limits 899084 ms and exit code 1 for the limit problems. None of the 186 names a ZONOS3 launch: all 40 of the family's live launch checks pass, and the three live failures are `flashnext_mtp fn_row_topk` and `exl3_experts tf_exl3_prompt_gu` and From bc896d4c2b404311141821ac4a830a7153a2ab57 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:43:52 +0000 Subject: [PATCH 335/361] zonos3 docs: the macOS build and unit tests --- docs/recipes/zonos3-mini.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index c2b6a9036fc..652468a9130 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -224,7 +224,12 @@ workflow runs them (`-Dfixed-cpu`, its test timeouts) and all passed: (`test-drama-host test-cuda-host`). They ran under umask 022: with 0002 one unrelated test (`serve --config`, which refuses a group-writable file) -fails. The macOS and Metal jobs were not run, and neither was any quality suite. +fails. + +On macOS (an M5 Ultra) the default build and `zig build native` succeed, and `zig build test` fails one test, GLM's +`a failed compile releases every pipeline built before it` (expected 52, found 64), which fails the same way on main +`9489c3817` there. The family has no Metal path; the Metal contract jobs were not run, and neither was any quality +suite. The family registers four kernel images, so `zig/tests/fixtures/gradient-serving.tsv` re-pins `zig/src/cuda/kernels.zig`, as earlier image registrations did. From 2482121c9a15ebf107a3da67c466456faa7c7319 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:56:01 +0000 Subject: [PATCH 336/361] zonos3 docs: the checks rerun on main 6d0a128b0, and Drama 3 from main and from the branch on Metal --- docs/recipes/zonos3-mini.md | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 652468a9130..af33898cc38 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -90,7 +90,7 @@ the difference. The port has no bf16 path and none is planned as an option. ## How it was checked All figures below were measured on one RTX 5090 (driver 615.71, nvcc 13.3, Zig 0.17.0, `-Dsm=120`). The table of -port-side checks was last run in full on the branch rebased onto main `9489c3817`, with the contract tests and the +port-side checks was last run in full on the branch rebased onto main `6d0a128b0`, with the contract tests and the two kernel changes they brought in; the reference dumps are one set, regenerated before the first full run. ### The reference side @@ -178,12 +178,12 @@ warm-up request: | Measure | Value | | --- | --- | -| The 17.8 s sampled reply, whole (three runs) | 0.61 to 0.62 s (29 times real time) | +| The 17.8 s sampled reply, whole (three runs) | 0.61 s (29 times real time) | | The same reply streamed (three runs) | first response byte at 0.04 s, done at 0.62 s, bytes equal to the whole reply | | Device memory in use after it | 3.57 GiB (2.36 GiB of it weights) | | Device memory once a clip has been cloned | 8.82 GiB (the clip encoder adds 4.43 GiB of weights) | | The first request with a clip (9.7 s), which loads the encoder | 9.0 s | -| Later requests with a clip: a 9.7 s mono clip, a 15.4 s stereo 48 kHz clip | 0.93 s, 1.32 s | +| Later requests with a clip: a 9.7 s mono clip, a 15.4 s stereo 48 kHz clip | 0.92 s, 1.31 to 1.32 s | | A second and a third request while one runs | 503 each | | An unknown voice, `top_k` above 4,096, malformed `speaker_reference_codes`, a `ref_audio` that is no WAV or is under half a second | 400 with the reason | @@ -211,8 +211,8 @@ browser by an automated test. ### Repo checks -On the branch rebased onto main `9489c3817`, the no-GPU workflow's steps were run on one Linux machine as the -workflow runs them (`-Dfixed-cpu`, its test timeouts) and all passed: +On the branch rebased onto main `6d0a128b0`, the no-GPU workflow's steps were run on one Linux machine as the +workflow runs them (`-Dfixed-cpu`, its test timeouts) and passed: - `zig fmt --check build.zig zig`; `tools/zig/lean_check.py` against the base with `lean_new.py` (221 problems on both, 0 new); `tools/zig/cuda_common_check.py` (0 violations), `cuda_fragment_check.py` (0 misses) and their unit @@ -224,12 +224,19 @@ workflow runs them (`-Dfixed-cpu`, its test timeouts) and all passed: (`test-drama-host test-cuda-host`). They ran under umask 022: with 0002 one unrelated test (`serve --config`, which refuses a group-writable file) -fails. +fails. In the first run of `test-host-a` one real-clock test of the rank bring-up (`two ranks settle on the real +clock and agree on one plan and view`) failed while other jobs shared the CPU; the step passed when run again alone. -On macOS (an M5 Ultra) the default build and `zig build native` succeed, and `zig build test` fails one test, GLM's -`a failed compile releases every pipeline built before it` (expected 52, found 64), which fails the same way on main -`9489c3817` there. The family has no Metal path; the Metal contract jobs were not run, and neither was any quality -suite. +On macOS (an M5 Ultra) the default build, `zig build native` and `zig build test` pass. The family has no Metal +path; the Metal contract jobs were not run, and neither was any quality suite. + +The branch changes the speech route Drama 3 is served through and moves Drama's `torch.save` reader and WAV code to +core, so Drama 3 (`fishaudio/drama-3`) was run on that M5 Ultra from main `6d0a128b0` and from the branch: six +`drama3-generate` runs (greedy, seeded, a reference clip encoded, a cloned voice, streamed PCM, frames) three times +each, and four `/v1/audio/speech` requests (seeded whole, seeded streamed PCM, default, sampled) twice from each of +two server starts. Every output is byte-identical between the two, and the speeds agree (the cloned run 73.2 to 73.6 +frames a second on main, 73.3 to 73.5 on the branch). Drama on CUDA was not run: the checkpoint does not fit the +5090. The family registers four kernel images, so `zig/tests/fixtures/gradient-serving.tsv` re-pins `zig/src/cuda/kernels.zig`, as earlier image registrations did. @@ -297,10 +304,10 @@ frames, codes and audio figures. On an RTX 5090 (driver 615.71.09, images from nvcc 13.0.88, the runner built for sm_80, 86, 89, 120 and 121), `tf-cuda-test kernel-contract zonos3` ended with - (filtered) SUMMARY 41 kernels: 41 pass gates 1-4, 0 fail, 0 known findings; 41 controls: 41 red as planted, 0 missed; 0 limit problems; gates 6450 ms, limits 9 ms + (filtered) SUMMARY 41 kernels: 41 pass gates 1-4, 0 fail, 0 known findings; 41 controls: 41 red as planted, 0 missed; 0 limit problems; gates 6395 ms, limits 8 ms The whole run on the same card and images (`tf-cuda-test kernel-contract`, 83 minutes of gates and 15 of limits, -while other builds shared the machine's CPU) ended with +while other builds shared the machine's CPU), made on the earlier base `9489c3817` and not repeated since, ended with SUMMARY 684 kernels: 684 pass gates 1-4, 0 fail, 8 known findings; 459 controls: 459 red as planted, 0 missed; 186 limit problems; gates 4966609 ms, limits 899084 ms From a1c2f20867d34e5b2e1a7069a4c7dd519d11a9d7 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:59:17 +0000 Subject: [PATCH 337/361] zonos3 docs: the Drama speeds to two places --- docs/recipes/zonos3-mini.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index af33898cc38..11c6cb94b8c 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -234,8 +234,8 @@ The branch changes the speech route Drama 3 is served through and moves Drama's core, so Drama 3 (`fishaudio/drama-3`) was run on that M5 Ultra from main `6d0a128b0` and from the branch: six `drama3-generate` runs (greedy, seeded, a reference clip encoded, a cloned voice, streamed PCM, frames) three times each, and four `/v1/audio/speech` requests (seeded whole, seeded streamed PCM, default, sampled) twice from each of -two server starts. Every output is byte-identical between the two, and the speeds agree (the cloned run 73.2 to 73.6 -frames a second on main, 73.3 to 73.5 on the branch). Drama on CUDA was not run: the checkpoint does not fit the +two server starts. Every output is byte-identical between the two, and the speeds agree (the cloned run 73.21 to 73.55 +frames a second on main, 73.31 to 73.49 on the branch). Drama on CUDA was not run: the checkpoint does not fit the 5090. The family registers four kernel images, so `zig/tests/fixtures/gradient-serving.tsv` re-pins From 64af850eb531a9a5d3db64c70c9bdd03e5a2fa57 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:05:25 +0000 Subject: [PATCH 338/361] zonos3 docs: the status line names the pull request --- docs/recipes/zonos3-mini.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 11c6cb94b8c..22ad8409be4 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -4,7 +4,7 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records what is ported, where every source came from, and how each part was checked, so the checks can be rerun. -Status: one branch, proposed in #3615 and not yet opened as a pull request. All 40 kernels have their limits +Status: one branch, proposed in #3615 and open as draft pull request #3720. All 40 kernels have their limits records, numeric contract tests and a planted control each; the quality suite has not been run on this build. ## Sources From 527ad7c6a350b95ae64736439a2a88a5fbed3788 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:32:44 +0000 Subject: [PATCH 339/361] zonos3 docs: the page after the rebase onto main with #4609: reply options, reruns, the Drama 3 A/B, the shared code left Main's reply options (24-bit and float WAV, FLAC, sample_rate, stereo) apply to ZONOS3's whole replies. The port-side checks, the repo checks and the Drama 3 A/B were run again on main 281d81b8b; the reader and WAV moves left the shared-code list with #3719, and the voices holder and parseFrom with #4609. --- docs/recipes/zonos3-mini.md | 64 ++++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 29 deletions(-) diff --git a/docs/recipes/zonos3-mini.md b/docs/recipes/zonos3-mini.md index 22ad8409be4..7c674006913 100644 --- a/docs/recipes/zonos3-mini.md +++ b/docs/recipes/zonos3-mini.md @@ -4,7 +4,7 @@ publisher released, and serves it on `POST /v1/audio/speech`. This page records what is ported, where every source came from, and how each part was checked, so the checks can be rerun. -Status: one branch, proposed in #3615 and open as draft pull request #3720. All 40 kernels have their limits +Status: one branch, proposed in #3615 and open as pull request #3720. All 40 kernels have their limits records, numeric contract tests and a planted control each; the quality suite has not been run on this build. ## Sources @@ -56,7 +56,9 @@ members, a pickle VM limited to the tensor allow-list, nested state dicts named runs in the publisher's lanes: 20 s each, a later lane carrying 10 s of what came before. - **Served route** (`native/zonos_host.zig`, `server/zonos_speech.zig`): one request at a time; the release's 27 default voices by their reference codes; a caller's own voice as `ref_audio` (a WAV file in base64, encoded by the - engine) or as `speaker_reference_codes`; WAV or PCM, whole or streamed in chunks of 1, 2, 4, 8 and then 15 frames. + engine) or as `speaker_reference_codes`; WAV or PCM, whole or streamed in chunks of 1, 2, 4, 8 and then 15 frames, + and the server's other reply options as for any speech model (24-bit and float WAV, FLAC, another `sample_rate`, + stereo), whole replies only. The clip encoder's weights load on the first request that brings a clip. Refused or absent: clips in formats other than WAV, text normalization (text is spoken as typed), speaker and control @@ -90,8 +92,8 @@ the difference. The port has no bf16 path and none is planned as an option. ## How it was checked All figures below were measured on one RTX 5090 (driver 615.71, nvcc 13.3, Zig 0.17.0, `-Dsm=120`). The table of -port-side checks was last run in full on the branch rebased onto main `6d0a128b0`, with the contract tests and the -two kernel changes they brought in; the reference dumps are one set, regenerated before the first full run. +port-side checks was run in full again on the branch rebased onto main `281d81b8b`, and every figure in it came out +as before; the reference dumps are one set, regenerated before the first full run. ### The reference side @@ -191,6 +193,14 @@ The standalone tool measured the parts: the decoder alone turns 11.4 s of codes encodes in 0.75 s and a 47.3 s clip in 5.1 s (the acoustic branch 0.48 s and the teacher 0.26 s a lane). There are no CUDA graphs and the sampler runs on the host; none of this is tuned. +The table above was measured on main `6d0a128b0`. After the rebase onto main `281d81b8b`, the branch before and after +it were served side by side on the 5090 and gave the same bytes, status and headers for twelve requests (a default +voice, a named one, greedy reference codes, sampled, a cloned 48 kHz stereo clip, whole and streamed PCM, and four +refusals) and the same 503s to requests that arrived while one spoke; the rebased build admitted the same +3,828,406,528 bytes at load and spoke a 17.1 s reply in 0.59 s whole (first streamed byte at 0.04 s). Its 24-bit, +float and FLAC replies decode to the 16-bit reply's samples within one 16-bit step, its stereo replies carry the same +samples in both channels, its 24 and 48 kHz replies have the resampled length, and a stream at 24 kHz is refused. + ### A test page `tools/zig/zonos3_test_page.py` serves a small browser page (`zonos3_test_page.html`) and passes its three routes @@ -211,32 +221,30 @@ browser by an automated test. ### Repo checks -On the branch rebased onto main `6d0a128b0`, the no-GPU workflow's steps were run on one Linux machine as the +On the branch rebased onto main `281d81b8b`, the no-GPU workflow's steps were run on one Linux machine as the workflow runs them (`-Dfixed-cpu`, its test timeouts) and passed: -- `zig fmt --check build.zig zig`; `tools/zig/lean_check.py` against the base with `lean_new.py` (221 problems on +- `zig fmt --check build.zig zig`; `tools/zig/lean_check.py` against the base with `lean_new.py` (165 problems on both, 0 new); `tools/zig/cuda_common_check.py` (0 violations), `cuda_fragment_check.py` (0 misses) and their unit - tests; `host_tests_test.py`. + tests; `test_pdl_early_loads.py`, `host_tests_test.py`, `build_options_test.py` and `flashnext_batch_serve_test.py`. - `zig build test-host-a`, `test-host-b`, `test-kernel-contract`, `test-golden`, - `test-gradient-serving test-qwen-serving-host`, `test-server-security test-pull-security`, `fuzz-cortheon`, `test` - and `check-release-paths`. -- The family's host tests alone (`zig build test-zonos-host`), with Drama's and the CUDA host suite - (`test-drama-host test-cuda-host`). + `test-gradient-serving test-qwen-serving-host test-glm-pdl-scan`, `test-server-security test-pull-security`, + `fuzz-cortheon`, `test` and `check-release-paths`. +- The family's host tests alone (`zig build test-zonos-host`) and the CUDA host suite (`test-cuda-host`). They ran under umask 022: with 0002 one unrelated test (`serve --config`, which refuses a group-writable file) -fails. In the first run of `test-host-a` one real-clock test of the rank bring-up (`two ranks settle on the real -clock and agree on one plan and view`) failed while other jobs shared the CPU; the step passed when run again alone. +fails. -On macOS (an M5 Ultra) the default build, `zig build native` and `zig build test` pass. The family has no Metal -path; the Metal contract jobs were not run, and neither was any quality suite. +On macOS (an M5 Ultra) `zig build native` builds the rebased branch (for the Drama 3 run below); `zig build test` +there was last run before the rebase onto `281d81b8b`. The family has no Metal path; the Metal contract jobs were +not run, and neither was any quality suite. -The branch changes the speech route Drama 3 is served through and moves Drama's `torch.save` reader and WAV code to -core, so Drama 3 (`fishaudio/drama-3`) was run on that M5 Ultra from main `6d0a128b0` and from the branch: six -`drama3-generate` runs (greedy, seeded, a reference clip encoded, a cloned voice, streamed PCM, frames) three times -each, and four `/v1/audio/speech` requests (seeded whole, seeded streamed PCM, default, sampled) twice from each of -two server starts. Every output is byte-identical between the two, and the speeds agree (the cloned run 73.21 to 73.55 -frames a second on main, 73.31 to 73.49 on the branch). Drama on CUDA was not run: the checkpoint does not fit the -5090. +The branch changes the speech route Drama 3 is served through, so Drama 3 (`fishaudio/drama-3`) was served on that +M5 Ultra from main `281d81b8b` and from the rebased branch, two server starts each: `GET /v1/voices` and twelve +`/v1/audio/speech` requests, each sent twice (seeded whole WAV, seeded streamed PCM, a plain one, sampled, `top_k` 64, +a 24 kHz stereo FLAC and a 24-bit WAV reply, and the refusals of `top_k` 0 and 65, a `ref_audio`, reference codes and +an unknown voice). Every reply is byte-identical between the two builds and between starts, with no leak or panic +line. Speeds were not measured in this run. Drama on CUDA was not run: the checkpoint does not fit the 5090. The family registers four kernel images, so `zig/tests/fixtures/gradient-serving.tsv` re-pins `zig/src/cuda/kernels.zig`, as earlier image registrations did. @@ -350,11 +358,9 @@ bf16-encoded references, clones as well from fp32 codes. ## Shared code this touches -- `drama3/codec_pth.zig` moved to `core/torch_pth.zig` (its zip half to `core/torch_zip.zig`) and gained nested - checkpoints and a raw reader; Drama 3's codec loads through the same code and its host tests pass. -- `drama3/wav.zig` moved to `core/wav.zig`: both families read WAV files and resample with it. - `core/speech_api.zig`: `SpeechRequest.speaker`, an optional speaker vector, and `reference_audio`, an optional clip. -- `server/`: voices load through `speech_voices.zig`; the speech route, the sampling parser, the voices listing, - model detection and the tokenizer loader each gained a branch for a release folder, which has no `config.json` - and is recognised by `lm/zonos3_mini/params.json`. -- `native/`: `zonos3` in the CUDA open dispatch, the capabilities list and the rank refusals. +- `server/`: `speech_voices.zig` (Drama 3's voices holder, #4609) also starts and lists a release's voices; the speech + route takes `ref_audio` and `speaker_reference_codes` only with a release and calls `parseFrom` with the family's + defaults and its top-k ceiling of 4,096; model detection and the tokenizer loader each gained a branch for a + release folder, which has no `config.json` and is recognised by `lm/zonos3_mini/params.json`. +- `native/`: `zonos3` in the CUDA open dispatch (`cuda_open.zig`), the capabilities list and the rank refusals. From 0141bd0e752c6a5804e94b5052e0ff3a197fff6b Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:57:36 +0000 Subject: [PATCH 340/361] zonos3: every frame budget a load admits opens the codec, its pass no longer than the budget --max-frames below 32 gave the codec its usual 32-frame pass, longer than the budget, and the codec refused the load; budgets above the codec's 8192 frames were admitted too. The load's plan now sizes the codec's pass to the budget and refuses what the codec would; a host test opens the plan at 12, 16, 31 and 32 frames. --- zig/src/native/zonos_host.zig | 40 +++++++++++++++++++++++++++++++---- zig/src/native/zonos_open.zig | 2 +- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/zig/src/native/zonos_host.zig b/zig/src/native/zonos_host.zig index 1a765921236..2b44a7d4c27 100644 --- a/zig/src/native/zonos_host.zig +++ b/zig/src/native/zonos_host.zig @@ -31,7 +31,12 @@ pub const clip_bytes: u64 = 5_643_510_688; /// Device bytes a load takes at a context and frame budget: the weights, then each part's own count of its state. pub fn need(context: u32, frames: u32) u64 { - return weight_bytes + z3.Engine.stateBytes(.{ .max_ctx = context }) + z3.Codec.stateBytes(.{ .max_frames = frames }); + return weight_bytes + z3.Engine.stateBytes(.{ .max_ctx = context }) + z3.Codec.stateBytes(codecOptions(frames)); +} + +/// The codec at a frame budget: its usual pass, or the whole budget when that is shorter. +pub fn codecOptions(frames: u32) z3.codec.Options { + return .{ .max_frames = frames, .pass_frames = @min(frames, (z3.codec.Options{}).pass_frames) }; } const Door = struct { @@ -53,9 +58,18 @@ pub fn budget(context: u32, max_frames: ?u32) !struct { frames: u32, prompt: u32 if (context < 1025 or context > cfg.max_seqlen) return error.BadZonosContext; const frames = max_frames orelse @min(default_frames, context / 2); if (frames < C + 2 or frames >= context) return error.BadZonosFrames; + codecOptions(frames).validate() catch return error.BadZonosFrames; return .{ .frames = frames, .prompt = context - frames }; } +/// What a load opens with, before it touches the device: the budget, the codec's options and the bytes it admits. +pub const Plan = struct { frames: u32, prompt: u32, codec: z3.codec.Options, need: u64 }; + +pub fn plan(o: Options) !Plan { + const b = try budget(o.context, o.max_frames); + return .{ .frames = b.frames, .prompt = b.prompt, .codec = codecOptions(b.frames), .need = need(o.context, b.frames) }; +} + /// What a request's prompt rows name: [reference prefix | speaker row] conditions, the text from BOS to EOS, silence. pub const Layout = struct { condition_row: usize, @@ -354,15 +368,15 @@ const Host = struct { /// `dir`: a snapshot of the release's repository. pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, o: Options) !api.Opened { - const b = try budget(o.context, o.max_frames); + const b = try plan(o); const h = try gpa.create(Host); errdefer gpa.destroy(h); var rel = try z3.release.open(gpa, io, dir, null); errdefer rel.deinit(); - var door: Door = .{ .o = o, .need = need(o.context, b.frames) }; + var door: Door = .{ .o = o, .need = b.need }; const e = try z3.Engine.create(gpa, io, rel.lm, .{ .device = o.device, .max_ctx = o.context, .gate = .{ .ptr = &door, .check = Door.check } }); errdefer e.destroy(); - const codec = try z3.Codec.create(gpa, io, &e.driver, e.stream, rel.generator, rel.head, .{ .max_frames = b.frames }); + const codec = try z3.Codec.create(gpa, io, &e.driver, e.stream, rel.generator, rel.head, b.codec); errdefer codec.destroy(); if (cuda.usage(false).device > door.need) return error.LoadOverItsAdmission; const kept = try gpa.dupe(u8, dir); @@ -410,6 +424,24 @@ test "budget: the release's frame budget where the context holds it, the rest fo try t.expectError(error.BadZonosContext, budget(32769, null)); try t.expectError(error.BadZonosFrames, budget(4096, 4096)); try t.expectError(error.BadZonosFrames, budget(4096, 5)); + try t.expectEqual(@as(u32, 8192), (try budget(32768, 8192)).frames); + try t.expectError(error.BadZonosFrames, budget(32768, 8193)); +} + +test "plan: every frame budget a load admits is one the codec opens with, its pass no longer than the budget" { + const t = std.testing; + for ([_]u32{ 12, 16, 31, 32 }) |n| { + const p = try plan(.{ .max_frames = n }); + try t.expectEqual(n, p.frames); + try p.codec.validate(); + try t.expectEqual(@as(usize, n), p.codec.max_frames); + try t.expectEqual(@as(usize, @min(n, 32)), p.codec.pass_frames); + try t.expectEqual(need(4096, n), p.need); + } + try t.expectError(error.BadZonosFrames, plan(.{ .max_frames = 11 })); + const d = try plan(.{}); + try t.expectEqual(@as(usize, 32), d.codec.pass_frames); + try t.expectEqual(@as(u64, 3_828_406_528), d.need); } test "chunkFrames: a streamed reply's chunks double to a second" { diff --git a/zig/src/native/zonos_open.zig b/zig/src/native/zonos_open.zig index 235191d1613..c13809f5a77 100644 --- a/zig/src/native/zonos_open.zig +++ b/zig/src/native/zonos_open.zig @@ -47,7 +47,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c _ = zonos_host.budget(std.math.cast(u32, window) orelse 0, o.max_frames) catch |e| { problem.* = switch (e) { error.BadZonosContext => "ZONOS3 Mini supports --context 1025 through 32768", - error.BadZonosFrames => "ZONOS3 Mini's --max-frames must be at least 12 and below --context", + error.BadZonosFrames => "ZONOS3 Mini's --max-frames must be 12 through 8192 and below --context", }; return null; }; From 3795e6054c497c6259ffafe5dfc72dbdbe24ccb3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:17:24 +0000 Subject: [PATCH 341/361] changelog: #3720 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b06866ca33..d9e3b6585d6 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 +- ZONOS3 Mini text to speech on CUDA: named voices, reference codes and cloning from a clip, with frame budgets checked at load; serving checkpoints other than ZONOS3 is unchanged (#3720). + - Flash Next on CUDA: on one GPU, a prompt chunk before the last skips its last layer's MLP stream and experts, which nothing reads; tokens unchanged, and tensor-parallel passes run as before (#4885). - Inkling 2 Mini on Metal serves images under `--vision`: PNG, JPEG and WebP decode to 40-pixel patch tokens (resized only past the image budget), the 23-layer vision tower and its projector run on the GPU with the processor's rounding, and the tower's rows replace the image placeholders in a prefill chunk, split across chunks and cache restores like text rows. Without `--vision` images stay refused by name. Each picture the tower runs logs one `inkling2 image tower:` line with the picture's content hash, its rows and the SHA-256 of the BF16 rows it hands to the splice. The tower is checked against an FP64 reference on the original checkpoint, and its kernels carry contract records and planted controls (#4704, refs #4274 and #4387). Thanks to @BlivionIaG. From 6b58c7196307d0152c4d6dc17264da782412c954 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:15:48 +0800 Subject: [PATCH 342/361] contract: resolve the glm_vision image both sides registered The glm vision records joined from both sides name the glm_vision fatbin; the merged resolver dropped it with inkling2_loop_math, whose image ours replaced with inkling2_loop. --- zig/tests/cuda/contract_limits.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index 31ca5927f81..5f44a6d63a2 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -48,7 +48,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { if (std.mem.eql(u8, name, "flashnext_hcn")) return kk.flashnext_hcn; inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_vision", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "idol", "idol_decoder", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "zonos3", "zonos3_codec", "zonos3_encoder", "zonos3_teacher" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); From 63bfba0bb76ab827dcdc7778517038957ac4e207 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:18:10 +0800 Subject: [PATCH 343/361] gradient-serving: pin the merged cublaslt, vit and qwen27_slots The merge's files combine both sides (cublaslt keeps our int8 and FP4 matmul types); the pins upstream measured on its own copies no longer match, so they pin the merged bytes as the ratchet rules require. --- zig/tests/fixtures/gradient-serving.tsv | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index d8b0bf8517c..b874df8f552 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -85,7 +85,7 @@ zig/src/cuda/aot.zig bd4e41f32eebf8e75e6f40e036847aaca2900aee7628167552c661824c7 zig/src/cuda/carveout.zig 5ebe77d420ec42d1494fbe7259ce12e20e56427d8f7d931d672b7ca1240b1759 raw main 6a1feb26e (malformed TF_CUDA_CARVEOUT settings refused by name) zig/src/cuda/ck.zig 5b247901025d0f001e44c98e022729d007758ffd4719ec34b957c55dcc008e46 raw commits 739c924de, a79678c56, e40bd6eae, 186c31eed, a6f4044fc, c0a58fd30, 48ea204ac, e367c8f55, 7e082a6df; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/context.zig f7c911e93cccd4f89d4a80a8a8786c765a94864a2c22102ff128a018eb55ec1f raw commits ac38ad1da, cc50aef49, e9bf05ffd, ef23b5934; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; #2914 (the release SM refusal before any retain) -zig/src/cuda/cublaslt.zig d87f865fc03cf94bdcbe83504f74a6e569d70c10ca792b675122e9eadda26eec raw main f1ab10fe98 (Clef's joint schema head on the GPU; a new path), 52375ee098 (#2285: layout_cols, the split-K and reduction algo-config attributes and cublasLtMatmulAlgoConfigGetAttribute for Qwen3 embeddings; existing entries unchanged), #1767 (Linear.initTyped: X and W as bf16, fp16 or fp32 for Idol's denoiser; initEpilogue passes bf16, so existing plans are unchanged) +zig/src/cuda/cublaslt.zig c390144222785d4a57c85f79dcba0b7240e8650be21f691f5e29cc7e84c79f2e raw main f1ab10fe98 (Clef's joint schema head on the GPU; a new path), 52375ee098 (#2285: layout_cols, the split-K and reduction algo-config attributes and cublasLtMatmulAlgoConfigGetAttribute for Qwen3 embeddings; existing entries unchanged), #1767 (Linear.initTyped: X and W as bf16, fp16 or fp32 for Idol's denoiser; initEpilogue passes bf16, so existing plans are unchanged) zig/src/cuda/driver.zig f20856bd06afe9365ab9ca1bc39800ccb260ade2704197c033e1344a0c8dd742 raw commits e9bf05ffd, b923e554c, b2c75a98a; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/embed_rows.zig 3fa5e28ab46b4daef2c820b3ad3f7d331bc77f55ea340a7a3cac64b21584c5f4 raw #3471: Gemma 4 holds its tied embedding once; token rows read the head's 4-bit tiles; replies unchanged zig/src/cuda/exlr8.zig 1e2164096ae949a8a9a4903df82c7c0c184a6f5e1ba5ba4423038a42b0633fc6 raw @@ -113,7 +113,7 @@ zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125d zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0bd5f468ace3 raw main 13d7450fd (#2354), 7ead07c92 (bounded peer warm-up, #2512) zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw -zig/src/cuda/vit.zig 3a22b6aaf70bcf83a1d3c7624c8c554e262e69d12be07b6e6b389702f77b5877 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) +zig/src/cuda/vit.zig d97a1fd2bec87908b1cbc2bada8650cfe5ce0cce34e4642c14c887ed0c3df1b6 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged); #3790 (GLM-5.3-Flash's image tower uses the shared head-64 full attention) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw zig/src/families/flashnext/cuda_batch.zig 8610c07449aa7068535f0c547fff3339091b2a1c74f61a4dc64d470eb8cd736d raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset); TF_FLASHNEXT_GDN_CHAIN_TPR's opt-in row dispatch; unset leaves the key unchanged; this change: a one-rank prompt chunk before the last that nothing taps skips its last layer's MLP stream and experts, which head(.none) never reads; outputs unchanged zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged @@ -172,4 +172,4 @@ zig/src/families/qwen27/attention_memory.zig 49b9a2643b1499d26cd3d41066ab77351eb zig/src/families/qwen27/attention_plan.zig 898964a99410620766416c5d5a350ab96061e9d2883354875f7da9e431a9ddc4 raw #2916 (solo prompt frames; decode and shared limits retained) zig/src/families/qwen27/decode_round.zig 67ef8d3358e5239943ae80fc67bc431bf40d119206df1cc6ab9fe0505e064cde raw main 1eed88bb09 (public attentionPlan and lane-core Drafter/tail state retained), #2916 (solo prompt frames; decode and shared limits retained) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/native/qwen27_slots.zig c98070c752614213466f8e5a5c431b25ba1db7f2b4dfb686569206005342c247 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig aaf211922695f77d932d266fb91c5c8c247de9b0acc1676fee1c64e0c4e94e08 raw #2916 (solo prompt frames; decode and shared limits retained) From b7ca5fa9cf6584a0f17f8ff2cc15a79662875ae6 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:15:11 +0800 Subject: [PATCH 344/361] =?UTF-8?q?fix:=20review=20round=201=20=E2=80=94?= =?UTF-8?q?=20startup-tail=20bound,=20upstream=20modelopt=20records,=20sm?= =?UTF-8?q?=5F110=20fused=20labels?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - benchmark_server_log_test: stretch the pipe-holding descendant's sleep to 8s and the bound to 7s so a loaded full-suite run can't race it - inkling2_experts_records: move inkling2_modelopt's five launches into cuda with upstream's measured usage (its kernel, kept by the merge, has static shared tiles); pending keeps only the fork's unmeasured loop kernels - contract_limits_fatbins: restore upstream's two sm_110 fused-BF16 raised-limit labels --- zig/src/core/contract/inkling2_experts_records.zig | 12 ++++++------ zig/src/server/benchmark_server_log_test.zig | 4 ++-- zig/tests/cuda/contract_limits_fatbins.zig | 2 ++ 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/zig/src/core/contract/inkling2_experts_records.zig b/zig/src/core/contract/inkling2_experts_records.zig index 89bb1ba5820..11b04be433c 100644 --- a/zig/src/core/contract/inkling2_experts_records.zig +++ b/zig/src/core/contract/inkling2_experts_records.zig @@ -10,18 +10,18 @@ pub const cuda = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_vision tf_ink2v_embed", .symbol = "tf_ink2v_embed", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 39, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 }, .{ .regs = 30, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_rope", .symbol = "tf_ink2v_rope", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 }, .{ .regs = 14, .static = 0, .bound = 256 } }, .later_pending = true }, .{ .launch = .{ .name = "inkling2_vision tf_ink2v_scale_add", .symbol = "tf_ink2v_scale_add", .image = "inkling2_vision", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 11, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 }, .{ .regs = 12, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 46, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 45, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 96, .static = 5120, .bound = 128 }, .{ .regs = 111, .static = 5120, .bound = 128 }, .{ .regs = 111, .static = 5120, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 242, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 }, .{ .regs = 198, .static = 20480, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 17, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 19, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 20, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, }; -/// ModelOpt measured on sm_121 alone (GB10, #4387); loop is unmeasured. Missing receipts refuse there (cuda_pending). +/// The fork's loop kernels stay unmeasured; their receipts are missing on every SM (cuda_pending). pub const pending = [_]registry.CudaRecord{ .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_mix", .symbol = "tf_ink2_loop_mix", .image = "inkling2_loop", .threads = 256, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop", .threads = 256, .dynamic = 18432, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_lin", .symbol = "tf_ink2_loop_gate_lin", .image = "inkling2_loop", .threads = 128, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, .{ .launch = .{ .name = "inkling2_loop tf_ink2_loop_gate_mix", .symbol = "tf_ink2_loop_gate_mix", .image = "inkling2_loop", .threads = 256, .min_sm = 80 }, .usage = registry.none, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_plan", .symbol = "tf_ink2moe_plan", .image = "inkling2_modelopt", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 44, .static = 0, .bound = 32 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_up", .symbol = "tf_ink2moe_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 102, .static = 0, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_prompt_up", .symbol = "tf_ink2moe_prompt_up", .image = "inkling2_modelopt", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 168, .static = 0, .bound = 128 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_act", .symbol = "tf_ink2moe_act", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 18, .static = 0, .bound = 256 } }, .later_pending = true }, - .{ .launch = .{ .name = "inkling2_modelopt tf_ink2moe_combine", .symbol = "tf_ink2moe_combine", .image = "inkling2_modelopt", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 0, .static = 0, .bound = 0 }, .{ .regs = 27, .static = 0, .bound = 256 } }, .later_pending = true }, }; /// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. pub const cuda_132 = [_]registry.Override{}; diff --git a/zig/src/server/benchmark_server_log_test.zig b/zig/src/server/benchmark_server_log_test.zig index 376067930d0..53ddd2a4ca2 100644 --- a/zig/src/server/benchmark_server_log_test.zig +++ b/zig/src/server/benchmark_server_log_test.zig @@ -64,7 +64,7 @@ test "managed log: an exited child's last diagnostic without a newline reaches i defer tmp.cleanup(); var s = try Setup.init(a, &tmp); for ([_][]const u8{ - "sleep 4 & printf 'loading\\nerror: bad model child-log-key'; exit 3", // a descendant keeps the pipe open + "sleep 8 & printf 'loading\\nerror: bad model child-log-key'; exit 3", // a descendant keeps the pipe open "printf 'loading\\nerror: bad model child-log-key'; exit 3", // ordinary end of stream }) |script| { var problem: []const u8 = ""; @@ -75,7 +75,7 @@ test "managed log: an exited child's last diagnostic without a newline reaches i try std.testing.expectEqualStrings("Benchmark server exited during startup; check the checkpoint and backend toolchain", problem); try lines(&.{"error: bad model [redacted]"}, tail); const took = t0.durationTo(std.Io.Clock.awake.now(std.testing.io)).toMilliseconds(); - try std.testing.expect(took < 4000); // bounded: no wait for the descendant + try std.testing.expect(took < 7000); // bounded: no wait for the descendant } } diff --git a/zig/tests/cuda/contract_limits_fatbins.zig b/zig/tests/cuda/contract_limits_fatbins.zig index 7f18980f15a..e9c173f8671 100644 --- a/zig/tests/cuda/contract_limits_fatbins.zig +++ b/zig/tests/cuda/contract_limits_fatbins.zig @@ -23,6 +23,7 @@ pub fn auditLaunch(launch: limits.CudaLaunch, sm: u32) limits.CudaLaunch { "qmmf FP8 64-row tile, cluster of 8", // zig/src/cuda/qmmf.zig:147 "qmmf BF16 32-row tile", // zig/src/cuda/qmmf.zig:147 "qmmf BF16 32-row tile, cluster of 8", // zig/src/cuda/qmmf.zig:147 + "qmmf BF16 32-row tile, fused slices", // zig/src/cuda/qmmf.zig:225 "qmmf shared down 32 stride", // zig/src/cuda/qmmf.zig:189 "prompt16 FP8", // zig/src/cuda/nvfp4.zig:122 "qmmf FP8 fp32 out 64-row tile", // zig/src/cuda/qmmf.zig:147 @@ -30,6 +31,7 @@ pub fn auditLaunch(launch: limits.CudaLaunch, sm: u32) limits.CudaLaunch { "qmmf FP8 fp32 out 64-row tile, fused slices", // zig/src/cuda/qmmf.zig:151 "qmmf BF16 fp32 out 32-row tile", // zig/src/cuda/qmmf.zig:147 "qmmf BF16 fp32 out 32-row tile, cluster of 8", // zig/src/cuda/qmmf.zig:147 + "qmmf BF16 fp32 out 32-row tile, fused slices", // zig/src/cuda/qmmf.zig:225 "h3 h3_attention", // zig/src/families/h3/cuda.zig:97 }; for (raised) |name| if (std.mem.eql(u8, launch.name, name)) { From d569ab46b52a7fff052f620958004cd92aa360a9 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:35:59 +0100 Subject: [PATCH 345/361] qwen27 metal: serve SenseNova-Loop-9B natively (BF16 and AWQ g128) The net change of #3859 at c07419f1f8 over its merge base 685851076f, carried as one commit because four of the branch's merge commits hold changes of their own. --- docs/optimization-ledger.md | 84 +-- docs/recipes/README.md | 1 + docs/recipes/sensenova-loop-9b.md | 56 ++ .../sensenova-loop-metal.json | 91 +++ zig/build/qwen27.zig | 1 + zig/build/qwen27_host.zig | 5 + zig/kernels/metal/core/sensenova_mhc.metal | 596 ++++++++++++++++++ zig/kernels/metal/qwen27/awq_m5_fast.metal | 295 +++++++++ zig/kernels/metal/qwen27/awq_w4a16.metal | 561 +++++++++++++++++ zig/kernels/metal/qwen27/bf16_linear.metal | 505 +++++++++++++++ zig/kernels/metal/qwen27/glue.metal | 26 +- zig/kernels/metal/qwen27/mlp_xs.metal | 13 +- zig/kernels/metal/qwen27/norm_input.metal | 22 +- zig/kernels/metal/qwen27/norm_xs.metal | 22 +- zig/kernels/metal/sources.zig | 6 + zig/qwen27_bank_boundary_host.zig | 7 + zig/qwen27_core.zig | 3 + zig/qwen27_quant_metal.zig | 10 +- zig/runtime_sources/qwen27.zig | 4 + zig/sensenova_loop_config_host.zig | 133 ++++ zig/src/cli/hub.zig | 1 + zig/src/core/checkpoint_metal.zig | 12 +- zig/src/core/contract.zig | 3 + zig/src/core/contract/registry.zig | 9 +- .../contract/sensenova_linear_records.zig | 135 ++++ .../core/contract/sensenova_mhc_records.zig | 24 + zig/src/core/qwen_vl/shards.zig | 9 +- zig/src/core/qwen_vl/tower.zig | 6 +- zig/src/core/qwen_vl/weights.zig | 43 +- zig/src/core/rope_yarn.zig | 13 + zig/src/families/qwen27/attention.zig | 52 +- zig/src/families/qwen27/attention_plan.zig | 15 +- zig/src/families/qwen27/attention_test.zig | 77 +++ zig/src/families/qwen27/config.zig | 127 +++- zig/src/families/qwen27/decode_round.zig | 155 +++-- zig/src/families/qwen27/forward.zig | 34 +- zig/src/families/qwen27/gdn_hook.zig | 15 + zig/src/families/qwen27/glue.zig | 25 +- zig/src/families/qwen27/glue_gpu.zig | 27 +- zig/src/families/qwen27/gpu_frame.zig | 6 +- zig/src/families/qwen27/gpu_weights.zig | 11 +- zig/src/families/qwen27/loop.zig | 547 ++++++++++++++++ zig/src/families/qwen27/model.zig | 46 +- zig/src/families/qwen27/projection.zig | 4 +- zig/src/families/qwen27/prompt_rows.zig | 8 +- zig/src/families/qwen27/quant_gpu.zig | 80 ++- zig/src/families/qwen27/qwen27.zig | 4 + zig/src/families/qwen27/residency.zig | 1 + zig/src/families/qwen27/rope_test.zig | 40 +- zig/src/families/qwen27/widths.zig | 105 ++- zig/src/families/qwen27/yarn.zig | 108 ++++ zig/src/families/sensenova_loop/awq.zig | 548 ++++++++++++++++ zig/src/families/sensenova_loop/config.zig | 563 +++++++++++++++++ .../families/sensenova_loop/linear_bench.zig | 130 ++++ .../families/sensenova_loop/linear_gpu.zig | 526 ++++++++++++++++ .../families/sensenova_loop/linear_quant.zig | 150 +++++ zig/src/families/sensenova_loop/mhc_metal.zig | 233 +++++++ zig/src/families/sensenova_loop/mhc_ref.zig | 561 +++++++++++++++++ .../sensenova_loop/sensenova_loop.zig | 14 + zig/src/native/metal.zig | 50 +- zig/src/native/qwen27_disk.zig | 2 +- zig/src/native/qwen27_engine.zig | 46 ++ zig/src/native/qwen27_images.zig | 8 +- zig/src/native/qwen27_lanes.zig | 43 +- zig/src/native/qwen27_reserve.zig | 7 +- zig/src/native/qwen27_served.zig | 10 +- zig/src/native/qwen27_shared_policy_test.zig | 2 +- zig/src/native/slide_open_test.zig | 33 + zig/src/qwen27_rows_test.zig | 7 + zig/src/qwen27_speed_test.zig | 6 +- zig/src/server/family_sampling.zig | 6 +- zig/src/tensorfold.zig | 2 + zig/tests/contract/metal_limits_all.zig | 2 + zig/tests/contract/metal_main.zig | 7 + zig/tests/contract/metal_sensenova_bf16.zig | 513 +++++++++++++++ zig/tests/contract/metal_sensenova_linear.zig | 509 +++++++++++++++ zig/tests/contract/metal_sensenova_mhc.zig | 592 +++++++++++++++++ zig/tests/fixtures/sensenova_loop_config.json | 90 +++ zig/tests/qwen27/classes.zig | 25 +- zig/tests/qwen27/sensenova_oracle.zig | 207 ++++++ 80 files changed, 8742 insertions(+), 333 deletions(-) create mode 100644 docs/recipes/sensenova-loop-9b.md create mode 100644 tools/conformance_profiles/sensenova-loop-metal.json create mode 100644 zig/kernels/metal/core/sensenova_mhc.metal create mode 100644 zig/kernels/metal/qwen27/awq_m5_fast.metal create mode 100644 zig/kernels/metal/qwen27/awq_w4a16.metal create mode 100644 zig/kernels/metal/qwen27/bf16_linear.metal create mode 100644 zig/sensenova_loop_config_host.zig create mode 100644 zig/src/core/contract/sensenova_linear_records.zig create mode 100644 zig/src/core/contract/sensenova_mhc_records.zig create mode 100644 zig/src/families/qwen27/attention_test.zig create mode 100644 zig/src/families/qwen27/loop.zig create mode 100644 zig/src/families/qwen27/yarn.zig create mode 100644 zig/src/families/sensenova_loop/awq.zig create mode 100644 zig/src/families/sensenova_loop/config.zig create mode 100644 zig/src/families/sensenova_loop/linear_bench.zig create mode 100644 zig/src/families/sensenova_loop/linear_gpu.zig create mode 100644 zig/src/families/sensenova_loop/linear_quant.zig create mode 100644 zig/src/families/sensenova_loop/mhc_metal.zig create mode 100644 zig/src/families/sensenova_loop/mhc_ref.zig create mode 100644 zig/src/families/sensenova_loop/sensenova_loop.zig create mode 100644 zig/tests/contract/metal_sensenova_bf16.zig create mode 100644 zig/tests/contract/metal_sensenova_linear.zig create mode 100644 zig/tests/contract/metal_sensenova_mhc.zig create mode 100644 zig/tests/fixtures/sensenova_loop_config.json create mode 100644 zig/tests/qwen27/sensenova_oracle.zig diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 21a820266ba..925a590ba86 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -221,51 +221,51 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 38. Greedy readback | ? | ? | ? | ? | | 39. Drafted rows share the walk | ? | ? | ? | ? | -| Optimization | gdsa | kimi | qwen3 | -| --- | --- | --- | --- | -| 1. Prompt tail | no (Metal) | no (Metal) | no (HIP only) | -| 2. Paged KV | yes | yes | no (prompt) | -| 3. Prompt store | yes | yes | no (prompt) | -| 4. iGPU states | no (unified) | no (unified) | no (prompt) | -| 5. State walk | yes | yes | no (prompt) | -| 6. KV ledger | yes | yes | no (prompt) | -| 7. Host KV tier | yes | yes | no (prompt) | -| 8. Disk cache | yes | yes | no (prompt) | -| 9. FP8 KV | yes | yes | no (prompt) | -| 10. FP4/FP8 decode | no (Metal) | no (Metal) | no (bf16) | -| 11. Fused proj. | yes | yes | yes | -| 12. Add + norm | done¹ | done M¹ | yes | -| 13. MoE grouped | done¹ | done¹ | no (dense) | -| 14. CUDA graphs | no (Metal) | no (Metal) | no (prompt) | -| 15. MTP | done¹ | no (DSpark) | no (prompt) | -| 16. DFlash(2) | yes | yes | no (prompt) | -| 17. DSpark | yes | yes | no (prompt) | -| 18. Copy drafts | done M¹ | done [#2221] | no (prompt) | -| 19. Shared drafts | yes | yes | no (prompt) | -| 20. Solo chunks | yes | yes | no (prompt) | -| 21. Read-ahead | no (Metal) | no (Metal) | yes | -| 22. Direct load | yes | yes | yes | -| 23. Page drop | done M[#1888] | yes | yes | -| 24. L2 prefetch | no (Metal) | no (Metal) | no (prompt) | -| 25. TP ranks | yes | yes | no (small) | -| 26. Pipeline | yes | yes | no (small) | -| 27. Profiles | yes | yes | yes | -| 28. Scale index | ? | ? | ? | -| 29. DSpine | no (no drafter) | no (no drafter) | no (prompt) | -| 30. Small-kernel fusion | ? | ? | ? | -| 31. Stream-tile prefetch | ? | ? | ? | -| 32. Filled-item prompt grid | ? | ? | ? | -| 33. Dependent launches | ? | ? | ? | -| 34. Rows together | no (Metal) | no (Metal) | no (prompt) | -| 35. FP8 KV prefill waits | ? | ? | ? | -| 36. Qwen normalization and head | ? | ? | ? | -| 37. Text metadata uploads | ? | ? | ? | -| 38. Greedy readback | ? | ? | ? | -| 39. Drafted rows share the walk | ? | ? | ? | +| Optimization | gdsa | kimi | qwen3 | snloop | +| --- | --- | --- | --- | --- | +| 1. Prompt tail | no (Metal) | no (Metal) | no (HIP only) | done M¹ | +| 2. Paged KV | yes | yes | no (prompt) | done M[#2283] | +| 3. Prompt store | yes | yes | no (prompt) | yes | +| 4. iGPU states | no (unified) | no (unified) | no (prompt) | no (unified) | +| 5. State walk | yes | yes | no (prompt) | yes | +| 6. KV ledger | yes | yes | no (prompt) | yes | +| 7. Host KV tier | yes | yes | no (prompt) | yes | +| 8. Disk cache | yes | yes | no (prompt) | done¹ | +| 9. FP8 KV | yes | yes | no (prompt) | yes | +| 10. FP4/FP8 decode | no (Metal) | no (Metal) | no (bf16) | no (Metal) | +| 11. Fused proj. | yes | yes | yes | open M[#3859] | +| 12. Add + norm | done¹ | done M¹ | yes | open M[#3859] | +| 13. MoE grouped | done¹ | done¹ | no (dense) | no (dense) | +| 14. CUDA graphs | no (Metal) | no (Metal) | no (prompt) | no (Metal) | +| 15. MTP | done¹ | no (DSpark) | no (prompt) | yes | +| 16. DFlash(2) | yes | yes | no (prompt) | yes | +| 17. DSpark | yes | yes | no (prompt) | yes | +| 18. Copy drafts | done M¹ | done [#2221] | no (prompt) | done¹ | +| 19. Shared drafts | yes | yes | no (prompt) | no (copies) | +| 20. Solo chunks | yes | yes | no (prompt) | yes | +| 21. Read-ahead | no (Metal) | no (Metal) | yes | no (Metal) | +| 22. Direct load | yes | yes | yes | yes | +| 23. Page drop | done M[#1888] | yes | yes | done M[#1885] | +| 24. L2 prefetch | no (Metal) | no (Metal) | no (prompt) | no (Metal) | +| 25. TP ranks | yes | yes | no (small) | no (9B) | +| 26. Pipeline | yes | yes | no (small) | no (9B) | +| 27. Profiles | yes | yes | yes | yes | +| 28. Scale index | ? | ? | ? | ? | +| 29. DSpine | no (no drafter) | no (no drafter) | no (prompt) | no (no drafter) | +| 30. Small-kernel fusion | ? | ? | ? | ? | +| 31. Stream-tile prefetch | ? | ? | ? | ? | +| 32. Filled-item prompt grid | ? | ? | ? | ? | +| 33. Dependent launches | ? | ? | ? | ? | +| 34. Rows together | no (Metal) | no (Metal) | no (prompt) | ? | +| 35. FP8 KV prefill waits | ? | ? | ? | ? | +| 36. Qwen normalization and head | ? | ? | ? | ? | +| 37. Text metadata uploads | ? | ? | ? | ? | +| 38. Greedy readback | ? | ? | ? | ? | +| 39. Drafted rows share the walk | ? | ? | ? | ? | q27 `qwen27` (M: Qwen3.8-27B and Qwen3.5-MoE), lfm2 `lfm2` (C: LFM2-VL, scores decisions and writes no text), llama `llama` (M), step5 `step5` (M), gdsa `glm_dsa` (M), kimi `kimi_k3` (M, native serving on [#2221]), -qwen3 `qwen3` (H: embeddings and rerankers, prompt only). +qwen3 `qwen3` (H: embeddings and rerankers, prompt only), snloop `sensenova_loop` (M: SenseNova-Loop-9B via `qwen27`). Not in the table: `h3` (MiniMax H3 denoising blocks), `drama3` (speech), `moss_image`, `qwen_image`, `radio`, and the HIP OCR families `dots_mocr` and `glm_ocr`. They are not autoregressive text servers on the lane host, so few rows diff --git a/docs/recipes/README.md b/docs/recipes/README.md index 2f9ae1dd248..4a5ea6171ee 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -38,6 +38,7 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Muse Spark Open | [EXL3 on CUDA, two-rank DGX Spark, plain decode](muse-spark.md) | | Ripple-65B-Preview | [Native CUDA, the publisher's NVFP4 release](ripple-65b-cuda.md), [native Metal, the publisher's NVFP4 and bf16 releases](ripple-65b-metal.md) | | Ling-3.0-tiny | [Native CPU on aarch64 Linux, the Q4_K_M GGUF, exact greedy decode from token IDs](ling-3.0-tiny-cpu.md) | +| SenseNova-Loop-9B | [Native Metal, BF16 and AWQ g128, 512k context, images](sensenova-loop-9b.md) | [Persisted serving-state identities](persisted-serving-keys.md) lists the disk owners, their compatibility keys and stale-state host checks. diff --git a/docs/recipes/sensenova-loop-9b.md b/docs/recipes/sensenova-loop-9b.md new file mode 100644 index 00000000000..0e529c07ce4 --- /dev/null +++ b/docs/recipes/sensenova-loop-9b.md @@ -0,0 +1,56 @@ +# SenseNova-Loop-9B on native Metal + +SenseNova-Loop-9B (`sensenova/SenseNova-Loop-9B`, `model_type: sensenova_loop`) runs natively on Apple Silicon in both full BF16 and AWQ 4-bit (`group_size=128`) weights through the Metal `qwen27` lane backend. + +## Architecture and execution schedule + +The checkpoint expands `32` physical decoder layers into `56` executed steps at runtime (`4` stem layers `0..3`, `24` looped trunk layers `4..27` run twice in sequence across two iterations, and `4` tail layers `28..31`). Across the `56` steps, `42` are Gated DeltaNet linear-attention layers and `14` are grouped-query full-attention layers (`16` query heads, `4` KV heads, `head_dim=256`, `rotary_dim=64`), with distinct KV/recurrent slots per loop step and shared weights across the trunk's two passes. + +Each trunk layer runs a two-stream manifold-constrained hyper-connection (`mHC`) pre/post routing block (`Sinkhorn-Knopp`, `20` iterations, `pre_scale=1.0`), fused across adjacent steps via `sn_mhc_post_and_pre_norm`. Sibling linear projections (`qkv` + `zba` on linear-attention layers and `q` + `k` + `v` on non-tail attention layers) are stacked with `OutSplits`, reducing executed dense dispatches from `281` to `226` per token. + +- **Weights and formats:** BF16 safetensors (`26,249 MB` executed linear traffic/step) and standard AutoAWQ GEMM `W4A16` `g128` (`7,398 MB` executed linear traffic/step, lossless FP32 scale/zero metadata). +- **AWQ g128 export config:** Converted from `sensenova/SenseNova-Loop-9B` (`rev 3e1ba6e8ac98090f9f7c03a55f26269eb3850fb6`) with `"quantization_config": {"quant_method": "awq", "bits": 4, "group_size": 128, "zero_point": true, "version": "gemm"}`, keeping `mhc_*`, `linear_attn.{in_proj_a,in_proj_b,conv1d,A_log,dt_bias,norm}`, RMSNorms, `embed_tokens`, `model.visual`, and `loop_gate` in BF16 (`modules_to_not_convert`), calibrating AWQ input activation scales across both loop passes of layers `4..27`. +- **Context length:** Static YaRN scaling enabled at `factor=2.0` (`262,144` base to `524,288` max context), plus `--rope-yarn` factor selection on SenseNova checkpoints. +- **Vision inputs:** Supports the checkpoint's `model.visual.` tower through `--vision`. +- **Prompt chunking and decoding:** Uses `2048`-row linear-attention prompt chunks on Apple M3 Ultra and M5 Ultra (via single-chain prompt planning on `wide_prompt`), Copy-Draft (`--no-drafts` disables drafting), and fused tail greedy argmax. + +## Launch + +```bash +./zig-out/native/bin/tensorfold-native serve sensenova/SenseNova-Loop-9B \ + --host 127.0.0.1 --port 18090 --parallel 4 --context 36864 +``` + +Serve an AWQ W4A16 `g128` export with the identical flags. On `256 GB` or `512 GB` unified-memory Macs, both formats comfortably hold four concurrent `36K` streams (`25.7 GiB` active memory in BF16, `15.1 GiB` in AWQ at startup with `--prompt-cache-gib 0`). + +## Verification receipts + +Measured against `sensenova/SenseNova-Loop-9B` (Apache-2.0, Hugging Face revision `3e1ba6e8ac98090f9f7c03a55f26269eb3850fb6`) and an AWQ W4A16 `g128` conversion on Apple M5 Ultra `512 GB` (macOS `27.2.1`, Apple Metal `32023.922`, Zig `0.17.0`). Prompt and concurrent throughput below were measured with `--parallel 4 --context 36864 --prompt-cache-gib 0`. + +### Oracle parity (`tf-sensenova-oracle`) + +- **BF16 vs Hugging Face PyTorch trace:** `embed_tokens cos=1.0000000`, `exec3_out cos=0.9999639`, `exec27_h_after_collapse cos=0.9998821`, `exec51_h_after_collapse cos=0.9999005`, `exec55_out cos=0.9998916`, `final_norm cos=0.9998723`, `logits_bf16 cos=0.9999594`, top-1 `4/4`, top-16 overlap `16/16`, `6/6` greedy generations exact (`4/4`, `4/4`, `42/42`, `64/64`, `64/64`, `64/64`). +- **AWQ W4A16 g128 vs quantized PyTorch trace:** `embed_tokens cos=1.0000000`, `exec3_out cos=0.9999746`, `exec27_h_after_collapse cos=0.9999127`, `exec51_h_after_collapse cos=0.9998882`, `exec55_out cos=0.9999162`, `final_norm cos=0.9998916`, `logits_bf16 cos=0.9999633`, top-1 `4/4`, top-16 overlap `16/16`, `6/6` greedy generations exact (`4/4`, `42/42`, `22/22`, `64/64`, `96/96`, `64/64`). + +### Decode, concurrency, and cold prefill (Apple M5 Ultra) + +| Check | Format | Prompt / Mode | Decode (`tok/s`) | TTFT / Prefill | Exactness | +| --- | --- | --- | --- | --- | --- | +| `tools/bench_openai.py` (`256` tok, `3` reps) | BF16 | `fibonacci-raw` `T=1.0` / `T=0` | `29.06` / `28.94` | `0.090s` / `0.092s` | `complete` | +| `tools/bench_openai.py` (`256` tok, `3` reps) | BF16 | `gpu-chat-no-think` `T=1.0` / `T=0` | `29.04` / `29.02` | `0.090s` / `0.090s` | `complete` | +| `tools/bench_openai.py` (`256` tok, `3` reps) | AWQ g128 | `fibonacci-raw` `T=1.0` / `T=0` | `55.51` / `54.32` | `0.058s` / `0.060s` | `complete` | +| `tools/bench_openai.py` (`256` tok, `3` reps) | AWQ g128 | `gpu-chat-no-think` `T=1.0` / `T=0` | `55.10` / `54.30` | `0.058s` / `0.058s` | `complete` | +| `tools/bench_concurrent.py` (`c=4`, `T=0`) | BF16 | `code` / `chat` (`agg`, `per-stream`) | `106.7` (`27.0`) / `109.1` (`27.9`) | `0` failed | `alone 12/12`, `serial 1/1` | +| `tools/bench_concurrent.py` (`c=4`, `T=0`) | AWQ g128 | `code` / `chat` (`agg`, `per-stream`) | `200.1` (`51.0`) / `200.0` (`51.5`) | `0` failed | `alone 12/12`, `serial 1/1` | +| `tools/bench_cache.py --require-cold` (`2,048` tok) | BF16 / AWQ | Raw token array, median `4` runs | — | `0.594s` (`3,445`) / `0.735s` (`2,786` tok/s) | `qualified: true` | +| `tools/bench_cache.py --require-cold` (`8,192` tok) | BF16 / AWQ | Raw token array, median `4` runs | — | `2.345s` (`3,493`) / `2.885s` (`2,840` tok/s) | `qualified: true` | +| `tools/bench_cache.py --require-cold` (`32,768` tok) | BF16 / AWQ | Raw token array, median `4` runs | — | `10.227s` (`3,204`) / `12.543s` (`2,613` tok/s) | `qualified: true` | + +### Metal kernel contracts + +- **Apple M5 Ultra (`applegpu_g17`, `tensor_units=true`):** + - `--only sensenova`: `24 kernels: 24 pass gates 1-4, 0 fail, 0 known findings; 45 controls: 45 red as planted, 0 missed; 0 limit problems`. + - `--only qwen27`: `40 kernels: 40 pass gates 1-4, 0 fail, 0 known findings; 6 controls: 6 red as planted, 0 missed; 0 limit problems`. +- **Apple M3 Ultra (`applegpu_g15`, `tensor_units=false`, macOS `26.6.2`):** + - `--only sensenova`: `17 kernels: 17 pass gates 1-4, 0 fail, 0 known findings; 37 controls: 37 red as planted, 0 missed; 0 limit problems`. + - `--only qwen27`: `30 kernels: 30 pass gates 1-4, 0 fail, 0 known findings; 3 controls: 3 red as planted, 0 missed; 0 limit problems`. diff --git a/tools/conformance_profiles/sensenova-loop-metal.json b/tools/conformance_profiles/sensenova-loop-metal.json new file mode 100644 index 00000000000..929827387ab --- /dev/null +++ b/tools/conformance_profiles/sensenova-loop-metal.json @@ -0,0 +1,91 @@ +{ + "name": "sensenova-loop-metal", + "family": "sensenova_loop on Metal", + "checkpoint": "SenseNova-Loop-9B (BF16 or AWQ g128) on Apple Silicon with Copy-Draft", + "serve": [ + "--context", + "16384", + "--parallel", + "4", + "--no-thinking" + ], + "sampled": { + "temperature": 0.8, + "top_p": 0.95, + "top_k": 20 + }, + "tokens": 64, + "seed": 7, + "levels": [ + 1, + 2, + 4 + ], + "prompt_cache_gib": 1, + "ignore_eos": true, + "prompts": { + "copy": "Repeat exactly: The harbor lights came on one by one as the fishing boats returned to the quay.", + "poem": "Write a short poem about the sea.", + "primes": "List the first twelve prime numbers, separated by commas.", + "sky": "Explain in two sentences why the sky is blue.", + "count": "Count from one to thirty in words." + }, + "long_items": 500, + "conversation": [ + "Name three rivers in Europe and one fact about each.", + "Now give the length of each river in kilometres.", + "Which of them is the longest? Answer in one sentence." + ], + "conversation_context_items": 900, + "refusals": [ + { + "name": "n_two", + "body": { + "n": 2 + }, + "status": 400, + "error": "n must be 1; multiple choices are not supported" + }, + { + "name": "top_logprobs_without_logprobs", + "body": { + "top_logprobs": 3 + }, + "status": 400, + "error": "top_logprobs requires logprobs: true" + }, + { + "name": "presence_penalty_out_of_range", + "body": { + "presence_penalty": 3 + }, + "status": 400, + "error": "presence_penalty must be between -2 and 2, or null" + }, + { + "name": "reply_past_context", + "body": { + "max_tokens": 10000000 + }, + "status": 400, + "error": "This server's maximum context length is" + } + ], + "settle_s": 120, + "fresh_env": { + "TF_QWEN27_SLOT_RESUME": "0" + }, + "cancel": { + "prompt": "count", + "tokens": 256, + "after_chunks": 4, + "rounds": 2, + "settle_s": 60 + }, + "evict": { + "fill_prompts": 10, + "fill_items": 900, + "fill_tokens": 1, + "settle_s": 60 + } +} diff --git a/zig/build/qwen27.zig b/zig/build/qwen27.zig index 8111518560d..c233e1ce93f 100644 --- a/zig/build/qwen27.zig +++ b/zig/build/qwen27.zig @@ -110,6 +110,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const family: []const std.Build.Module.Import = &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal } }; _ = program(b, "tf-qwen27-run", "Build the native greedy, chunk and prompt-speed check on real weights", "zig/tests/qwen27/run.zig", target, true, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal }, .{ .name = "core_lane", .module = core_lane }, .{ .name = "qwen_runtime_sources", .module = s.runtime_sources }, .{ .name = "qwen_gdn_source", .module = s.gdn_source } }); + _ = program(b, "tf-sensenova-oracle", "Build the SenseNova-Loop-9B HF PyTorch oracle verifier and LinearGpu microbench", "zig/tests/qwen27/sensenova_oracle.zig", target, true, family); _ = program(b, "tf-qwen27-attention-fused", "Build the fused-chain versus tail-kernel attention byte check on this Mac's GPU, no models", "zig/tests/qwen27/attention_fused.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal }, .{ .name = "qwen_runtime_sources", .module = s.runtime_sources } }); _ = program(b, "tf-qwen27-attention-pages", "Build the KV-page attention kernels against main's, bit for bit through shuffled pages, no models", "zig/tests/qwen27/attention_pages.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal } }); _ = program(b, "tf-qwen27-attention-share", "Build the KV-page attention timed with streams on one prefix's pages against copies, no models", "zig/tests/qwen27/attention_share.zig", target, false, &.{ .{ .name = "qwen27", .module = qwen27 }, .{ .name = "metal", .module = metal } }); diff --git a/zig/build/qwen27_host.zig b/zig/build/qwen27_host.zig index 15d417a603f..4dbb6606513 100644 --- a/zig/build/qwen27_host.zig +++ b/zig/build/qwen27_host.zig @@ -10,6 +10,11 @@ pub fn tests(b: *std.Build, test_step: *std.Build.Step) void { const quant_run = b.addRunArtifact(quant_test); test_step.dependOn(&quant_run.step); b.step("test-qwen27-quant-host", "Prepared head cache identity and prompt row capacity without a GPU").dependOn(&quant_run.step); + const loop_cfg = b.createModule(.{ .root_source_file = b.path("zig/sensenova_loop_config_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true }); + loop_cfg.addImport("core", loop_cfg); + const loop_cfg_run = b.addRunArtifact(b.addTest(.{ .root_module = loop_cfg, .filters = &.{"SenseNova loop config table:"} })); + test_step.dependOn(&loop_cfg_run.step); + b.step("test-sensenova-loop-config-host", "SenseNova loop config table through config reader and Metal admission without a GPU").dependOn(&loop_cfg_run.step); const metrics = b.createModule(.{ .root_source_file = b.path("zig/src/metal/pass_metrics.zig"), .target = b.graph.host }); b.step("test-qwen27-pass-metrics-host", "Pass timing and forwarding allocator without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = metrics })).step); const mtp_flags = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_mtp_flags.zig"), .target = b.graph.host }) })); diff --git a/zig/kernels/metal/core/sensenova_mhc.metal b/zig/kernels/metal/core/sensenova_mhc.metal new file mode 100644 index 00000000000..35977861059 --- /dev/null +++ b/zig/kernels/metal/core/sensenova_mhc.metal @@ -0,0 +1,596 @@ +// Two-stream mHC Metal kernels for SenseNova-Loop: enter, pre_norm, post_merge, post_and_pre_norm. +#include +using namespace metal; +#pragma clang fp contract(off) + +#ifndef TF_CTL +#define TF_CTL 0 +#endif + +#define SN_TG 256u +#define SN_SG (SN_TG / 32u) + +struct SnMhcEnterArgs { + uint rows; + uint hidden; + uint has_pending; + uint write_h; +}; + +struct SnMhcPreNormArgs { + uint rows; + uint hidden; + uint iters; + uint shift_norm; + uint xs_group; + uint xs_stride; + float pre_scale; + float eps; +}; + +struct SnMhcPostMergeArgs { + uint rows; + uint hidden; + uint exit; + uint pad0; +}; + +inline float sn_nv(float v) { +#if TF_CTL == 1 + return isfinite(v) ? v : 0.0f; +#else + return v; +#endif +} + +inline float sn_bf(ushort bits) { + return as_type(uint(bits) << 16); +} + +inline ushort sn_to_bits(float v) { + return as_type(bfloat(v)); +} + +inline float sn_acc(float acc, float term) { +#if TF_CTL == 3 + return float(half(acc) + half(term)); +#else + return acc + term; +#endif +} + +inline float sn_simd_sum(float v) { + for (ushort m = 1; m < 32; m *= 2) { +#if TF_CTL == 3 + v = float(half(v) + half(simd_shuffle_xor(v, m))); +#else + v = v + simd_shuffle_xor(v, m); +#endif + } + return v; +} + +inline float sn_lse2(float a, float b) { + if (isnan(a) || isnan(b)) return NAN; + const float mx = max(a, b); + if (isinf(mx) && mx < 0.0f) return mx; + return mx + metal::precise::log(1.0f + metal::precise::exp(-metal::abs(a - b))); +} + +inline ushort2 sn_post_pair(float r0, float r1, float yv, float post0, float post1, + float m00, float m01, float m10, float m11) { +#if TF_CTL == 3 + const float mixed0 = float(bfloat(float(half(m00 * r0)) + float(half(m01 * r1)))); + const float mixed1 = float(bfloat(float(half(m10 * r0)) + float(half(m11 * r1)))); +#else + const float mixed0 = float(bfloat(m00 * r0 + m01 * r1)); + const float mixed1 = float(bfloat(m10 * r0 + m11 * r1)); +#endif +#if TF_CTL == 2 + const float upd0 = yv; + const float upd1 = yv; +#else + const float upd0 = float(bfloat(post0 * yv)); + const float upd1 = float(bfloat(post1 * yv)); +#endif + return ushort2(sn_to_bits(mixed0 + upd0), sn_to_bits(mixed1 + upd1)); +} + +inline void sn_post_vec8(uint4 a0, uint4 a1, uint4 yv, float post0, float post1, float m00, float m01, float m10, + float m11, thread uint4& o0, thread uint4& o1) { + for (uint w = 0; w < 4u; ++w) { + const ushort2 p0 = sn_post_pair(sn_nv(sn_bf(ushort(a0[w] & 0xffffu))), sn_nv(sn_bf(ushort(a1[w] & 0xffffu))), + sn_nv(sn_bf(ushort(yv[w] & 0xffffu))), post0, post1, m00, m01, m10, m11); + const ushort2 p1 = sn_post_pair(sn_nv(sn_bf(ushort(a0[w] >> 16))), sn_nv(sn_bf(ushort(a1[w] >> 16))), + sn_nv(sn_bf(ushort(yv[w] >> 16))), post0, post1, m00, m01, m10, m11); + o0[w] = uint(p0.x) | (uint(p1.x) << 16); + o1[w] = uint(p0.y) | (uint(p1.y) << 16); + } +} + +inline void sn_load_post_coeff(const device bfloat* COEFF_IN, uint r, thread float& post0, thread float& post1, + thread float& m00, thread float& m01, thread float& m10, thread float& m11) { + const device ushort* co = (const device ushort*)(COEFF_IN + ulong(r) * 6u); + post0 = sn_nv(sn_bf(co[0])); post1 = sn_nv(sn_bf(co[1])); m00 = sn_nv(sn_bf(co[2])); +#if TF_CTL == 5 + m01 = sn_nv(sn_bf(co[4])); m10 = sn_nv(sn_bf(co[3])); +#else + m01 = sn_nv(sn_bf(co[3])); m10 = sn_nv(sn_bf(co[4])); +#endif + m11 = sn_nv(sn_bf(co[5])); +} + +inline void sn_pre_norm_from_tg( + threadgroup ushort* tg_r, + threadgroup float* tg_red, + threadgroup float* tg_dot, + threadgroup float* tg_pre, + const device float* W, + const device float* B, + const device bfloat* SUB_W, + device bfloat* COEFF_OUT, + device bfloat* NORM_OUT, + device float* XS_OUT, + constant SnMhcPreNormArgs& a, + uint r, + uint t, + uint lane, + uint sg) { + const uint H = a.hidden; + const uint two_h = 2u * H; + + float ss = 0.0f; + float dot[8]; + for (uint m = 0; m < 8; ++m) dot[m] = 0.0f; + +#if TF_CTL != 5 + if ((two_h & 3u) == 0u && ((ulong(W) & 15u) == 0u)) { + const threadgroup ushort4* tg4 = (const threadgroup ushort4*)tg_r; + const device float4* W4 = (const device float4*)W; + const uint n4 = two_h >> 2; + for (uint j4 = t; j4 < n4; j4 += SN_TG) { + const ushort4 rs = tg4[j4]; + const float r0 = sn_nv(sn_bf(rs.x)), r1 = sn_nv(sn_bf(rs.y)); + const float r2 = sn_nv(sn_bf(rs.z)), r3 = sn_nv(sn_bf(rs.w)); + ss = sn_acc(sn_acc(sn_acc(sn_acc(ss, r0 * r0), r1 * r1), r2 * r2), r3 * r3); + for (uint m = 0; m < 8; ++m) { + const float4 wv = W4[ulong(m) * n4 + j4]; + dot[m] = sn_acc(sn_acc(sn_acc(sn_acc(dot[m], r0 * sn_nv(wv.x)), r1 * sn_nv(wv.y)), + r2 * sn_nv(wv.z)), r3 * sn_nv(wv.w)); + } + } + } else +#endif + { + for (uint j = t; j < two_h; j += SN_TG) { + const float rv = sn_nv(sn_bf(tg_r[j])); + ss = sn_acc(ss, rv * rv); + for (uint m = 0; m < 8; ++m) { +#if TF_CTL == 5 + dot[m] = sn_acc(dot[m], rv * sn_nv(W[ulong(j) * 8u + m])); +#else + dot[m] = sn_acc(dot[m], rv * sn_nv(W[ulong(m) * two_h + j])); +#endif + } + } + } + + const float ss_sg = sn_simd_sum(ss); + float dot_sg[8]; + for (uint m = 0; m < 8; ++m) dot_sg[m] = sn_simd_sum(dot[m]); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0u) { + tg_red[sg] = ss_sg; + for (uint m = 0; m < 8; ++m) tg_dot[sg * 8u + m] = dot_sg[m]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (sg == 0u) { + float z_lane = 0.0f; + if (lane < 8u) { + float tot_ss = tg_red[0]; + for (uint s = 1; s < SN_SG; ++s) tot_ss = sn_acc(tot_ss, tg_red[s]); + const float inv_rms = metal::precise::rsqrt(tot_ss / float(two_h) + a.eps); + float dm = tg_dot[lane]; + for (uint s = 1; s < SN_SG; ++s) dm = sn_acc(dm, tg_dot[s * 8u + lane]); + z_lane = dm * inv_rms + sn_nv(B[lane]); + } + float sig = 0.0f; + if (lane < 4u) { + const float num = (lane < 2u) ? 1.0f : 2.0f; + sig = metal::precise::divide(num, 1.0f + metal::precise::exp(-z_lane)); + } + const float pre0 = simd_shuffle(sig, 0), pre1 = simd_shuffle(sig, 1); + const float post0 = simd_shuffle(sig, 2), post1 = simd_shuffle(sig, 3); + float a0 = simd_shuffle(z_lane, ushort(4u + (lane & 1u) * 2u)); + float a1 = simd_shuffle(z_lane, ushort(5u + (lane & 1u) * 2u)); +#if TF_CTL == 2 + const uint iters = 0u; +#else + const uint iters = a.iters; +#endif + for (uint it = 0; it < iters; ++it) { + const float rn = sn_lse2(a0, a1); + a0 -= rn; + a1 -= rn; + const float p0 = simd_shuffle_xor(a0, 1), p1 = simd_shuffle_xor(a1, 1); + const float cn = (lane == 0u) ? sn_lse2(a0, p0) : sn_lse2(p1, a1); + const float c0 = simd_shuffle(cn, 0), c1 = simd_shuffle(cn, 1); + a0 -= c0; + a1 -= c1; + } + const float e0 = metal::precise::exp(a0), e1 = metal::precise::exp(a1); + const float mix00 = simd_shuffle(e0, 0), mix01 = simd_shuffle(e1, 0); + const float mix10 = simd_shuffle(e0, 1), mix11 = simd_shuffle(e1, 1); + if (lane == 0u) { + device bfloat* co = COEFF_OUT + ulong(r) * 6u; + co[0] = bfloat(post0); co[1] = bfloat(post1); + co[2] = bfloat(mix00); co[3] = bfloat(mix01); co[4] = bfloat(mix10); co[5] = bfloat(mix11); + tg_pre[0] = float(bfloat(pre0)); tg_pre[1] = float(bfloat(pre1)); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const float p0 = tg_pre[0], p1 = tg_pre[1]; + float br_reg[16]; + float ss_b = 0.0f; + const device ushort* sub_u = (const device ushort*)SUB_W; + device ushort* norm_u = (device ushort*)(NORM_OUT + ulong(r) * H); +#if TF_CTL == 4 + const bool vec4_h = false; +#else + const bool vec4_h = ((H & 3u) == 0u) && ((ulong(sub_u) & 7u) == 0u) && ((ulong(norm_u) & 7u) == 0u); +#endif + uint k = 0; + if (vec4_h) { + const threadgroup ushort4 *t0_4 = (const threadgroup ushort4*)tg_r, *t1_4 = (const threadgroup ushort4*)(tg_r + H); + const uint n4 = H >> 2; + for (uint d4 = t; d4 < n4; d4 += SN_TG, k += 4u) { + const ushort4 r0_s = t0_4[d4], r1_s = t1_4[d4]; + for (uint c = 0; c < 4u; ++c) { + float br = float(bfloat(p0 * sn_nv(sn_bf(r0_s[c])) + p1 * sn_nv(sn_bf(r1_s[c])))); + if (a.pre_scale != 1.0f) br = float(bfloat(a.pre_scale * br)); + br_reg[k + c] = br; ss_b = sn_acc(ss_b, br * br); + } + } + } else { + for (uint d = t; d < H; d += SN_TG, ++k) { + float br = float(bfloat(p0 * sn_nv(sn_bf(tg_r[d])) + p1 * sn_nv(sn_bf(tg_r[H + d])))); + if (a.pre_scale != 1.0f) br = float(bfloat(a.pre_scale * br)); + br_reg[k] = br; ss_b = sn_acc(ss_b, br * br); + } + } + + const float ss_b_sg = sn_simd_sum(ss_b); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0u) tg_red[sg] = ss_b_sg; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0u) { + float tot_b = tg_red[0]; + for (uint s = 1; s < SN_SG; ++s) tot_b = sn_acc(tot_b, tg_red[s]); + tg_pre[2] = metal::precise::rsqrt(tot_b / float(H) + a.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const float inv_b = tg_pre[2]; + k = 0; + if (vec4_h) { + const device ushort4* sub4 = (const device ushort4*)sub_u; + device ushort4* out4 = (device ushort4*)norm_u; + threadgroup ushort4* tg4 = (threadgroup ushort4*)tg_r; + const uint n4 = H >> 2; + for (uint d4 = t; d4 < n4; d4 += SN_TG, k += 4u) { + const ushort4 sws = sub4[d4]; + ushort4 ov; + for (uint c = 0; c < 4u; ++c) { + const float sw = sn_nv(sn_bf(sws[c])); + ov[c] = sn_to_bits((br_reg[k + c] * inv_b) * ((a.shift_norm != 0u) ? (1.0f + sw) : sw)); + } + out4[d4] = ov; + if (a.xs_group != 0u) tg4[d4] = ov; + } + } else { + for (uint d = t; d < H; d += SN_TG, ++k) { +#if TF_CTL == 4 + if (d + 1u == H) continue; +#endif + const float sw = sn_nv(sn_bf(as_type(SUB_W[d]))); + const bfloat out_b = bfloat((br_reg[k] * inv_b) * ((a.shift_norm != 0u) ? (1.0f + sw) : sw)); + NORM_OUT[ulong(r) * H + d] = out_b; + if (a.xs_group != 0u) tg_r[d] = as_type(out_b); + } + } + + if (a.xs_group != 0u) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if ((a.xs_group == 128u && (H & 127u) == 0u) || (a.xs_group == 64u && (H & 63u) == 0u)) { + const uint num_groups = H / a.xs_group, sub_groups = SN_TG >> 3, u = t & 7u; + const uint q_cnt = (a.xs_group == 128u) ? 2u : 1u, per_t = q_cnt * 8u; + for (uint g0 = 0; g0 < num_groups; g0 += sub_groups) { + const uint g = g0 + (t >> 3); + float xv[16]; + if (g < num_groups) { + const threadgroup uint4* p8 = (const threadgroup uint4*)(tg_r + g * a.xs_group + u * per_t); + for (uint q = 0; q < q_cnt; ++q) { + const uint4 w = p8[q]; + for (uint c = 0; c < 4u; ++c) { + xv[q * 8u + c * 2u] = sn_bf(ushort(w[c] & 0xffffu)); + xv[q * 8u + c * 2u + 1u] = sn_bf(ushort(w[c] >> 16)); + } + } + } + float gs = 0.0f; + for (uint turn = 0; turn < 8u; ++turn) { + if (g < num_groups && u == turn) for (uint i = 0; i < per_t; ++i) gs = sn_acc(gs, xv[i]); + gs = simd_shuffle(gs, ushort((lane & ~7u) | turn)); + } + if (g < num_groups && u == 0u) XS_OUT[ulong(g) * a.xs_stride + r] = gs; + } + } else { + const uint num_groups = (H + a.xs_group - 1u) / a.xs_group; + for (uint g = t; g < num_groups; g += SN_TG) { + float gs = 0.0f; + const uint base = g * a.xs_group, lim = min(base + a.xs_group, H); + for (uint i = base; i < lim; ++i) gs = sn_acc(gs, sn_bf(tg_r[i])); + XS_OUT[ulong(g) * a.xs_stride + r] = gs; + } + } + } +} + +[[kernel, max_total_threads_per_threadgroup(SN_TG)]] void sn_mhc_enter( + const device bfloat* H_IN [[buffer(0)]], + const device bfloat* PENDING [[buffer(1)]], + device bfloat* R_OUT [[buffer(2)]], + device bfloat* H_OUT [[buffer(3)]], + constant SnMhcEnterArgs& a [[buffer(4)]], + uint2 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + const uint r = tg.y; + if (r >= a.rows) return; + const uint H = a.hidden; + const bool vec8 = ((H & 7u) == 0u); + const uint idx = tg.x * SN_TG + t; + if (vec8) { + const uint chunks = H >> 3; + if (idx >= chunks) return; + const ulong off_h = (ulong(r) * H + (idx << 3)) >> 3; + const uint4 hv = ((const device uint4*)H_IN)[off_h]; + uint4 out_v = hv; + const bool has_p = (a.has_pending != 0u); +#if TF_CTL == 1 + const bool check_nv = true; +#else + const bool check_nv = false; +#endif + if (has_p || check_nv) { + const uint4 pv = has_p ? ((const device uint4*)PENDING)[off_h] : uint4(0u); + for (uint w = 0; w < 4u; ++w) { + const uint h0 = hv[w] & 0xffffu; + const uint h1 = hv[w] >> 16; + const float f0 = sn_nv(sn_bf(ushort(h0))); + const float f1 = sn_nv(sn_bf(ushort(h1))); + const float v0 = has_p ? (f0 + sn_nv(sn_bf(ushort(pv[w] & 0xffffu)))) : f0; + const float v1 = has_p ? (f1 + sn_nv(sn_bf(ushort(pv[w] >> 16)))) : f1; + out_v[w] = uint(sn_to_bits(v0)) | (uint(sn_to_bits(v1)) << 16); + } + } + const ulong r0_off = (ulong(r) * 2u * H + (idx << 3)) >> 3; + const ulong r1_off = (ulong(r) * 2u * H + H + (idx << 3)) >> 3; +#if TF_CTL == 4 + if (idx + 1u == chunks) { + device ushort* dst0 = (device ushort*)(R_OUT + ulong(r) * 2u * H + (idx << 3)); + device ushort* dst1 = (device ushort*)(R_OUT + ulong(r) * 2u * H + H + (idx << 3)); + for (uint q = 0; q < 7u; ++q) { + const ushort val = ushort((out_v[q >> 1u] >> ((q & 1u) << 4u)) & 0xffffu); + dst0[q] = val; + dst1[q] = val; + if (a.write_h != 0u) ((device ushort*)(H_OUT + ulong(r) * H + (idx << 3)))[q] = val; + } + return; + } +#endif + ((device uint4*)R_OUT)[r0_off] = out_v; +#if TF_CTL == 2 + ((device uint4*)R_OUT)[r1_off] = uint4(0u); +#else + ((device uint4*)R_OUT)[r1_off] = out_v; +#endif + if (a.write_h != 0u) ((device uint4*)H_OUT)[off_h] = out_v; + return; + } + if (idx >= H) return; +#if TF_CTL == 4 + if (idx + 1u == H) return; +#endif + const float fv = sn_nv(sn_bf(as_type(H_IN[ulong(r) * H + idx]))); + const float v = (a.has_pending != 0u) ? (fv + sn_nv(sn_bf(as_type(PENDING[ulong(r) * H + idx])))) : fv; + const bfloat hb = bfloat(v); + R_OUT[ulong(r) * 2u * H + idx] = hb; +#if TF_CTL == 2 + R_OUT[ulong(r) * 2u * H + H + idx] = bfloat(0.0f); +#else + R_OUT[ulong(r) * 2u * H + H + idx] = hb; +#endif + if (a.write_h != 0u) H_OUT[ulong(r) * H + idx] = hb; +} + +[[kernel, max_total_threads_per_threadgroup(SN_TG)]] void sn_mhc_pre_norm( + const device bfloat* R_IN [[buffer(0)]], + const device float* W [[buffer(1)]], + const device float* B [[buffer(2)]], + const device bfloat* SUB_W [[buffer(3)]], + device bfloat* COEFF_OUT [[buffer(4)]], + device bfloat* NORM_OUT [[buffer(5)]], + device float* XS_OUT [[buffer(6)]], + constant SnMhcPreNormArgs& a [[buffer(7)]], + uint r [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + alignas(16) threadgroup ushort tg_r[8192]; + threadgroup float tg_red[SN_SG]; + threadgroup float tg_dot[SN_SG * 8u]; + threadgroup float tg_pre[3]; + if (r >= a.rows || a.hidden == 0u || a.hidden > 4096u) return; + + const uint two_h = 2u * a.hidden; + const device ushort* src = (const device ushort*)(R_IN + ulong(r) * two_h); + if ((a.hidden & 7u) == 0u && ((ulong(src) & 15u) == 0u)) { + const device uint4* src4 = (const device uint4*)src; + threadgroup uint4* dst4 = (threadgroup uint4*)tg_r; + const uint n4 = two_h >> 3; + for (uint j = t; j < n4; j += SN_TG) dst4[j] = src4[j]; + } else { + for (uint j = t; j < two_h; j += SN_TG) tg_r[j] = src[j]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + sn_pre_norm_from_tg(tg_r, tg_red, tg_dot, tg_pre, W, B, SUB_W, COEFF_OUT, NORM_OUT, XS_OUT, a, r, t, lane, sg); +} + +[[kernel, max_total_threads_per_threadgroup(SN_TG)]] void sn_mhc_post_merge( + const device bfloat* R_IN [[buffer(0)]], + const device bfloat* Y_IN [[buffer(1)]], + const device bfloat* COEFF_IN [[buffer(2)]], + device bfloat* OUT [[buffer(3)]], + constant SnMhcPostMergeArgs& a [[buffer(4)]], + uint2 tg [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + const uint r = tg.y; + if (r >= a.rows) return; + const uint H = a.hidden; + float post0, post1, m00, m01, m10, m11; + sn_load_post_coeff(COEFF_IN, r, post0, post1, m00, m01, m10, m11); + + const uint idx = tg.x * SN_TG + t; + if ((H & 7u) == 0u) { + const uint chunks = H >> 3; + if (idx >= chunks) return; + const uint d = idx << 3; + const uint4 v0 = ((const device uint4*)(R_IN + ulong(r) * 2u * H + d))[0]; + const uint4 v1 = ((const device uint4*)(R_IN + ulong(r) * 2u * H + H + d))[0]; + const uint4 vy = ((const device uint4*)(Y_IN + ulong(r) * H + d))[0]; + uint4 o0, o1, oe; + sn_post_vec8(v0, v1, vy, post0, post1, m00, m01, m10, m11, o0, o1); + if (a.exit != 0u) { + for (uint w = 0; w < 4u; ++w) { + const ushort e0 = sn_to_bits(0.5f * (sn_bf(ushort(o0[w] & 0xffffu)) + sn_bf(ushort(o1[w] & 0xffffu)))); + const ushort e1 = sn_to_bits(0.5f * (sn_bf(ushort(o0[w] >> 16)) + sn_bf(ushort(o1[w] >> 16)))); + oe[w] = uint(e0) | (uint(e1) << 16); + } + } +#if TF_CTL == 4 + if (idx + 1u == chunks) { + if (a.exit != 0u) { + device ushort* dst = (device ushort*)(OUT + ulong(r) * H + d); + for (uint q = 0; q < 7u; ++q) dst[q] = ushort((oe[q >> 1u] >> ((q & 1u) << 4u)) & 0xffffu); + } else { + device ushort* d0 = (device ushort*)(OUT + ulong(r) * 2u * H + d); + device ushort* d1 = (device ushort*)(OUT + ulong(r) * 2u * H + H + d); + for (uint q = 0; q < 7u; ++q) { + d0[q] = ushort((o0[q >> 1u] >> ((q & 1u) << 4u)) & 0xffffu); + d1[q] = ushort((o1[q >> 1u] >> ((q & 1u) << 4u)) & 0xffffu); + } + } + return; + } +#endif + if (a.exit != 0u) { + ((device uint4*)(OUT + ulong(r) * H + d))[0] = oe; + } else { + ((device uint4*)(OUT + ulong(r) * 2u * H + d))[0] = o0; + ((device uint4*)(OUT + ulong(r) * 2u * H + H + d))[0] = o1; + } + return; + } + + if (idx >= H) return; +#if TF_CTL == 4 + if (idx + 1u == H) return; +#endif + const float r0 = sn_nv(sn_bf(as_type(R_IN[ulong(r) * 2u * H + idx]))); + const float r1 = sn_nv(sn_bf(as_type(R_IN[ulong(r) * 2u * H + H + idx]))); + const float yv = sn_nv(sn_bf(as_type(Y_IN[ulong(r) * H + idx]))); + const ushort2 rn = sn_post_pair(r0, r1, yv, post0, post1, m00, m01, m10, m11); + if (a.exit != 0u) { + OUT[ulong(r) * H + idx] = bfloat(0.5f * (sn_bf(rn.x) + sn_bf(rn.y))); + } else { + OUT[ulong(r) * 2u * H + idx] = as_type(rn.x); + OUT[ulong(r) * 2u * H + H + idx] = as_type(rn.y); + } +} + +[[kernel, max_total_threads_per_threadgroup(SN_TG)]] void sn_mhc_post_and_pre_norm( + const device bfloat* R_IN [[buffer(0)]], + const device bfloat* Y_IN [[buffer(1)]], + const device bfloat* COEFF_IN [[buffer(2)]], + const device float* W_NEXT [[buffer(3)]], + const device float* B_NEXT [[buffer(4)]], + const device bfloat* SUB_W_NEXT [[buffer(5)]], + device bfloat* R_OUT [[buffer(6)]], + device bfloat* COEFF_OUT [[buffer(7)]], + device bfloat* NORM_OUT [[buffer(8)]], + device float* XS_OUT [[buffer(9)]], + constant SnMhcPreNormArgs& a [[buffer(10)]], + uint r [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + alignas(16) threadgroup ushort tg_r[8192]; + threadgroup float tg_red[SN_SG]; + threadgroup float tg_dot[SN_SG * 8u]; + threadgroup float tg_pre[3]; + if (r >= a.rows || a.hidden == 0u || a.hidden > 4096u) return; + + const uint H = a.hidden; + float post0, post1, m00, m01, m10, m11; + sn_load_post_coeff(COEFF_IN, r, post0, post1, m00, m01, m10, m11); + + const device ushort* r0_ptr = (const device ushort*)(R_IN + ulong(r) * 2u * H); + const device ushort* r1_ptr = r0_ptr + H; + const device ushort* y_ptr = (const device ushort*)(Y_IN + ulong(r) * H); + device ushort* ro0 = (device ushort*)(R_OUT + ulong(r) * 2u * H); + device ushort* ro1 = ro0 + H; + + if ((H & 7u) == 0u && ((ulong(r0_ptr) & 15u) == 0u) && ((ulong(y_ptr) & 15u) == 0u) && + ((ulong(ro0) & 15u) == 0u)) { + const device uint4 *r0_v = (const device uint4*)r0_ptr, *r1_v = (const device uint4*)r1_ptr; + const device uint4* y_v = (const device uint4*)y_ptr; + threadgroup uint4 *t0_v = (threadgroup uint4*)tg_r, *t1_v = (threadgroup uint4*)(tg_r + H); + device uint4 *o0_v = (device uint4*)ro0, *o1_v = (device uint4*)ro1; + const uint n4 = H >> 3; + for (uint i = t; i < n4; i += SN_TG) { + uint4 o0, o1; + sn_post_vec8(r0_v[i], r1_v[i], y_v[i], post0, post1, m00, m01, m10, m11, o0, o1); + t0_v[i] = o0; t1_v[i] = o1; +#if TF_CTL == 4 + if ((i << 3) + 7u == H - 1u) { + const uint d = i << 3; + for (uint q = 0; q < 7u; ++q) { + ro0[d + q] = ushort((o0[q >> 1u] >> ((q & 1u) << 4u)) & 0xffffu); + ro1[d + q] = ushort((o1[q >> 1u] >> ((q & 1u) << 4u)) & 0xffffu); + } + continue; + } +#endif + o0_v[i] = o0; o1_v[i] = o1; + } + } else { + for (uint d = t; d < H; d += SN_TG) { + const ushort2 rn = sn_post_pair(sn_nv(sn_bf(r0_ptr[d])), sn_nv(sn_bf(r1_ptr[d])), + sn_nv(sn_bf(y_ptr[d])), post0, post1, m00, m01, m10, m11); + tg_r[d] = rn.x; + tg_r[H + d] = rn.y; +#if TF_CTL == 4 + if (d + 1u == H) continue; +#endif + ro0[d] = rn.x; + ro1[d] = rn.y; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + sn_pre_norm_from_tg(tg_r, tg_red, tg_dot, tg_pre, W_NEXT, B_NEXT, SUB_W_NEXT, COEFF_OUT, NORM_OUT, XS_OUT, a, r, t, + lane, sg); +} diff --git a/zig/kernels/metal/qwen27/awq_m5_fast.metal b/zig/kernels/metal/qwen27/awq_m5_fast.metal new file mode 100644 index 00000000000..d224c13bf21 --- /dev/null +++ b/zig/kernels/metal/qwen27/awq_m5_fast.metal @@ -0,0 +1,295 @@ +// Fast M5 AWQ W4A16 g128 kernels reading .m5_tile layout: cooperative MV (M=1..32) and 64x64 NAX GEMM. +#ifndef TF_SIMD_FRAGS + +template +inline void sn_awq_m5_mv_impl( + const device bfloat* X, + const device uint* W, + const device float2* SB, + constant SnAwqArgs& a, + device bfloat* Y, + uint2 tg, + uint sg, + uint lane, + threadgroup float* red) { +#pragma clang fp contract(off) + const uint KG = uint(a.K) >> 7; + const uint tile = tg.x >> 2; + const uint c_base = (tg.x & 3u) * 8u; + const uint c_sub = lane >> 2; + const uint u4_idx = lane & 3u; + const uint j = tile * 32u + c_base + c_sub; + const bool live = (int(j) < a.N); + const uint vec_k = uint(a.K) >> 3; + const device uint4* X4 = (const device uint4*)X; + + const uint g_begin = (sg * KG) / SK; + const uint g_end_raw = ((sg + 1u) * KG) / SK; + const uint g_end = (TF_CTL == 3 && g_end_raw == KG && g_end_raw > g_begin) ? (g_end_raw - 1u) : g_end_raw; + +#if TF_CTL == 2 + if (tg.x == 0 && sg == 0 && lane == 0) ((device ushort*)X)[0] ^= 1u; +#endif + + sn_awq_acc_t acc[ROWS]; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) acc[r] = sn_awq_acc_t(0); + + for (uint g = g_begin; g < g_end; ++g) { + const device uint4* W4 = (const device uint4*)(W + (((size_t)tile * KG + g) * 32u + c_base) * 16u); + const uint4 wq = W4[lane]; + sn_awq_acc_t qx[ROWS], xs[ROWS]; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + qx[r] = sn_awq_acc_t(0); + xs[r] = sn_awq_acc_t(0); + } + _Pragma("clang loop unroll(full)") + for (uint u = 0; u < 4u; ++u) { + const uint word = wq[u]; + const vec qlo = vec( + float(word & 0xfu), float((word >> 4) & 0xfu), float((word >> 8) & 0xfu), float((word >> 12) & 0xfu)); + const vec qhi = vec( + float((word >> 16) & 0xfu), float((word >> 20) & 0xfu), float((word >> 24) & 0xfu), float(word >> 28)); + const uint x_u4 = g * 16u + u4_idx * 4u + u; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + const uint rr = (int(r) < a.M) ? r : 0u; + const uint4 xv = X4[(size_t)rr * vec_k + x_u4]; + const vec xlo = vec(as_type(xv.xy)); + const vec xhi = vec(as_type(xv.zw)); + qx[r] += dot(qlo, xlo) + dot(qhi, xhi); + xs[r] += (xlo.x + xlo.y + xlo.z + xlo.w) + (xhi.x + xhi.y + xhi.z + xhi.w); + } + } + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + qx[r] += simd_shuffle_xor(qx[r], 1); + qx[r] += simd_shuffle_xor(qx[r], 2); + xs[r] += simd_shuffle_xor(xs[r], 1); + xs[r] += simd_shuffle_xor(xs[r], 2); + } + if (u4_idx == 0u && live) { + const float2 sb = SB[(size_t)g * uint(a.N) + j]; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { +#if TF_CTL == 4 + acc[r] = sn_awq_acc_t(fma(sb.x, float(qx[r]), fma(sb.y, float(xs[r]), float(acc[r])))); +#else + acc[r] = fma(sb.x, qx[r], fma(sb.y, xs[r], acc[r])); +#endif + } + } + } + + if constexpr (SK == 1u) { + if (u4_idx == 0u && live) { + uint j_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, j, j_loc, ldy_eff); + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + if (int(r) < a.M) { + float out_v = float(acc[r]); +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y_dst[(size_t)r * ldy_eff + j_loc] = bfloat(out_v); + } + } + } + return; + } + + if (sg > 0u && u4_idx == 0u && live) { + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + if (int(r) < a.M) red[((sg - 1u) * 8u + c_sub) * ROWS + r] = float(acc[r]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (sg == 0u && u4_idx == 0u && live) { + uint j_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, j, j_loc, ldy_eff); + for (uint r = 0u; int(r) < a.M; ++r) { + sn_awq_acc_t total = acc[r]; + _Pragma("clang loop unroll(full)") + for (uint s2 = 1u; s2 < SK; ++s2) { + total += sn_awq_acc_t(red[((s2 - 1u) * 8u + c_sub) * ROWS + r]); + } + float out_v = float(total); +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y_dst[(size_t)r * ldy_eff + j_loc] = bfloat(out_v); + } + } +} + +#define SN_AWQ_M5_MV(ROWS, SK) \ + [[max_total_threads_per_threadgroup(SK * 32)]] \ + [[kernel]] void sn_awq_m5_mv_r##ROWS##_sk##SK( \ + const device bfloat* X [[buffer(0)]], \ + const device uint* W [[buffer(1)]], \ + const device float2* SB [[buffer(2)]], \ + constant SnAwqArgs& a [[buffer(3)]], \ + device bfloat* Y [[buffer(4)]], \ + uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], \ + uint2 tg [[threadgroup_position_in_grid]]) { \ + threadgroup float red[(SK > 1 ? (SK - 1) * 8 * ROWS : 1)]; \ + sn_awq_m5_mv_impl(X, W, SB, a, Y, tg, sg, lane, red); \ + } + +#define SN_AWQ_M5_MV_R(ROWS) \ + SN_AWQ_M5_MV(ROWS, 1) \ + SN_AWQ_M5_MV(ROWS, 2) \ + SN_AWQ_M5_MV(ROWS, 4) \ + SN_AWQ_M5_MV(ROWS, 8) + +SN_AWQ_M5_MV_R(1) +SN_AWQ_M5_MV_R(2) +SN_AWQ_M5_MV_R(4) +SN_AWQ_M5_MV_R(8) +SN_AWQ_M5_MV_R(16) +SN_AWQ_M5_MV_R(32) + +template +inline void sn_awq_nax_acc(thread float (&C)[16], thread const P_t& P, float2 my_sb, float xs0, float xs1, short fn) { +#pragma clang fp contract(off) + TF_UNROLL + for (int f = 0; f < 2; f++) { + TF_UNROLL + for (int j = 0; j < 4; j++) { + const float2 sb = simd_shuffle(my_sb, ushort(f * 16 + fn + j)); + TF_UNROLL + for (int r = 0; r < 2; r++) { + const float xs = r ? xs1 : xs0; + const int i = f * 8 + r * 4 + j; +#if TF_CTL == 4 + C[i] = float(half(fma(sb.x, P[i], fma(sb.y, xs, C[i])))); +#else + C[i] = fma(sb.x, P[i], fma(sb.y, xs, C[i])); +#endif + } + } + } +} + +// M5 prefill NAX GEMM (BM=64, BN=128, 8 simdgroups = 2x4): each simdgroup runs two 16x32 M-tiles sharing B. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void sn_awq_gemm_m5( + const device bfloat* X [[buffer(0)]], + const device uint* W [[buffer(1)]], + const device float2* SB [[buffer(2)]], + constant SnAwqArgs& a [[buffer(3)]], + device bfloat* Y [[buffer(4)]], + const device float* XS [[buffer(5)]], + uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint2 tg [[threadgroup_position_in_grid]]) { +#pragma clang fp contract(off) + constexpr int NT = 32, GS = 128, NF = 2, SWZ = 2; + const int tn = (a.N + 127) / 128, tm = (a.M + 63) / 64; + const int ty = (int(tg.y) << SWZ) + (int(tg.x) & ((1 << SWZ) - 1)); + const int tx = int(tg.x) >> SWZ; + if (tx >= tn || ty >= tm) return; + +#if TF_CTL == 2 + if (tx == 0 && ty == 0 && sg == 0 && lane == 0) ((device ushort*)X)[0] ^= 1u; +#endif + + const int sg_m = int(sg >> 2), sg_n = int(sg & 3u); + const int row0 = ty * 64 + sg_m * 32; + const int rem = a.M - row0; + const int tile = tx * 4 + sg_n; + const int n0 = tile * NT; + const bool active = (rem > 0 && n0 < a.N); + const bool two_m = (rem > 16); + const int M0 = active ? min(rem, 16) : 1; + const int M1 = (active && two_m) ? min(rem - 16, 16) : 1; + const int KG = a.K / GS; + const int g_end = (TF_CTL == 3 && KG > 0) ? (KG - 1) : KG; + const short qid = short(lane) >> 2; + const short fm = (qid & 4) | ((short(lane) >> 1) & 3); + const short fn = ((qid & 2) | (short(lane) & 1)) * 4; + + constexpr auto desc = matmul2d_descriptor(16, NT, GS, false, true, false, matmul2d_descriptor::mode::multiply); + matmul2d op; + tensor, tensor_inline> tA0( + (device bfloat*)(X + (size_t)(active ? row0 : 0) * a.K), dextents(a.K, M0)); + tensor, tensor_inline> tA1( + (device bfloat*)(X + (size_t)((active && two_m) ? (row0 + 16) : 0) * a.K), dextents(a.K, M1)); + + float C0[16], C1[16]; + TF_UNROLL + for (int i = 0; i < 16; i++) { + C0[i] = 0.0f; + C1[i] = 0.0f; + } + + float2 my_sb = (active && 0 < g_end && n0 + int(lane) < a.N) ? SB[(size_t)n0 + lane] : float2(0.0f); + const device float* XS0 = XS + (active ? row0 : 0); + const device float* XS1 = XS + ((active && two_m) ? (row0 + 16) : 0); + + for (int g = 0; g < g_end; g++) { + if ((g & 3) == 0) threadgroup_barrier(mem_flags::mem_none); + if (!active) continue; + const float2 my_sb_next = (g + 1 < g_end && n0 + int(lane) < a.N) + ? SB[(size_t)(g + 1) * a.N + n0 + lane] : float2(0.0f); + tensor, tensor_inline> b( + (device uchar*)W + ((size_t)tile * KG + g) * (NT * GS / 2), dextents(GS, NT)); + { + auto a0_slice = tA0.slice(g * GS, 0); + auto P = op.template get_destination_cooperative_tensor(); + op.run(a0_slice, b, P); + const float xs00 = (fm < M0) ? XS0[(size_t)g * a.MP + fm] : 0.0f; + const float xs01 = (fm + 8 < M0) ? XS0[(size_t)g * a.MP + fm + 8] : 0.0f; + sn_awq_nax_acc(C0, P, my_sb, xs00, xs01, fn); + } + if (two_m) { + auto a1_slice = tA1.slice(g * GS, 0); + auto P = op.template get_destination_cooperative_tensor(); + op.run(a1_slice, b, P); + const float xs10 = (fm < M1) ? XS1[(size_t)g * a.MP + fm] : 0.0f; + const float xs11 = (fm + 8 < M1) ? XS1[(size_t)g * a.MP + fm + 8] : 0.0f; + sn_awq_nax_acc(C1, P, my_sb, xs10, xs11, fn); + } + my_sb = my_sb_next; + } + + if (!active) return; + uint n0_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, uint(n0), n0_loc, ldy_eff); + device bfloat* Y0 = Y_dst + (size_t)row0 * ldy_eff; + for (int f = 0; f < NF; f++) { + for (int r = 0; r < 2; r++) { + const int m = fm + 8 * r; + const int col0_glob = n0 + f * 16 + fn; + const int col0_loc = int(n0_loc) + f * 16 + fn; + if (m < M0) { + for (int j = 0; j < 4; j++) { + if (col0_glob + j < a.N) { + float out_v = C0[f * 8 + r * 4 + j]; +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y0[(size_t)m * ldy_eff + col0_loc + j] = bfloat(out_v); + } + } + } + if (two_m && m < M1) { + for (int j = 0; j < 4; j++) { + if (col0_glob + j < a.N) { + float out_v = C1[f * 8 + r * 4 + j]; +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y0[(size_t)(m + 16) * ldy_eff + col0_loc + j] = bfloat(out_v); + } + } + } + } + } +} +#endif diff --git a/zig/kernels/metal/qwen27/awq_w4a16.metal b/zig/kernels/metal/qwen27/awq_w4a16.metal new file mode 100644 index 00000000000..bb865480e8f --- /dev/null +++ b/zig/kernels/metal/qwen27/awq_w4a16.metal @@ -0,0 +1,561 @@ +// Zero-lossless AWQ W4A16 (g128, FP32 scale+bias) decode and prefill kernels for M5 and M3. +#include +using namespace metal; +#include "../nax.h" + +#ifndef TF_CTL +#define TF_CTL 0 +#endif + +#if TF_CTL == 4 +typedef half sn_awq_acc_t; +#else +typedef float sn_awq_acc_t; +#endif + +struct SnAwqArgs { + int M, N, K, MP, LDY; + uint split1; + ulong y1_addr, y2_addr; + uint ldy1, split2, ldy2, _pad; +}; + +inline device bfloat* sn_awq_split_dest( + device bfloat* Y0, + constant SnAwqArgs& a, + uint col, + thread uint& col_out, + thread uint& ldy_out) { + if (a.y2_addr != 0ul && col >= a.split2) { + col_out = col - a.split2; + ldy_out = a.ldy2; + return (device bfloat*)a.y2_addr; + } else if (a.y1_addr != 0ul && col >= a.split1) { + col_out = col - a.split1; + ldy_out = a.ldy1; + return (device bfloat*)a.y1_addr; + } + col_out = col; + ldy_out = uint(a.LDY); + return Y0; +} + +inline float sn_awq_xsum_inline(const device bfloat* X, int m, int g, int M, int K) { +#pragma clang fp contract(off) + float acc = 0.0f; + if (m < M) { + const device bfloat* xp = X + (size_t)m * K + g * 128; + for (int i = 0; i < 128; i++) acc += float(xp[i]); + } + return acc; +} + +#ifndef TF_SIMD_FRAGS +using namespace mpp::tensor_ops; + +inline void sn_awq_sb_fetch( + const device float2* SB, int g, int g_end, int N, int n0, int lane, short fn, + thread float2 (&sb)[2][4]) { + const bool ok = g < g_end; + const float2 my_sb = (ok && n0 + lane < N) ? SB[(size_t)g * N + n0 + lane] : float2(0.0f); + for (int f = 0; f < 2; f++) { + for (int j = 0; j < 4; j++) { + sb[f][j] = simd_shuffle(my_sb, ushort(f * 16 + fn + j)); + } + } +} + +template +inline void sn_awq_lane_impl( + const device bfloat* X, + const device uint* W, + const device float2* SB, + constant SnAwqArgs& a, + device bfloat* Y, + const device float* XS, + uint sgi, + uint lanei, + uint2 tg, + threadgroup float* part) { +#pragma clang fp contract(off) + constexpr int NT = 32, GS = 128, NF = 2; + const int row0 = ROW_BLOCKS ? int(tg.y) * 16 : 0; + int M_local = a.M; + if constexpr (ROW_BLOCKS) { + const int rem = a.M - row0; + if (rem <= 0) return; + X += (size_t)row0 * a.K; + if constexpr (PRECOMPUTE_SUMS) XS += row0; + M_local = min(rem, 16); + } + const int tile = int(tg.x); + const int lane = int(lanei), sg = int(sgi); + const int KG = a.K / GS, n0 = tile * NT; + if (n0 >= a.N) return; + const short qid = short(lane) >> 2; + const short fm = (qid & 4) | ((short(lane) >> 1) & 3); + const short fn = ((qid & 2) | (short(lane) & 1)) * 4; + const int g_begin = (sg * KG) / SK; + int g_end = ((sg + 1) * KG) / SK; +#if TF_CTL == 3 + if (g_end == KG && g_end > g_begin) g_end -= 1; +#endif +#if TF_CTL == 2 + if (tile == 0 && (!ROW_BLOCKS || tg.y == 0) && sg == 0 && lane == 0) { + ((device ushort*)X)[0] ^= 1u; + } +#endif + + constexpr auto desc = matmul2d_descriptor(16, NT, GS, false, true, false, matmul2d_descriptor::mode::multiply); + matmul2d op; + tensor, tensor_inline> tA((device bfloat*)X, dextents(a.K, M_local)); + + float C[16]; + for (int i = 0; i < 16; i++) C[i] = 0.0f; + + float2 sb_cur[2][4]; + sn_awq_sb_fetch(SB, g_begin, g_end, a.N, n0, lane, fn, sb_cur); + const ushort x_leader = ushort(lane & 22); + + for (int g = g_begin; g < g_end; g++) { + float2 sb_next[2][4]; + sn_awq_sb_fetch(SB, g + 1, g_end, a.N, n0, lane, fn, sb_next); + tensor, tensor_inline> b( + (device uchar*)W + ((size_t)tile * KG + g) * (NT * GS / 2), dextents(GS, NT)); + auto a_slice = tA.slice(g * GS, 0); + auto P = op.template get_destination_cooperative_tensor(); + op.run(a_slice, b, P); + + float xs0, xs1; + if constexpr (PRECOMPUTE_SUMS) { + xs0 = (fm < M_local) ? XS[(size_t)g * a.MP + fm] : 0.0f; + xs1 = (fm + 8 < M_local) ? XS[(size_t)g * a.MP + fm + 8] : 0.0f; + } else { + float lx0 = 0.0f, lx1 = 0.0f; + if ((lane & 9) == 0) { + lx0 = sn_awq_xsum_inline(X, fm, g, M_local, a.K); + lx1 = sn_awq_xsum_inline(X, fm + 8, g, M_local, a.K); + } + xs0 = simd_shuffle(lx0, x_leader); + xs1 = simd_shuffle(lx1, x_leader); + } + + for (int f = 0; f < NF; f++) { + for (int r = 0; r < 2; r++) { + const float xs = r ? xs1 : xs0; + for (int j = 0; j < 4; j++) { + const int i = f * 8 + r * 4 + j; +#if TF_CTL == 4 + C[i] = float(half(fma(sb_cur[f][j].x, P[i], fma(sb_cur[f][j].y, xs, C[i])))); +#else + C[i] = fma(sb_cur[f][j].x, P[i], fma(sb_cur[f][j].y, xs, C[i])); +#endif + } + } + } + for (int f = 0; f < NF; f++) + for (int j = 0; j < 4; j++) sb_cur[f][j] = sb_next[f][j]; + } + + if constexpr (SK > 1) { + if (sg > 0) { + for (int i = 0; i < 16; i++) part[((sg - 1) * 16 + i) * 32 + lane] = C[i]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + for (int s2 = 1; s2 < SK; s2++) { + for (int i = 0; i < 16; i++) { +#if TF_CTL == 4 + C[i] = float(half(C[i]) + half(part[((s2 - 1) * 16 + i) * 32 + lane])); +#else + C[i] += part[((s2 - 1) * 16 + i) * 32 + lane]; +#endif + } + } + } + } + + if (sg == 0) { + uint n0_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, uint(n0), n0_loc, ldy_eff); + if constexpr (ROW_BLOCKS) Y_dst += (size_t)row0 * ldy_eff; + for (int f = 0; f < NF; f++) { + for (int r = 0; r < 2; r++) { + const int m = fm + 8 * r; + const int col0_glob = n0 + f * 16 + fn; + const int col0_loc = int(n0_loc) + f * 16 + fn; + if (m < M_local) { + for (int j = 0; j < 4; j++) { + if (col0_glob + j < a.N) { + float out_v = C[f * 8 + r * 4 + j]; +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y_dst[(size_t)m * ldy_eff + col0_loc + j] = bfloat(out_v); + } + } + } + } + } + } +} + +#define SN_AWQ_LANE(SK, PS, RB) \ + [[max_total_threads_per_threadgroup(SK * 32)]] \ + [[kernel]] void sn_awq_lane_sk##SK##_p##PS##_r##RB( \ + const device bfloat* X [[buffer(0)]], \ + const device uint* W [[buffer(1)]], \ + const device float2* SB [[buffer(2)]], \ + constant SnAwqArgs& a [[buffer(3)]], \ + device bfloat* Y [[buffer(4)]], \ + const device float* XS [[buffer(5)]], \ + uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], \ + uint2 tg [[threadgroup_position_in_grid]]) { \ + threadgroup float part[(SK > 1 ? SK - 1 : 1) * 16 * 32]; \ + sn_awq_lane_impl(X, W, SB, a, Y, XS, sg, lane, tg, part); \ + } + +#define SN_AWQ_LANE_SK(SK) \ + SN_AWQ_LANE(SK, 0, 0) \ + SN_AWQ_LANE(SK, 0, 1) \ + SN_AWQ_LANE(SK, 1, 0) \ + SN_AWQ_LANE(SK, 1, 1) + +SN_AWQ_LANE_SK(1) +SN_AWQ_LANE_SK(2) +SN_AWQ_LANE_SK(4) +SN_AWQ_LANE_SK(8) +#endif + +// M3 (and universal fallback) coalesced AWQ W4A16 decode/verify kernel: [N][K/8] u32, [N][KG] float2. +#define SN_AWQ_COLS(R) (((R) >= 2u && (R) <= 8u) ? 2u : 1u) + +template +inline void sn_awq_row_mv_impl( + const device bfloat* X, + const device uint* W, + const device float2* SB, + constant SnAwqArgs& a, + device bfloat* Y, + uint3 tg, + uint sg, + uint lane, + threadgroup float* red) { +#pragma clang fp contract(off) + constexpr uint COLS = SN_AWQ_COLS(ROWS); + constexpr uint SG = 8u; + constexpr uint GROUPS = SG / SK; + constexpr uint NO = GROUPS * COLS; + const uint g_idx = sg / SK; + const uint s = sg % SK; + const uint j0 = tg.x * NO + g_idx * COLS; + const uint KG = uint(a.K) >> 7; + const uint num_u4 = uint(a.K) >> 5; + const uint end_u4 = (TF_CTL == 3 && num_u4 > 0u) ? (num_u4 - 1u) : num_u4; + const device uint4* X4 = (const device uint4*)X; + + sn_awq_acc_t acc[COLS][ROWS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) acc[col][r] = sn_awq_acc_t(0); + } + + if (int(j0) < a.N) { +#if TF_CTL == 2 + if (tg.x == 0 && sg == 0 && lane == 0) { + ((device ushort*)X)[0] ^= 1u; + } +#endif + const device uint4* W_ptr[COLS]; + const device float2* SB_ptr[COLS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + const uint jj = (int(j0 + col) < a.N) ? (j0 + col) : 0u; + W_ptr[col] = (const device uint4*)(W + (size_t)jj * (uint(a.K) >> 3)); + SB_ptr[col] = SB + (size_t)jj * KG; + } + for (uint idx = s * 32u + lane; idx < end_u4; idx += SK * 32u) { + uint4 wq[COLS]; + float2 sb[COLS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + wq[col] = W_ptr[col][idx]; + sb[col] = SB_ptr[col][idx >> 2]; + } + _Pragma("clang loop unroll(full)") + for (uint u = 0; u < 4u; ++u) { + vec wlo[COLS], whi[COLS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + const uint word = wq[col][u]; + const float scale = sb[col].x, bias = sb[col].y; + wlo[col] = vec( + fma(float(word & 0xfu), scale, bias), fma(float((word >> 4) & 0xfu), scale, bias), + fma(float((word >> 8) & 0xfu), scale, bias), fma(float((word >> 12) & 0xfu), scale, bias)); + whi[col] = vec( + fma(float((word >> 16) & 0xfu), scale, bias), fma(float((word >> 20) & 0xfu), scale, bias), + fma(float((word >> 24) & 0xfu), scale, bias), fma(float((word >> 28) & 0xfu), scale, bias)); + } + const size_t x_off = ((size_t)idx * 4u) + u; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + const uint rr = (int(r) < a.M) ? r : 0u; + const uint4 xv = X4[(size_t)rr * (num_u4 * 4u) + x_off]; + const vec xlo = vec(as_type(xv.xy)); + const vec xhi = vec(as_type(xv.zw)); + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) acc[col][r] += dot(wlo[col], xlo) + dot(whi[col], xhi); + } + } + } + } + + if constexpr (SK == 1u) { + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + if (int(j0 + col) < a.N) { + uint j_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, j0 + col, j_loc, ldy_eff); + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + float v = float(simd_sum(acc[col][r])); + if (lane == 0 && int(r) < a.M) { +#if TF_CTL == 1 + if (isnan(v) || isinf(v)) v = 0.0f; +#endif + Y_dst[(size_t)r * ldy_eff + j_loc] = bfloat(v); + } + } + } + } + return; + } + + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + const float v = float(simd_sum(acc[col][r])); + if (int(j0 + col) < a.N && lane == 0 && int(r) < a.M) { + red[((g_idx * COLS + col) * SK + s) * ROWS + r] = v; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (s == 0) { + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + if (int(j0 + col) < a.N) { + uint j_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, j0 + col, j_loc, ldy_eff); + for (uint r = lane; int(r) < a.M; r += 32u) { + sn_awq_acc_t total = sn_awq_acc_t(0); + _Pragma("clang loop unroll(full)") + for (uint k = 0; k < SK; ++k) total += sn_awq_acc_t(red[((g_idx * COLS + col) * SK + k) * ROWS + r]); + float out_v = float(total); +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y_dst[(size_t)r * ldy_eff + j_loc] = bfloat(out_v); + } + } + } + } +} + +#define SN_AWQ_ROW_MV(ROWS, SK) \ + [[max_total_threads_per_threadgroup(256)]] \ + [[kernel]] void sn_awq_row_mv_r##ROWS##_sk##SK( \ + const device bfloat* X [[buffer(0)]], \ + const device uint* W [[buffer(1)]], \ + const device float2* SB [[buffer(2)]], \ + constant SnAwqArgs& a [[buffer(3)]], \ + device bfloat* Y [[buffer(4)]], \ + uint3 tg [[threadgroup_position_in_grid]], \ + uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]]) { \ + threadgroup float red[SK > 1 ? 8 * SN_AWQ_COLS(ROWS) * ROWS : 1]; \ + sn_awq_row_mv_impl(X, W, SB, a, Y, tg, sg, lane, red); \ + } + +#define SN_AWQ_ROW_MV_R(ROWS) \ + SN_AWQ_ROW_MV(ROWS, 1) \ + SN_AWQ_ROW_MV(ROWS, 2) \ + SN_AWQ_ROW_MV(ROWS, 4) \ + SN_AWQ_ROW_MV(ROWS, 8) + +SN_AWQ_ROW_MV_R(1) +SN_AWQ_ROW_MV_R(2) +SN_AWQ_ROW_MV_R(4) +SN_AWQ_ROW_MV_R(8) +SN_AWQ_ROW_MV_R(16) +SN_AWQ_ROW_MV_R(32) + +inline void sn_qmm_m3_load( + const device uint* W, const device float2* SB, int n_row, int N, int KG, int kw, int half_k, + int step, thread uint2& wq, thread float2& sb) { + if (n_row < N) { + const int g = step >> 2, sub = step & 3, k_base = (g << 7) + (sub << 5); + sb = SB[(size_t)n_row * KG + g]; + wq = ((const device uint2*)(W + (size_t)n_row * kw + (k_base >> 3)))[half_k]; + } else { + sb = float2(0.0f); + wq = uint2(0u); + } +} + +inline void sn_qmm_m3_store(threadgroup float* Bs_buf, int n_row, int N, int r_loc, int half_k, uint2 wq, float2 sb) { + threadgroup float* dst = Bs_buf + r_loc * 36 + half_k * 16; + if (n_row < N) { + TF_UNROLL + for (int u = 0; u < 2; u++) { + const uint word = (u == 0) ? wq.x : wq.y; + TF_UNROLL + for (int e = 0; e < 8; e++) { + dst[u * 8 + e] = fma(float((word >> (4 * e)) & 0xfu), sb.x, sb.y); + } + } + } else { + TF_UNROLL + for (int e = 0; e < 16; e++) dst[e] = 0.0f; + } +} + +// M3 prefill QMM (M > 32): double-buffered cooperative dequant of 64x32 weight tiles, mma_16x32 via nax.h. +[[max_total_threads_per_threadgroup(128)]] +[[kernel]] void sn_awq_qmm_m3( + const device bfloat* X [[buffer(0)]], + const device uint* W [[buffer(1)]], + const device float2* SB [[buffer(2)]], + constant SnAwqArgs& a [[buffer(3)]], + device bfloat* Y [[buffer(4)]], + uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint2 tg [[threadgroup_position_in_grid]]) { +#pragma clang fp contract(off) + const int n0 = int(tg.x) * 64, m0 = int(tg.y) * 64; + if (m0 >= a.M || n0 >= a.N) return; +#if TF_CTL == 2 + if (tg.x == 0 && tg.y == 0 && sg == 0 && lane == 0) ((device ushort*)X)[0] ^= 1u; +#endif + threadgroup float Bs[2][64 * 36]; + const uint tid = sg * 32u + lane; + const int r_loc = int(tid >> 1), half_k = int(tid & 1u); + const int n_row = n0 + r_loc; + const int KG = a.K / 128, kw = a.K / 8; + const int sg_m = int(sg >> 1), sg_n = int(sg & 1u); + const int row_sg = m0 + 32 * sg_m, col_sg = n0 + 32 * sg_n; + const int rows = min(32, a.M - row_sg), cols = min(32, a.N - col_sg); + const bool sg_live = (rows > 0 && cols > 0); + const bool full = (rows == 32 && cols == 32); + const short2 home = tfp::frag_home(ushort(lane)); + + tfp::frag acc[2][2]; + TF_UNROLL + for (short i = 0; i < 2; i++) + TF_UNROLL + for (short j = 0; j < 2; j++) acc[i][j] = tfp::frag(0); + + const int total_steps = (TF_CTL == 3 && KG > 0) ? (KG * 4 - 1) : (KG * 4); + if (total_steps > 0) { + uint2 wq0; + float2 sb0; + sn_qmm_m3_load(W, SB, n_row, a.N, KG, kw, half_k, 0, wq0, sb0); + sn_qmm_m3_store(Bs[0], n_row, a.N, r_loc, half_k, wq0, sb0); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (int step = 0; step < total_steps; step++) { + uint2 wq_next; + float2 sb_next; + const bool has_next = (step + 1 < total_steps); + if (has_next) sn_qmm_m3_load(W, SB, n_row, a.N, KG, kw, half_k, step + 1, wq_next, sb_next); + if (sg_live) { + const int k_base = step * 32; + const threadgroup float* Bs_cur = Bs[step & 1]; + const device bfloat* Ap = X + (size_t)row_sg * a.K + k_base; + tfp::frag af[2][2], bf[2][2]; + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + if (full) { + tfp::frag_get(af[i][j], Ap, a.K, 16 * i, 16 * j, home); + tfp::frag_get_t(bf[i][j], Bs_cur, 36, 32 * sg_n + 16 * j, 16 * i, home); + } else { + tfp::frag_get_in(af[i][j], Ap, a.K, 16 * i, 16 * j, home, rows, a.K - k_base); + tfp::frag_get_t(bf[i][j], Bs_cur, 36, 32 * sg_n + 16 * j, 16 * i, home); + } + } + } + TF_UNROLL + for (short m = 0; m < 2; m++) + TF_UNROLL + for (short k2 = 0; k2 < 2; k2++) { + tfp::mma_16x32(acc[m][0], acc[m][1], af[m][k2], bf[k2][0], bf[k2][1]); + } +#if TF_CTL == 4 + TF_UNROLL + for (short m = 0; m < 2; m++) + TF_UNROLL + for (short n = 0; n < 2; n++) + TF_UNROLL + for (short e = 0; e < 8; e++) acc[m][n][e] = float(half(acc[m][n][e])); +#endif + } + if (has_next) sn_qmm_m3_store(Bs[(step + 1) & 1], n_row, a.N, r_loc, half_k, wq_next, sb_next); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + if (sg_live) { +#if TF_CTL == 1 + TF_UNROLL + for (short m = 0; m < 2; m++) + TF_UNROLL + for (short n = 0; n < 2; n++) + TF_UNROLL + for (short e = 0; e < 8; e++) { + if (isnan(acc[m][n][e]) || isinf(acc[m][n][e])) acc[m][n][e] = 0.0f; + } +#endif + uint col_loc, ldy_eff; + device bfloat* Y_dst = sn_awq_split_dest(Y, a, uint(col_sg), col_loc, ldy_eff); + device bfloat* Yp = Y_dst + (size_t)row_sg * ldy_eff + col_loc; + TF_UNROLL + for (short i = 0; i < 2; i++) + TF_UNROLL + for (short j = 0; j < 2; j++) { + if (full) tfp::frag_put(acc[i][j], Yp, int(ldy_eff), 16 * i, 16 * j, home); + else tfp::frag_put_in(acc[i][j], Yp, int(ldy_eff), 16 * i, 16 * j, home, rows, cols); + } + } +} + +// Deterministic [KG][MP] FP32 group sums for GS=128, matching sn_awq_xsum_inline bit-for-bit. +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void sn_awq_xsum_128( + const device bfloat* X [[buffer(0)]], + constant int4& dims [[buffer(1)]], + device float* XS [[buffer(2)]], + uint index [[thread_position_in_grid]]) { + const int M = dims.x, MP = dims.y, K = dims.z; + const int KG = K / 128; + const int m = int(index) % MP, g = int(index) / MP; + if (g >= KG) return; + XS[index] = sn_awq_xsum_inline(X, m, g, M, K); +} + +// Optional runtime input scaling for AWQ smooth input_scale: bf16(f32(x) / input_scale[k]). +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void sn_awq_scale_input( + const device bfloat* X [[buffer(0)]], + const device float* scale [[buffer(1)]], + constant int2& dims [[buffer(2)]], + device bfloat* Y [[buffer(3)]], + uint2 gid [[thread_position_in_grid]]) { + if (int(gid.x) >= dims.y || int(gid.y) >= dims.x) return; + const size_t idx = (size_t)gid.y * dims.y + gid.x; + Y[idx] = bfloat(float(X[idx]) / scale[gid.x]); +} diff --git a/zig/kernels/metal/qwen27/bf16_linear.metal b/zig/kernels/metal/qwen27/bf16_linear.metal new file mode 100644 index 00000000000..e0afc99984a --- /dev/null +++ b/zig/kernels/metal/qwen27/bf16_linear.metal @@ -0,0 +1,505 @@ +// BF16 linear kernels for M5 and M3: row-invariant decode/verify (M=1..32) and NAX/SIMD prefill GEMM (M>32). +#include +using namespace metal; +#include "../nax.h" + +#ifndef TF_CTL +#define TF_CTL 0 +#endif + +#if TF_CTL == 4 +typedef half sn_mv_acc_t; +#else +typedef float sn_mv_acc_t; +#endif + +struct SnBf16MvArgs { + uint rows, n, k, ldy; + ulong y1_addr, y2_addr; + uint split1, ldy1, split2, ldy2; +}; + +struct SnBf16GemmArgs { + int32_t p[16]; + ulong y1_addr, y2_addr; + uint split1, ldy1, split2, ldy2; +}; + +struct SnBf16SumArgs { + int32_t p[6]; + ulong y1_addr, y2_addr; + uint split1, ldy1, split2, ldy2; +}; + +inline device bfloat* sn_bf16_split_dest( + device bfloat* Y0, + uint ldy0, + ulong y1_addr, + uint split1, + uint ldy1, + ulong y2_addr, + uint split2, + uint ldy2, + uint col, + thread uint& col_out, + thread uint& ldy_out) { + if (y2_addr != 0ul && col >= split2) { + col_out = col - split2; + ldy_out = ldy2; + return (device bfloat*)y2_addr; + } else if (y1_addr != 0ul && col >= split1) { + col_out = col - split1; + ldy_out = ldy1; + return (device bfloat*)y1_addr; + } + col_out = col; + ldy_out = ldy0; + return Y0; +} + +#define SN_BF16_COLS(R) ((R) == 1 ? 1u : ((R) <= 4 ? 2u : 1u)) + +// Y[r, j] = bf16(sum_i X[r, i] * W[j, i]) in FP32; SK slices per output row reduce in fixed slice order. +template +inline void sn_bf16_mv_impl( + const device bfloat* X, + const device bfloat* W, + constant SnBf16MvArgs& a, + device bfloat* Y, + uint3 tg, + uint sg, + uint lane, + threadgroup float* red) { +#pragma clang fp contract(off) + constexpr uint COLS = SN_BF16_COLS(ROWS); + constexpr uint SG = 8u; + constexpr uint GROUPS = SG / SK; + constexpr uint NO = GROUPS * COLS; + const uint g_idx = sg / SK; + const uint s = sg % SK; + const uint j0 = tg.x * NO + g_idx * COLS; + const uint vec_k = a.k >> 3; + const uint k_end = (TF_CTL == 3 && vec_k > 0) ? (vec_k - 1u) : vec_k; + const device uint4* X4 = (const device uint4*)X; + + sn_mv_acc_t acc[COLS][ROWS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) acc[col][r] = sn_mv_acc_t(0); + } + +#if TF_CTL == 2 + if (tg.x == 0 && sg == 0 && lane == 0 && a.n > 0) { + ((device ushort*)X)[0] ^= 1u; + } +#endif + + const uint step = SK * 32u; + if (j0 + COLS <= a.n) { + const device uint4* W_ptr[COLS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + W_ptr[col] = (const device uint4*)(W + (size_t)(j0 + col) * a.k); + } + for (uint c = s * 32u + lane; c < k_end; c += step) { + vec fx0[ROWS], fx1[ROWS]; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + const uint rr = (r < a.rows) ? r : 0u; + const uint4 xv = X4[(size_t)rr * vec_k + c]; + fx0[r] = vec(as_type(xv.xy)); + fx1[r] = vec(as_type(xv.zw)); + } + uint4 wv[COLS]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) wv[col] = W_ptr[col][c]; + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + const vec fw0 = vec(as_type(wv[col].xy)); + const vec fw1 = vec(as_type(wv[col].zw)); + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + acc[col][r] += dot(fw0, fx0[r]) + dot(fw1, fx1[r]); + } + } + } + } else if (j0 < a.n) { + for (uint c = s * 32u + lane; c < k_end; c += step) { + vec fx0[ROWS], fx1[ROWS]; + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + const uint rr = (r < a.rows) ? r : 0u; + const uint4 xv = X4[(size_t)rr * vec_k + c]; + fx0[r] = vec(as_type(xv.xy)); + fx1[r] = vec(as_type(xv.zw)); + } + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + if (j0 + col < a.n) { + const uint4 wv = ((const device uint4*)(W + (size_t)(j0 + col) * a.k))[c]; + const vec fw0 = vec(as_type(wv.xy)); + const vec fw1 = vec(as_type(wv.zw)); + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + acc[col][r] += dot(fw0, fx0[r]) + dot(fw1, fx1[r]); + } + } + } + } + } + + if constexpr (SK == 1u) { + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + if (j0 + col < a.n) { + uint j_loc, ldy_eff; + device bfloat* Y_dst = sn_bf16_split_dest( + Y, a.ldy, a.y1_addr, a.split1, a.ldy1, a.y2_addr, a.split2, a.ldy2, j0 + col, j_loc, ldy_eff); + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + float v = float(simd_sum(acc[col][r])); + if (lane == 0 && r < a.rows) { +#if TF_CTL == 1 + if (isnan(v) || isinf(v)) v = 0.0f; +#endif + Y_dst[(size_t)r * ldy_eff + j_loc] = bfloat(v); + } + } + } + } + return; + } + + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + _Pragma("clang loop unroll(full)") + for (uint r = 0; r < ROWS; ++r) { + const float v = float(simd_sum(acc[col][r])); + if (j0 + col < a.n && lane == 0 && r < a.rows) { + red[((g_idx * COLS + col) * SK + s) * ROWS + r] = v; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (s == 0) { + _Pragma("clang loop unroll(full)") + for (uint col = 0; col < COLS; ++col) { + if (j0 + col < a.n) { + uint j_loc, ldy_eff; + device bfloat* Y_dst = sn_bf16_split_dest( + Y, a.ldy, a.y1_addr, a.split1, a.ldy1, a.y2_addr, a.split2, a.ldy2, j0 + col, j_loc, ldy_eff); + for (uint r = lane; r < a.rows; r += 32u) { + sn_mv_acc_t total = sn_mv_acc_t(0); + _Pragma("clang loop unroll(full)") + for (uint k = 0; k < SK; ++k) { + total += sn_mv_acc_t(red[((g_idx * COLS + col) * SK + k) * ROWS + r]); + } + float out_v = float(total); +#if TF_CTL == 1 + if (isnan(out_v) || isinf(out_v)) out_v = 0.0f; +#endif + Y_dst[(size_t)r * ldy_eff + j_loc] = bfloat(out_v); + } + } + } + } +} + +#define SN_BF16_MV(ROWS, SK) \ + [[max_total_threads_per_threadgroup(256)]] \ + [[kernel]] void sn_bf16_mv_r##ROWS##_sk##SK( \ + const device bfloat* X [[buffer(0)]], \ + const device bfloat* W [[buffer(1)]], \ + constant SnBf16MvArgs& a [[buffer(2)]], \ + device bfloat* Y [[buffer(3)]], \ + uint3 tg [[threadgroup_position_in_grid]], \ + uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]]) { \ + threadgroup float red[SK > 1 ? 8 * SN_BF16_COLS(ROWS) * ROWS : 1]; \ + sn_bf16_mv_impl(X, W, a, Y, tg, sg, lane, red); \ + } + +#define SN_BF16_MV_ROW(ROWS) \ + SN_BF16_MV(ROWS, 1) \ + SN_BF16_MV(ROWS, 2) \ + SN_BF16_MV(ROWS, 4) \ + SN_BF16_MV(ROWS, 8) + +SN_BF16_MV_ROW(1) +SN_BF16_MV_ROW(2) +SN_BF16_MV_ROW(4) +SN_BF16_MV_ROW(8) +SN_BF16_MV_ROW(16) +SN_BF16_MV_ROW(32) + +namespace sn_prefill { + +template +inline void gemm_step( + thread tfp::frag (&acc)[2][2], + const device bfloat* A, + const device bfloat* B, + int lda, + int ldb, + int kk, + int kn, + int rows, + int cols, + short2 home) { + tfp::frag a[2][2], b[2][2]; + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + const int ar = 16 * i, ac = kk + 16 * j; + const int br = TB ? 16 * j : kk + 16 * i; + const int bc = TB ? kk + 16 * i : 16 * j; +#ifdef TF_SIMD_FRAGS + if (BOUND) { + tfp::frag_get_in(a[i][j], A, lda, ar, ac, home, rows, kk + kn); + if (TB) tfp::frag_get_t_in(b[i][j], B, ldb, br, bc, home, cols, kk + kn); + else tfp::frag_get_in(b[i][j], B, ldb, br, bc, home, kk + kn, cols); + } else { + tfp::frag_get(a[i][j], A, lda, ar, ac, home); + if (TB) tfp::frag_get_t(b[i][j], B, ldb, br, bc, home); + else tfp::frag_get(b[i][j], B, ldb, br, bc, home); + } +#else + if (BOUND) { + tfp::frag_get_in(a[i][j], A, lda, ar, ac, home, rows, kk + kn); + tfp::frag_get_in(b[i][j], B, ldb, br, bc, home, TB ? cols : kk + kn, TB ? kk + kn : cols); + } else { + tfp::frag_get(a[i][j], A, lda, ar, ac, home); + tfp::frag_get(b[i][j], B, ldb, br, bc, home); + } +#endif + } + } + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short k = 0; k < 2; k++) { + tfp::mma_16x32(acc[m][0], acc[m][1], a[m][k], b[k][0], b[k][1]); + } + } +#if TF_CTL == 4 + TF_UNROLL + for (short m = 0; m < 2; m++) { + TF_UNROLL + for (short n = 0; n < 2; n++) { + TF_UNROLL + for (short e = 0; e < 8; e++) acc[m][n][e] = float(half(acc[m][n][e])); + } + } +#endif +} + +template +inline void gemm_block( + thread tfp::frag (&acc)[2][2], + const device bfloat* A, + const device bfloat* B, + int lda, + int ldb, + int K, + int kblocks, + int rows, + int cols, + short2 home) { + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) acc[i][j] = tfp::frag(0); + } + const bool live = rows > 0 && cols > 0; +#pragma clang loop unroll(disable) + for (int kb = 0; kb < kblocks; kb++) { + threadgroup_barrier(mem_flags::mem_none); + if (!FULL && !live) continue; +#pragma clang loop unroll(disable) + for (int kk = 0; kk < BK; kk += 32) { + gemm_step(acc, A, B, lda, ldb, kk, 32, rows, cols, home); + } + A += BK; + B += TB ? BK : BK * ldb; + } + const int rest = K - kblocks * BK; + if (rest > 0) { + simdgroup_barrier(mem_flags::mem_none); + if (!FULL && !live) return; +#pragma clang loop unroll(disable) + for (int kk = 0; kk < rest; kk += 32) { + gemm_step(acc, A, B, lda, ldb, kk, max(0, rest - kk), rows, cols, home); + } + } +} + +template +inline void gemm_store( + thread tfp::frag (&acc)[2][2], + device O* D, + int ldd, + int rows, + int cols, + short2 home) { +#if TF_CTL == 1 + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + if (isnan(acc[i][j][e]) || isinf(acc[i][j][e])) acc[i][j][e] = 0.0f; + } + } + } +#endif + TF_UNROLL + for (short i = 0; i < 2; i++) { + TF_UNROLL + for (short j = 0; j < 2; j++) { + if (FULL) tfp::frag_put(acc[i][j], D, ldd, 16 * i, 16 * j, home); + else tfp::frag_put_in(acc[i][j], D, ldd, 16 * i, 16 * j, home, rows, cols); + } + } +} + +template +inline void gemm_nax( + const device bfloat* A, + const device bfloat* B, + device bfloat* D, + constant SnBf16GemmArgs& args, + uint3 tg, + uint sg, + uint lane) { + static_assert(BM / WM == 32 && BN / WN == 32, "a simdgroup owns a 32x32 block"); + constant int32_t* P = args.p; + const int swz = P[8]; + const int ty = (int(tg.y) << swz) + (int(tg.x) & ((1 << swz) - 1)); + const int tx = int(tg.x) >> swz; + if (tx >= P[6] || ty >= P[7]) return; +#if TF_CTL == 2 + if (tx == 0 && ty == 0 && sg == 0 && lane == 0) ((device ushort*)A)[0] ^= 1u; +#endif + constexpr bool TB = (TF_CTL == 3) ? false : true; + const int lda = P[3], ldb = P[4], ldd = P[5]; + const int row = ty * BM + 32 * int(sg / WN); + const int col = tx * BN + 32 * int(sg % WN); + A += long(P[13]) + long(P[10]) * tg.z + long(row) * lda; + B += long(P[14]) + long(P[11]) * tg.z + (TB ? long(col) * ldb : long(col)); + const int rows = AM ? 32 : min(32, P[0] - row); + const int cols = AN ? 32 : min(32, P[1] - col); + const bool full = (AM || rows == 32) && (AN || cols == 32); + const short2 home = tfp::frag_home(ushort(lane)); + tfp::frag acc[2][2]; + if (full) { + gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + } else { + gemm_block(acc, A, B, lda, ldb, P[2], P[9], rows, cols, home); + } + if (full || (rows > 0 && cols > 0)) { + uint col_loc, ldd_eff; + device bfloat* D_dst = sn_bf16_split_dest( + D, uint(ldd), args.y1_addr, args.split1, args.ldy1, + args.y2_addr, args.split2, args.ldy2, uint(col), col_loc, ldd_eff); + D_dst += long(P[12]) * tg.z + long(row) * int(ldd_eff) + int(col_loc); + if (full) gemm_store(acc, D_dst, int(ldd_eff), rows, cols, home); + else gemm_store(acc, D_dst, int(ldd_eff), rows, cols, home); + } +} + +template +inline void gemm_splitk_nax( + const device bfloat* A, + const device bfloat* B, + device float* C, + const device int* P, + uint3 tg, + uint sg, + uint lane) { + static_assert(BM / WM == 32 && BN / WN == 32, "a simdgroup owns a 32x32 block"); + const int swz = P[11]; + const int span_n = P[6] << swz; + const int span_m = (P[7] + (1 << swz) - 1) >> swz; + const int part = int(tg.x) / (span_n * span_m); + const int at = int(tg.x) % (span_n * span_m); + const int gx = at % span_n, gy = at / span_n; + const int ty = (gy << swz) + (gx & ((1 << swz) - 1)), tx = gx >> swz; + if (tx >= P[6] || ty >= P[7]) return; + const int lda = P[3], ldb = P[4], ldc = P[5]; + const int k0 = P[10] * part, kn = min(k0 + P[10], P[2]) - k0; + const int row = ty * BM + 32 * int(sg / WN), col = tx * BN + 32 * int(sg % WN); + A += long(P[12]) + long(k0) + long(row) * lda; + B += long(P[13]) + long(k0) + long(col) * ldb; + C += long(P[9]) * part + long(row) * ldc + col; + const int rows = AM ? 32 : min(32, P[0] - row); + const int cols = AN ? 32 : min(32, P[1] - col); + const bool full = (AM || rows == 32) && (AN || cols == 32); + const short2 home = tfp::frag_home(ushort(lane)); + tfp::frag acc[2][2]; + if (full) { + gemm_block(acc, A, B, lda, ldb, kn, kn / BK, rows, cols, home); + gemm_store(acc, C, ldc, rows, cols, home); + } else { + gemm_block(acc, A, B, lda, ldb, kn, kn / BK, rows, cols, home); + if (rows > 0 && cols > 0) gemm_store(acc, C, ldc, rows, cols, home); + } +} + +} // namespace sn_prefill + +#define SN_BF16_GEMM(NAME, AM, AN) \ + [[max_total_threads_per_threadgroup(256)]] \ + [[kernel]] void NAME( \ + const device bfloat* A [[buffer(0)]], \ + const device bfloat* B [[buffer(1)]], \ + constant SnBf16GemmArgs& P [[buffer(2)]], \ + device bfloat* D [[buffer(3)]], \ + uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], \ + uint3 tg [[threadgroup_position_in_grid]]) { \ + sn_prefill::gemm_nax(A, B, D, P, tg, sg, lane); \ + } + +SN_BF16_GEMM(sn_bf16_gemm_00, false, false) +SN_BF16_GEMM(sn_bf16_gemm_01, false, true) +SN_BF16_GEMM(sn_bf16_gemm_10, true, false) +SN_BF16_GEMM(sn_bf16_gemm_11, true, true) + +#define SN_BF16_SPLITK(NAME, AM, AN) \ + [[max_total_threads_per_threadgroup(128)]] \ + [[kernel]] void NAME( \ + const device bfloat* A [[buffer(0)]], \ + const device bfloat* B [[buffer(1)]], \ + const device int32_t* P [[buffer(2)]], \ + device float* C [[buffer(3)]], \ + uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], \ + uint3 tg [[threadgroup_position_in_grid]]) { \ + sn_prefill::gemm_splitk_nax(A, B, C, P, tg, sg, lane); \ + } + +SN_BF16_SPLITK(sn_bf16_gemm_splitk_00, false, false) +SN_BF16_SPLITK(sn_bf16_gemm_splitk_01, false, true) +SN_BF16_SPLITK(sn_bf16_gemm_splitk_10, true, false) +SN_BF16_SPLITK(sn_bf16_gemm_splitk_11, true, true) + +[[max_total_threads_per_threadgroup(256)]] +[[kernel]] void sn_bf16_gemm_splitk_sum( + const device float* C [[buffer(0)]], + constant SnBf16SumArgs& args [[buffer(1)]], + device bfloat* D [[buffer(2)]], + uint2 at [[thread_position_in_grid]]) { + if (int(at.x) >= args.p[3] || int(at.y) >= args.p[4]) return; + const long ci = long(at.x) + long(at.y) * args.p[2]; + float s = 0.0f; + for (int p = 0; p < args.p[0]; p++) s += C[ci + long(p) * args.p[1]]; + uint col_loc, ldy_eff; + device bfloat* D_dst = sn_bf16_split_dest( + D, uint(args.p[5]), args.y1_addr, args.split1, args.ldy1, + args.y2_addr, args.split2, args.ldy2, at.x, col_loc, ldy_eff); + D_dst[long(col_loc) + long(at.y) * int(ldy_eff)] = bfloat(s); +} diff --git a/zig/kernels/metal/qwen27/glue.metal b/zig/kernels/metal/qwen27/glue.metal index b59878d1a3e..b101175ae1c 100644 --- a/zig/kernels/metal/qwen27/glue.metal +++ b/zig/kernels/metal/qwen27/glue.metal @@ -18,9 +18,9 @@ inline void q27_write(device uchar* p, uint i, float v, uint type) { else ((device float*)p)[i] = v; } -struct Head { uint width, rows, stride, activation, gain; float eps; }; +struct Head { uint width, rows, stride, activation, gain; float eps; uint shift; }; -// Head RMSNorm retains its native-input rounding before gain multiplication, as the shared Metal RMS implementation. +// Head RMSNorm retains its native-input rounding before gain multiplication for MLX, or 1+w in FP32 when shift != 0. kernel void q27_head_norm(device const uchar* X [[buffer(0)]], device const uchar* W [[buffer(1)]], constant Head& a [[buffer(2)]], device uchar* Y [[buffer(3)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], @@ -51,13 +51,15 @@ kernel void q27_head_norm(device const uchar* X [[buffer(0)]], device const ucha for (uint j = 0; j != 4 && column + j < a.width; ++j) { const uint at = column + j; const float value = q27_read(X, row * a.stride + at, a.activation); - const float normal = q27_round(value * inverse[0], a.activation); - q27_write(Y, row * a.width + at, q27_read(W, at, a.gain) * normal, a.activation); + const float w = q27_read(W, at, a.gain); + const float out = a.shift != 0 ? (1.0f + w) * (value * inverse[0]) : w * q27_round(value * inverse[0], a.activation); + q27_write(Y, row * a.width + at, out, a.activation); } } } struct Embed { uint width, rows, vocab, bits, group, metadata; }; +struct EmbedBf16 { uint width, rows, vocab; }; // Native metadata promotes to FP32 for affine decode, then the activation rounds once. kernel void q27_embed(device const uint* ids [[buffer(0)]], device const uint* words [[buffer(1)]], @@ -74,7 +76,14 @@ kernel void q27_embed(device const uint* ids [[buffer(0)]], device const uint* w q27_write(out, at.y * a.width + at.x, value, a.metadata); } -struct Rope { uint width, heads, rows, rotary, activation; float theta; uint h_end, w_end, plane; }; +kernel void q27_embed_bf16(device const uint* ids [[buffer(0)]], device const bfloat* table [[buffer(1)]], + constant EmbedBf16& a [[buffer(2)]], device bfloat* out [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + if (at.x >= a.width || at.y >= a.rows || ids[at.y] >= a.vocab) return; + out[ulong(at.y) * ulong(a.width) + ulong(at.x)] = table[ulong(ids[at.y]) * ulong(a.width) + ulong(at.x)]; +} + +struct Rope { uint width, heads, rows, rotary, activation; float theta; uint h_end, w_end, plane; float yarn_scale; float yarn_freq[32]; }; // Rotate paired halves at each row's position: pair d's axis plane under M-RoPE, plane 0 (t) otherwise. kernel void q27_rope(device const uchar* X [[buffer(0)]], device const int* positions [[buffer(1)]], @@ -87,9 +96,12 @@ kernel void q27_rope(device const uchar* X [[buffer(0)]], device const int* posi const bool second = at.x >= pairs; const uint d = second ? at.x - pairs : at.x; const uint axis = d % 3 == 1 && d < a.h_end ? 1u : (d % 3 == 2 && d < a.w_end ? 2u : 0u); - const float angle = float(positions[axis * a.plane + at.z]) * pow(a.theta, -float(d) / float(pairs)); + const float freq = a.yarn_scale != 0.0f ? a.yarn_freq[d] : pow(a.theta, -float(d) / float(pairs)); + const float angle = float(positions[axis * a.plane + at.z]) * freq; + const float cs = a.yarn_scale != 0.0f ? cos(angle) * a.yarn_scale : cos(angle); + const float sn = a.yarn_scale != 0.0f ? sin(angle) * a.yarn_scale : sin(angle); const float partner = q27_read(X, base + (second ? d : d + pairs), a.activation); - value = second ? value * cos(angle) + partner * sin(angle) : value * cos(angle) - partner * sin(angle); + value = second ? value * cs + partner * sn : value * cs - partner * sn; } q27_write(Y, base + at.x, value, a.activation); } diff --git a/zig/kernels/metal/qwen27/mlp_xs.metal b/zig/kernels/metal/qwen27/mlp_xs.metal index ab26d52c3df..086580c5de4 100644 --- a/zig/kernels/metal/qwen27/mlp_xs.metal +++ b/zig/kernels/metal/qwen27/mlp_xs.metal @@ -16,16 +16,21 @@ Q27_SPECIALIZE const uint t = thread_position_in_threadgroup.x; const uint g = threadgroup_position_in_grid.x; const uint m = threadgroup_position_in_grid.y; + #if Q27_XS == 128 + constexpr int G = 128; + #else + constexpr int G = 64; + #endif #if Q27_XS const int M = dims[0], MP = dims[1]; - threadgroup bfloat hb[64]; + threadgroup bfloat hb[G]; if (int(m) >= M) { if (t == 0) XS[g * MP + m] = 0.0f; return; } #endif - const int e = int(m) * N + int(g) * 64 + int(t); - const int fused = int(m) * 2 * N + int(g) * 64 + int(t); // GATE and UP point into the fused gate_up rows + const int e = int(m) * N + int(g) * G + int(t); + const int fused = int(m) * 2 * N + int(g) * G + int(t); // GATE and UP point into the fused gate_up rows const float gf = float(GATE[fused]); const bfloat h = bfloat(gf / (1.0f + metal::exp(-gf)) * float(UP[fused])); HOUT[e] = h; @@ -34,7 +39,7 @@ Q27_SPECIALIZE threadgroup_barrier(mem_flags::mem_threadgroup); if (t == 0) { float acc = 0.0f; - for (int i = 0; i < 64; i++) acc += float(hb[i]); + for (int i = 0; i < G; i++) acc += float(hb[i]); XS[g * MP + m] = acc; } #endif diff --git a/zig/kernels/metal/qwen27/norm_input.metal b/zig/kernels/metal/qwen27/norm_input.metal index 10b60b7b25b..0a8ecc15e44 100644 --- a/zig/kernels/metal/qwen27/norm_input.metal +++ b/zig/kernels/metal/qwen27/norm_input.metal @@ -20,13 +20,16 @@ Q27_SPECIALIZE const uint m = threadgroup_position_in_grid.y; #if Q27_XS const int M = dims[0], MP = dims[1]; + constexpr uint XS_T = (Q27_XS == 128) ? 8u : 4u; + constexpr uint XS_M = XS_T - 1u; + constexpr uint XS_S = (Q27_XS == 128) ? 3u : 2u; #endif constexpr int E = 16; constexpr int TPG = K / E; threadgroup float red[TPG / 32]; #if Q27_XS if (int(m) >= M) { - if ((t & 3) == 0) XS[(t >> 2) * MP + m] = 0.0f; + if ((t & XS_M) == 0) XS[(t >> XS_S) * MP + m] = 0.0f; return; } #endif @@ -49,19 +52,24 @@ Q27_SPECIALIZE float xv[E]; #endif for (int i = 0; i < E; i++) { - const bfloat x = bfloat(float(Wt[int(t) * E + i]) * (hv[i] * inv)); + #if defined(Q27_SHIFT) && Q27_SHIFT + const float gw = 1.0f + float(Wt[int(t) * E + i]); + #else + const float gw = float(Wt[int(t) * E + i]); + #endif + const bfloat x = bfloat(gw * (hv[i] * inv)); XO[base + i] = x; #if Q27_XS xv[i] = float(x); #endif } #if Q27_XS - // a group's 64 values summed in order from zero, as the lane projection's sums are: its four threads take turns + // Each group's values are summed in index order from zero, matching the lane projection sums. float gs = 0.0f; - for (uint turn = 0; turn < 4; turn++) { - if ((t & 3) == turn) for (int i = 0; i < E; i++) gs += xv[i]; - gs = simd_shuffle(gs, ushort((thread_index_in_simdgroup & ~3u) | turn)); + for (uint turn = 0; turn < XS_T; turn++) { + if ((t & XS_M) == turn) for (int i = 0; i < E; i++) gs += xv[i]; + gs = simd_shuffle(gs, ushort((thread_index_in_simdgroup & ~XS_M) | turn)); } - if ((t & 3) == 0) XS[(t >> 2) * MP + m] = gs; + if ((t & XS_M) == 0) XS[(t >> XS_S) * MP + m] = gs; #endif } diff --git a/zig/kernels/metal/qwen27/norm_xs.metal b/zig/kernels/metal/qwen27/norm_xs.metal index c240d72f435..feafa8df8ec 100644 --- a/zig/kernels/metal/qwen27/norm_xs.metal +++ b/zig/kernels/metal/qwen27/norm_xs.metal @@ -22,13 +22,16 @@ Q27_SPECIALIZE const uint m = threadgroup_position_in_grid.y; #if Q27_XS const int M = dims[0], MP = dims[1]; + constexpr uint XS_T = (Q27_XS == 128) ? 8u : 4u; + constexpr uint XS_M = XS_T - 1u; + constexpr uint XS_S = (Q27_XS == 128) ? 3u : 2u; #endif constexpr int E = 16; constexpr int TPG = K / E; threadgroup float red[TPG / 32]; #if Q27_XS if (int(m) >= M) { - if ((t & 3) == 0) XS[(t >> 2) * MP + m] = 0.0f; + if ((t & XS_M) == 0) XS[(t >> XS_S) * MP + m] = 0.0f; return; } #endif @@ -52,19 +55,24 @@ HO[base + i] = h; float xv[E]; #endif for (int i = 0; i < E; i++) { - const bfloat x = bfloat(float(Wt[int(t) * E + i]) * (hv[i] * inv)); + #if defined(Q27_SHIFT) && Q27_SHIFT + const float gw = 1.0f + float(Wt[int(t) * E + i]); + #else + const float gw = float(Wt[int(t) * E + i]); + #endif + const bfloat x = bfloat(gw * (hv[i] * inv)); XO[base + i] = x; #if Q27_XS xv[i] = float(x); #endif } #if Q27_XS - // a group's 64 values summed in order from zero, as the lane projection's sums are: its four threads take turns + // Each group's values are summed in index order from zero, matching the lane projection sums. float gs = 0.0f; - for (uint turn = 0; turn < 4; turn++) { - if ((t & 3) == turn) for (int i = 0; i < E; i++) gs += xv[i]; - gs = simd_shuffle(gs, ushort((thread_index_in_simdgroup & ~3u) | turn)); + for (uint turn = 0; turn < XS_T; turn++) { + if ((t & XS_M) == turn) for (int i = 0; i < E; i++) gs += xv[i]; + gs = simd_shuffle(gs, ushort((thread_index_in_simdgroup & ~XS_M) | turn)); } - if ((t & 3) == 0) XS[(t >> 2) * MP + m] = gs; + if ((t & XS_M) == 0) XS[(t >> XS_S) * MP + m] = gs; #endif } diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 8586e92ddc7..db3b0663e55 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -228,6 +228,12 @@ pub const core_lane_order = @embedFile("core/lane_order.metal"); pub const core_shared_attention = @embedFile("core/shared_attention.metal"); /// The core DeltaNet kernels (core/deltanet_kernels.zig). pub const core_deltanet = @embedFile("core/deltanet.metal") ++ "\n" ++ @embedFile("core/deltanet_slots.metal"); +/// SenseNova-Loop two-stream mHC routing, stream enter/leave collapse, and norm kernels. +pub const core_sensenova_mhc = @embedFile("core/sensenova_mhc.metal"); +/// SenseNova-Loop BF16 row matvec and nax.h prefill GEMM kernels. +pub const qwen27_bf16_linear = @embedFile("qwen27/bf16_linear.metal"); +/// SenseNova-Loop AWQ W4A16 g128 lossless FP32-metadata M5 and M3 kernels. +pub const qwen27_awq_w4a16 = @embedFile("qwen27/awq_w4a16.metal") ++ "\n" ++ @embedFile("qwen27/awq_m5_fast.metal"); /// 4-bit projections on simdgroup-matrix tiles before the M5 (core/simd_qmm.zig). pub const core_simd_qmm = @embedFile("core/simd_qmm.metal"); /// 2- to 8-bit projections on the same tiles, rows written at a stride (core/simd_qmm_bits.zig). diff --git a/zig/qwen27_bank_boundary_host.zig b/zig/qwen27_bank_boundary_host.zig index 5cd77aa6ef2..b019b8472c5 100644 --- a/zig/qwen27_bank_boundary_host.zig +++ b/zig/qwen27_bank_boundary_host.zig @@ -6,6 +6,7 @@ test "qwen27 bank boundary: a pending keep rejects resizing and trimming" { var runner: q.decode_round.Runner = undefined; runner.failed = false; runner.active = @splat(0x17); + runner.pending_keep = null; runner.gdn.before = null; runner.gdn.before_slots = 7; runner.gdn.scratch = @TypeOf(runner.gdn).emptyScratch(std.testing.allocator); @@ -28,9 +29,11 @@ fn unusedTail(ptr: *anyopaque, _: @import("metal").ComputeEncoder) !void { test "qwen27 bank boundary: a verify tail cannot run on prompt heads or accepted chains" { var model: q.model.Model = undefined; model.frame.capacity = 16; + model.config.looped = false; var runner: q.decode_round.Runner = undefined; runner.failed = false; runner.active = null; + runner.pending_keep = null; runner.model = &model; var called = false; runner.tail = .{ .ptr = &called, .encode = unusedTail }; @@ -38,6 +41,9 @@ test "qwen27 bank boundary: a verify tail cannot run on prompt heads or accepted round.ids = @constCast(&[_]u32{0}); try std.testing.expectError(error.BadVerifyTail, runner.verifyHead(&round, .none)); try std.testing.expectError(error.BadVerifyTail, runner.advance(&round, .all)); + model.config.looped = true; + try std.testing.expectError(error.BadVerifyTail, runner.verifyHead(&round, .none)); + try std.testing.expectError(error.BadVerifyTail, runner.advance(&round, .none)); try std.testing.expect(!called); } @@ -59,6 +65,7 @@ test "qwen27 bank boundary: a rank's verify never runs a tail" { var runner: q.decode_round.Runner = undefined; runner.failed = false; runner.active = null; + runner.pending_keep = null; runner.model = &model; var called = false; runner.tail = .{ .ptr = &called, .encode = unusedTail }; diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index 61847339d18..b309ce2fd32 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -1,5 +1,6 @@ //! Qwen's view of shared checkpoint contracts and native tensor storage. pub const checkpoint = @import("src/core/checkpoint.zig"); +pub const rope_yarn = @import("src/core/rope_yarn.zig"); pub const gguf = @import("src/core/gguf.zig"); pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); pub const safetensors = @import("src/core/safetensors.zig"); @@ -18,6 +19,7 @@ pub const qwen35_stages = @import("src/families/qwen3_5/stages.zig"); pub const checkpoint_host = checkpoint; pub const lane_projection = @import("core_lane"); +pub const frags = @import("core_lane").frags; pub const gpu_profile = @import("src/core/gpu_profile.zig"); /// Startup phase timing, as core/root.zig exports it for the served engine (TF_STARTUP_RECEIPT). @@ -47,3 +49,4 @@ pub const tree_commit_gpu = @import("tree_commit_gpu"); pub const tree_slots = @import("src/core/tree_slots.zig"); pub const recurrent_workspace = @import("src/core/recurrent_workspace.zig"); +pub const sensenova_loop = @import("src/families/sensenova_loop/sensenova_loop.zig"); diff --git a/zig/qwen27_quant_metal.zig b/zig/qwen27_quant_metal.zig index ea0451bb3d5..e59cc12144d 100644 --- a/zig/qwen27_quant_metal.zig +++ b/zig/qwen27_quant_metal.zig @@ -96,7 +96,15 @@ pub const Library = struct { xs: ?bool = null, pub fn fromSource(d: Device, source: []const u8, _: CompileOptions) !Library { d.r.libraries += 1; - return .{ .xs = if (std.mem.startsWith(u8, source, "#define Q27_XS 0\n")) false else if (std.mem.startsWith(u8, source, "#define Q27_XS 1\n")) true else null }; + const xs: ?bool = if (std.mem.startsWith(u8, source, "#define Q27_XS 0\n")) + false + else if (std.mem.startsWith(u8, source, "#define Q27_XS 64\n") or + std.mem.startsWith(u8, source, "#define Q27_XS 128\n") or + std.mem.startsWith(u8, source, "#define Q27_XS 1\n")) + true + else + null; + return .{ .xs = xs }; } pub fn deinit(_: Library) void {} }; diff --git a/zig/runtime_sources/qwen27.zig b/zig/runtime_sources/qwen27.zig index a3483636987..301b8cc87db 100644 --- a/zig/runtime_sources/qwen27.zig +++ b/zig/runtime_sources/qwen27.zig @@ -16,4 +16,8 @@ pub fn add(s: *Set) !void { const attention = @import("../src/families/qwen27/simd_attention.zig"); for ([_]bool{ false, true }) |paged| for ([_]bool{ false, true }) |prompt| for ([_][2]u32{ .{ 6, 4 }, .{ 4, 4 }, .{ 8, 4 } }) |g| try s.raw("qwen27", try std.fmt.allocPrint(s.a, "attention-paged{}-prompt{}-g{d}", .{ paged, prompt, g[0] }), try attention.grouped(s.a, s.units, prompt, g[0], g[1], paged)); + const ksrc = @import("kernel_sources"); + try s.raw("sensenova", "mhc", ksrc.core_sensenova_mhc); + try s.fragments("sensenova", "bf16_linear", ksrc.qwen27_bf16_linear); + try s.fragments("sensenova", "awq_w4a16", ksrc.qwen27_awq_w4a16); } diff --git a/zig/sensenova_loop_config_host.zig b/zig/sensenova_loop_config_host.zig new file mode 100644 index 00000000000..193eded1767 --- /dev/null +++ b/zig/sensenova_loop_config_host.zig @@ -0,0 +1,133 @@ +//! SenseNova Loop config rules: the shared case table through the SenseNova reader and Metal qwen27 admission. +const std = @import("std"); +const t = std.testing; + +pub const checkpoint = @import("src/core/checkpoint.zig"); +pub const checkpoint_host = checkpoint; +pub const Checkpoint = checkpoint.Checkpoint; +pub const quant = @import("src/core/quant/quant.zig"); +pub const rope_yarn = @import("src/core/rope_yarn.zig"); +pub const sensenova_loop = struct { + pub const config = @import("src/families/sensenova_loop/config.zig"); +}; + +const sn_cfg = sensenova_loop.config; +const qwen27_cfg = @import("src/families/qwen27/config.zig"); +const table = @embedFile("tests/fixtures/sensenova_loop_config.json"); + +const Expect = enum { accept, config, admission }; +const Case = struct { name: []const u8, set: ?std.json.Value = null, remove: []const []const u8 = &.{}, expect: Expect }; +const Table = struct { base: std.json.Value, cases: []const Case }; + +/// JSON merge: objects merge key by key; any other value, null included, replaces. +fn merge(a: std.mem.Allocator, into: *std.json.Value, patch: std.json.Value) !void { + if (into.* != .object or patch != .object) { + into.* = patch; + return; + } + var it = patch.object.iterator(); + while (it.next()) |entry| { + if (into.object.getPtr(entry.key_ptr.*)) |slot| try merge(a, slot, entry.value_ptr.*) else try into.object.put(a, entry.key_ptr.*, entry.value_ptr.*); + } +} + +fn remove(root: *std.json.Value, path: []const u8) !void { + var node = root; + var it = std.mem.splitScalar(u8, path, '.'); + while (it.next()) |key| { + if (it.peek() == null) { + try t.expect(node.object.orderedRemove(key)); + } else node = node.object.getPtr(key) orelse return error.UnknownPath; + } +} + +/// The error classes: loop, layer, and tied contradictions refuse as config; engine limits refuse as admission. +fn outcome(err: anyerror) ?Expect { + return switch (err) { + error.BadLoopSettings, + error.BadMhcConfig, + error.MhcCrossesLoopBoundary, + error.BadLayerTypes, + error.UnsupportedLayerTypes, + error.BadFullAttentionInterval, + error.LayerTypesContradictFullAttentionInterval, + error.MissingFullAttention, + error.BadTiedHead, + => .config, + error.UnsupportedSenseNovaMhc, error.TiedEmbeddingHead => .admission, + else => null, + }; +} + +fn patchedBytes(a: std.mem.Allocator, base: std.json.Value, patch: ?std.json.Value, rem: []const []const u8) ![]u8 { + var doc = try std.json.parseFromSliceLeaky(std.json.Value, a, try std.json.Stringify.valueAlloc(a, base, .{}), .{}); + if (patch) |p| try merge(a, &doc, p); + for (rem) |path| try remove(&doc, path); + return std.json.Stringify.valueAlloc(a, doc, .{}); +} + +test "SenseNova loop config table: every case reaches its outcome" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const parsed = try std.json.parseFromSliceLeaky(Table, a, table, .{}); + try t.expect(parsed.cases.len > 0); + for (parsed.cases) |c| { + const bytes = try patchedBytes(a, parsed.base, c.set, c.remove); + if (qwen27_cfg.parse(t.allocator, bytes, null)) |cfg| { + t.expectEqual(Expect.accept, c.expect) catch |e| { + std.debug.print("case '{s}' was accepted\n", .{c.name}); + return e; + }; + if (std.mem.eql(u8, c.name, "mhc range of one layer")) { + try t.expectEqual(sn_cfg.MhcRole.both, cfg.mhc_roles[4]); + try t.expectEqual(sn_cfg.MhcRole.both, cfg.mhc_roles[28]); + try t.expectEqual(sn_cfg.MhcRole.none, cfg.mhc_roles[5]); + } + if (std.mem.eql(u8, c.name, "mhc range of one layer at the loop end")) { + try t.expectEqual(sn_cfg.MhcRole.both, cfg.mhc_roles[27]); + try t.expectEqual(sn_cfg.MhcRole.both, cfg.mhc_roles[51]); + try t.expectEqual(sn_cfg.MhcRole.none, cfg.mhc_roles[26]); + } + } else |err| { + t.expectEqual(c.expect, outcome(err) orelse { + std.debug.print("case '{s}' failed with {s}\n", .{ c.name, @errorName(err) }); + return err; + }) catch |e| { + std.debug.print("case '{s}' failed with {s}\n", .{ c.name, @errorName(err) }); + return e; + }; + } + // The SenseNova reader alone accepts both accept and admission cases and refuses only config cases. + if (sn_cfg.Config.parse(t.allocator, bytes)) |sn| { + t.expect(c.expect != .config) catch |e| { + std.debug.print("case '{s}' passed sensenova reader unexpectedly\n", .{c.name}); + return e; + }; + if (std.mem.eql(u8, c.name, "mhc range of one layer")) try t.expectEqual(sn_cfg.MhcRole.both, sn.mhcRole(4)); + } else |sn_err| { + try t.expectEqual(Expect.config, c.expect); + try t.expectEqual(Expect.config, outcome(sn_err) orelse return sn_err); + } + } +} + +test "SenseNova loop config table: pre_scale FP32 overflow and root sensenova_loop_text" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const parsed = try std.json.parseFromSliceLeaky(Table, a, table, .{}); + + const over = try patchedBytes(a, parsed.base, (try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"mhc\":{\"pre_scale\":1e39}}", .{})), &.{}); + const sn_over = try sn_cfg.Config.parse(t.allocator, over); + try t.expect(sn_over.mhc.?.pre_scale > std.math.floatMax(f32)); + try t.expectError(error.UnsupportedSenseNovaMhc, qwen27_cfg.parse(t.allocator, over, null)); + + const root_text = try patchedBytes(a, parsed.base, (try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"model_type\":\"sensenova_loop_text\"}", .{})), &.{}); + try t.expectError(error.UnsupportedModel, sn_cfg.Config.parse(t.allocator, root_text)); + try t.expectError(error.NotQwenDense, qwen27_cfg.parse(t.allocator, root_text, null)); + + const inner_text = try patchedBytes(a, parsed.base, (try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"text_config\":{\"model_type\":\"sensenova_loop_text\"}}", .{})), &.{}); + _ = try sn_cfg.Config.parse(t.allocator, inner_text); + _ = try qwen27_cfg.parse(t.allocator, inner_text, null); +} diff --git a/zig/src/cli/hub.zig b/zig/src/cli/hub.zig index b775d72fd9a..ad7ed8cbc98 100644 --- a/zig/src/cli/hub.zig +++ b/zig/src/cli/hub.zig @@ -15,6 +15,7 @@ const titles = [_]struct { model_type: []const u8, title: []const u8 }{ .{ .model_type = "glm5_next", .title = "GLM-5.3-Flash" }, .{ .model_type = "mistral3", .title = "Mistral3 wrapper (LightOnOCR-3-1B only)" }, .{ .model_type = "lighton_ocr", .title = "LightOnOCR-3-1B" }, + .{ .model_type = "sensenova_loop", .title = "SenseNova Loop" }, .{ .model_type = "qwen3_5", .title = "Qwen3.5-2B or Qwen3.8-27B" }, .{ .model_type = "qwen3_5_moe", .title = "Qwen3.5-MoE (Ornith-1.5-122B)" }, .{ .model_type = "gemma4", .title = "Gemma 4 31B" }, diff --git a/zig/src/core/checkpoint_metal.zig b/zig/src/core/checkpoint_metal.zig index 95e69ffdda6..635365c47d4 100644 --- a/zig/src/core/checkpoint_metal.zig +++ b/zig/src/core/checkpoint_metal.zig @@ -66,6 +66,12 @@ pub const Checkpoint = struct { /// As addFileSelected; with `later`, its named tensors stay in the file for `read`, the rest pack into one buffer. pub fn addFileSplit(self: *Checkpoint, device: mtl.Device, path: [:0]const u8, prefix: []const u8, selected: ?[]const u8, later: ?Later) !void { + const prefixes: []const []const u8 = if (selected) |s| &.{s} else &.{}; + return self.addFileSplitPrefixes(device, path, prefix, prefixes, later); + } + + /// As addFileSplit, selecting any tensor starting with one of `prefixes` (empty selects all). + pub fn addFileSplitPrefixes(self: *Checkpoint, device: mtl.Device, path: [:0]const u8, prefix: []const u8, prefixes: []const []const u8, later: ?Later) !void { const fd = platform.c.open(path, .{ .ACCMODE = .RDONLY }); if (fd < 0) { std.log.err("cannot open {s}", .{path}); @@ -90,10 +96,10 @@ pub const Checkpoint = struct { var arena = std.heap.ArenaAllocator.init(self.allocator); defer arena.deinit(); - const entries = try st.parseHeaderPrefix(arena.allocator(), header, data_len, selected); + const entries = try st.parseHeaderPrefixes(arena.allocator(), header, data_len, prefixes); if (entries.count() == 0) return; - var begin: usize = if (selected == null) 0 else data_len; - var limit: usize = if (selected == null) data_len else 0; + var begin: usize = if (prefixes.len == 0) 0 else data_len; + var limit: usize = if (prefixes.len == 0) data_len else 0; for (entries.values()) |e| { begin = @min(begin, e.begin); limit = @max(limit, e.end); diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index d4528b8ed4b..0ed1c4c90ac 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -18,6 +18,7 @@ pub const inkling2_loop_metal_records = @import("contract/inkling2_loop_metal_re pub const inkling2_runtime_metal_records = @import("contract/inkling2_runtime_metal_records.zig"); pub const lane_q8 = @import("contract/lane_q8_records.zig"); pub const q27_prompt = @import("contract/qwen27_prompt_records.zig"); +pub const sensenova_linear_records = @import("contract/sensenova_linear_records.zig"); pub const registry = @import("contract/registry.zig"); pub const h3_image_records = @import("contract/h3_image_records.zig"); pub const cubin = @import("contract/cubin.zig"); @@ -77,6 +78,8 @@ test { _ = @import("contract/hip_records_qwen3.zig"); _ = @import("contract/hip_records_families.zig"); _ = @import("contract/fakes.zig"); + _ = sensenova_linear_records; + _ = @import("contract/sensenova_mhc_records.zig"); } test { diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index c4830015eb4..ba1cfebd49a 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -464,13 +464,6 @@ test "the registered launches fit every Apple family and every SM, and each plan try std.testing.expectEqual(@as(usize, 0), try checkCuda(a, &cuda, false)); for (cuda_controls) |r| try std.testing.expect(try checkCuda(a, &.{r}, true) > 0); } -test { - _ = @import("registry_sets_test.zig"); - _ = @import("nvfp4_tile_pending.zig"); - _ = paging; - _ = @import("minimax_records.zig"); - _ = @import("nemotron_ssd_records.zig"); -} const paging = @import("paging_pending.zig"); /// The Metal collector keeps measured slots and the restored vision declarations. pub const all_metal = joins.all_metal; @@ -481,7 +474,9 @@ pub const glm_pending = @import("glm_sampling_pending.zig"); pub const landed_cuda = joins.landed_cuda; pub const all_cuda = joins.all_cuda; pub const dsv41_pending = joins.dsv41_pending; +pub const sensenova_mhc = @import("sensenova_mhc_records.zig"); test { + _ = sensenova_mhc; _ = learning; _ = @import("qwen4_cuda_receipts_test.zig"); _ = @import("moss_image_cuda_records.zig"); diff --git a/zig/src/core/contract/sensenova_linear_records.zig b/zig/src/core/contract/sensenova_linear_records.zig new file mode 100644 index 00000000000..7d8e6ddde90 --- /dev/null +++ b/zig/src/core/contract/sensenova_linear_records.zig @@ -0,0 +1,135 @@ +//! SenseNova-Loop BF16 and AWQ W4A16 g128 Metal kernel launch declarations for Gate 5. +const std = @import("std"); +const limits = @import("limits.zig"); +const M = limits.MetalLaunch; + +const row_tiers = [_]u32{ 1, 2, 4, 8, 16, 32 }; +const sk_vals = [_]u32{ 1, 2, 4, 8 }; + +pub const bf16_records = blk: { + @setEvalBranchQuota(20000); + var out: [row_tiers.len * sk_vals.len + 9]M = undefined; + var at: usize = 0; + for (row_tiers) |r| { + const cols: u32 = if (r == 1) 1 else if (r <= 4) 2 else 1; + for (sk_vals) |sk| { + const tg: u32 = if (sk == 1) 16 else 8 * cols * r * 4; + out[at] = .{ + .name = std.fmt.comptimePrint("sensenova linear sn_bf16_mv_r{d}_sk{d}", .{ r, sk }), + .threads = 256, + .tg_memory = tg, + .reserved = 256, + .offline = false, + }; + at += 1; + } + } + for ([_][]const u8{ "00", "01", "10", "11" }) |sfx| { + out[at] = .{ + .name = "sensenova linear sn_bf16_gemm_" ++ sfx, + .threads = 256, + .tg_memory = 0, + .reserved = 256, + .offline = false, + }; + at += 1; + out[at] = .{ + .name = "sensenova linear sn_bf16_gemm_splitk_" ++ sfx, + .threads = 128, + .tg_memory = 0, + .reserved = 128, + .offline = false, + }; + at += 1; + } + out[at] = .{ + .name = "sensenova linear sn_bf16_gemm_splitk_sum", + .threads = 256, + .tg_memory = 0, + .reserved = 256, + .offline = false, + }; + at += 1; + if (at != out.len) @compileError("bf16 record count mismatch"); + break :blk out; +}; + +pub const awq_m5_records = blk: { + @setEvalBranchQuota(20000); + var out: [sk_vals.len * 4 + row_tiers.len * sk_vals.len + 1]M = undefined; + var at: usize = 0; + for (sk_vals) |sk| { + const tg: u32 = if (sk == 1) 16 else (sk - 1) * 16 * 32 * 4; + for ([_]u32{ 0, 1 }) |ps| { + for ([_]u32{ 0, 1 }) |rb| { + out[at] = .{ + .name = std.fmt.comptimePrint("sensenova awq-m5 sn_awq_lane_sk{d}_p{d}_r{d}", .{ sk, ps, rb }), + .threads = sk * 32, + .tg_memory = tg, + .reserved = sk * 32, + .offline = false, + }; + at += 1; + } + } + } + for (row_tiers) |r| { + for (sk_vals) |sk| { + const tg: u32 = if (sk == 1) 16 else (sk - 1) * 8 * r * 4; + out[at] = .{ + .name = std.fmt.comptimePrint("sensenova awq-m5 sn_awq_m5_mv_r{d}_sk{d}", .{ r, sk }), + .threads = sk * 32, + .tg_memory = tg, + .reserved = sk * 32, + .offline = false, + }; + at += 1; + } + } + out[at] = .{ .name = "sensenova awq-m5 sn_awq_gemm_m5", .threads = 256, .tg_memory = 0, .reserved = 256, .offline = false }; + at += 1; + if (at != out.len) @compileError("awq m5 record count mismatch"); + break :blk out; +}; + +pub const awq_common_records = blk: { + @setEvalBranchQuota(20000); + var out: [row_tiers.len * sk_vals.len + 3]M = undefined; + var at: usize = 0; + for (row_tiers) |r| { + const cols: u32 = if (r >= 2 and r <= 8) 2 else 1; + for (sk_vals) |sk| { + const tg: u32 = if (sk == 1) 16 else 8 * cols * r * 4; + out[at] = .{ + .name = std.fmt.comptimePrint("sensenova awq sn_awq_row_mv_r{d}_sk{d}", .{ r, sk }), + .threads = 256, + .tg_memory = tg, + .reserved = 256, + .offline = false, + }; + at += 1; + } + } + const tail = [_]struct { []const u8, u32, u32 }{ + .{ "sensenova awq sn_awq_qmm_m3", 128, 2 * 64 * 36 * 4 }, + .{ "sensenova awq sn_awq_xsum_128", 256, 0 }, + .{ "sensenova awq sn_awq_scale_input", 256, 0 }, + }; + for (tail) |t| { + out[at] = .{ .name = t[0], .threads = t[1], .tg_memory = t[2], .reserved = t[1], .offline = false }; + at += 1; + } + if (at != out.len) @compileError("awq common record count mismatch"); + break :blk out; +}; + +pub const records = bf16_records ++ awq_m5_records ++ awq_common_records; + +pub fn isM5Only(name: []const u8) bool { + return std.mem.startsWith(u8, name, "sensenova awq-m5 "); +} + +test "SenseNova linear launches fit every Apple family" { + const reg = @import("registry.zig"); + try std.testing.expectEqual(@as(usize, 0), try reg.checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/sensenova_mhc_records.zig b/zig/src/core/contract/sensenova_mhc_records.zig new file mode 100644 index 00000000000..1a09191ebc0 --- /dev/null +++ b/zig/src/core/contract/sensenova_mhc_records.zig @@ -0,0 +1,24 @@ +//! SenseNova-Loop two-stream mHC Metal launches: 256 threads reserved, under 17 KiB threadgroup memory. +const std = @import("std"); +const limits = @import("limits.zig"); +const M = limits.MetalLaunch; + +pub const pre_norm_tg_memory: u32 = 16704; + +pub const records = [_]M{ + .{ .name = "sensenova mhc enter sn_mhc_enter", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "sensenova mhc pre_norm sn_mhc_pre_norm", .threads = 256, .tg_memory = pre_norm_tg_memory, .reserved = 256 }, + .{ .name = "sensenova mhc post_merge sn_mhc_post_merge", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "sensenova mhc post_and_pre_norm sn_mhc_post_and_pre_norm", .threads = 256, .tg_memory = pre_norm_tg_memory, .reserved = 256 }, +}; + +test "SenseNova mHC launches fit every Apple GPU family" { + const a = std.testing.allocator; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(a); + var problems: usize = 0; + for (records) |l| for (limits.apple) |f| { + problems += try limits.metal(l, f, &out, a); + }; + try std.testing.expectEqual(@as(usize, 0), problems); +} diff --git a/zig/src/core/qwen_vl/shards.zig b/zig/src/core/qwen_vl/shards.zig index 44b4e5236f6..6b0cdd06876 100644 --- a/zig/src/core/qwen_vl/shards.zig +++ b/zig/src/core/qwen_vl/shards.zig @@ -8,13 +8,18 @@ pub const Src = struct { path: [:0]const u8, off: u64, e: st.Entry }; /// Every vision tensor's file, offset and header entry, found through the shard index (or the one file). pub fn headers(arena: std.mem.Allocator, io: std.Io, dir: []const u8) !std.StringArrayHashMapUnmanaged(Src) { + return headersFor(arena, io, dir, prefix); +} + +/// Every vision tensor matching `pfx` across the checkpoint's shards. +pub fn headersFor(arena: std.mem.Allocator, io: std.Io, dir: []const u8, pfx: []const u8) !std.StringArrayHashMapUnmanaged(Src) { var files: std.StringArrayHashMapUnmanaged(void) = .empty; const index = try std.fs.path.join(arena, &.{ dir, "model.safetensors.index.json" }); if (std.Io.Dir.cwd().readFileAlloc(io, index, arena, .limited(64 << 20))) |text| { const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}); const map = (doc.object.get("weight_map") orelse return error.BadIndex).object; var it = map.iterator(); - while (it.next()) |kv| if (std.mem.startsWith(u8, kv.key_ptr.*, prefix)) try files.put(arena, kv.value_ptr.string, {}); + while (it.next()) |kv| if (std.mem.startsWith(u8, kv.key_ptr.*, pfx)) try files.put(arena, kv.value_ptr.string, {}); } else |_| try files.put(arena, "model.safetensors", {}); var out: std.StringArrayHashMapUnmanaged(Src) = .empty; for (files.keys()) |name| { @@ -30,7 +35,7 @@ pub fn headers(arena: std.mem.Allocator, io: std.Io, dir: []const u8) !std.Strin const hlen = try st.headerSize(std.mem.readInt(u64, &head, .little), end); const header = try arena.alloc(u8, hlen); try readAll(fd, header, 8); - const parsed = try st.parseHeaderPrefix(arena, header, @intCast(end - 8 - hlen), prefix); + const parsed = try st.parseHeaderPrefix(arena, header, @intCast(end - 8 - hlen), pfx); var it = parsed.iterator(); while (it.next()) |kv| try out.put(arena, kv.key_ptr.*, .{ .path = path, .off = 8 + hlen + kv.value_ptr.begin, .e = kv.value_ptr.* }); } diff --git a/zig/src/core/qwen_vl/tower.zig b/zig/src/core/qwen_vl/tower.zig index 2d597689b6b..0a28af6e38f 100644 --- a/zig/src/core/qwen_vl/tower.zig +++ b/zig/src/core/qwen_vl/tower.zig @@ -133,13 +133,17 @@ pub const Tower = struct { } pub fn loadWith(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8, c: Config, max_tokens: u32, factory: anytype) !*Tower { + return loadWithPrefixes(gpa, io, device, dir, c, max_tokens, factory, &.{wts.prefix}); + } + + pub fn loadWithPrefixes(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8, c: Config, max_tokens: u32, factory: anytype, prefixes: []const []const u8) !*Tower { const t = try gpa.create(Tower); errdefer gpa.destroy(t); t.gpa = gpa; t.c = c; t.k = try Kernels.load(gpa, device); errdefer t.k.deinit(); - t.w = try wts.loadWith(gpa, io, factory, dir, c); + t.w = try wts.loadWithPrefixes(gpa, io, factory, dir, c, prefixes); errdefer t.w.deinit(gpa); t.inv = try gpa.alloc(f32, c.headDim() / 4); errdefer gpa.free(t.inv); diff --git a/zig/src/core/qwen_vl/weights.zig b/zig/src/core/qwen_vl/weights.zig index 3f14cd00ece..06666bb1644 100644 --- a/zig/src/core/qwen_vl/weights.zig +++ b/zig/src/core/qwen_vl/weights.zig @@ -94,21 +94,35 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const } pub fn loadWith(gpa: std.mem.Allocator, io: std.Io, factory: anytype, dir: []const u8, c: Config) !Weights { + return loadWithPrefixes(gpa, io, factory, dir, c, &.{prefix}); +} + +/// Search `prefixes` in order so looped SenseNova checkpoints can opt into `"model.visual."` without widening others. +pub fn loadWithPrefixes(gpa: std.mem.Allocator, io: std.Io, factory: anytype, dir: []const u8, c: Config, prefixes: []const []const u8) !Weights { var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); - const found = try shards.headers(arena, io, dir); + var used_prefix: []const u8 = prefix; + var found: std.StringArrayHashMapUnmanaged(Src) = .empty; + for (prefixes, 0..) |pfx, pi| { + found = shards.headersFor(arena, io, dir, pfx) catch |err| switch (err) { + error.NoVisionTower => if (pi + 1 < prefixes.len) continue else return err, + else => return err, + }; + used_prefix = pfx; + break; + } var w: Weights = .{ .buf = undefined, .blocks = try gpa.alloc(Block, c.depth) }; errdefer gpa.free(w.blocks); const wants = (try wanted(arena, c, &w)).items; if (found.count() != wants.len) { - std.log.err("qwen vision: the checkpoint has {d} {s}* tensors; this tower reads {d}", .{ found.count(), prefix, wants.len }); + std.log.err("qwen vision: the checkpoint has {d} {s}* tensors; this tower reads {d}", .{ found.count(), used_prefix, wants.len }); return error.UnexpectedVisionTensors; } const srcs = try arena.alloc(Src, wants.len); var total: usize = 0; for (wants, srcs, 0..) |want, *s, i| { - const name = try std.fmt.allocPrint(arena, prefix ++ "{s}", .{want.name}); + const name = try std.fmt.allocPrint(arena, "{s}{s}", .{ used_prefix, want.name }); s.* = found.get(name) orelse { std.log.err("qwen vision: the checkpoint has no tensor {s}", .{name}); return error.MissingVisionTensor; @@ -168,3 +182,26 @@ test "the buffer holds the 27B tower's 333 tensors in bf16" { const n = try bytes(std.testing.allocator, c); try std.testing.expect(n > 900_000_000 and n < 930_000_000); // about 460 million weights } + +test "loadWith keeps vision_tower. only; model.visual. requires explicit prefix opt-in" { + const io = std.testing.io; + const gpa = std.testing.allocator; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const sample = @import("config.zig"); + const c = (try Config.parse(arena.allocator(), sample.sample_config, null, null)).?; + const hdr = "{\"model.visual.patch_embed.proj.weight\":{\"dtype\":\"BF16\",\"shape\":[1],\"data_offsets\":[0,2]}}"; + var buf: [8 + hdr.len + 2]u8 = undefined; + std.mem.writeInt(u64, buf[0..8], hdr.len, .little); + @memcpy(buf[8..][0..hdr.len], hdr); + buf[8 + hdr.len ..][0..2].* = .{ 0, 0 }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = &buf }); + const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); + defer gpa.free(dir); + try std.testing.expectError(error.NoVisionTower, loadWith(gpa, io, @as(mtl.Device, undefined), dir, c)); + const found = try shards.headersFor(arena.allocator(), io, dir, "model.visual."); + try std.testing.expectEqual(@as(usize, 1), found.count()); + try std.testing.expect(found.contains("model.visual.patch_embed.proj.weight")); +} diff --git a/zig/src/core/rope_yarn.zig b/zig/src/core/rope_yarn.zig index c3a6c32db8f..d67633c6d18 100644 --- a/zig/src/core/rope_yarn.zig +++ b/zig/src/core/rope_yarn.zig @@ -37,3 +37,16 @@ test "Qwen3.6's YaRN table (theta 1e7, factor 4 over 262,144) equals transformer for (y.freq, torch) |got, want| try std.testing.expectEqual(want, @as(u32, @bitCast(got))); try std.testing.expectEqual(@as(f32, @floatCast(1.138629436111989)), y.scale); } + +test "SenseNova-Loop-9B's YaRN table (theta 1e7, factor 2 over 262,144) equals transformers 5.14.1's, word for word" { + // transformers 5.14.1 static YaRN inv_freq and attention_scaling under torch 2.13.0, fp32 words + const torch = [32]u32{ + 0x3f800000, 0x3f1ab32b, 0x3ebaf81b, 0x3e61f835, 0x3e088d77, 0x3da50956, 0x3d47763f, 0x3cf11177, + 0x3c91ad39, 0x3c301052, 0x3bd4ca15, 0x3b80967d, 0x3b1b690d, 0x3abbd3ed, 0x3a6301e2, 0x3a009b22, + 0x399111f4, 0x3922ce9d, 0x38b5a1aa, 0x384939ae, 0x37dd1727, 0x37707cc9, 0x37012dab, 0x369c1fc4, + 0x363cb0c1, 0x35e40cc6, 0x3589cf4a, 0x35268e4c, 0x34c94c57, 0x3473499d, 0x3413048e, 0x33b1af44, + }; + const y = yarn(10000000, 2, 262144); + for (y.freq, torch) |got, want| try std.testing.expectEqual(want, @as(u32, @bitCast(got))); + try std.testing.expectEqual(@as(u32, 0x3f88df4e), @as(u32, @bitCast(y.scale))); +} diff --git a/zig/src/families/qwen27/attention.zig b/zig/src/families/qwen27/attention.zig index 05e31e4854c..cc616fc9d55 100644 --- a/zig/src/families/qwen27/attention.zig +++ b/zig/src/families/qwen27/attention.zig @@ -18,9 +18,9 @@ pub const Cache = struct { }; /// A paged stream's table (u32 page ids, 256 rows a page) and the bytes from one page to the next in the arena. pub const Pages = struct { table: Ref, page_bytes: u64 }; -const CachePtrs = extern struct { keys: u64, values: u64 }; +pub const CachePtrs = extern struct { keys: u64, values: u64 }; /// The paged kernels' read pointers (kernels/metal/qwen27/paged.zig): main's two and the stream's table and page size. -const PagedPtrs = extern struct { keys: u64, values: u64, table: u64, page_bytes: u64 }; +pub const PagedPtrs = extern struct { keys: u64, values: u64, table: u64, page_bytes: u64 }; /// The pack and append kernels' arguments (public for the kernel contract's io check). pub const PackArgs = extern struct { rows: u32, packed_rows: u32, heads: u32 = 24, kv_heads: u32 = 4, dim: u32 = 256, group: u32 = 6 }; /// Keep's gather and scatter: rows kept, and the KV heads a staging row holds. @@ -198,7 +198,7 @@ pub const Scratch = struct { if (!std.mem.eql(u8, &uploaded, &fingerprint(plan))) return error.AttentionNotUploaded; } }; -fn validLimits(limits: Limits) !void { +pub fn validLimits(limits: Limits) !void { try limits.geometry.check(); if (limits.rows == 0 or limits.rows > @import("gpu_frame.zig").max_rows or limits.streams == 0 or limits.streams > planning.max_streams or limits.keys == 0 or limits.keys > std.math.maxInt(i32) / limits.geometry.dim) return error.AttentionLimits; } @@ -211,7 +211,7 @@ fn spanAligned(r: Ref, bytes: usize, alignment: usize) !void { fn disjoint(a: Ref, an: usize, b: Ref, bn: usize) !void { if (a.buffer.id == b.buffer.id and a.offset < b.offset + bn and b.offset < a.offset + an) return error.AttentionAlias; } -fn fingerprint(plan: Plan) [32]u8 { +pub fn fingerprint(plan: Plan) [32]u8 { var hash = std.crypto.hash.sha2.Sha256.init(.{}); // Preserve the canonical 27B's descriptor hash; any new numeric shape gets its own identity. if (!plan.geometry.sameShape(.{})) { @@ -225,7 +225,7 @@ fn fingerprint(plan: Plan) [32]u8 { hash.final(&digest); return digest; } -fn cacheBytes(cache: Cache, key: bool, geometry: planning.Geometry) usize { +pub fn cacheBytes(cache: Cache, key: bool, geometry: planning.Geometry) usize { const requested = if (key) cache.key_stride else cache.value_stride; const stride: usize = if (requested == 0) @as(usize, cache.capacity) * geometry.dim else requested; return ((@as(usize, geometry.kv_heads) - 1) * stride + @as(usize, cache.capacity) * geometry.dim) * 2; @@ -259,7 +259,7 @@ fn bind(e: mtl.ComputeEncoder, refs: anytype) void { /// The prompt kernel's threads a group: eight simdgroups, both kernels (attention_prompt*.metal's SG = 8). const prompt_threads = 256; /// h_end and w_end above 0: an M-RoPE round, the h and w position planes `plane` rows past each other in `positions`. -pub const Preprocess = struct { qg: Ref, key: Ref, q_gain: Ref, k_gain: Ref, norm_q: Ref, norm_k: Ref, query: Ref, rotated_key: Ref, positions: Ref, rows: u32, eps: f32, theta: f64, h_end: u32 = 0, w_end: u32 = 0, plane: u32 = 0, geometry: planning.Geometry = .{} }; +pub const Preprocess = struct { qg: Ref, key: Ref, q_gain: Ref, k_gain: Ref, norm_q: Ref, norm_k: Ref, query: Ref, rotated_key: Ref, positions: Ref, rows: u32, eps: f32, theta: f64, h_end: u32 = 0, w_end: u32 = 0, plane: u32 = 0, geometry: planning.Geometry = .{}, shift: bool = false, rope: @import("yarn.zig").Rope = .plain }; pub const Attention = struct { profiler: ?*profile.Trace = null, prefix: [32]mtl.Pipeline, // q27_attn_prefix_1 to _16, then q27_attn_prefix_masked_1 to _16 @@ -340,19 +340,19 @@ pub const Attention = struct { } e.setPipeline(a.io[7]); bind(e, .{ p.qg, p.q_gain }); - e.setValue(glue.Head{ .width = g.dim, .rows = p.rows * g.heads, .stride = 2 * g.dim, .activation = .bf16, .gain = .bf16, .eps = p.eps }, 2); + e.setValue(glue.Head{ .width = g.dim, .rows = p.rows * g.heads, .stride = 2 * g.dim, .activation = .bf16, .gain = .bf16, .eps = p.eps, .shift = @intFromBool(p.shift) }, 2); e.setBuffer(p.norm_q.buffer, p.norm_q.offset, 3); e.dispatchGroups(mtl.Size.of(p.rows * g.heads, 1, 1), mtl.Size.of(64, 1, 1)); e.setPipeline(a.io[7]); bind(e, .{ p.key, p.k_gain }); - e.setValue(glue.Head{ .width = g.dim, .rows = p.rows * g.kv_heads, .stride = g.dim, .activation = .bf16, .gain = .bf16, .eps = p.eps }, 2); + e.setValue(glue.Head{ .width = g.dim, .rows = p.rows * g.kv_heads, .stride = g.dim, .activation = .bf16, .gain = .bf16, .eps = p.eps, .shift = @intFromBool(p.shift) }, 2); e.setBuffer(p.norm_k.buffer, p.norm_k.offset, 3); e.dispatchGroups(mtl.Size.of(p.rows * g.kv_heads, 1, 1), mtl.Size.of(64, 1, 1)); e.barrier(); for ([_]struct { x: Ref, y: Ref, heads: u32 }{ .{ .x = p.norm_q, .y = p.query, .heads = g.heads }, .{ .x = p.norm_k, .y = p.rotated_key, .heads = g.kv_heads } }) |r| { e.setPipeline(a.io[8]); bind(e, .{ r.x, p.positions }); - e.setValue(glue.Rope{ .width = g.dim, .heads = r.heads, .rows = p.rows, .rotary = g.rotary, .activation = .bf16, .theta = @floatCast(p.theta), .h_end = p.h_end, .w_end = p.w_end, .plane = p.plane }, 2); + e.setValue(p.rope.apply(.{ .width = g.dim, .heads = r.heads, .rows = p.rows, .rotary = g.rotary, .activation = .bf16, .theta = @floatCast(p.theta), .h_end = p.h_end, .w_end = p.w_end, .plane = p.plane }), 2); e.setBuffer(r.y.buffer, r.y.offset, 3); e.dispatchThreads(mtl.Size.of(g.dim, r.heads, p.rows), mtl.Size.of(32, 1, 1)); } @@ -385,13 +385,13 @@ pub const Attention = struct { const e = timing.encoder; e.setPipeline(a.io[7]); bind(e, .{ p.key, p.k_gain }); - e.setValue(glue.Head{ .width = pg.dim, .rows = p.rows * pg.kv_heads, .stride = pg.dim, .activation = .bf16, .gain = .bf16, .eps = p.eps }, 2); + e.setValue(glue.Head{ .width = pg.dim, .rows = p.rows * pg.kv_heads, .stride = pg.dim, .activation = .bf16, .gain = .bf16, .eps = p.eps, .shift = @intFromBool(p.shift) }, 2); e.setBuffer(p.norm_k.buffer, p.norm_k.offset, 3); e.dispatchGroups(mtl.Size.of(p.rows * pg.kv_heads, 1, 1), mtl.Size.of(64, 1, 1)); e.barrier(); e.setPipeline(a.io[8]); bind(e, .{ p.norm_k, p.positions }); - e.setValue(glue.Rope{ .width = pg.dim, .heads = pg.kv_heads, .rows = p.rows, .rotary = pg.rotary, .activation = .bf16, .theta = @floatCast(p.theta), .h_end = p.h_end, .w_end = p.w_end, .plane = p.plane }, 2); + e.setValue(p.rope.apply(.{ .width = pg.dim, .heads = pg.kv_heads, .rows = p.rows, .rotary = pg.rotary, .activation = .bf16, .theta = @floatCast(p.theta), .h_end = p.h_end, .w_end = p.w_end, .plane = p.plane }), 2); e.setBuffer(p.rotated_key.buffer, p.rotated_key.offset, 3); e.dispatchThreads(mtl.Size.of(pg.dim, pg.kv_heads, p.rows), mtl.Size.of(32, 1, 1)); e.barrier(); @@ -570,31 +570,7 @@ pub const Attention = struct { e.barrier(); } }; -test "cache and pack descriptors match native pointer and six-word ABI" { - try std.testing.expectEqual(@as(usize, 16), @sizeOf(CachePtrs)); - try std.testing.expectEqual(@as(usize, 32), @sizeOf(PagedPtrs)); - try std.testing.expectEqual(@as(usize, 24), @sizeOf(PackArgs)); - try std.testing.expectEqual(@as(usize, 16), @sizeOf(planning.KeepRow)); -} -test "plan fingerprint changes for an ancestor mutation rather than only counts" { - var plan = try Plan.init(std.testing.allocator, &.{.{ .parents = &.{ -1, 0, 0 }, .start = 63, .capacity = 512 }}, .{}); - defer plan.deinit(); - const before = fingerprint(plan); - plan.paths[2 * planning.path_width + 1] = 1; - try std.testing.expect(!std.mem.eql(u8, &before, &fingerprint(plan))); -} -test "cache span includes padded head strides but no unused trailing padding" { - const cache = Cache{ .keys = undefined, .values = undefined, .capacity = 8, .key_stride = 4096, .value_stride = 8192 }; - try std.testing.expectEqual(@as(usize, 28672), cacheBytes(cache, true, .{})); - try std.testing.expectEqual(@as(usize, 53248), cacheBytes(cache, false, .{})); - const contiguous = Cache{ .keys = undefined, .values = undefined, .capacity = 8 }; - try std.testing.expectEqual(@as(usize, 16384), cacheBytes(contiguous, true, .{})); -} -test "descriptor identity includes numeric geometry and limits still refuse new shaders" { - var plan = try Plan.init(std.testing.allocator, &.{.{ .parents = &.{-1}, .start = 0, .capacity = 8 }}, .{}); - defer plan.deinit(); - const before = fingerprint(plan); - plan.geometry.heads = 20; // GQA 5: no shader build takes it - try std.testing.expect(!std.mem.eql(u8, &before, &fingerprint(plan))); - try std.testing.expectError(error.TargetAttentionShape, validLimits(.{ .geometry = plan.geometry })); + +test { + _ = @import("attention_test.zig"); } diff --git a/zig/src/families/qwen27/attention_plan.zig b/zig/src/families/qwen27/attention_plan.zig index ecf7fd1058c..3c73961271e 100644 --- a/zig/src/families/qwen27/attention_plan.zig +++ b/zig/src/families/qwen27/attention_plan.zig @@ -32,15 +32,11 @@ pub const Geometry = struct { fuse_chain: bool = true, /// One chain of prompt rows may use the simdgroup prompt kernel beyond a tree round's row bound. solo_prompt: bool = false, + /// SenseNova-Loop allows single-chain 2,048-row prompt chunks when `shared_prefix` is false (M3/M4). + wide_prompt: bool = false, /// Read the target's attention geometry; the current kernel qualification still applies. pub fn fromConfig(c: @import("config.zig").Config, shared_prefix: bool) !Geometry { - const g = Geometry{ - .heads = std.math.cast(u32, c.heads) orelse return error.TargetAttentionShape, - .kv_heads = std.math.cast(u32, c.kv_heads) orelse return error.TargetAttentionShape, - .dim = std.math.cast(u32, c.head_dim) orelse return error.TargetAttentionShape, - .rotary = std.math.cast(u32, c.rope_dims) orelse return error.TargetAttentionShape, - .shared_prefix = shared_prefix, - }; + const g = Geometry{ .heads = std.math.cast(u32, c.heads) orelse return error.TargetAttentionShape, .kv_heads = std.math.cast(u32, c.kv_heads) orelse return error.TargetAttentionShape, .dim = std.math.cast(u32, c.head_dim) orelse return error.TargetAttentionShape, .rotary = std.math.cast(u32, c.rope_dims) orelse return error.TargetAttentionShape, .shared_prefix = shared_prefix, .wide_prompt = c.looped }; try g.check(); return g; } @@ -56,13 +52,14 @@ pub const Geometry = struct { if (g.heads / g.kv_heads != 6 and !one_mac) return error.TargetAttentionShape; } pub fn promptRows(g: Geometry, requested: u32) u32 { - return @min(requested, @as(u32, if ((g.shared_prefix and g.fuse_chain) or g.solo_prompt) chain_rows else max_rows)); + return @min(requested, @as(u32, if ((g.shared_prefix and g.fuse_chain) or g.solo_prompt or (g.fuse_chain and g.wide_prompt)) chain_rows else max_rows)); } pub fn group(g: Geometry) u32 { return g.heads / g.kv_heads; } }; + pub const Plan = struct { gpa: std.mem.Allocator, geometry: Geometry, @@ -95,7 +92,7 @@ pub const Plan = struct { chain = false; }; const fused = geometry.shared_prefix and geometry.fuse_chain and chain; - const solo = geometry.solo_prompt and windows.len == 1 and chain; + const solo = (geometry.solo_prompt or (geometry.wide_prompt and geometry.fuse_chain)) and windows.len == 1 and chain; const row_limit: usize = if (fused or solo) chain_rows else max_rows; for (windows, 0..) |w, st| { if (w.parents.len == 0 or w.parents.len > row_limit or w.start > w.capacity or @as(u64, w.start) + w.parents.len > w.capacity or w.capacity > std.math.maxInt(i32) / geometry.dim) return error.AttentionCapacity; diff --git a/zig/src/families/qwen27/attention_test.zig b/zig/src/families/qwen27/attention_test.zig new file mode 100644 index 00000000000..7bf48833f93 --- /dev/null +++ b/zig/src/families/qwen27/attention_test.zig @@ -0,0 +1,77 @@ +//! Unit tests split out of attention.zig plus M3 Ultra 2048-row prompt layout coverage. +const std = @import("std"); +const attn = @import("attention.zig"); +const mem_layout = @import("attention_memory.zig").Layout; +const prompt_rows = @import("prompt_rows.zig"); +const planning = attn.planning; +const Plan = attn.Plan; + +test "cache and pack descriptors match native pointer and six-word ABI" { + try std.testing.expectEqual(@as(usize, 16), @sizeOf(attn.CachePtrs)); + try std.testing.expectEqual(@as(usize, 32), @sizeOf(attn.PagedPtrs)); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(attn.PackArgs)); + try std.testing.expectEqual(@as(usize, 16), @sizeOf(planning.KeepRow)); +} + +test "plan fingerprint changes for an ancestor mutation rather than only counts" { + var plan = try Plan.init(std.testing.allocator, &.{.{ .parents = &.{ -1, 0, 0 }, .start = 63, .capacity = 512 }}, .{}); + defer plan.deinit(); + const before = attn.fingerprint(plan); + plan.paths[2 * planning.path_width + 1] = 1; + try std.testing.expect(!std.mem.eql(u8, &before, &attn.fingerprint(plan))); +} + +test "cache span includes padded head strides but no unused trailing padding" { + const cache = attn.Cache{ .keys = undefined, .values = undefined, .capacity = 8, .key_stride = 4096, .value_stride = 8192 }; + try std.testing.expectEqual(@as(usize, 28672), attn.cacheBytes(cache, true, .{})); + try std.testing.expectEqual(@as(usize, 53248), attn.cacheBytes(cache, false, .{})); + const contiguous = attn.Cache{ .keys = undefined, .values = undefined, .capacity = 8 }; + try std.testing.expectEqual(@as(usize, 16384), attn.cacheBytes(contiguous, true, .{})); +} + +test "descriptor identity includes numeric geometry and limits still refuse new shaders" { + var plan = try Plan.init(std.testing.allocator, &.{.{ .parents = &.{-1}, .start = 0, .capacity = 8 }}, .{}); + defer plan.deinit(); + const before = attn.fingerprint(plan); + plan.geometry.heads = 20; // GQA 5: no shader build takes it + try std.testing.expect(!std.mem.eql(u8, &before, &attn.fingerprint(plan))); + try std.testing.expectError(error.TargetAttentionShape, attn.validLimits(.{ .geometry = plan.geometry })); +} + +test "M3 Ultra unlocks 2048-row linear chains without 4x pob over-allocation" { + try std.testing.expectEqual(@as(u32, 2048), prompt_rows.requested(17, false, null)); + try std.testing.expectEqual(@as(u32, 512), prompt_rows.requested(15, false, null)); + try std.testing.expectEqual(@as(u32, 2048), prompt_rows.requestedModel(15, false, true, null)); + try std.testing.expectEqual(@as(u32, 512), prompt_rows.requestedModel(15, false, false, null)); + try std.testing.expectEqual(@as(u32, 512), prompt_rows.requestedModel(14, false, true, null)); + + const g_m3 = planning.Geometry{ .heads = 16, .kv_heads = 4, .shared_prefix = false, .fuse_chain = true, .wide_prompt = true }; + try std.testing.expectEqual(@as(u32, 2048), g_m3.promptRows(2048)); + try std.testing.expectEqual(@as(u32, 128), (planning.Geometry{ .shared_prefix = false, .fuse_chain = true }).promptRows(2048)); + try std.testing.expectEqual(@as(u32, 128), (planning.Geometry{ .shared_prefix = false, .fuse_chain = false, .wide_prompt = true }).promptRows(2048)); + + var chain: [@import("gpu_frame.zig").max_rows]i32 = undefined; + for (&chain, 0..) |*p, r| p.* = @as(i32, @intCast(r)) - 1; + var p = try Plan.init(std.testing.allocator, &.{.{ .parents = &chain, .start = 0, .capacity = 4096 }}, g_m3); + defer p.deinit(); + try std.testing.expectEqual(@as(u32, 2048), p.rows); + try std.testing.expect(!p.fused); + + var tree: [129]i32 = undefined; + for (&tree, 0..) |*q, r| q.* = if (r == 0) -1 else 0; + try std.testing.expectError(error.AttentionCapacity, Plan.init(std.testing.allocator, &.{.{ .parents = &tree, .start = 0, .capacity = 4096 }}, g_m3)); + + const lim_m3 = attn.Limits{ .rows = 2048, .streams = 1, .keys = 32768, .shared_prefix = false, .geometry = g_m3 }; + const lay_m3 = mem_layout.init(lim_m3); + const pob_idx = @backingInt(attn.Field.pob); + const old_b = @as(usize, g_m3.kv_heads) * lay_m3.tail_chunks * lim_m3.rows * 16 * g_m3.dim * 4; + try std.testing.expect(lay_m3.sizes[pob_idx] < old_b / 2); + try std.testing.expect(lay_m3.sizes[pob_idx] >= @as(usize, g_m3.kv_heads) * lay_m3.chunks * p.tiles * 16 * g_m3.dim * 4); + + const lim_m5 = attn.Limits{ .rows = 2048, .streams = 1, .keys = 32768, .shared_prefix = true, .geometry = .{ .heads = 16, .kv_heads = 4, .wide_prompt = true } }; + const lay_m5 = mem_layout.init(lim_m5); + const expected_m5_b = @as(usize, 4) * 3 * planning.max_rows * 16 * 256 * 4; + try std.testing.expectEqual(expected_m5_b, lay_m5.sizes[pob_idx]); + const lim_default = attn.Limits{ .rows = 2048, .streams = 1, .keys = 32768, .shared_prefix = true, .geometry = .{ .heads = 16, .kv_heads = 4 } }; + try std.testing.expectEqual(@as(usize, 4) * 3 * 2048 * 16 * 256 * 4, mem_layout.init(lim_default).sizes[pob_idx]); +} diff --git a/zig/src/families/qwen27/config.zig b/zig/src/families/qwen27/config.zig index 1e0812d0d59..232ac34ba81 100644 --- a/zig/src/families/qwen27/config.zig +++ b/zig/src/families/qwen27/config.zig @@ -3,12 +3,20 @@ const std = @import("std"); const layer_pattern = @import("qwen35_layers"); const rules = @import("qwen35_rules"); const rope_config = @import("rope_config"); +const yarn = @import("yarn.zig"); const fields = @import("config_fields"); const eos_ids = @import("checkpoint_eos"); +pub const MhcRole = if (@hasDecl(@import("core"), "sensenova_loop")) + @import("core").sensenova_loop.config.MhcRole +else + enum { none, enter, inner, exit, both }; + pub const Kind = enum { linear, attention }; pub const max_layers = 128; pub const max_eos = 8; +pub const max_mhc_iterations: u32 = 1000; +pub const ParseOptions = struct { rope_yarn: ?f64 = null, loops: ?u32 = null, allow_tied: bool = false }; pub const Problem = fields.Problem; comptime { std.debug.assert(eos_ids.qwen35.max.? == max_eos); @@ -39,6 +47,14 @@ pub const Config = struct { rank: u32 = 0, ranks: u32 = 1, split_attention: bool = false, + looped: bool = false, + physical_layers: usize = 0, + exec_phys: [max_layers]u8 = initExecPhys(), + mhc_roles: [max_layers]MhcRole = @splat(.none), + mhc_iterations: u32 = 0, + mhc_pre_scale: f32 = 1.0, + shift_norms: bool = false, + rope: yarn.Rope = .plain, /// Routed experts (qwen3_5_moe): their count and the picks a row makes; 0: a dense MLP of `intermediate`. experts: usize = 0, top_k: usize = 0, @@ -49,6 +65,21 @@ pub const Config = struct { /// The head is the embedding (`tie_word_embeddings`), admitted only by `parseTied` with its switch on. tied_head: bool = false, + fn initExecPhys() [max_layers]u8 { + var out: [max_layers]u8 = undefined; + for (&out, 0..) |*x, i| x.* = @intCast(i); + return out; + } + + pub fn physicalLayers(c: Config) usize { + return if (c.physical_layers != 0) c.physical_layers else c.layers; + } + + pub fn physKind(c: Config, phys: usize) Kind { + for (0..c.layers) |exec| if (c.exec_phys[exec] == phys) return c.kinds[exec]; + return c.kinds[phys]; + } + pub fn moe(c: Config) bool { return c.experts != 0; } @@ -198,8 +229,8 @@ pub const Mode = enum { full, mlp }; /// Split the even dimensions: heads, GQA groups, GDN heads, MLP width and vocabulary; embeddings and norms stay whole. pub fn split(c: *Config, rank: u32, ranks: u32, mode: Mode) !Shard { if (ranks < 2 or ranks > 8 or rank >= ranks) return error.BadShard; - // routed experts are one Mac's only: no rank split of the experts or the router is qualified - if (c.moe()) return error.BadShard; + // routed experts and looped mHC run on one Mac only: no rank split is qualified + if (c.moe() or c.looped) return error.BadShard; if (c.intermediate % ranks != 0 or c.vocab % ranks != 0) return error.BadShard; if (mode == .full and (c.heads % ranks != 0 or c.kv_heads % ranks != 0 or c.k_heads % ranks != 0 or c.v_heads % ranks != 0 or c.hidden % ranks != 0)) return error.BadShard; const global = c.*; @@ -258,31 +289,66 @@ fn shapeProducts(c: Config) !void { pub fn parse(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8) !Config { var p: Problem = .{}; - return parseWhy(gpa, json, generation, &p); + return parseWithOptionsWhy(gpa, json, generation, .{}, &p); } /// `parse`, with `p` naming the field behind a BadConfig the field layer refused. pub fn parseWhy(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8, p: *Problem) !Config { - return parseTied(gpa, json, generation, p, false); + return parseWithOptionsWhy(gpa, json, generation, .{}, p); } /// `parseWhy`, admitting a dense tied head when `allow_tied`; a routed tied head stays refused. pub fn parseTied(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8, p: *Problem, allow_tied: bool) !Config { + return parseWithOptionsWhy(gpa, json, generation, .{ .allow_tied = allow_tied }, p); +} + +/// Whether `json`'s root object declares `model_type == "sensenova_loop"`. +pub fn isSenseNovaRoot(gpa: std.mem.Allocator, json: []const u8) bool { + const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return false; + defer parsed.deinit(); + if (parsed.value != .object) return false; + const mt = parsed.value.object.get("model_type") orelse return false; + return mt == .string and std.mem.eql(u8, mt.string, "sensenova_loop"); +} + +/// Resolved context ceiling for a `sensenova_loop` checkpoint directory under optional `--rope-yarn`. +pub fn senseNovaMaxContext(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, rope_yarn: ?f64) !usize { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(16 << 20)); + defer gpa.free(text); + const gen_path = try std.fs.path.join(gpa, &.{ dir, "generation_config.json" }); + defer gpa.free(gen_path); + const gen_text = std.Io.Dir.cwd().readFileAlloc(io, gen_path, gpa, .limited(1 << 20)) catch null; + defer if (gen_text) |gt| gpa.free(gt); + return (try parseWithOptions(gpa, text, gen_text, .{ .rope_yarn = rope_yarn })).max_position; +} + +pub fn parseWithOptions(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8, opts: ParseOptions) !Config { + var p: Problem = .{}; + return parseWithOptionsWhy(gpa, json, generation, opts, &p); +} + +/// `parseWithOptions`, with `p` naming the field behind a BadConfig the field layer refused. +pub fn parseWithOptionsWhy(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8, opts: ParseOptions, p: *Problem) !Config { const parsed = try std.json.parseFromSlice(std.json.Value, gpa, json, .{}); defer parsed.deinit(); const root = try object(parsed.value); const t = if (root.get("text_config")) |v| try object(v) else root; const tower: fields.Reader = .{ .object = t, .source = if (root.get("text_config") == null) "config.json" else "config.json text_config", .problem = p }; - const model = t.get("model_type") orelse root.get("model_type") orelse return error.BadConfig; + const root_model = root.get("model_type"); + if (root_model) |rm| if (rm == .string and std.mem.eql(u8, rm.string, "sensenova_loop_text")) return error.NotQwenDense; + const looped = root_model != null and root_model.? == .string and std.mem.eql(u8, root_model.?.string, "sensenova_loop"); + const model = if (looped) root_model.? else (t.get("model_type") orelse root_model orelse return error.BadConfig); const kinds_of = [_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text" }; if (model != .string) return error.NotQwenDense; - const routed = for (kinds_of, 0..) |k, i| { + const routed = if (looped) false else for (kinds_of, 0..) |k, i| { if (std.mem.eql(u8, model.string, k)) break i >= 2; } else return error.NotQwenDense; const experts = if (t.get("num_experts")) |v| try integer(v, true, tower.at("num_experts"), p) else 0; if (routed != (experts != 0)) return error.NotQwenDense; const tied_head = try rules.tied(root, t, .metal27); - if (tied_head and (!allow_tied or routed)) return error.TiedEmbeddingHead; + if (tied_head and (!opts.allow_tied or routed)) return error.TiedEmbeddingHead; try rules.check(t, .metal27); const heads = try required(tower, "num_attention_heads"); const hidden = try required(tower, "hidden_size"); @@ -291,8 +357,8 @@ pub fn parseTied(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const break :blk try integer(v, false, tower.at("head_dim"), p); } else hidden / heads; const rope = rope_config.params(t) catch return error.BadConfig; - // theta alone: a scaled rope (rope_scaling from the tower when it has the key, else the root) runs as plain rope - if (rope_config.typed(rope) != null or rope_config.legacy(if (t.contains("rope_scaling")) t else root)) return error.UnsupportedRopeScaling; + // theta alone: non-SenseNova checkpoints refuse YaRN/rope_scaling and --rope-yarn as before + if (!looped and (opts.rope_yarn != null or rope_config.typed(rope) != null or rope_config.legacy(if (t.contains("rope_scaling")) t else root))) return error.UnsupportedRopeScaling; const rp: ?fields.Reader = if (rope) |r| .{ .object = r, .source = "config.json rope_parameters", .problem = p } else null; const factor = if (rp) |r| try optional(r, "partial_rotary_factor", try optional(tower, "partial_rotary_factor", 0.25)) else try optional(tower, "partial_rotary_factor", 0.25); if (factor <= 0 or factor > 1) return error.BadConfig; @@ -322,7 +388,16 @@ pub fn parseTied(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const c.renorm = (tower.optionalFlag("norm_topk_prob", .refused) catch return error.BadConfig) orelse true; if (c.experts > 256 or c.top_k >= c.experts or c.top_k > 15 or c.moe_intermediate != c.intermediate) return error.UnsupportedRouting; } - if (t.get("max_position_embeddings")) |v| c.max_position = try integer(v, false, tower.at("max_position_embeddings"), p); + if (t.get("max_position_embeddings")) |v| { + c.max_position = try integer(v, false, tower.at("max_position_embeddings"), p); + } else if (looped) if (root.get("max_position_embeddings")) |v| { + c.max_position = try integer(v, false, .{ .source = "config.json", .key = "max_position_embeddings" }, p); + }; + if (looped) { + const res = try yarn.resolve(t, root, rope, c.rope_theta, c.max_position, opts.rope_yarn); + c.rope = res.rope; + c.max_position = res.ceiling; + } if (rope) |r| if (r.get("mrope_interleaved")) |v| { if (v != .bool or !v.bool) return error.UnsupportedMrope; c.mrope_interleaved = v.bool; @@ -333,9 +408,35 @@ pub fn parseTied(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const if (v != .array or v.array.items.len != 3) return error.BadConfig; for (v.array.items, 0..) |x, i| c.mrope_section[i] = try integer(x, true, .{ .source = "config.json rope_parameters", .key = "mrope_section" }, p); }; - var full: [max_layers]bool = undefined; - try layer_pattern.read(full[0..c.layers], t); - for (c.kinds[0..c.layers], full[0..c.layers]) |*k, f| k.* = if (f) .attention else .linear; + if (looped) { + if (comptime @hasDecl(@import("core"), "sensenova_loop")) { + const sn_cfg = @import("core").sensenova_loop.config; + const sn = try sn_cfg.Config.parseWithGeneration(gpa, json, generation); + var step_buf: [max_layers]sn_cfg.ExecutionStep = undefined; + const steps = try sn.fillPlan(&step_buf, opts.loops); + c.looped = true; + c.shift_norms = true; + c.physical_layers = sn.num_hidden_layers; + c.layers = steps.len; + if (sn.mhc) |mhc| { + const scale32: f32 = @floatCast(mhc.pre_scale); + if (mhc.streams != 2 or mhc.fixed_identity or mhc.iterations > max_mhc_iterations or !std.math.isFinite(scale32) or scale32 <= 0) { + return error.UnsupportedSenseNovaMhc; + } + c.mhc_iterations = mhc.iterations; + c.mhc_pre_scale = scale32; + } + for (steps, 0..) |st, exec| { + c.kinds[exec] = if (st.is_linear) .linear else .attention; + c.exec_phys[exec] = st.phys; + c.mhc_roles[exec] = st.mhc_role; + } + } else return error.NotQwenDense; + } else { + var full: [max_layers]bool = undefined; + try layer_pattern.read(full[0..c.layers], t); + for (c.kinds[0..c.layers], full[0..c.layers]) |*k, f| k.* = if (f) .attention else .linear; + } // generation_config.json is parsed before config.json's ids: only when both are bad does the refusal differ const gen = if (generation) |text| try std.json.parseFromSlice(std.json.Value, gpa, text, .{}) else null; defer if (gen) |g| g.deinit(); diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 10455b8e35b..4f5e80c2276 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -84,6 +84,9 @@ pub const Runner = struct { images: ?image_rows.Images = null, /// A kept state's blit still reading a slot, by slot: the slot's next write waits for it (settleSlot). reading: [attn.planning.max_streams]?mtl.CommandBuffer = @splat(null), + /// Host-submitted keep in flight on the queue, and slots waiting for it before `trimSlot` runs. + pending_keep: ?mtl.CommandBuffer = null, + pending_trim_slots: [attn.planning.max_streams]bool = @splat(false), /// A tensor-parallel rank's all-reduce, threaded straight into the layer program; null on one Mac. reduce: ?forward.Reduce = null, /// The pair's head-seam picks (one u32 a row), required with `reduce`: unexchanged halves make the ranks diverge. @@ -115,6 +118,8 @@ pub const Runner = struct { // with the MTP head loaded, its block is one more attention layer past the last (forward.layerAt) const attention_index = try a.alloc(u32, m.config.layers + @intFromBool(m.weights.mtp != null)); errdefer a.free(attention_index); + @memset(linear_index, std.math.maxInt(u32)); + @memset(attention_index, std.math.maxInt(u32)); var ng: u32 = 0; var na: u32 = 0; for (linear_index, attention_index[0..m.config.layers], 0..) |*g, *v, block| { @@ -198,6 +203,7 @@ pub const Runner = struct { } pub fn kvSpans(r: *const Runner, a: std.mem.Allocator, slot: u32, at: u32, list: *std.ArrayList(KvSpan)) !void { // first `at` rows of K then V, head by head, page by page + if (r.pending_keep != null) try @constCast(r).settleKeep(); return kv_pages.spans(r, a, slot, at, list); } @@ -269,12 +275,18 @@ pub const Runner = struct { return r.verifyImpl(round, head, true); } + fn fail(r: *Runner, err: anytype) @TypeOf(err) { + r.failed = true; + return err; + } + fn verifyImpl(r: *Runner, round: *const Round, head: forward.Head, accepted: bool) !void { const metric = mtl.pass_metrics.phase(.verify); defer metric.end(); + try r.settleKeep(); if (r.failed or r.active != null or round.ids.len > r.model.frame.capacity) return error.RoundNotReady; mtl.pass_metrics.rows(round.ids.len); - if (r.tail != null and (accepted or head != .all)) return error.BadVerifyTail; + if (r.tail != null and (if (r.model.config.looped) head == .none else (accepted or head != .all))) return error.BadVerifyTail; // A rank's head writes only this rank's vocabulary columns; the tail's matcher reads the whole vocabulary. if (r.tail != null and r.reduce != null) return error.TailOnRank; for (round.slots, round.windows) |slot, window| if (slot >= r.ready or r.offsets[slot] != window.start) return error.CachePositionDiffers; @@ -335,14 +347,8 @@ pub const Runner = struct { return err; }; // A seam cannot fail while encoding: the transport reports it out of band, and a broken pair fails the round. - if (r.reduce) |red| if (red.broken()) { - r.failed = true; - return error.PairFailed; - }; - if (r.model.ane) |share| share.drain() catch |err| { - r.failed = true; - return err; - }; + if (r.reduce) |red| if (red.broken()) return r.fail(error.PairFailed); + if (r.model.ane) |share| share.drain() catch |err| return r.fail(err); if (r.trace) |t| { r.gpu_seconds += r.last_gpu_seconds + (t.spanned - spanned) + (if (r.model.ane) |share| share.gpu_seconds - handed else 0); t.round(); @@ -363,8 +369,8 @@ pub const Runner = struct { } pub fn keep(r: *Runner, round: *const Round, paths: []const []const u32) !void { - const active = r.active orelse return error.RoundNotReady; - if (r.failed or !std.mem.eql(u8, &active, &fingerprint(round))) return error.RoundNotReady; + try r.settleKeep(); + if (r.failed or r.active == null or !std.mem.eql(u8, &r.active.?, &fingerprint(round))) return error.RoundNotReady; var recurrent = try round.recurrent(try r.params(round.ids.len), paths); defer recurrent.deinit(); var attention_plan = try r.attentionPlan(round); @@ -377,36 +383,33 @@ pub const Runner = struct { errdefer if (!ended) e.end(); // an encoder the pool releases unended aborts the process, and the error is lost var gi: usize = 0; var ai: usize = 0; - for (r.model.weights.layers) |layer| switch (layer.mixer) { - .linear => { - try r.gdn.commit(gi, .{ .host = recurrent, .metadata = r.metadata() }, e); - gi += 1; - }, - .attention => { - var views: [attn.planning.max_streams]attn.Cache = undefined; - const caches = r.layerCaches(ai, round, &views); - const kept = try r.bindings[ai].uploadKeep(attention_plan, caches, paths); - try r.attention.keep(e, &r.scratch, &r.bindings[ai], kept, caches); - ai += 1; - }, + for (r.model.weights.layers) |layer| if (layer.mixer == .linear) { + try r.gdn.commit(gi, .{ .host = recurrent, .metadata = r.metadata() }, e); + gi += 1; + } else { + var views: [attn.planning.max_streams]attn.Cache = undefined; + const caches = r.layerCaches(ai, round, &views); + const kept = try r.bindings[ai].uploadKeep(attention_plan, caches, paths); + try r.attention.keep(e, &r.scratch, &r.bindings[ai], kept, caches); + ai += 1; }; e.end(); ended = true; cb.commit(); - cb.wait(); - if (gpuFailed(cb, "a round's keep")) { - r.failed = true; - return error.RoundGpuFailure; + if (r.model.config.looped) r.pending_keep = cb.retain() else { + cb.wait(); + if (gpuFailed(cb, "a round's keep")) return r.fail(error.RoundGpuFailure); } for (round.slots, round.windows, paths) |slot, window, path| { r.offsets[slot] = (try window.keep(path)).length; - r.trimSlot(slot); // the keep waited: its dropped rows' pages are read by nothing + if (r.model.config.looped) r.pending_trim_slots[slot] = true else r.trimSlot(slot); } r.active = null; } /// A validated single-window round consumes authoritative GPU keep metadata without host path selection. pub fn keepDevice(r: *Runner, round: *const Round, e: mtl.ComputeEncoder, ops: @import("core").tree_commit_gpu.Ops, result: @import("core").tree_commit_gpu.Ref) !void { + try r.settleKeep(); try r.checkDeviceKeep(round); var recurrent = try round.recurrent(try r.params(round.ids.len), &.{&.{}}); defer recurrent.deinit(); @@ -418,25 +421,19 @@ pub const Runner = struct { } pub fn checkDeviceKeep(r: *const Runner, round: *const Round) !void { - const active = r.active orelse return error.RoundNotReady; - if (r.failed or round.windows.len != 1 or round.ids.len > @import("core").tree_round.max_rows or !std.mem.eql(u8, &active, &fingerprint(round))) return error.RoundNotReady; + if (r.failed or r.active == null or round.windows.len != 1 or round.ids.len > @import("core").tree_round.max_rows or !std.mem.eql(u8, &r.active.?, &fingerprint(round))) return error.RoundNotReady; } /// Encode only: the caller commits after the lane core publishes its authoritative path. pub fn prepareDeviceKeep(r: *Runner, round: *const Round, e: mtl.ComputeEncoder, ops: @import("core").tree_commit_gpu.Ops, result: @import("core").tree_commit_gpu.Ref) !void { - if (r.failed or r.accepted_chain or r.current_round != round or r.tail == null) return error.RoundNotReady; - if (round.windows.len != 1) return error.RoundNotReady; - const recurrent = r.current_gdn orelse return error.RoundNotReady; - const attention_plan = r.current_attention orelse return error.RoundNotReady; - return r.encodeDeviceKeep(round, recurrent.*, attention_plan.*, e, ops, result); + if (r.failed or r.accepted_chain or r.current_round != round or r.tail == null or round.windows.len != 1) return error.RoundNotReady; + return r.encodeDeviceKeep(round, (r.current_gdn orelse return error.RoundNotReady).*, (r.current_attention orelse return error.RoundNotReady).*, e, ops, result); } fn encodeDeviceKeep(r: *Runner, round: *const Round, recurrent: GdnPlan, attention_plan: attn.Plan, e: mtl.ComputeEncoder, ops: @import("core").tree_commit_gpu.Ops, result: @import("core").tree_commit_gpu.Ref) !void { const m = r.metadata(); const p = @import("core").tree_commit_gpu.Meta{ .rows = @intCast(round.ids.len), .slot = round.slots[0] }; - const keep_ref = @import("core").tree_commit_gpu.Ref{ .buf = m.keeps.buffer, .off = m.keeps.offset }; - const rows = @import("core").tree_commit_gpu.Ref{ .buf = m.kept_rows.buffer, .off = m.kept_rows.offset }; - try ops.metadata(e, result, keep_ref, rows, null, p); + try ops.metadata(e, result, .{ .buf = m.keeps.buffer, .off = m.keeps.offset }, .{ .buf = m.kept_rows.buffer, .off = m.kept_rows.offset }, null, p); e.barrier(); const plan = @import("gdn_pool_gpu.zig").DevicePlan{ .host = recurrent, .metadata = m }; for (0..r.gdn.budget.layers) |gi| try r.gdn.commitScan(gi, plan, e); @@ -444,41 +441,54 @@ pub const Runner = struct { for (0..r.gdn.budget.layers) |gi| try r.gdn.commitPublish(gi, plan, e); e.barrier(); var ai: usize = 0; - for (r.model.weights.layers) |layer| switch (layer.mixer) { - .linear => {}, - .attention => { - var views: [attn.planning.max_streams]attn.Cache = undefined; - const caches = r.layerCaches(ai, round, &views); - try r.bindings[ai].admitDeviceKeep(attention_plan, caches, p.rows); - const map = r.bindings[ai].get(.keep_map); - try ops.metadata(e, result, keep_ref, rows, .{ .buf = map.buffer, .off = map.offset }, p); - e.barrier(); - try r.attention.keep(e, &r.scratch, &r.bindings[ai], p.rows, caches); - ai += 1; - }, + for (r.model.weights.layers) |layer| if (layer.mixer == .attention) { + var views: [attn.planning.max_streams]attn.Cache = undefined; + const caches = r.layerCaches(ai, round, &views); + try r.bindings[ai].admitDeviceKeep(attention_plan, caches, p.rows); + const map = r.bindings[ai].get(.keep_map); + try ops.metadata(e, result, .{ .buf = m.keeps.buffer, .off = m.keeps.offset }, .{ .buf = m.kept_rows.buffer, .off = m.kept_rows.offset }, .{ .buf = map.buffer, .off = map.offset }, p); + e.barrier(); + try r.attention.keep(e, &r.scratch, &r.bindings[ai], p.rows, caches); + ai += 1; }; } pub fn completeDeviceKeep(r: *Runner, round: *const Round, path: []const u32) !void { - const active = r.active orelse return error.RoundNotReady; - if (r.failed or round.windows.len != 1 or path.len == 0 or !std.mem.eql(u8, &active, &fingerprint(round))) return error.RoundNotReady; + if (r.failed or r.active == null or round.windows.len != 1 or path.len == 0 or !std.mem.eql(u8, &r.active.?, &fingerprint(round))) return error.RoundNotReady; r.offsets[round.slots[0]] = (try round.windows[0].keep(path)).length; r.active = null; } /// After a GPU failure, once no stream holds a slot: rounds run again, each slot reset by its next prompt. pub fn recover(r: *Runner) void { + r.settleKeep() catch {}; r.failed = false; r.active = null; } /// An idle or newly lone host may drop scratch only after the previous verify has been kept. pub fn trimBefore(r: *Runner) void { + r.settleKeep() catch {}; if (r.active == null) r.gdn.releaseBefore(); } + /// Finish any committed keep pass on the GPU and trim dropped KV pages. + pub fn settleKeep(r: *Runner) !void { + const cb = r.pending_keep orelse return; + r.pending_keep = null; + defer cb.release(); + cb.wait(); + const failed = gpuFailed(cb, "a round's keep"); + for (&r.pending_trim_slots, 0..) |*p, slot| if (p.*) { + p.* = false; + if (!failed) r.trimSlot(@intCast(slot)); + }; + if (failed) return r.fail(error.RoundGpuFailure); + } + /// A kept state's blit reading `slot` lands before the slot is written: its reset, next chunk or first round. pub fn settleSlot(r: *Runner, slot: u32) void { + r.settleKeep() catch {}; const cb = r.reading[slot] orelse return; r.reading[slot] = null; cb.wait(); @@ -493,6 +503,7 @@ pub const Runner = struct { /// `reset` that keeps the slot's pages: a rewind writes its K/V rows again only from its rewind point on. pub fn clearState(r: *Runner, slot: u32) !void { + try r.settleKeep(); r.settleSlot(slot); if (r.failed or r.active != null or slot >= r.ready) return error.RoundNotReady; const pool = mtl.objc.Pool.push(); @@ -503,10 +514,7 @@ pub const Runner = struct { e.end(); cb.commit(); cb.wait(); - if (gpuFailed(cb, "a slot reset")) { - r.failed = true; - return error.RoundGpuFailure; - } + if (gpuFailed(cb, "a slot reset")) return r.fail(error.RoundGpuFailure); r.offsets[slot] = 0; } @@ -554,20 +562,27 @@ pub const Runner = struct { var views: [attn.planning.max_streams]attn.Cache = undefined; const caches = r.layerCaches(layer, r.current_round orelse return error.RoundNotReady, &views); try r.bindings[layer].upload(plan, caches); - // the tail's other rows' queries reach only rows its o projection skips: their q rows stay unwritten - const t0: u32 = if (block + 1 == r.model.config.layers) r.tail_from orelse 0 else 0; - var q_sums = forward.sums(f, .sums, rows); - q_sums.ref.offset += @as(usize, t0) * 4; - const q_in: Ref = .{ .buffer = f.get(.input).buffer, .offset = f.get(.input).offset + @as(usize, t0) * weights.q.k * 2 }; - const q_out: Ref = .{ .buffer = f.get(.q_gate).buffer, .offset = f.get(.q_gate).offset + @as(usize, t0) * weights.q.n * 2 }; - try r.model.kernels.quant(e, weights.q, q_in, q_sums, f.get(.dims), q_out, rows - t0); - try r.model.kernels.quant(e, weights.kv, f.get(.input), forward.sums(f, .sums, rows), f.get(.dims), f.get(.mixed), rows); - e.barrier(); - const kv: u32 = @intCast(r.model.config.kvDim()); - try r.model.glue.unstack(e, f.get(.mixed), f.get(.key), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = 0 }); - try r.model.glue.unstack(e, f.get(.mixed), f.get(.value), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = kv }); - e.barrier(); - try r.attention.preprocess(e, .{ .qg = f.get(.q_gate), .key = f.get(.key), .q_gain = wts.ref(weights.q_norm), .k_gain = wts.ref(weights.k_norm), .norm_q = f.get(.norm_query), .norm_k = f.get(.norm_key), .query = f.get(.query), .rotated_key = f.get(.rotated_key), .positions = f.get(.positions), .rows = rows, .eps = r.model.config.eps, .theta = r.model.config.rope_theta, .h_end = r.current_placed.h_end, .w_end = r.current_placed.w_end, .plane = f.capacity, .geometry = r.geometry }); + const attn_loop = if (comptime @hasDecl(@import("core"), "sensenova_loop")) blk: { + if (!r.model.config.looped) break :blk false; + try @import("loop.zig").encodeAttnProj(&r.model.kernels, r.model.glue, e, weights, f, rows, @intCast(r.model.config.qDim()), @intCast(r.model.config.kvDim())); + break :blk true; + } else false; + if (!attn_loop) { + // the tail's other rows' queries reach only rows its o projection skips: their q rows stay unwritten + const t0: u32 = if (block + 1 == r.model.config.layers) r.tail_from orelse 0 else 0; + var q_sums = forward.sums(f, .sums, rows); + q_sums.ref.offset += @as(usize, t0) * 4; + const q_in: Ref = .{ .buffer = f.get(.input).buffer, .offset = f.get(.input).offset + @as(usize, t0) * weights.q.k * 2 }; + const q_out: Ref = .{ .buffer = f.get(.q_gate).buffer, .offset = f.get(.q_gate).offset + @as(usize, t0) * weights.q.n * 2 }; + try r.model.kernels.quant(e, weights.q, q_in, q_sums, f.get(.dims), q_out, rows - t0); + try r.model.kernels.quant(e, weights.kv, f.get(.input), forward.sums(f, .sums, rows), f.get(.dims), f.get(.mixed), rows); + e.barrier(); + const kv: u32 = @intCast(r.model.config.kvDim()); + try r.model.glue.unstack(e, f.get(.mixed), f.get(.key), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = 0 }); + try r.model.glue.unstack(e, f.get(.mixed), f.get(.value), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = kv }); + e.barrier(); + } + try r.attention.preprocess(e, .{ .qg = f.get(.q_gate), .key = f.get(.key), .q_gain = wts.ref(weights.q_norm), .k_gain = wts.ref(weights.k_norm), .norm_q = f.get(.norm_query), .norm_k = f.get(.norm_key), .query = f.get(.query), .rotated_key = f.get(.rotated_key), .positions = f.get(.positions), .rows = rows, .eps = r.model.config.eps, .theta = r.model.config.rope_theta, .h_end = r.current_placed.h_end, .w_end = r.current_placed.w_end, .plane = f.capacity, .geometry = r.geometry, .shift = r.model.config.shift_norms, .rope = r.model.config.rope }); try r.attention.encode(e, &r.scratch, &r.bindings[layer], plan, f.get(.query), f.get(.rotated_key), f.get(.value), f.get(.mixer_out), caches, f.get(.q_gate), r.model.kernels.prompt, r.reduce != null); } diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index 896ca2456e8..19e7017bf54 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -97,7 +97,11 @@ pub const Stages = struct { if (s.rows == 0 or s.rows > m.frame.capacity or lane.k != 0) return error.BadFrameRows; s.hidden = m.frame.get(.hidden); s.residual = m.frame.get(.residual); - try m.glue.embedding(lane.enc, m.config, m.weights.embed, m.frame.get(.ids), s.hidden, s.rows); + if (m.weights.embed_bf16) |t| { + try m.glue.embeddingBf16(lane.enc, m.config.hidden, m.config.vocab, wts.ref(t), m.frame.get(.ids), s.hidden, s.rows); + } else { + try m.glue.embedding(lane.enc, m.config, m.weights.embed, m.frame.get(.ids), s.hidden, s.rows); + } lane.enc.barrier(); if (s.images) |rows| { m.glue.imageRows(lane.enc, s.hidden, rows, m.frame.get(.takes), @intCast(m.config.hidden), s.rows); @@ -115,7 +119,12 @@ pub const Stages = struct { const e = lane.enc; const layer = layerAt(m, index); const h: u32 = @intCast(m.config.hidden); - try m.kernels.norm(e, s.hidden, s.pending, wts.ref(layer.norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), h, s.rows); + if (m.config.mhc_roles[index] != .none) { + const tap: ?@import("loop.zig").TapHook = if (s.hooks.tap) |cb| .{ .ptr = s.hooks.ptr, .cb = cb } else null; + try @import("loop.zig").preMhc(&m.mhc.?, &m.kernels, m.config, index, layer, m.weights.mhc[m.config.exec_phys[index]], &s.hidden, &s.residual, &s.pending, f, s.rows, e, tap); + return; + } + try m.kernels.normShift(e, s.hidden, s.pending, wts.ref(layer.norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), h, s.rows, m.config.shift_norms); e.barrier(); if (s.pending != null) { std.mem.swap(Ref, &s.hidden, &s.residual); @@ -174,10 +183,14 @@ pub const Stages = struct { if (s.reduce.?.broken()) return error.PairFailed; e.barrier(); } - try m.kernels.norm(e, t.at(s.hidden, h), t.at(f.get(.output), h), wts.ref(layer.post_norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n); - e.barrier(); - std.mem.swap(Ref, &s.hidden, &s.residual); - if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .mixer = index }, s.hidden, s.rows); + if (m.config.mhc_roles[index] != .none) { + try @import("loop.zig").postMhcMid(&m.mhc.?, &m.kernels, m.config, layer, m.weights.mhc[m.config.exec_phys[index]], f, s.rows, e); + } else { + try m.kernels.normShift(e, t.at(s.hidden, h), t.at(f.get(.output), h), wts.ref(layer.post_norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n, m.config.shift_norms); + e.barrier(); + std.mem.swap(Ref, &s.hidden, &s.residual); + if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .mixer = index }, s.hidden, s.rows); + } if (layer.moe) |*mo| if (!m.moe.?.sorted(mo, m.kernels.prompt)) { // decode rows: the routed block runs the shared expert as one more slot of the experts' kernel try m.moe.?.block(lane.enc, m.config, mo, f, s.rows, m.kernels.prompt); @@ -254,6 +267,13 @@ pub const Stages = struct { try m.moe.?.block(lane.enc, m.config, mo, f, s.rows, m.kernels.prompt); lane.enc.barrier(); } + if (m.config.mhc_roles[index] != .none) { + const tap: ?@import("loop.zig").TapHook = if (s.hooks.tap) |cb| .{ .ptr = s.hooks.ptr, .cb = cb } else null; + const next_l: ?wts.Layer = if (index + 1 < m.config.layers) m.weights.layers[index + 1] else null; + const next_ml: ?@import("loop.zig").MhcLayer = if (index + 1 < m.config.layers) m.weights.mhc[m.config.exec_phys[index + 1]] else null; + try @import("loop.zig").postMhcEnd(&m.mhc.?, &m.kernels, m.config, index, next_l, next_ml, &s.hidden, &s.pending, f, s.rows, lane.enc, tap); + return; + } s.pending = f.get(.output); } pub fn finish(s: *Stages, lane: *@import("core").segments.Lane) !void { @@ -265,7 +285,7 @@ pub const Stages = struct { const h: u32 = @intCast(m.config.hidden); const t = s.rowsAt(m.config.layers - 1); const pending: ?Ref = if (s.pending) |p| t.at(p, h) else null; - try m.kernels.norm(e, t.at(s.hidden, h), pending, wts.ref(s.norm orelse m.weights.norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n); + try m.kernels.normShift(e, t.at(s.hidden, h), pending, wts.ref(s.norm orelse m.weights.norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n, m.config.shift_norms); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); diff --git a/zig/src/families/qwen27/gdn_hook.zig b/zig/src/families/qwen27/gdn_hook.zig index 944fd7aa307..2f7e35819a5 100644 --- a/zig/src/families/qwen27/gdn_hook.zig +++ b/zig/src/families/qwen27/gdn_hook.zig @@ -21,6 +21,21 @@ pub const Hook = struct { if (block >= hook.linear_index.len or hook.linear_index[block] >= hook.pool.budget.layers or rows != hook.plan.parents.len) return error.BadGdnHook; const layer = hook.linear_index[block]; const sums = @import("forward.zig").sums(frame, .sums, rows); + if (comptime @hasDecl(@import("core"), "sensenova_loop")) { + if (weight.zba.n == 0) { + const c = frame.config; + const qkv_dim: u32 = @intCast(c.gdnQkvDim()); + const mixed = frame.get(.mixed); + try @import("loop.zig").quantSplit(hook.quant, e, weight.qkv, frame.get(.input), try hook.pool.projected(layer), rows, qkv_dim, .{ + .split1 = qkv_dim, + .y1 = .{ .buf = mixed.buffer, .off = mixed.offset }, + .ldy1 = @intCast(c.zbaDim()), + }); + e.barrier(); + if (hook.accepted_chain) try hook.pool.forwardChain(layer, devicePlan(hook.plan.*, frame), try refs(weight, frame), e, hook.quant.prompt) else try hook.pool.forward(layer, devicePlan(hook.plan.*, frame), try refs(weight, frame), e); + return; + } + } try hook.quant.quant(e, weight.qkv, frame.get(.input), sums, frame.get(.dims), try hook.pool.projected(layer), rows); try hook.quant.quant(e, weight.zba, frame.get(.input), sums, frame.get(.dims), frame.get(.mixed), rows); e.barrier(); diff --git a/zig/src/families/qwen27/glue.zig b/zig/src/families/qwen27/glue.zig index 0ff8c6ab6f9..45e32cdf3f4 100644 --- a/zig/src/families/qwen27/glue.zig +++ b/zig/src/families/qwen27/glue.zig @@ -13,10 +13,23 @@ pub fn floatType(dtype: DType) !Float { }; } -pub const Head = extern struct { width: u32, rows: u32, stride: u32, activation: Float, gain: Float, eps: f32 }; +pub const Head = extern struct { width: u32, rows: u32, stride: u32, activation: Float, gain: Float, eps: f32, shift: u32 = 0 }; pub const Embed = extern struct { width: u32, rows: u32, vocab: u32, bits: u32, group: u32, metadata: Float }; -/// h_end, w_end: M-RoPE's interleaved h and w pairs end there (0: every pair turns by plane 0); planes `plane` apart. -pub const Rope = extern struct { width: u32, heads: u32, rows: u32, rotary: u32, activation: Float, theta: f32, h_end: u32 = 0, w_end: u32 = 0, plane: u32 = 0 }; +pub const EmbedBf16 = extern struct { width: u32, rows: u32, vocab: u32 }; +/// M-RoPE's axis ends (`plane` stride); nonzero `yarn_scale` turns rotated pairs via `yarn_freq`. +pub const Rope = extern struct { + width: u32, + heads: u32, + rows: u32, + rotary: u32, + activation: Float, + theta: f32, + h_end: u32 = 0, + w_end: u32 = 0, + plane: u32 = 0, + yarn_scale: f32 = 0, + yarn_freq: [32]f32 = @splat(0), +}; pub const Element = extern struct { width: u32, heads: u32, rows: u32, activation: Float }; pub fn headThreads(a: Head) !u32 { @@ -30,10 +43,12 @@ pub fn checkEmbed(a: Embed) !void { } test "operator parameters match their Metal structs word for word" { - try std.testing.expectEqual(@as(usize, 24), @sizeOf(Head)); + try std.testing.expectEqual(@as(usize, 28), @sizeOf(Head)); try std.testing.expectEqual(@as(usize, 24), @sizeOf(Embed)); - try std.testing.expectEqual(@as(usize, 36), @sizeOf(Rope)); + try std.testing.expectEqual(@as(usize, 12), @sizeOf(EmbedBf16)); + try std.testing.expectEqual(@as(usize, 168), @sizeOf(Rope)); try std.testing.expectEqual(@as(usize, 24), @offsetOf(Rope, "h_end")); + try std.testing.expectEqual(@as(usize, 36), @offsetOf(Rope, "yarn_scale")); try std.testing.expectEqual(@as(usize, 16), @sizeOf(Element)); } diff --git a/zig/src/families/qwen27/glue_gpu.zig b/zig/src/families/qwen27/glue_gpu.zig index 57a49650d4f..558207fb6fd 100644 --- a/zig/src/families/qwen27/glue_gpu.zig +++ b/zig/src/families/qwen27/glue_gpu.zig @@ -14,6 +14,7 @@ pub const Gather = extern struct { rows: u32, width: u32, capacity: u32, planes: pub const Kernels = struct { embed: mtl.Pipeline, + embed_bf16: mtl.Pipeline, head: mtl.Pipeline, slice: mtl.Pipeline, add: mtl.Pipeline, @@ -28,6 +29,8 @@ pub const Kernels = struct { defer copy.deinit(); const embed = try mtl.Pipeline.init(device, lib, "q27_embed", false); errdefer embed.deinit(); + const embed_bf16 = try mtl.Pipeline.init(device, lib, "q27_embed_bf16", false); + errdefer embed_bf16.deinit(); const head = try mtl.Pipeline.init(device, lib, "q27_head_norm", false); errdefer head.deinit(); const slice = try mtl.Pipeline.init(device, copy, "q27_slice", false); @@ -37,11 +40,11 @@ pub const Kernels = struct { const gather = try mtl.Pipeline.init(device, copy, "q27_tap_gather", false); errdefer gather.deinit(); const take = try mtl.Pipeline.init(device, copy, "q27_take", false); - return .{ .embed = embed, .head = head, .slice = slice, .add = add, .gather = gather, .take = take }; + return .{ .embed = embed, .embed_bf16 = embed_bf16, .head = head, .slice = slice, .add = add, .gather = gather, .take = take }; } pub fn deinit(k: Kernels) void { - inline for (.{ k.embed, k.head, k.slice, k.add, k.gather, k.take }) |p| p.deinit(); + inline for (.{ k.embed, k.embed_bf16, k.head, k.slice, k.add, k.gather, k.take }) |p| p.deinit(); } /// Each row whose `takes` entry names an image row gets that row's bits from `images` over its embedding. @@ -74,12 +77,30 @@ pub const Kernels = struct { try span.end(); } + pub fn embeddingBf16(k: Kernels, input_encoder: mtl.ComputeEncoder, width: usize, vocab: usize, table: Ref, ids: Ref, out: Ref, rows: u32) !void { + var span = profile.begin(k.profiler, input_encoder, .embedding); + errdefer span.cancel(); + const e = span.encoder; + if (width == 0 or rows == 0 or vocab == 0) return error.BadEmbedding; + e.setPipeline(k.embed_bf16); + e.setBuffer(ids.buffer, ids.offset, 0); + e.setBuffer(table.buffer, table.offset, 1); + e.setValue(abi.EmbedBf16{ .width = @intCast(width), .rows = rows, .vocab = @intCast(vocab) }, 2); + e.setBuffer(out.buffer, out.offset, 3); + e.dispatchThreads(mtl.Size.of(width, rows, 1), mtl.Size.of(256, 1, 1)); + try span.end(); + } + pub fn headNorm(k: Kernels, input_encoder: mtl.ComputeEncoder, x: Ref, weight: Ref, out: Ref, width: u32, rows: u32, eps: f32) !void { + return k.headNormWith(input_encoder, x, weight, out, width, rows, eps, false); + } + + pub fn headNormWith(k: Kernels, input_encoder: mtl.ComputeEncoder, x: Ref, weight: Ref, out: Ref, width: u32, rows: u32, eps: f32, shift: bool) !void { var span = profile.begin(k.profiler, input_encoder, .norm); errdefer span.cancel(); const e = span.encoder; - const a = abi.Head{ .width = width, .rows = rows, .stride = width, .activation = .bf16, .gain = .bf16, .eps = eps }; + const a = abi.Head{ .width = width, .rows = rows, .stride = width, .activation = .bf16, .gain = .bf16, .eps = eps, .shift = @intFromBool(shift) }; e.setPipeline(k.head); bind(e, .{ x, weight }); e.setValue(a, 2); diff --git a/zig/src/families/qwen27/gpu_frame.zig b/zig/src/families/qwen27/gpu_frame.zig index bc906319fac..42887ea8f9d 100644 --- a/zig/src/families/qwen27/gpu_frame.zig +++ b/zig/src/families/qwen27/gpu_frame.zig @@ -4,7 +4,7 @@ const mtl = @import("metal"); const Config = @import("config.zig").Config; const Ref = @import("projection.zig").Ref; -pub const Field = enum { ids, dims, positions, hidden, residual, input, sums, mixed, mixer_out, output, z, a, b, query, key, value, norm_query, norm_key, q_gate, gate, up, activated, act_sums, logits, drawn, eps, parents, windows, row_slots, segments, keeps, kept_rows, rotated_key, takes, slot_steps, router, picks, route_weights, offsets, order, sorted_weights, sorted_rows, expert_gate, expert_up, expert_act, expert_out, expert_sums, tail_dims }; +pub const Field = enum { ids, dims, positions, hidden, residual, input, sums, mixed, mixer_out, output, z, a, b, query, key, value, norm_query, norm_key, q_gate, gate, up, activated, act_sums, logits, drawn, eps, parents, windows, row_slots, segments, keeps, kept_rows, rotated_key, takes, slot_steps, router, picks, route_weights, offsets, order, sorted_weights, sorted_rows, expert_gate, expert_up, expert_act, expert_out, expert_sums, tail_dims, h_streams, mhc_coeff }; /// A prompt pass's rows at most (a chain); rounds with trees and every logits row stay within `logit_rows`. pub const max_rows = 2048; @@ -38,11 +38,13 @@ pub fn allocationSizes(config: Config, capacity: u32) [std.enums.values(Field).l slots * config.moe_intermediate * 2, slots * config.moe_intermediate * 2, slots * config.moe_intermediate * 2, slots * config.hidden * 2, slots * @max(config.hidden, config.moe_intermediate) / 64 * 4, 8 * 4, // the prompt tail's dims: its rows, then the whole chunk's padded rows (the group sums' stride) + if (config.looped) capacity * 2 * config.hidden * 2 else 0, + if (config.looped) capacity * 6 * 2 else 0, }; } pub const small_rows = 512; -const scratch_fields = [_]Field{ .hidden, .residual, .input, .sums, .mixed, .mixer_out, .output, .z, .a, .b, .query, .key, .value, .norm_query, .norm_key, .q_gate, .gate, .up, .activated, .act_sums }; +const scratch_fields = [_]Field{ .hidden, .residual, .input, .sums, .mixed, .mixer_out, .output, .z, .a, .b, .query, .key, .value, .norm_query, .norm_key, .q_gate, .gate, .up, .activated, .act_sums, .h_streams, .mhc_coeff }; pub fn decodeSizes(config: Config, capacity: u32) [scratch_fields.len]usize { const widths = allocationSizes(config, @min(capacity, small_rows)); diff --git a/zig/src/families/qwen27/gpu_weights.zig b/zig/src/families/qwen27/gpu_weights.zig index f28f054f2b1..99e01bb82a0 100644 --- a/zig/src/families/qwen27/gpu_weights.zig +++ b/zig/src/families/qwen27/gpu_weights.zig @@ -28,19 +28,27 @@ pub const mtp_file = "mtp-4bit.safetensors"; pub const Weights = struct { allocator: std.mem.Allocator, layers: []Layer, + physical_layers: []Layer = &.{}, embed: projection.Triple, + embed_bf16: ?Tensor = null, norm: Tensor, head: Linear, /// The draft head, once loadMtp read it; embed and head stay the target's. mtp: ?Mtp = null, owned: std.ArrayList(mtl.Buffer) = .empty, runs: std.ArrayList([]projection.Run) = .empty, + sn_runs: std.ArrayList([]@import("loop.zig").SnRun) = .empty, + mhc: []@import("loop.zig").MhcLayer = &.{}, pub fn deinit(w: *Weights) void { for (w.owned.items) |b| b.deinit(); w.owned.deinit(w.allocator); for (w.runs.items) |r| w.allocator.free(r); w.runs.deinit(w.allocator); + for (w.sn_runs.items) |r| w.allocator.free(r); + w.sn_runs.deinit(w.allocator); + if (w.mhc.len > 0) w.allocator.free(w.mhc); + if (w.physical_layers.len > 0) w.allocator.free(w.physical_layers); w.allocator.free(w.layers); } @@ -52,7 +60,7 @@ pub const Weights = struct { }; fn uniform(p: Linear) bool { - return p.bits == 4 and p.group == 64 and p.runs.len == 0; + return p.sn == null and p.bits == 4 and p.group == 64 and p.runs.len == 0; } /// Modules the graph reads only through repacked copies: their tensors stay in the files until load stages them. @@ -376,6 +384,7 @@ fn decayLog(t: Tensor, shape: []const usize) !Tensor { /// Graph from `checkpoint`; each Linear is staged, repacked, dropped. `s` is the rank's share, `local` from `global`. pub fn load(allocator: std.mem.Allocator, device: mtl.Device, checkpoint: *const cp.Checkpoint, s: *const cfg.Shard, ws: *const widths.Widths) !Weights { const c = s.local; + if (c.looped) return @import("loop.zig").loadWeights(allocator, device, checkpoint, c, ws); const g = s.global; const prefix: []const u8 = if (checkpoint.has("language_model.model.embed_tokens.weight")) "language_model." else if (checkpoint.has("model.embed_tokens.weight")) "" else return error.MissingTextNamespace; if (checkpoint.has("language_model.model.embed_tokens.weight") and checkpoint.has("model.embed_tokens.weight")) return error.AmbiguousTextNamespace; diff --git a/zig/src/families/qwen27/loop.zig b/zig/src/families/qwen27/loop.zig new file mode 100644 index 00000000000..07720a54a3b --- /dev/null +++ b/zig/src/families/qwen27/loop.zig @@ -0,0 +1,547 @@ +//! Looped SenseNova-Loop-9B weight loading, BF16/AWQ linear dispatch and two-stream mHC hooks. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const cp = core.checkpoint_metal; +const sn_cfg = core.sensenova_loop.config; +const sn_awq = core.sensenova_loop.awq; +const linear_gpu = core.sensenova_loop.linear_gpu; +const mhc_metal = core.sensenova_loop.mhc_metal; +const profile = core.gpu_profile; +const cfg = @import("config.zig"); +const wts = @import("gpu_weights.zig"); +const projection = @import("projection.zig"); +const widths = @import("widths.zig"); +const Frame = @import("gpu_frame.zig").Frame; + +pub const SnMat = union(enum) { bf16: linear_gpu.Bf16Matrix, awq: linear_gpu.AwqMatrix }; +pub const SnRun = struct { mat: SnMat, first: u32 }; +pub const SnLinear = struct { runs: []const SnRun, n: u32, k: u32 }; +pub const MhcLayer = struct { attn_w: cp.Tensor, attn_b: cp.Tensor, ffn_w: cp.Tensor, ffn_b: cp.Tensor }; + +const PartSpec = struct { name: []const u8, n: usize, width: widths.Width }; +pub const TapHook = struct { ptr: *anyopaque, cb: *const fn (*anyopaque, mtl.ComputeEncoder, usize, projection.Ref, u32) anyerror!void }; + +const stacked_modules = [_][]const u8{ + ".mlp.gate_proj", + ".mlp.up_proj", + ".self_attn.q_proj", + ".self_attn.k_proj", + ".self_attn.v_proj", + ".linear_attn.in_proj_qkv", + ".linear_attn.in_proj_z", + ".linear_attn.in_proj_b", + ".linear_attn.in_proj_a", +}; + +/// Whether a tensor is repacked, dtype-rounded, or ignored during SenseNova shard loading. +pub fn repackedSenseNova(name: []const u8, _: usize) bool { + if (sn_cfg.isSkippedTensor(name)) return true; + const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return false; + const leaf = name[dot + 1 ..]; + if (std.mem.eql(u8, leaf, "qweight") or std.mem.eql(u8, leaf, "qzeros") or + std.mem.eql(u8, leaf, "scales") or std.mem.eql(u8, leaf, "input_scale")) return true; + if (std.mem.eql(u8, leaf, "A_log") or std.mem.eql(u8, leaf, "dt_bias")) return true; + if (!std.mem.eql(u8, leaf, "weight")) return false; + const module = name[0..dot]; + for (stacked_modules) |suffix| if (std.mem.endsWith(u8, module, suffix)) return true; + return false; +} + +/// Dispatch one SenseNova-Loop linear projection (BF16, AWQ, or mixed runs), optionally split across output buffers. +pub fn encodeSnSplit(sn_gpu: *linear_gpu.LinearGpu, profiler: ?*profile.Trace, e: mtl.ComputeEncoder, s: SnLinear, x: projection.Ref, xs_opt: ?linear_gpu.Sums, y: projection.Ref, rows: u32, ldy: u32, prompt: bool, splits: linear_gpu.OutSplits) !void { + if (s.runs.len == 0) return error.BadCoreProjectionRows; + const Seg = struct { lo: u32, hi: u32, ref: linear_gpu.Ref, ldy: u32 }; + var segs: [3]Seg = undefined; + var seg_n: usize = 0; + const s0_hi: u32 = if (splits.y1 != null) splits.split1 else s.n; + segs[seg_n] = .{ .lo = 0, .hi = s0_hi, .ref = .{ .buf = y.buffer, .off = y.offset }, .ldy = ldy }; + seg_n += 1; + if (splits.y1) |y1| { + const s1_hi: u32 = if (splits.y2 != null) splits.split2 else s.n; + segs[seg_n] = .{ .lo = splits.split1, .hi = s1_hi, .ref = y1, .ldy = splits.ldy1 }; + seg_n += 1; + if (splits.y2) |y2| { + segs[seg_n] = .{ .lo = splits.split2, .hi = s.n, .ref = y2, .ldy = splits.ldy2 }; + seg_n += 1; + } + } + var span = profile.begin(profiler, e, .dense); + const first_awq = s.runs[0].mat == .awq; + const sk: usize = if (prompt) 1 else linear_gpu.decodeSk(sn_gpu.tensor_units, first_awq, s.n, s.k); + span.shape = .{ .n = s.n, .k = s.k, .sk = sk, .bits = if (first_awq) 4 else 16 }; + errdefer span.cancel(); + const xr = linear_gpu.Ref{ .buf = x.buffer, .off = x.offset }; + for (s.runs) |run| { + const start = run.first; + const run_n: u32 = switch (run.mat) { + .bf16 => |m| m.n, + .awq => |m| m.n, + }; + const end = start + run_n; + var hit: [3]Seg = undefined; + var hit_n: usize = 0; + for (segs[0..seg_n]) |seg| if (seg.hi > start and seg.lo < end) { + hit[hit_n] = seg; + hit_n += 1; + }; + if (hit_n == 0) return error.BadCoreProjectionRows; + const ry = linear_gpu.Ref{ .buf = hit[0].ref.buf, .off = hit[0].ref.off + @as(usize, start - hit[0].lo) * 2 }; + var rsplits = linear_gpu.OutSplits{}; + if (hit_n > 1) { + rsplits.split1 = hit[1].lo - start; + rsplits.y1 = hit[1].ref; + rsplits.ldy1 = hit[1].ldy; + } + if (hit_n > 2) { + rsplits.split2 = hit[2].lo - start; + rsplits.y2 = hit[2].ref; + rsplits.ldy2 = hit[2].ldy; + } + switch (run.mat) { + .bf16 => |m| try sn_gpu.encodeBf16Split(span.encoder, m, xr, ry, rows, hit[0].ldy, prompt, null, rsplits), + .awq => |m| try sn_gpu.encodeAwqSplit(span.encoder, m, xr, xs_opt, ry, rows, hit[0].ldy, prompt, null, rsplits), + } + } + try span.end(); +} + +/// Dispatch one SenseNova-Loop linear projection (BF16, AWQ, or mixed runs). +pub fn encodeSn(sn_gpu: *linear_gpu.LinearGpu, profiler: ?*profile.Trace, e: mtl.ComputeEncoder, s: SnLinear, x: projection.Ref, xs_opt: ?linear_gpu.Sums, y: projection.Ref, rows: u32, prompt: bool) !void { + return encodeSnSplit(sn_gpu, profiler, e, s, x, xs_opt, y, rows, s.n, prompt, .{}); +} + +/// Dispatch a SenseNova-Loop `projection.Linear` across up to 3 output destinations using active fused `sn_xs128` sums. +pub fn quantSplit(kernels: anytype, e: mtl.ComputeEncoder, p: projection.Linear, x: projection.Ref, y: projection.Ref, rows: u32, ldy: u32, splits: linear_gpu.OutSplits) !void { + const s = p.sn orelse return error.BadCoreProjectionRows; + const sn_xs = if (kernels.sn_xs128) |xs128| if (std.meta.eql(xs128.x.buffer, x.buffer) and xs128.x.offset == x.offset) xs128.sums else null else null; + return encodeSnSplit(&kernels.sn.?, kernels.profiler, e, s, x, sn_xs, y, rows, ldy, kernels.prompt, splits); +} + +/// Dispatch attention Q/K/V via single stacked `OutSplits` GEMM/MV when `.kv` is folded, else split Q + KV + unstack. +pub fn encodeAttnProj(kernels: anytype, glue: anytype, e: mtl.ComputeEncoder, weights: wts.Attention, f: *Frame, rows: u32, q_dim: u32, kv_dim: u32) !void { + if (weights.kv.n == 0) { + const key = f.get(.key); + const val = f.get(.value); + try quantSplit(kernels, e, weights.q, f.get(.input), f.get(.q_gate), rows, q_dim, .{ + .split1 = q_dim, + .y1 = .{ .buf = key.buffer, .off = key.offset }, + .ldy1 = kv_dim, + .split2 = q_dim + kv_dim, + .y2 = .{ .buf = val.buffer, .off = val.offset }, + .ldy2 = kv_dim, + }); + e.barrier(); + return; + } + const sums = @import("forward.zig").sums(f, .sums, rows); + try kernels.quant(e, weights.q, f.get(.input), sums, f.get(.dims), f.get(.q_gate), rows); + try kernels.quant(e, weights.kv, f.get(.input), sums, f.get(.dims), f.get(.mixed), rows); + e.barrier(); + try glue.unstack(e, f.get(.mixed), f.get(.key), .{ .rows = rows, .width = kv_dim, .stride = 2 * kv_dim, .offset = 0 }); + try glue.unstack(e, f.get(.mixed), f.get(.value), .{ .rows = rows, .width = kv_dim, .stride = 2 * kv_dim, .offset = kv_dim }); + e.barrier(); +} + +pub fn callCfg(c: cfg.Config, use_xs: bool, rows: u32) mhc_metal.PreNormCall { + const stride = if (use_xs) @import("quant_gpu.zig").padded(rows) else 0; + return .{ .iters = c.mhc_iterations, .shift_norm = c.shift_norms, .xs_group = if (use_xs) 128 else 0, .xs_stride = stride, .pre_scale = c.mhc_pre_scale, .eps = c.eps }; +} + +fn mref(r: projection.Ref) mhc_metal.Ref { + return .{ .buf = r.buffer, .off = r.offset }; +} + +fn tref(t: cp.Tensor) mhc_metal.Ref { + return .{ .buf = t.buffer, .off = t.offset }; +} + +fn setInputXs128(kernels: anytype, f: *Frame, rows: u32, enabled: bool) ?mhc_metal.Ref { + if (!enabled) { + kernels.sn_xs128 = null; + return null; + } + const xr = f.get(.input); + const sr = f.get(.sums); + const stride = @import("quant_gpu.zig").padded(rows); + kernels.sn_xs128 = .{ .x = xr, .sums = .{ .ref = .{ .buf = sr.buffer, .off = sr.offset }, .stride = stride } }; + return mref(sr); +} + +/// Enter two-stream residual if `enter`, then compute mHC coefficients and collapsed pre-norm (unless fused from prev). +pub fn preMhc(mhc: *const mhc_metal.Pipelines, kernels: anytype, c: cfg.Config, index: usize, layer: wts.Layer, ml: MhcLayer, hidden: *projection.Ref, residual: *projection.Ref, pending: *?projection.Ref, f: *Frame, rows: u32, e: mtl.ComputeEncoder, tap: ?TapHook) !void { + if (index > 0 and (c.mhc_roles[index] == .inner or c.mhc_roles[index] == .exit) and + (c.mhc_roles[index - 1] == .enter or c.mhc_roles[index - 1] == .inner)) return; + const h: u32 = @intCast(c.hidden); + const want_xs = kernels.device.tensorUnits() and layer.gu.bits == 4; + const xs = setInputXs128(kernels, f, rows, want_xs); + var span = profile.begin(kernels.profiler, e, .norm); + errdefer span.cancel(); + const enc = span.encoder; + const enters = c.mhc_roles[index] == .enter or c.mhc_roles[index] == .both; + const need_tap = enters and tap != null and pending.* != null; + if (enters) { + try mhc_metal.enter(mhc, enc, mref(hidden.*), if (pending.*) |p| mref(p) else null, mref(f.get(.h_streams)), if (need_tap) mref(residual.*) else null, rows, h); + enc.barrier(); + pending.* = null; + } + try mhc_metal.preNorm(mhc, enc, mref(f.get(.h_streams)), tref(ml.attn_w), tref(ml.attn_b), tref(layer.norm), mref(f.get(.mhc_coeff)), mref(f.get(.input)), xs, rows, h, callCfg(c, want_xs, rows)); + enc.barrier(); + try span.end(); + if (need_tap) try tap.?.cb(tap.?.ptr, e, index - 1, residual.*, rows); +} + +/// Fuse attention residual merge into two streams with FFN mHC coefficients and pre-norm. +pub fn postMhcMid(mhc: *const mhc_metal.Pipelines, kernels: anytype, c: cfg.Config, layer: wts.Layer, ml: MhcLayer, f: *Frame, rows: u32, e: mtl.ComputeEncoder) !void { + const h: u32 = @intCast(c.hidden); + const hs = mref(f.get(.h_streams)); + const co = mref(f.get(.mhc_coeff)); + const want_xs = kernels.device.tensorUnits() and layer.gu.bits == 4; + const xs = setInputXs128(kernels, f, rows, want_xs); + var span = profile.begin(kernels.profiler, e, .norm); + errdefer span.cancel(); + const enc = span.encoder; + try mhc_metal.postAndPreNorm(mhc, enc, hs, mref(f.get(.output)), co, tref(ml.ffn_w), tref(ml.ffn_b), tref(layer.post_norm), hs, co, mref(f.get(.input)), xs, rows, h, callCfg(c, want_xs, rows)); + enc.barrier(); + try span.end(); +} + +/// Merge FFN branch into next layer's pre-norm when continuing in two streams, else mean-collapse on exit. +pub fn postMhcEnd(mhc: *const mhc_metal.Pipelines, kernels: anytype, c: cfg.Config, index: usize, next_layer: ?wts.Layer, next_ml: ?MhcLayer, hidden: *projection.Ref, pending: *?projection.Ref, f: *Frame, rows: u32, e: mtl.ComputeEncoder, tap: ?TapHook) !void { + const h: u32 = @intCast(c.hidden); + const exit = c.mhc_roles[index] == .exit or c.mhc_roles[index] == .both; + const fuse_next = !exit and next_layer != null and next_ml != null and index + 1 < c.layers and + (c.mhc_roles[index + 1] == .inner or c.mhc_roles[index + 1] == .exit); + var span = profile.begin(kernels.profiler, e, .norm); + errdefer span.cancel(); + const enc = span.encoder; + const hs = mref(f.get(.h_streams)); + const co = mref(f.get(.mhc_coeff)); + if (fuse_next) { + const nl = next_layer.?; + const nml = next_ml.?; + const want_xs = kernels.device.tensorUnits() and nl.gu.bits == 4; + const xs = setInputXs128(kernels, f, rows, want_xs); + try mhc_metal.postAndPreNorm(mhc, enc, hs, mref(f.get(.output)), co, tref(nml.attn_w), tref(nml.attn_b), tref(nl.norm), hs, co, mref(f.get(.input)), xs, rows, h, callCfg(c, want_xs, rows)); + } else { + kernels.sn_xs128 = null; + const dst = if (exit) hidden.* else f.get(.h_streams); + try mhc_metal.postMerge(mhc, enc, hs, mref(f.get(.output)), co, mref(dst), rows, h, exit); + } + enc.barrier(); + try span.end(); + pending.* = null; + if (exit) if (tap) |t| try t.cb(t.ptr, e, index, hidden.*, rows); +} + +fn namespace(ck: *const cp.Checkpoint) !struct { text: []const u8, head: []const u8 } { + const text: []const u8 = if (ck.has("model.language_model.embed_tokens.weight")) + "model.language_model." + else if (ck.has("language_model.model.embed_tokens.weight")) + "language_model.model." + else if (ck.has("model.embed_tokens.weight")) + "model." + else + return error.MissingTextNamespace; + const head = if (ck.has("lm_head.weight") or ck.has("lm_head.qweight")) "lm_head" else try std.fmt.allocPrint(ck.allocator, "{s}lm_head", .{text}); + return .{ .text = text, .head = head }; +} + +fn checked(t: cp.Tensor, dtype: cp.DType, shape: []const usize) !cp.Tensor { + if (t.dtype != dtype or t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) return error.BadNativeTensor; + return t; +} + +fn checkedInt32(t: cp.Tensor, shape: []const usize) !cp.Tensor { + if ((t.dtype != .i32 and t.dtype != .u32) or t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) return error.BadNativeTensor; + return t; +} + +fn checkedConv(t: cp.Tensor, n: usize, kernel: usize) !cp.Tensor { + if (t.dtype != .bf16) return error.BadNativeTensor; + const ok = (t.rank == 2 and t.shape[0] == n and t.shape[1] == kernel) or + (t.rank == 3 and t.shape[0] == n and ((t.shape[1] == kernel and t.shape[2] == 1) or (t.shape[1] == 1 and t.shape[2] == kernel))); + if (!ok) return error.BadNativeTensor; + var out = t; + out.rank = 3; + out.shape = .{ n, kernel, 1, 1, 1 }; + return out; +} + +fn roundF32ToBf16(x: f32) u16 { + const u: u32 = @bitCast(x); + if ((u & 0x7fff_ffff) > 0x7f80_0000) return @truncate((u >> 16) | 0x0040); + return @truncate((u +% 0x7fff +% ((u >> 16) & 1)) >> 16); +} + +fn roundScalarBf16(a: std.mem.Allocator, device: mtl.Device, ck: *const cp.Checkpoint, stage: *cp.Stage, owned: *std.ArrayList(mtl.Buffer), name: []const u8, n: usize) !cp.Tensor { + _ = a; + try stage.reserve(ck, &.{name}); + defer stage.reset(); + const src = try stage.read(ck, name); + if (src.rank != 1 or src.shape[0] != n or (src.dtype != .f32 and src.dtype != .bf16)) return error.BadNativeTensor; + const buf = try device.buffer(n * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + owned.append(ck.allocator, buf) catch |err| { + buf.deinit(); + return err; + }; + const dst = buf.slice(u16, n); + if (src.dtype == .bf16) { + @memcpy(dst, src.host(u16)[0..n]); + } else { + for (src.host(f32)[0..n], dst) |v, *d| d.* = roundF32ToBf16(v); + } + return .{ .buffer = buf, .offset = 0, .bytes = n * 2, .dtype = .bf16, .shape = .{ n, 1, 1, 1, 1 }, .rank = 1 }; +} + +fn scaleDType(dt: cp.DType) !sn_awq.ScaleDType { + return switch (dt) { + .f16 => .f16, + .bf16 => .bf16, + .f32 => .f32, + else => error.BadNativeTensor, + }; +} + +fn ownBuffer(a: std.mem.Allocator, owned: *std.ArrayList(mtl.Buffer), b: mtl.Buffer) !void { + owned.append(a, b) catch |err| { + b.deinit(); + return err; + }; +} + +fn loadBf16Run(a: std.mem.Allocator, device: mtl.Device, ck: *const cp.Checkpoint, stage: *cp.Stage, owned: *std.ArrayList(mtl.Buffer), parts: []const PartSpec, k: usize) !linear_gpu.Bf16Matrix { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const ta = arena.allocator(); + if (parts.len == 1) { + const wname = try std.mem.concat(ta, u8, &.{ parts[0].name, ".weight" }); + if (ck.tensors.contains(wname)) { + const t = try checked(try ck.get(wname), .bf16, &.{ parts[0].n, k }); + if (t.offset % 16 == 0) return linear_gpu.LinearGpu.prepareBf16(t.buffer, t.offset, @intCast(parts[0].n), @intCast(k)); + } + } + const names = try ta.alloc([]const u8, parts.len); + var total_n: usize = 0; + for (parts, names) |p, *nm| { + nm.* = try std.mem.concat(ta, u8, &.{ p.name, ".weight" }); + total_n += p.n; + } + try stage.reserve(ck, names); + defer stage.reset(); + const buf = try device.buffer(total_n * k * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + try ownBuffer(a, owned, buf); + var dst_row: usize = 0; + const dst = buf.contents(); + for (parts, names) |p, nm| { + const t = try checked(try stage.read(ck, nm), .bf16, &.{ p.n, k }); + const row_bytes = p.n * k * 2; + @memcpy(dst[dst_row * k * 2 ..][0..row_bytes], t.buffer.contents()[t.offset..][0..row_bytes]); + dst_row += p.n; + } + return linear_gpu.LinearGpu.prepareBf16(buf, 0, @intCast(total_n), @intCast(k)); +} + +fn loadAwqRun(a: std.mem.Allocator, ck: *const cp.Checkpoint, stage: *cp.Stage, sn_gpu: *const linear_gpu.LinearGpu, owned: *std.ArrayList(mtl.Buffer), parts: []const PartSpec, k: usize, out_runs: *std.ArrayList(SnRun), first: *u32) !void { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const ta = arena.allocator(); + var names: std.ArrayList([]const u8) = .empty; + const has_in_scale = try ta.alloc(bool, parts.len); + for (parts, has_in_scale) |p, *hs| { + for ([_][]const u8{ ".qweight", ".qzeros", ".scales" }) |suf| try names.append(ta, try std.mem.concat(ta, u8, &.{ p.name, suf })); + const is_name = try std.mem.concat(ta, u8, &.{ p.name, ".input_scale" }); + hs.* = ck.has(is_name); + if (hs.*) try names.append(ta, is_name); + } + try stage.reserve(ck, names.items); + defer stage.reset(); + const awq_parts = try ta.alloc(sn_awq.Part, parts.len); + for (parts, awq_parts, has_in_scale) |p, *ap, hs| { + const qw_name = try std.mem.concat(ta, u8, &.{ p.name, ".qweight" }); + const qz_name = try std.mem.concat(ta, u8, &.{ p.name, ".qzeros" }); + const sc_name = try std.mem.concat(ta, u8, &.{ p.name, ".scales" }); + const qw = try checkedInt32(try stage.read(ck, qw_name), &.{ k, p.n / 8 }); + const qz = try checkedInt32(try stage.read(ck, qz_name), &.{ k / 128, p.n / 8 }); + const sc = try stage.read(ck, sc_name); + const sdt = try scaleDType(sc.dtype); + if (sc.rank != 2 or sc.shape[0] != k / 128 or sc.shape[1] != p.n) return error.BadNativeTensor; + var in_scale: ?[]const f32 = null; + if (hs) { + const is_t = try checked(try stage.read(ck, try std.mem.concat(ta, u8, &.{ p.name, ".input_scale" })), .f32, &.{k}); + in_scale = is_t.host(f32); + } + ap.* = .{ .n = p.n, .k = k, .qweight = qw.host(u32), .qzeros = qz.host(u32), .scales = sc.buffer.contents()[sc.offset..][0..sc.bytes], .scales_dtype = sdt, .input_scale = in_scale }; + } + const mats = try sn_gpu.prepareAwq(awq_parts); + defer sn_gpu.allocator.free(mats); + for (mats) |m| { + var copy = m; + copy.owns = false; + owned.appendSlice(a, &.{ copy.w, copy.sb }) catch |err| { + var tmp = m; + tmp.deinit(); + return err; + }; + if (copy.input_scale) |ib| owned.append(a, ib) catch |err| { + ib.deinit(); + return err; + }; + try out_runs.append(a, .{ .mat = .{ .awq = copy }, .first = first.* }); + first.* += copy.n; + } +} + +fn loadSnLinear(a: std.mem.Allocator, device: mtl.Device, ck: *const cp.Checkpoint, stage: *cp.Stage, sn_gpu: *const linear_gpu.LinearGpu, owned: *std.ArrayList(mtl.Buffer), sn_runs: *std.ArrayList([]SnRun), parts: []const PartSpec, k: usize) !projection.Linear { + if (parts.len == 0) return error.BadProjectionShape; + var runs: std.ArrayList(SnRun) = .empty; + defer runs.deinit(a); + var first: u32 = 0; + var i: usize = 0; + while (i < parts.len) { + const kind = parts[i].width.kind; + var j = i + 1; + while (j < parts.len and parts[j].width.kind == kind) : (j += 1) {} + switch (kind) { + .bf16 => { + const mat = try loadBf16Run(a, device, ck, stage, owned, parts[i..j], k); + try runs.append(a, .{ .mat = .{ .bf16 = mat }, .first = first }); + first += mat.n; + }, + .awq => try loadAwqRun(a, ck, stage, sn_gpu, owned, parts[i..j], k, &runs, &first), + .affine => return error.UnqualifiedQwenFormat, + } + i = j; + } + const owned_runs = try runs.toOwnedSlice(a); + sn_runs.append(a, owned_runs) catch |err| { + a.free(owned_runs); + return err; + }; + const dummy: projection.Ref = .{ .buffer = owned.items[0] }; + return .{ .words = dummy, .pairs = dummy, .n = first, .k = @intCast(k), .tile = 32, .slices = 1, .bits = if (parts[0].width.kind == .awq) 4 else 16, .group = parts[0].width.group, .sn = .{ .runs = owned_runs, .n = first, .k = @intCast(k) } }; +} + +fn zeroSnLinear(owned: *const std.ArrayList(mtl.Buffer), k: usize) projection.Linear { + const dummy: projection.Ref = .{ .buffer = owned.items[0] }; + return .{ .words = dummy, .pairs = dummy, .n = 0, .k = @intCast(k), .tile = 32, .slices = 1, .sn = .{ .runs = &.{}, .n = 0, .k = @intCast(k) } }; +} + +fn loadPhysicalLayer(a: std.mem.Allocator, device: mtl.Device, ck: *const cp.Checkpoint, stage: *cp.Stage, sn_gpu: *const linear_gpu.LinearGpu, owned: *std.ArrayList(mtl.Buffer), sn_runs: *std.ArrayList([]SnRun), c: cfg.Config, w: [17]widths.Width, prefix: []const u8, i: usize, phys_n: usize, need_mhc: bool) !struct { layer: wts.Layer, mhc: MhcLayer } { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const ta = arena.allocator(); + const lp = try std.fmt.allocPrint(ta, "{s}layers.{d}.", .{ prefix, i }); + const cat = struct { + fn s(alloc: std.mem.Allocator, p: []const u8, sub: []const u8) ![]const u8 { + return std.mem.concat(alloc, u8, &.{ p, sub }); + } + }.s; + const M = widths.Member; + const kind = c.physKind(i); + const mixer: @FieldType(wts.Layer, "mixer") = switch (kind) { + .linear => .{ .linear = .{ + .qkv = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{ + .{ .name = try cat(ta, lp, "linear_attn.in_proj_qkv"), .n = c.gdnQkvDim(), .width = w[@backingInt(M.qkv)] }, + .{ .name = try cat(ta, lp, "linear_attn.in_proj_z"), .n = c.gdnValueDim(), .width = w[@backingInt(M.z)] }, + .{ .name = try cat(ta, lp, "linear_attn.in_proj_b"), .n = c.v_heads, .width = w[@backingInt(M.b)] }, + .{ .name = try cat(ta, lp, "linear_attn.in_proj_a"), .n = c.v_heads, .width = w[@backingInt(M.a)] }, + }, c.hidden), + .zba = zeroSnLinear(owned, c.hidden), + .out = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{.{ .name = try cat(ta, lp, "linear_attn.out_proj"), .n = c.hidden, .width = w[@backingInt(M.out)] }}, c.gdnValueDim()), + .conv = try checkedConv(try ck.get(try cat(ta, lp, "linear_attn.conv1d.weight")), c.gdnQkvDim(), c.conv_kernel), + .a_log = try roundScalarBf16(a, device, ck, stage, owned, try cat(ta, lp, "linear_attn.A_log"), c.v_heads), + .dt = try roundScalarBf16(a, device, ck, stage, owned, try cat(ta, lp, "linear_attn.dt_bias"), c.v_heads), + .norm = try checked(try ck.get(try cat(ta, lp, "linear_attn.norm.weight")), .bf16, &.{c.dv}), + } }, + .attention => if (i + 1 < phys_n) .{ .attention = .{ + .q = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{ + .{ .name = try cat(ta, lp, "self_attn.q_proj"), .n = c.qDim(), .width = w[@backingInt(M.q)] }, + .{ .name = try cat(ta, lp, "self_attn.k_proj"), .n = c.kvDim(), .width = w[@backingInt(M.k)] }, + .{ .name = try cat(ta, lp, "self_attn.v_proj"), .n = c.kvDim(), .width = w[@backingInt(M.v)] }, + }, c.hidden), + .kv = zeroSnLinear(owned, c.hidden), + .out = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{.{ .name = try cat(ta, lp, "self_attn.o_proj"), .n = c.hidden, .width = w[@backingInt(M.o)] }}, c.heads * c.head_dim), + .q_norm = try checked(try ck.get(try cat(ta, lp, "self_attn.q_norm.weight")), .bf16, &.{c.head_dim}), + .k_norm = try checked(try ck.get(try cat(ta, lp, "self_attn.k_norm.weight")), .bf16, &.{c.head_dim}), + } } else .{ .attention = .{ + .q = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{.{ .name = try cat(ta, lp, "self_attn.q_proj"), .n = c.qDim(), .width = w[@backingInt(M.q)] }}, c.hidden), + .kv = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{ + .{ .name = try cat(ta, lp, "self_attn.k_proj"), .n = c.kvDim(), .width = w[@backingInt(M.k)] }, + .{ .name = try cat(ta, lp, "self_attn.v_proj"), .n = c.kvDim(), .width = w[@backingInt(M.v)] }, + }, c.hidden), + .out = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{.{ .name = try cat(ta, lp, "self_attn.o_proj"), .n = c.hidden, .width = w[@backingInt(M.o)] }}, c.heads * c.head_dim), + .q_norm = try checked(try ck.get(try cat(ta, lp, "self_attn.q_norm.weight")), .bf16, &.{c.head_dim}), + .k_norm = try checked(try ck.get(try cat(ta, lp, "self_attn.k_norm.weight")), .bf16, &.{c.head_dim}), + } }, + }; + const gu = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{ + .{ .name = try cat(ta, lp, "mlp.gate_proj"), .n = c.intermediate, .width = w[@backingInt(M.gate)] }, + .{ .name = try cat(ta, lp, "mlp.up_proj"), .n = c.intermediate, .width = w[@backingInt(M.up)] }, + }, c.hidden); + const down = try loadSnLinear(a, device, ck, stage, sn_gpu, owned, sn_runs, &.{.{ .name = try cat(ta, lp, "mlp.down_proj"), .n = c.hidden, .width = w[@backingInt(M.down)] }}, c.intermediate); + const layer = wts.Layer{ + .norm = try checked(try ck.get(try cat(ta, lp, "input_layernorm.weight")), .bf16, &.{c.hidden}), + .post_norm = try checked(try ck.get(try cat(ta, lp, "post_attention_layernorm.weight")), .bf16, &.{c.hidden}), + .gu = gu, + .down = down, + .mixer = mixer, + }; + const ml: MhcLayer = if (need_mhc) .{ + .attn_w = try checked(try ck.get(try cat(ta, lp, "mhc_attn.weight")), .f32, &.{ 8, 2 * c.hidden }), + .attn_b = try checked(try ck.get(try cat(ta, lp, "mhc_attn.bias")), .f32, &.{8}), + .ffn_w = try checked(try ck.get(try cat(ta, lp, "mhc_ffn.weight")), .f32, &.{ 8, 2 * c.hidden }), + .ffn_b = try checked(try ck.get(try cat(ta, lp, "mhc_ffn.bias")), .f32, &.{8}), + } else undefined; + return .{ .layer = layer, .mhc = ml }; +} + +/// Load physical SenseNova-Loop-9B weights and build execution-step aliases. +pub fn loadWeights(a: std.mem.Allocator, device: mtl.Device, ck: *const cp.Checkpoint, c: cfg.Config, ws: *const widths.Widths) !wts.Weights { + const ns = try namespace(ck); + defer if (!std.mem.eql(u8, ns.head, "lm_head")) a.free(ns.head); + var sn_gpu = linear_gpu.LinearGpu.init(a, device); + defer sn_gpu.deinit(); + var owned: std.ArrayList(mtl.Buffer) = .empty; + errdefer { + for (owned.items) |b| b.deinit(); + owned.deinit(a); + } + var sn_runs: std.ArrayList([]SnRun) = .empty; + errdefer { + for (sn_runs.items) |r| a.free(r); + sn_runs.deinit(a); + } + const phys_n = c.physicalLayers(); + const physical = try a.alloc(wts.Layer, phys_n); + errdefer a.free(physical); + const exec_layers = try a.alloc(wts.Layer, c.layers); + errdefer a.free(exec_layers); + const mhc = try a.alloc(MhcLayer, phys_n); + errdefer a.free(mhc); + var need_mhc = try a.alloc(bool, phys_n); + defer a.free(need_mhc); + @memset(need_mhc, false); + for (0..c.layers) |exec| if (c.mhc_roles[exec] != .none) { + need_mhc[c.exec_phys[exec]] = true; + }; + const embed_name = try std.mem.concat(a, u8, &.{ ns.text, "embed_tokens.weight" }); + defer a.free(embed_name); + const embed_bf16 = try checked(try ck.get(embed_name), .bf16, &.{ c.vocab, c.hidden }); + // Ensure owned[0] exists even when every unstacked weight borrows shard buffers. + try ownBuffer(a, &owned, try device.buffer(16, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked)); + var stage = cp.Stage{ .device = device }; + defer stage.deinit(); + for (0..phys_n) |i| { + const res = try loadPhysicalLayer(a, device, ck, &stage, &sn_gpu, &owned, &sn_runs, c, ws.layers[i], ns.text, i, phys_n, need_mhc[i]); + physical[i] = res.layer; + mhc[i] = res.mhc; + } + for (exec_layers, 0..) |*dst, exec| dst.* = physical[c.exec_phys[exec]]; + const norm_name = try std.mem.concat(a, u8, &.{ ns.text, "norm.weight" }); + defer a.free(norm_name); + const norm = try checked(try ck.get(norm_name), .bf16, &.{c.hidden}); + const head = try loadSnLinear(a, device, ck, &stage, &sn_gpu, &owned, &sn_runs, &.{.{ .name = ns.head, .n = c.vocab, .width = ws.head }}, c.hidden); + const dummy_embed: projection.Triple = .{ .weight = embed_bf16, .scales = embed_bf16, .biases = embed_bf16, .bits = 4, .group = 64 }; + return .{ .allocator = a, .layers = exec_layers, .physical_layers = physical, .embed = dummy_embed, .embed_bf16 = embed_bf16, .norm = norm, .head = head, .owned = owned, .sn_runs = sn_runs, .mhc = mhc }; +} diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index 444c1f6018e..9b9f1b7528d 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -4,7 +4,6 @@ const platform = @import("sys"); const mtl = @import("metal"); const core = @import("core"); const cfg = @import("config.zig"); -const affine = @import("affine.zig"); const widths = @import("widths.zig"); const wts = @import("gpu_weights.zig"); const quant = @import("quant_gpu.zig"); @@ -29,6 +28,8 @@ pub const Model = struct { glue: glue.Kernels, /// The routed block's kernels, with experts. moe: ?moe_gpu.Kernels = null, + /// Two-stream mHC pipelines for looped checkpoints. + mhc: ?core.sensenova_loop.mhc_metal.Pipelines = null, frame: Frame, /// The Neural Engine's share of prompt-chunk MLPs, when it loaded. ane: ?*ane_mlp.Share = null, @@ -39,22 +40,26 @@ pub const Model = struct { /// Immediate share loading for tools; `share_fits` null keeps their existing unrestricted behavior. pub fn load(a: std.mem.Allocator, io: std.Io, dir: []const u8, rows: u32, share_fits: ?*const fn (u64) bool) !*Model { - return loadWith(a, io, dir, rows, share_fits, false); + return loadWith(a, io, dir, rows, share_fits, false, .{}); } /// Serving decides the share after the drafter, residency and slots are accounted for. pub fn loadDeferred(a: std.mem.Allocator, io: std.Io, dir: []const u8, rows: u32) !*Model { - return loadWith(a, io, dir, rows, null, true); + return loadWith(a, io, dir, rows, null, true, .{}); + } + + pub fn loadDeferredOpts(a: std.mem.Allocator, io: std.Io, dir: []const u8, rows: u32, opts: cfg.ParseOptions) !*Model { + return loadWith(a, io, dir, rows, null, true, opts); } /// One rank of a `ranks`-way tensor-parallel run: the same checkpoint, sliced in the engine. pub fn loadShard(a: std.mem.Allocator, io: std.Io, dir: []const u8, rows: u32, rank: u32, ranks: u32, mode: cfg.Mode, share_fits: ?*const fn (u64) bool) !*Model { - return loadShared(a, io, dir, rows, rank, ranks, mode, share_fits, false); + return loadShared(a, io, dir, rows, rank, ranks, mode, share_fits, false, .{}); } /// One rank of a pair, its share decided after everything else is accounted for (the serving order). pub fn loadShardDeferred(a: std.mem.Allocator, io: std.Io, dir: []const u8, rows: u32, rank: u32, ranks: u32, mode: cfg.Mode) !*Model { - return loadShared(a, io, dir, rows, rank, ranks, mode, null, true); + return loadShared(a, io, dir, rows, rank, ranks, mode, null, true, .{}); } fn loadWith( @@ -64,8 +69,9 @@ pub const Model = struct { rows: u32, share_fits: ?*const fn (u64) bool, later: bool, + opts: cfg.ParseOptions, ) !*Model { - return loadShared(a, io, dir, rows, 0, 1, .full, share_fits, later); + return loadShared(a, io, dir, rows, 0, 1, .full, share_fits, later, opts); } fn loadShared( @@ -78,6 +84,7 @@ pub const Model = struct { mode: cfg.Mode, share_fits: ?*const fn (u64) bool, later: bool, + opts: cfg.ParseOptions, ) !*Model { if ((platform.environment.Process{}).get("TF_PROMPT_ROWS")) |raw| { const n = std.fmt.parseInt(u32, raw, 10) catch 0; @@ -101,7 +108,9 @@ pub const Model = struct { }; defer if (generation) |g| a.free(g); var problem: cfg.Problem = .{}; - const c = parseServed(a, text, generation, &problem) catch |e| { + var served = opts; // main's opt-in tied head, as parseServed reads it + served.allow_tied = try platform.environment.read(bool, @import("tied_head.zig").flag, false); + const c = cfg.parseWithOptionsWhy(a, text, generation, served, &problem) catch |e| { if (problem.len != 0) std.log.err("{s}: {s}", .{ path, problem.text() }); return e; }; @@ -109,9 +118,7 @@ pub const Model = struct { var local = c; const shard = if (ranks == 1) cfg.Shard{ .rank = 0, .ranks = 1, .global = c, .local = local } else try cfg.split(&local, rank, ranks, mode); try supported(shard.global); - var formats = try affine.Formats.init(a, text); - defer formats.deinit(); - var ws = try widths.Widths.resolve(a, &formats, shard.local); + var ws = try widths.Widths.resolveModel(a, text, shard.local); defer ws.deinit(); const m = try a.create(Model); errdefer a.destroy(m); @@ -135,20 +142,30 @@ pub const Model = struct { const headers = timing.span(.checkpoint_headers); const files = try core.checkpoint_host.shardFiles(a, io, dir); defer core.checkpoint_host.freeShardFiles(a, files); + const sn_prefixes = [_][]const u8{ "model.language_model.", "language_model.", "model.layers.", "model.embed_tokens.", "model.norm.", "lm_head." }; // projections stay in the files until load repacks them: the weights live once, in their lane layouts - for (files) |file| try m.checkpoint.addFileSplit(m.device, file, "", "language_model.", wts.repacked); + for (files) |file| { + if (shard.local.looped) { + try m.checkpoint.addFileSplitPrefixes(m.device, file, "", &sn_prefixes, @import("loop.zig").repackedSenseNova); + } else { + try m.checkpoint.addFileSplit(m.device, file, "", "language_model.", wts.repacked); + } + } headers.end(); const packing = timing.span(.read_pack); m.weights = try wts.load(a, m.device, &m.checkpoint, &m.shard, &ws); errdefer m.weights.deinit(); packing.end(); const pipelines = timing.span(.weight_pipelines); - m.kernels = .{ .allocator = a, .device = m.device, .raw_tiles = !m.device.tensorUnits(), .long_prompt = quant.longPrompt(std.mem.span(m.device.name()), m.device.tensorUnits()) }; + m.kernels = .{ .allocator = a, .device = m.device, .raw_tiles = !m.device.tensorUnits(), .long_prompt = quant.longPrompt(std.mem.span(m.device.name()), m.device.tensorUnits()), .sn = if (shard.local.looped) core.sensenova_loop.linear_gpu.LinearGpu.init(a, m.device) else null }; errdefer m.kernels.deinit(); + if (m.kernels.sn) |*sn| try sn.reserve(@import("gpu_frame.zig").max_rows, ws.head.kind == .awq); m.glue = try glue.Kernels.init(m.device); errdefer m.glue.deinit(); m.moe = if (c.moe()) try moe_gpu.Kernels.init(a, m.device) else null; errdefer if (m.moe) |*k| k.deinit(); + m.mhc = if (shard.local.looped and shard.local.mhc_iterations != 0) try core.sensenova_loop.mhc_metal.Pipelines.load(m.device) else null; + errdefer if (m.mhc) |*p| p.deinit(); pipelines.end(); const allocation = timing.span(.initial_allocation); // Serving defers automatic widening until its context and streams are known; explicit widths stay exact. @@ -222,6 +239,7 @@ pub const Model = struct { pub fn deinit(m: *Model) void { if (m.ane) |share| share.deinit(); m.frame.deinit(); + if (m.mhc) |*p| p.deinit(); if (m.moe) |*k| k.deinit(); m.glue.deinit(); m.kernels.deinit(); @@ -236,6 +254,7 @@ pub const Model = struct { /// Default frame rows follow attention geometry; a validated environment override keeps its width. pub fn promptRows(c: cfg.Config, generation: u32, geometry: @import("attention_plan.zig").Geometry) u32 { const value = (platform.environment.Process{}).get("TF_PROMPT_ROWS"); + if (c.looped) return @import("prompt_rows.zig").requestedModel(generation, c.moe(), c.looped, value); return @import("prompt_rows.zig").frameRequested(generation, c.moe(), value, geometry); } @@ -252,7 +271,8 @@ pub fn parseServed(a: std.mem.Allocator, text: []const u8, generation: ?[]const } fn qualifiedSize(c: cfg.Config) bool { - for (sizes) |z| if (c.hidden == z.hidden and c.intermediate == z.intermediate and c.layers == z.layers and c.heads == z.heads and c.v_heads == z.v_heads) return true; + const layers = c.physicalLayers(); + for (sizes) |z| if (c.hidden == z.hidden and c.intermediate == z.intermediate and layers == z.layers and c.heads == z.heads and c.v_heads == z.v_heads) return true; return false; } diff --git a/zig/src/families/qwen27/projection.zig b/zig/src/families/qwen27/projection.zig index 6612a4435ee..20a90041ffc 100644 --- a/zig/src/families/qwen27/projection.zig +++ b/zig/src/families/qwen27/projection.zig @@ -7,7 +7,9 @@ const lane = @import("core").lane_projection; pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; /// A device matrix; `runs` non-empty means fused members of different widths. `gn`: the checkpoint's rows (0 = `n`). -pub const Linear = struct { words: Ref, pairs: Ref, n: u32, k: u32, tile: u32, slices: u32, raw: ?row.Weights = null, bits: u8 = 4, group: u32 = 64, runs: []const Run = &.{}, gn: usize = 0 }; +const SnLinear = if (@hasDecl(@import("core"), "sensenova_loop")) @import("loop.zig").SnLinear else void; + +pub const Linear = struct { words: Ref, pairs: Ref, n: u32, k: u32, tile: u32, slices: u32, raw: ?row.Weights = null, bits: u8 = 4, group: u32 = 64, runs: []const Run = &.{}, gn: usize = 0, sn: ?SnLinear = null }; /// One product inside a mixed fused matrix, writing output columns [first, first + linear.n). pub const Run = struct { linear: Linear, first: u32 }; /// Staged tensors: `gn` the part's rows when `weight.shape[0]` is a slice, `whole` its tensor's rows as a block. diff --git a/zig/src/families/qwen27/prompt_rows.zig b/zig/src/families/qwen27/prompt_rows.zig index 40d7be49c33..ef1ed9bea02 100644 --- a/zig/src/families/qwen27/prompt_rows.zig +++ b/zig/src/families/qwen27/prompt_rows.zig @@ -4,7 +4,13 @@ const planning = @import("attention_plan.zig"); /// With experts, 1,024 on every chip: a chunk reads every expert once, and Ornith's numbers were measured there. pub fn requested(generation: u32, routed: bool, value: ?[]const u8) u32 { - const default: u32 = if (routed) 1024 else if (generation == 17) 2048 else 512; + return requestedModel(generation, routed, false, value); +} + +/// SenseNova-Loop opens 2,048-row prompt chunks from M3 (gen 15); Qwen3.5 keeps 2,048 on gen 17 and 512 elsewhere. +pub fn requestedModel(generation: u32, routed: bool, looped: bool, value: ?[]const u8) u32 { + const wide = if (looped) generation >= 15 else generation == 17; + const default: u32 = if (routed) 1024 else if (wide) 2048 else 512; return override(value) orelse default; } diff --git a/zig/src/families/qwen27/quant_gpu.zig b/zig/src/families/qwen27/quant_gpu.zig index d8b583eb491..fbfcb5219b3 100644 --- a/zig/src/families/qwen27/quant_gpu.zig +++ b/zig/src/families/qwen27/quant_gpu.zig @@ -10,7 +10,7 @@ pub const Ref = projection.Ref; /// Group sums the input's producer wrote: XS[group * stride + row], in the lane projection's order. pub const Sums = struct { ref: Ref, stride: u32 }; -pub const Key = struct { kind: Kind, n: u32 = 0, k: u32, slices: u32 = 0, tile: u32 = 0, tmr: u32 = 0, edge: bool = false, skip: u32 = 0, cut: [2]u32 = .{ 0, 0 }, bits: u8 = 4, group: u32 = 64, long: bool = false, xs: bool = true }; +pub const Key = struct { kind: Kind, n: u32 = 0, k: u32, slices: u32 = 0, tile: u32 = 0, tmr: u32 = 0, edge: bool = false, skip: u32 = 0, cut: [2]u32 = .{ 0, 0 }, bits: u8 = 4, group: u32 = 64, long: bool = false, xs: bool = true, xs_group: u16 = 64, shift: bool = false }; pub const Kind = enum { projection, xsum, norm, input_norm, mlp, ane_input, mlp_ane, add_ane }; /// Whether prompt chunks take one dispatch a projection (`Kernels.long_prompt`): Ultras with tensor units only. @@ -70,6 +70,11 @@ pub const Kernels = struct { prep_words: ?mtl.Buffer = null, /// tf_sq_prep_s's sums for a chunk-pair projection's prompt rows, written just before it. sum_words: ?mtl.Buffer = null, + sn: ?(if (@hasDecl(@import("core"), "sensenova_loop")) @import("core").sensenova_loop.linear_gpu.LinearGpu else void) = null, + sn_xs128: ?(if (@hasDecl(@import("core"), "sensenova_loop")) struct { + x: Ref, + sums: @import("core").sensenova_loop.linear_gpu.Sums, + } else void) = null, pub fn setResident(k: *Kernels, hook: ?mtl.ResidencySet.Follow) void { var it = k.lanes.valueIterator(); @@ -103,15 +108,20 @@ pub const Kernels = struct { var it = k.cache.valueIterator(); while (it.next()) |p| p.deinit(); k.cache.deinit(k.allocator); + if (comptime @hasDecl(@import("core"), "sensenova_loop")) { + if (k.sn) |*s| s.deinit(); + } } fn get(k: *Kernels, key: Key) !mtl.Pipeline { - if (k.cache.get(key)) |p| return p; - const source = try specializedSource(k.allocator, key); + var cache_key = key; + if (!cache_key.xs) cache_key.xs_group = 0; + if (k.cache.get(cache_key)) |p| return p; + const source = try specializedSource(k.allocator, cache_key); defer k.allocator.free(source); const library = try mtl.Library.fromSource(k.device, source, mtl.CompileOptions.mlx()); defer library.deinit(); - const name: [:0]const u8 = switch (key.kind) { + const name: [:0]const u8 = switch (cache_key.kind) { .projection => unreachable, .xsum => "custom_kernel_q27_xsum_bfloat16_t_int32_t_float", .norm => "custom_kernel_q27_norm_xs_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float", @@ -123,10 +133,16 @@ pub const Kernels = struct { }; const p = try mtl.Pipeline.init(k.device, library, name, false); errdefer p.deinit(); - try k.cache.put(k.allocator, key, p); + try k.cache.put(k.allocator, cache_key, p); return p; } + fn xsGroup(k: *const Kernels, width: u32) u16 { + if (!k.device.tensorUnits()) return 0; + if (k.sn != null) return if (width % 128 == 0) 128 else 0; + return 64; + } + /// Encodes the product without ordering its output; the caller barriers before dependent reads or writes. pub fn quant(k: *Kernels, input_encoder: mtl.ComputeEncoder, p: projection.Linear, x: Ref, xs: ?Sums, dims: Ref, y: Ref, rows: u32) !void { return k.quantSkip(input_encoder, p, x, xs, dims, y, rows, 0); @@ -143,6 +159,13 @@ pub const Kernels = struct { } fn quantImpl(k: *Kernels, input_encoder: mtl.ComputeEncoder, p: projection.Linear, x: Ref, xs: ?Sums, dims: Ref, y: Ref, rows: u32, skip: u32, cut: [2]u32) !void { + if (comptime @hasDecl(@import("core"), "sensenova_loop")) { + if (p.sn) |s| { + if (skip > 0 or cut[1] > 0) return error.BadCoreProjectionRows; + const sn_xs = if (k.sn_xs128) |xs128| if (std.meta.eql(xs128.x.buffer, x.buffer) and xs128.x.offset == x.offset) xs128.sums else null else null; + return @import("loop.zig").encodeSn(&k.sn.?, k.profiler, input_encoder, s, x, sn_xs, y, rows, k.prompt); + } + } if (p.runs.len > 0) return k.quantRuns(input_encoder, p, x, xs, dims, y, rows, skip, cut); return k.quantOne(input_encoder, p, x, xs, dims, y, rows, skip, cut); } @@ -410,14 +433,22 @@ pub const Kernels = struct { } pub fn norm(k: *Kernels, input_encoder: mtl.ComputeEncoder, h: Ref, residual: ?Ref, weight: Ref, eps: Ref, dims: Ref, combined: Ref, out: Ref, xs: Ref, width: u32, rows: u32) !void { + return k.normShift(input_encoder, h, residual, weight, eps, dims, combined, out, xs, width, rows, false); + } + + pub fn normShift(k: *Kernels, input_encoder: mtl.ComputeEncoder, h: Ref, residual: ?Ref, weight: Ref, eps: Ref, dims: Ref, combined: Ref, out: Ref, xs: Ref, width: u32, rows: u32, shift: bool) !void { var span = profile.begin(k.profiler, input_encoder, .norm); errdefer span.cancel(); const e = span.encoder; - const xs_on = k.device.tensorUnits(); - e.setPipeline(try k.get(.{ .kind = if (residual != null) .norm else .input_norm, .k = width, .xs = xs_on })); + const xs_group = k.xsGroup(width); + const xs_on = xs_group != 0; + e.setPipeline(try k.get(.{ .kind = if (residual != null) .norm else .input_norm, .k = width, .xs = xs_on, .xs_group = xs_group, .shift = shift })); if (residual) |r| bind(e, .{ h, r, weight, eps, dims, combined, out, xs }) else bind(e, .{ h, weight, eps, dims, out, xs }); e.dispatchGroups(mtl.Size.of(1, if (xs_on) padded(rows) else rows, 1), mtl.Size.of(width / 16, 1, 1)); + if (comptime @hasDecl(@import("core"), "sensenova_loop")) { + k.sn_xs128 = if (xs_group == 128) .{ .x = out, .sums = .{ .ref = .{ .buf = xs.buffer, .off = xs.offset }, .stride = padded(rows) } } else null; + } k.fits = null; // tf_sq_fits's words and tf_sq_prep_h's sums and halves for this output: its prompt rows may take half operands if (k.raw_tiles and rows >= half_rows) { @@ -497,10 +528,15 @@ pub const Kernels = struct { errdefer span.cancel(); const e = span.encoder; - const xs_on = k.device.tensorUnits(); - e.setPipeline(try k.get(.{ .kind = .mlp, .k = width, .n = width, .xs = xs_on })); + const xs_group = k.xsGroup(width); + const xs_on = xs_group != 0; + const grp_w: u32 = if (xs_group == 128) 128 else 64; + e.setPipeline(try k.get(.{ .kind = .mlp, .k = width, .n = width, .xs = xs_on, .xs_group = xs_group })); bind(e, .{ gate, up, dims, out, xs }); - e.dispatchGroups(mtl.Size.of(width / 64, if (xs_on) padded(rows) else rows, 1), mtl.Size.of(64, 1, 1)); + e.dispatchGroups(mtl.Size.of(width / grp_w, if (xs_on) padded(rows) else rows, 1), mtl.Size.of(grp_w, 1, 1)); + if (comptime @hasDecl(@import("core"), "sensenova_loop")) { + k.sn_xs128 = if (xs_group == 128) .{ .x = out, .sums = .{ .ref = .{ .buf = xs.buffer, .off = xs.offset }, .stride = padded(rows) } } else null; + } try span.end(); } }; @@ -533,12 +569,32 @@ pub fn specializedSource(a: std.mem.Allocator, key: Key) ![]u8 { const definitions = switch (key.kind) { .projection => unreachable, .xsum => try std.fmt.allocPrint(a, "constexpr int K={d}, GS=64;", .{key.k}), - .norm, .input_norm => try std.fmt.allocPrint(a, "constexpr int K={d};", .{key.k}), + .norm, .input_norm => try std.fmt.allocPrint(a, "constexpr int K={d};{s}", .{ key.k, if (key.shift) "\n#define Q27_SHIFT 1" else "" }), .mlp => try std.fmt.allocPrint(a, "constexpr int N={d};", .{key.n}), .ane_input, .mlp_ane, .add_ane => try std.fmt.allocPrint(a, "constant constexpr int H={d}, N={d}, A={d};", .{ key.k, key.n, key.tile }), }; defer a.free(definitions); - const xs_define = if (key.xs) "#define Q27_XS 1\n" else "#define Q27_XS 0\n"; + const eff_xs: u16 = if (!key.xs) 0 else key.xs_group; + const xs_define = switch (eff_xs) { + 0 => "#define Q27_XS 0\n", + 128 => "#define Q27_XS 128\n", + else => "#define Q27_XS 64\n", + }; const source = try std.mem.concat(a, u8, &.{ xs_define, template[0..mark], definitions, template[mark + "Q27_SPECIALIZE".len ..] }); return source; } + +test "specialized source selects zero, 64, and 128 group sums" { + const a = std.testing.allocator; + for ([_]struct { xs: bool, xg: u16, want: []const u8 }{ + .{ .xs = false, .xg = 64, .want = "#define Q27_XS 0\n" }, + .{ .xs = true, .xg = 64, .want = "#define Q27_XS 64\n" }, + .{ .xs = true, .xg = 128, .want = "#define Q27_XS 128\n" }, + }) |case| { + for ([_]Kind{ .norm, .input_norm, .mlp }) |kind| { + const src = try specializedSource(a, .{ .kind = kind, .k = 4096, .n = 12288, .xs = case.xs, .xs_group = case.xg }); + defer a.free(src); + try std.testing.expect(std.mem.startsWith(u8, src, case.want)); + } + } +} diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index e9908680b3e..b523d55dfbb 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -1,5 +1,7 @@ //! Dense Qwen text configuration and checkpoint contracts. GPU forward pieces follow separately. pub const dflash = @import("dflash/root.zig"); +pub const yarn = @import("yarn.zig"); +pub const loop = @import("loop.zig"); pub const gguf = @import("gguf.zig"); pub const config = @import("config.zig"); pub const tied_head = @import("tied_head.zig"); @@ -55,6 +57,8 @@ pub const stage_planes = @import("stage_planes.zig"); pub const runtime_sources = @import("qwen_runtime_sources"); test { _ = dflash; + _ = yarn; + _ = loop; _ = disk; _ = @import("core").gpu_profile; _ = @import("core").qwen35_stages; diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index 32daac24729..70a8452e424 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -135,6 +135,7 @@ pub fn hold(h: anytype, io: std.Io) !void { } var projections = h.model.kernels.lanes.valueIterator(); while (projections.next()) |projection| try fields.append(h.gpa, &list, projection); + if (h.model.kernels.sn) |*sn| try sn.appendBuffers(h.gpa, &list); try appendRunner(&h.runner, h.gpa, &list); try fields.append(h.gpa, &list, h.back); for (h.back.contexts) |c| if (c) |x| try x.buffers(&list, h.gpa); diff --git a/zig/src/families/qwen27/rope_test.zig b/zig/src/families/qwen27/rope_test.zig index aeaa35f4840..353df039607 100644 --- a/zig/src/families/qwen27/rope_test.zig +++ b/zig/src/families/qwen27/rope_test.zig @@ -20,7 +20,7 @@ const Rig = struct { y: mtl.Buffer, /// Y for X at the planes' positions; h_end = w_end = 0 reads plane 0 alone. - fn run(r: *Rig, planes: [3][rows]i32, h_end: u32, w_end: u32) ![rows * heads * width]u16 { + fn run(r: *Rig, planes: [3][rows]i32, h_end: u32, w_end: u32, rope: @import("yarn.zig").Rope) ![rows * heads * width]u16 { const p = r.pos.slice(i32, 3 * plane); for (planes, 0..) |row, k| @memcpy(p[k * plane ..][0..rows], &row); const cb = r.queue.commandBuffer(); @@ -28,7 +28,7 @@ const Rig = struct { e.setPipeline(r.pipe); e.setBuffer(r.x, 0, 0); e.setBuffer(r.pos, 0, 1); - e.setValue(glue.Rope{ .width = width, .heads = heads, .rows = rows, .rotary = 64, .activation = .bf16, .theta = 1e7, .h_end = h_end, .w_end = w_end, .plane = plane }, 2); + e.setValue(rope.apply(.{ .width = width, .heads = heads, .rows = rows, .rotary = 64, .activation = .bf16, .theta = 1e7, .h_end = h_end, .w_end = w_end, .plane = plane }), 2); e.setBuffer(r.y, 0, 3); e.dispatchThreads(mtl.Size.of(width, heads, rows), mtl.Size.of(32, 1, 1)); e.end(); @@ -62,19 +62,47 @@ test "q27_rope: t = h = w is plain rope bit for bit, and an image row's pairs tu var rng = std.Random.DefaultPrng.init(0x5eed); for (r.x.slice(u16, n)) |*v| v.* = @truncate(@as(u32, @bitCast(rng.random().floatNorm(f32))) >> 16); const text = [rows]i32{ 5, 900, 70000, 262143 }; - const plain = try r.run(.{ text, @splat(0), @splat(0) }, 0, 0); - const mrope = try r.run(.{ text, text, text }, 33, 30); + const plain = try r.run(.{ text, @splat(0), @splat(0) }, 0, 0, .plain); + const mrope = try r.run(.{ text, text, text }, 33, 30, .plain); try std.testing.expectEqualSlices(u16, &plain, &mrope); // each row an image row at (t, h, w); a pair's two values equal plain rope's at its axis's position const t = [rows]i32{ 10, 300, 4000, 9 }; const h = [rows]i32{ 13, 302, 4010, 9 }; const w = [rows]i32{ 17, 301, 4003, 40 }; - const image = try r.run(.{ t, h, w }, 33, 30); - const at = [3][rows * heads * width]u16{ try r.run(.{ t, @splat(0), @splat(0) }, 0, 0), try r.run(.{ h, @splat(0), @splat(0) }, 0, 0), try r.run(.{ w, @splat(0), @splat(0) }, 0, 0) }; + const image = try r.run(.{ t, h, w }, 33, 30, .plain); + const at = [3][rows * heads * width]u16{ try r.run(.{ t, @splat(0), @splat(0) }, 0, 0, .plain), try r.run(.{ h, @splat(0), @splat(0) }, 0, 0, .plain), try r.run(.{ w, @splat(0), @splat(0) }, 0, 0, .plain) }; for (0..rows * heads) |rh| for (0..width) |x| { const i = rh * width + x; // past the rotary dims every plane copies const k: usize = if (x < 64) axis(@intCast(x % 32), .{ 11, 11, 10 }) else 0; try std.testing.expectEqual(at[k][i], image[i]); }; + + // Static YaRN up to 512K: rotated dims use yarn_freq and yarn_scale; dims >= 64 stay raw passthrough. + const y_tbl = @import("core").rope_yarn.yarn(1e7, 2.0, 262144); + const yarn_rope: @import("yarn.zig").Rope = .{ .yarn = .{ .factor = 2.0, .trained = 262144, .scale = y_tbl.scale, .freq = y_tbl.freq } }; + const y_pos = [rows]i32{ 5, 900, 70000, 450000 }; + const y_gpu = try r.run(.{ y_pos, @splat(0), @splat(0) }, 0, 0, yarn_rope); + const x_host = r.x.slice(u16, n); + for (0..rows) |row| for (0..heads) |hd| for (0..width) |x| { + const idx = (row * heads + hd) * width + x; + if (x >= 64) { + try std.testing.expectEqual(x_host[idx], y_gpu[idx]); + continue; + } + const second = x >= 32; + const d = if (second) x - 32 else x; + const base_idx = (row * heads + hd) * width; + const v: f32 = @bitCast(@as(u32, x_host[idx]) << 16); + const partner_u16 = x_host[base_idx + if (second) d else d + 32]; + const pval: f32 = @bitCast(@as(u32, partner_u16) << 16); + const angle = @as(f32, @floatFromInt(y_pos[row])) * y_tbl.freq[d]; + const cs = @cos(angle) * y_tbl.scale; + const sn = @sin(angle) * y_tbl.scale; + const ref_f = if (second) v * cs + pval * sn else v * cs - pval * sn; + const ref_b: u16 = @truncate((@as(u32, @bitCast(ref_f)) + 0x7fff + ((@as(u32, @bitCast(ref_f)) >> 16) & 1)) >> 16); + const ulp_ok = ((ref_b & 0x7fff) == 0 and (y_gpu[idx] & 0x7fff) == 0) or + ((ref_b ^ y_gpu[idx]) < 0x8000 and @abs(@as(i32, ref_b) - @as(i32, y_gpu[idx])) <= 1); + try std.testing.expect(ulp_ok); + }; } diff --git a/zig/src/families/qwen27/widths.zig b/zig/src/families/qwen27/widths.zig index 1bba272009e..f9d0908636f 100644 --- a/zig/src/families/qwen27/widths.zig +++ b/zig/src/families/qwen27/widths.zig @@ -7,13 +7,14 @@ const glue = @import("glue.zig"); const row = core.row_projection; const lane = core.lane_projection; -/// One affine width, as core.quant.mlx.Width: `bits` per weight, a scale and bias a `group` of K. -pub const Width = struct { bits: u8, group: u16 }; +/// Affine or native/AWQ width of one module. +pub const Kind = enum(u8) { affine, bf16, awq }; +pub const Width = struct { bits: u8, group: u16, kind: Kind = .affine }; /// The qualified format: today's kernels and launches, unchanged. pub const uniform = Width{ .bits = 4, .group = 64 }; pub fn isUniform(w: Width) bool { - return w.bits == uniform.bits and w.group == uniform.group; + return w.kind == .affine and w.bits == uniform.bits and w.group == uniform.group; } /// A layer's projections; a layer stores entries for both mixers and uses those of its kind. @@ -94,12 +95,14 @@ pub const Widths = struct { /// Resolves only loaded modules, so draft-head (MTP) and vision overrides never decide admission. pub fn resolve(a: std.mem.Allocator, f: *const affine.Formats, c: cfg.Config) !Widths { if ((try f.resolve(null)) == null) return error.MissingAffineFormat; - const layers = try a.alloc([members]Width, c.layers); + const n = c.physicalLayers(); + const layers = try a.alloc([members]Width, n); errdefer a.free(layers); var name: [96]u8 = undefined; for (layers, 0..) |*l, i| { l.* = @splat(uniform); - for (stacks(c.kind(i))) |stack| for (stack) |m| { + const k = if (c.looped) c.physKind(i) else c.kind(i); + for (stacks(k)) |stack| for (stack) |m| { l[@backingInt(m)] = try one(f, try std.fmt.bufPrint(&name, "model.layers.{d}.{s}", .{ i, leaf(c, m) })); }; if (c.moe()) for (routed) |m| { @@ -110,6 +113,48 @@ pub const Widths = struct { return .{ .allocator = a, .layers = layers, .embed = embed, .head = if (c.tied_head) embed else try one(f, "lm_head") }; } + /// Resolve native BF16 or AWQ w4g128 on looped models, or MLX affine everywhere else. + pub fn resolveModel(a: std.mem.Allocator, json: []const u8, c: cfg.Config) !Widths { + if (!c.looped) { + var formats = try affine.Formats.init(a, json); + defer formats.deinit(); + return Widths.resolve(a, &formats, c); + } + if (comptime !@hasDecl(@import("core"), "sensenova_loop")) return error.UnsupportedLoopedWidths; + const parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{}); + defer parsed.deinit(); + if (parsed.value != .object) return error.BadConfig; + const awq_mod = @import("core").sensenova_loop.awq; + if (try awq_mod.parseConfig(a, parsed.value.object)) |ac_const| { + var ac = ac_const; + defer ac.deinit(a); + const layers = try a.alloc([members]Width, c.physicalLayers()); + errdefer a.free(layers); + var name: [128]u8 = undefined; + const bf16: Width = .{ .bits = 16, .group = 0, .kind = .bf16 }; + const w4: Width = .{ .bits = ac.bits, .group = @intCast(ac.group_size), .kind = .awq }; + for (layers, 0..) |*l, i| { + l.* = @splat(bf16); + for (stacks(c.physKind(i))) |stack| for (stack) |m| { + const p = try std.fmt.bufPrint(&name, "model.language_model.layers.{d}.{s}", .{ i, leaf(c, m) }); + l[@backingInt(m)] = if (ac.isQuantized(p)) w4 else bf16; + }; + } + if (ac.isQuantized("model.language_model.embed_tokens")) return error.UnqualifiedQwenFormat; + return .{ .allocator = a, .layers = layers, .embed = bf16, .head = if (ac.isQuantized("lm_head")) w4 else bf16 }; + } + var formats = affine.Formats.init(a, json) catch |err| switch (err) { + error.NotAffine => return error.UnqualifiedQwenFormat, + else => return err, + }; + defer formats.deinit(); + if (formats.quant != null) return Widths.resolve(a, &formats, c); + const bf16: Width = .{ .bits = 16, .group = 0, .kind = .bf16 }; + const layers = try a.alloc([members]Width, c.physicalLayers()); + for (layers) |*l| l.* = @splat(bf16); + return .{ .allocator = a, .layers = layers, .embed = bf16, .head = bf16 }; + } + /// Every module 4-bit g64, for synthetic graphs. pub fn uniformAll(a: std.mem.Allocator, layers: usize) !Widths { const all = try a.alloc([members]Width, layers); @@ -131,10 +176,12 @@ pub const Widths = struct { var mixed = false; for (w.layers) |l| for (l) |x| { mixed = mixed or !isUniform(x); + if (x.kind != .affine) h.update(&.{@backingInt(x.kind)}); h.update(&.{ x.bits, @as(u8, @truncate(x.group)), @as(u8, @truncate(x.group >> 8)) }); }; for ([_]Width{ w.embed, w.head }) |x| { mixed = mixed or !isUniform(x); + if (x.kind != .affine) h.update(&.{@backingInt(x.kind)}); h.update(&.{ x.bits, @as(u8, @truncate(x.group)), @as(u8, @truncate(x.group >> 8)) }); } return if (mixed) h.final() | 1 else 0; @@ -149,8 +196,10 @@ fn one(f: *const affine.Formats, path: []const u8) !Width { /// The timed window costs' model shape; mixed widths add their tag, so checkpoints of one shape keep their own costs. pub fn costShape(c: cfg.Config, tag: u64, buf: []u8, rows: usize, drafted: bool) ![]const u8 { const s = try std.fmt.bufPrint(buf, "{d}/{d}/{d}/{d}/{d}/{d}", .{ c.layers, c.hidden, c.intermediate, c.vocab, rows, @intFromBool(drafted) }); - if (tag == 0) return s; - return buf[0 .. s.len + (try std.fmt.bufPrint(buf[s.len..], "/w{x:0>16}", .{tag})).len]; + if (tag == 0 and !c.looped) return s; + const t = if (tag != 0) s.len + (try std.fmt.bufPrint(buf[s.len..], "/w{x:0>16}", .{tag})).len else s.len; + if (!c.looped) return buf[0..t]; + return buf[0 .. t + (try std.fmt.bufPrint(buf[t..], "/sn2", .{})).len]; } /// What the chip's projection kernels run: lane kernels on tensor units for whole 32-row tiles, else the row kernels. @@ -161,7 +210,7 @@ pub const Why = struct { layer: ?usize = null, module: []const u8 = "", width: W pub fn admit(w: *const Widths, c: cfg.Config, chip: Chip, why: *Why) !void { var buf: [3][2]usize = undefined; - for (0..c.layers) |i| for (stacks(c.kind(i))) |stack| { + for (0..w.layers.len) |i| for (stacks(if (c.looped) c.physKind(i) else c.kind(i))) |stack| { var ws: [3]Width = undefined; for (stack, 0..) |m, j| ws[j] = w.of(i, m); const list = runs(ws[0..stack.len], &buf); @@ -200,7 +249,12 @@ pub fn admit(w: *const Widths, c: cfg.Config, chip: Chip, why: *Why) !void { } } }; - glue.checkEmbed(.{ .width = @intCast(c.hidden), .rows = 1, .vocab = @intCast(c.vocab), .bits = w.embed.bits, .group = w.embed.group, .metadata = .bf16 }) catch |err| { + if (w.embed.kind == .bf16) { + if (c.hidden == 0 or c.vocab == 0) { + why.* = .{ .module = "embed_tokens", .width = w.embed, .reason = error.BadEmbedding }; + return error.UnqualifiedQwenFormat; + } + } else glue.checkEmbed(.{ .width = @intCast(c.hidden), .rows = 1, .vocab = @intCast(c.vocab), .bits = w.embed.bits, .group = w.embed.group, .metadata = .bf16 }) catch |err| { why.* = .{ .module = "embed_tokens", .width = w.embed, .reason = err }; return error.UnqualifiedQwenFormat; }; @@ -212,6 +266,14 @@ pub fn admit(w: *const Widths, c: cfg.Config, chip: Chip, why: *Why) !void { /// One run's kernel: 4-, 5-, and 6-bit g64 take reg lanes; other widths take non-reg lanes or row kernels. fn check(chip: Chip, n: usize, k: usize, w: Width) !void { + if (w.kind == .bf16) { + if (n == 0 or k == 0 or k % 8 != 0) return error.BadProjectionShape; + return; + } + if (w.kind == .awq) { + if (w.bits != 4 or w.group != 128 or n == 0 or k == 0 or n % 8 != 0 or k % 128 != 0) return error.UnsupportedLaneGroup; + return; + } _ = try @import("projection.zig").split(n, k); // The lane sums and odd word counts assume group 64 off the 4-bit kernel. if (chip.tensor_units and w.bits != 4 and w.group != 64) return error.UnsupportedLaneGroup; @@ -459,3 +521,28 @@ test "Qwen3.6-35B-A3B's published widths are admitted with and without tensor un try std.testing.expectError(error.UnqualifiedQwenFormat, testAdmitA3b(split_gate, false, &why)); try std.testing.expectEqual(error.SharedGateWidth, why.reason); } + +test "looped costShape appends cache-busting tag without altering Qwen shapes" { + const a = std.testing.allocator; + const text = try testConfig(a, "{\"bits\":4,\"group_size\":64}"); + defer a.free(text); + var c = try cfg.parse(a, text, null); + var buf: [96]u8 = undefined; + try std.testing.expectEqualStrings("64/5120/17408/248320/16/1", try costShape(c, 0, &buf, 16, true)); + c.looped = true; + try std.testing.expectEqualStrings("64/5120/17408/248320/16/1/sn2", try costShape(c, 0, &buf, 16, true)); + try std.testing.expectEqualStrings("64/5120/17408/248320/16/0/w000000000000002a/sn2", try costShape(c, 0x2a, &buf, 16, false)); +} + +test "affine widths tag keeps main's three-byte key while non-affine kinds hash distinctly" { + const a = std.testing.allocator; + var w = try Widths.uniformAll(a, 1); + defer w.deinit(); + w.layers[0][0] = .{ .bits = 8, .group = 64 }; + var want_hash = std.hash.Wyhash.init(0x27); + for (w.layers) |l| for (l) |x| want_hash.update(&.{ x.bits, @as(u8, @truncate(x.group)), @as(u8, @truncate(x.group >> 8)) }); + for ([_]Width{ w.embed, w.head }) |x| want_hash.update(&.{ x.bits, @as(u8, @truncate(x.group)), @as(u8, @truncate(x.group >> 8)) }); + try std.testing.expectEqual(want_hash.final() | 1, w.tag()); + w.layers[0][0] = .{ .bits = 4, .group = 128, .kind = .awq }; + try std.testing.expect(w.tag() != (want_hash.final() | 1)); +} diff --git a/zig/src/families/qwen27/yarn.zig b/zig/src/families/qwen27/yarn.zig new file mode 100644 index 00000000000..e5dd9cce61f --- /dev/null +++ b/zig/src/families/qwen27/yarn.zig @@ -0,0 +1,108 @@ +//! Static YaRN configuration parsing and frequency/scale computation for Qwen27 / SenseNova-Loop. +const std = @import("std"); +const core = @import("core"); +const rope_config = @import("rope_config"); +const glue = @import("glue.zig"); + +pub const Yarn = struct { + factor: f64, + trained: usize, + scale: f32, + freq: [32]f32, +}; + +pub const Rope = union(enum) { + plain, + yarn: Yarn, + + /// Populate a Metal `glue.Rope` descriptor (leaves `yarn_scale == 0` for plain RoPE). + pub fn apply(r: Rope, base: glue.Rope) glue.Rope { + var out = base; + switch (r) { + .plain => {}, + .yarn => |y| { + out.yarn_scale = y.scale; + out.yarn_freq = y.freq; + }, + } + return out; + } +}; + +pub const Resolved = struct { rope: Rope, ceiling: usize }; + +pub const Error = error{ UnsupportedRopeScaling, RopeYarnFactor, RopeYarnConflict, BadConfig }; + +/// Resolve YaRN from `rope_parameters` / `rope_scaling` or `--rope-yarn`; non-default YaRN params are refused. +pub fn resolve(tower: std.json.ObjectMap, root: std.json.ObjectMap, rope_opt: ?std.json.ObjectMap, theta: f64, max_pos: usize, flag: ?f64) Error!Resolved { + if (flag) |f| if (!std.math.isFinite(f) or f < 1) return error.RopeYarnFactor; + const host = if (tower.contains("rope_scaling")) tower else root; + const legacy_v = host.get("rope_scaling"); + if (legacy_v) |lv| switch (lv) { + .null => {}, + .object => |lo| return resolveBlock(lo, true, theta, max_pos, flag), + else => return error.BadConfig, + }; + if (rope_opt) |ro| return resolveBlock(ro, false, theta, max_pos, flag); + return applyFlag(theta, max_pos, flag); +} + +fn resolveBlock(block: std.json.ObjectMap, older: bool, theta: f64, max_pos: usize, flag: ?f64) Error!Resolved { + const kind = block.get("rope_type") orelse block.get("type") orelse return if (older) error.UnsupportedRopeScaling else .{ .rope = .plain, .ceiling = max_pos }; + if (kind != .string) return error.UnsupportedRopeScaling; + if (std.mem.eql(u8, kind.string, "default") and !older) return applyFlag(theta, max_pos, flag); + if (!std.mem.eql(u8, kind.string, "yarn")) return error.UnsupportedRopeScaling; + for ([_][]const u8{ "mscale", "mscale_all_dim", "attention_factor" }) |key| if (block.get(key)) |v| if (v != .null) return error.UnsupportedRopeScaling; + for ([_]struct { []const u8, f64 }{ .{ "beta_fast", 32 }, .{ "beta_slow", 1 } }) |b| if (block.get(b[0])) |v| { + if (v != .null and (try number(v)) != b[1]) return error.UnsupportedRopeScaling; + }; + if (block.get("truncate")) |v| if (v != .null and !(v == .bool and v.bool)) return error.UnsupportedRopeScaling; + const factor = try number(block.get("factor") orelse return error.UnsupportedRopeScaling); + const tv = block.get("original_max_position_embeddings") orelse return error.UnsupportedRopeScaling; + if (tv != .integer or tv.integer < 1 or tv.integer > std.math.maxInt(u32)) return error.UnsupportedRopeScaling; + const trained: usize = @intCast(tv.integer); + if (factor == 1 and trained == max_pos) return applyFlag(theta, max_pos, flag); + if (!(factor > 1) or @as(f64, @floatFromInt(trained)) * factor != @as(f64, @floatFromInt(max_pos))) return error.UnsupportedRopeScaling; + if (flag) |f| if (f != factor) return error.RopeYarnConflict; + if (comptime @hasDecl(core, "rope_yarn")) { + const y = core.rope_yarn.yarn(theta, factor, trained); + return .{ .rope = .{ .yarn = .{ .factor = factor, .trained = trained, .scale = y.scale, .freq = y.freq } }, .ceiling = max_pos }; + } else return error.UnsupportedRopeScaling; +} + +fn applyFlag(theta: f64, max_pos: usize, flag: ?f64) Error!Resolved { + const f = flag orelse return .{ .rope = .plain, .ceiling = max_pos }; + if (f == 1) return .{ .rope = .plain, .ceiling = max_pos }; + const ceil = @as(f64, @floatFromInt(max_pos)) * f; + if (ceil != @floor(ceil) or ceil > std.math.maxInt(u32)) return error.RopeYarnFactor; + if (comptime @hasDecl(core, "rope_yarn")) { + const y = core.rope_yarn.yarn(theta, f, max_pos); + return .{ .rope = .{ .yarn = .{ .factor = f, .trained = max_pos, .scale = y.scale, .freq = y.freq } }, .ceiling = @intFromFloat(ceil) }; + } else return error.RopeYarnFactor; +} + +fn number(v: std.json.Value) Error!f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |x| if (std.math.isFinite(x)) x else error.UnsupportedRopeScaling, + else => error.UnsupportedRopeScaling, + }; +} + +test "SenseNova-Loop-9B 512K static YaRN (theta 1e7, factor 2 over 262144) matches core.rope_yarn" { + const a = std.testing.allocator; + const json_text = + \\{"max_position_embeddings":524288,"rope_parameters":{"mrope_interleaved":true,"mrope_section":[11,11,10], + \\ "partial_rotary_factor":0.25,"rope_theta":10000000,"rope_type":"yarn","factor":2.0, + \\ "original_max_position_embeddings":262144,"truncate":true}} + ; + const parsed = try std.json.parseFromSlice(std.json.Value, a, json_text, .{}); + defer parsed.deinit(); + const t = parsed.value.object; + const r = try resolve(t, t, rope_config.params(t) catch unreachable, 10000000, 524288, null); + try std.testing.expectEqual(@as(usize, 524288), r.ceiling); + const y = core.rope_yarn.yarn(10000000, 2.0, 262144); + try std.testing.expectEqual(y.scale, r.rope.yarn.scale); + try std.testing.expectEqualSlices(f32, &y.freq, &r.rope.yarn.freq); + try std.testing.expectError(error.RopeYarnConflict, resolve(t, t, rope_config.params(t) catch unreachable, 10000000, 524288, 4.0)); +} diff --git a/zig/src/families/sensenova_loop/awq.zig b/zig/src/families/sensenova_loop/awq.zig new file mode 100644 index 00000000000..fe1ed2a8750 --- /dev/null +++ b/zig/src/families/sensenova_loop/awq.zig @@ -0,0 +1,548 @@ +//! AutoAWQ (4-bit, group_size 128, zero_point=true) unpacker and lossless FP32 metadata repacker for M5 and M3. +const std = @import("std"); + +pub const group_size: usize = 128; +pub const bits: u8 = 4; + +/// AutoAWQ packs logical columns [0,2,4,6,1,3,5,7] into nibbles 0..7; column c sits at nibble awq_nibble_order[c]. +pub const awq_nibble_order = [8]u5{ 0, 4, 1, 5, 2, 6, 3, 7 }; +pub const awq_shifts = [8]u5{ 0, 16, 4, 20, 8, 24, 12, 28 }; + +/// Lossless group metadata: f32 scale and bias = -z * scale (0-ULP exact for F16/BF16 scales and 4-bit zero). +pub const Float2 = extern struct { + scale: f32, + bias: f32, +}; + +pub const ScaleDType = enum { + f16, + bf16, + f32, + + pub fn byteSize(d: ScaleDType) usize { + return switch (d) { + .f16, .bf16 => 2, + .f32 => 4, + }; + } +}; + +pub const Layout = enum { m5_tile, m3_row }; + +/// Parsed `quantization_config` / `quantization` for AutoAWQ GEMM. +pub const Config = struct { + bits: u8 = 4, + group_size: usize = 128, + zero_point: bool = true, + modules_to_not_convert: []const []const u8 = &.{}, + + pub fn deinit(c: *Config, a: std.mem.Allocator) void { + for (c.modules_to_not_convert) |m| a.free(m); + a.free(c.modules_to_not_convert); + c.* = .{}; + } + + pub fn isQuantized(c: Config, key: []const u8) bool { + for (c.modules_to_not_convert) |skip| { + if (std.mem.eql(u8, key, skip)) return false; + if (std.mem.startsWith(u8, key, skip) and key.len > skip.len and key[skip.len] == '.') return false; + if (std.mem.endsWith(u8, key, skip) and key.len > skip.len and + key[key.len - skip.len - 1] == '.') return false; + var buf: [256]u8 = undefined; + if (skip.len + 2 <= buf.len) { + buf[0] = '.'; + @memcpy(buf[1..][0..skip.len], skip); + buf[1 + skip.len] = '.'; + if (std.mem.indexOf(u8, key, buf[0 .. skip.len + 2]) != null) return false; + } + } + return true; + } +}; + +fn findQuantObject(root: std.json.ObjectMap) ?std.json.ObjectMap { + for ([_][]const u8{ "quantization_config", "quantization" }) |k| { + if (root.get(k)) |v| if (v == .object) return v.object; + } + if (root.get("text_config")) |tc| if (tc == .object) { + for ([_][]const u8{ "quantization_config", "quantization" }) |k| { + if (tc.object.get(k)) |v| if (v == .object) return v.object; + } + }; + return null; +} + +pub fn parseConfig(a: std.mem.Allocator, root: std.json.ObjectMap) !?Config { + const obj = findQuantObject(root) orelse return null; + if (obj.get("quant_method")) |qm| { + if (qm != .string) return error.UnsupportedQuantization; + if (!std.ascii.eqlIgnoreCase(qm.string, "awq")) { + return null; + } + } else return null; + + if (obj.get("version")) |ver| { + if (ver != .string or !std.ascii.eqlIgnoreCase(ver.string, "gemm")) return error.UnsupportedQuantization; + } + const b_val = obj.get("bits") orelse obj.get("w_bit"); + const b_int: i64 = if (b_val) |v| (if (v == .integer) v.integer else return error.UnsupportedQuantization) else 4; + if (b_int != 4) return error.UnsupportedQuantization; + + const g_val = obj.get("group_size") orelse obj.get("q_group_size"); + const g_int: i64 = if (g_val) |v| (if (v == .integer) v.integer else return error.UnsupportedQuantization) else 128; + if (g_int != 128) return error.UnsupportedQuantization; + + const zp_val = obj.get("zero_point"); + const zp = if (zp_val) |v| (if (v == .bool) v.bool else return error.UnsupportedQuantization) else true; + if (!zp) return error.UnsupportedQuantization; + + var skips: std.ArrayList([]const u8) = .empty; + errdefer { + for (skips.items) |s| a.free(s); + skips.deinit(a); + } + if (obj.get("modules_to_not_convert")) |m| { + if (m != .array) return error.UnsupportedQuantization; + for (m.array.items) |item| { + if (item != .string) return error.UnsupportedQuantization; + try skips.append(a, try a.dupe(u8, item.string)); + } + } + return .{ .bits = 4, .group_size = 128, .zero_point = true, .modules_to_not_convert = try skips.toOwnedSlice(a) }; +} + +pub inline fn unpackNibble(word: u32, col_mod_8: usize) u4 { + return @truncate(word >> awq_shifts[col_mod_8]); +} + +pub inline fn packAwqWord(cols: [8]u4) u32 { + const order = [8]usize{ 0, 2, 4, 6, 1, 3, 5, 7 }; + var w: u32 = 0; + for (order, 0..) |c, i| w |= @as(u32, cols[c]) << @intCast(4 * i); + return w; +} + +pub inline fn loadScale(dtype: ScaleDType, bytes: []const u8, idx: usize) f32 { + return switch (dtype) { + .f16 => @floatCast(@as(f16, @bitCast(std.mem.readInt(u16, bytes[2 * idx ..][0..2], .little)))), + .bf16 => @bitCast(@as(u32, std.mem.readInt(u16, bytes[2 * idx ..][0..2], .little)) << 16), + .f32 => @bitCast(std.mem.readInt(u32, bytes[4 * idx ..][0..4], .little)), + }; +} + +pub inline fn losslessMeta(scale: f32, zero: u4) Float2 { + const bias: f32 = if (zero == 0) 0.0 else -@as(f32, @floatFromInt(zero)) * scale; + return .{ .scale = scale, .bias = bias }; +} + +/// Raw AutoAWQ tensors for a single projection [N, K]: qweight [K, N/8], qzeros [K/128, N/8], scales [K/128, N]. +pub const Part = struct { + n: usize, + k: usize, + qweight: []const u32, + qzeros: []const u32, + scales: []const u8, + scales_dtype: ScaleDType, + input_scale: ?[]const f32 = null, +}; + +pub fn validatePart(p: Part) !void { + if (p.n == 0 or p.n % 8 != 0 or p.k == 0 or p.k % group_size != 0) return error.InvalidAwqShape; + const kg = p.k / group_size; + if (p.qweight.len != p.k * (p.n / 8)) return error.InvalidAwqStorage; + if (p.qzeros.len != kg * (p.n / 8)) return error.InvalidAwqStorage; + if (p.scales.len != kg * p.n * p.scales_dtype.byteSize()) return error.InvalidAwqStorage; + if (p.input_scale) |is| if (is.len != p.k) return error.InvalidAwqStorage; +} + +fn inputScaleEql(a_opt: ?[]const f32, b_opt: ?[]const f32) bool { + if (a_opt == null and b_opt == null) return true; + const a_s = a_opt orelse return false; + const b_s = b_opt orelse return false; + return std.mem.eql(u8, std.mem.sliceAsBytes(a_s), std.mem.sliceAsBytes(b_s)); +} + +/// True when parts share the same K and identical optional input_scale (can stack along N into one projection). +pub fn canStack(parts: []const Part) !bool { + if (parts.len == 0) return error.EmptyAwqParts; + for (parts) |p| try validatePart(p); + const k0 = parts[0].k; + const is0 = parts[0].input_scale; + for (parts[1..]) |p| { + if (p.k != k0) return error.MismatchedAwqK; + if (!inputScaleEql(is0, p.input_scale)) return false; + } + return true; +} + +pub fn weightWords(n_total: usize, k: usize, layout: Layout) usize { + return switch (layout) { + .m5_tile => ((n_total + 31) / 32) * (k / group_size) * 32 * 16, + .m3_row => n_total * (k / 8), + }; +} + +pub fn metaCount(n_total: usize, k: usize) usize { + return n_total * (k / group_size); +} + +/// Repacks 1 or more AutoAWQ parts (stacked along N) into M5 tile [tile_n][KG][32][16] or M3 row [N][K/8] layout. +pub fn packParts(parts: []const Part, layout: Layout, out_w: []u32, out_sb: []Float2) !void { + if (parts.len == 0) return error.EmptyAwqParts; + const k = parts[0].k; + var n_total: usize = 0; + for (parts) |p| { + try validatePart(p); + if (p.k != k) return error.MismatchedAwqK; + n_total += p.n; + } + if (out_w.len != weightWords(n_total, k, layout) or out_sb.len != metaCount(n_total, k)) { + return error.InvalidAwqStorage; + } + @memset(out_w, 0); + const kg = k / group_size; + const kw_row = k / 8; + + var n_base: usize = 0; + for (parts) |p| { + const pn8 = p.n / 8; + for (0..kg) |g| { + for (0..p.n) |nl| { + const ng = n_base + nl; + const sc = loadScale(p.scales_dtype, p.scales, g * p.n + nl); + const zp = unpackNibble(p.qzeros[g * pn8 + nl / 8], nl % 8); + const sb = losslessMeta(sc, zp); + switch (layout) { + .m5_tile => out_sb[g * n_total + ng] = sb, + .m3_row => out_sb[ng * kg + g] = sb, + } + } + for (0..pn8) |c8| { + for (0..16) |w16| { + const k0 = g * group_size + w16 * 8; + var row_words: [8]u32 = undefined; + for (0..8) |j| row_words[j] = p.qweight[(k0 + j) * pn8 + c8]; + for (0..8) |c| { + var packed_k: u32 = 0; + inline for (0..8) |j| { + packed_k |= @as(u32, unpackNibble(row_words[j], c)) << @intCast(4 * j); + } + const ng = n_base + c8 * 8 + c; + switch (layout) { + .m5_tile => { + const tile = ng / 32; + const col = ng % 32; + out_w[((tile * kg + g) * 32 + col) * 16 + w16] = packed_k; + }, + .m3_row => out_w[ng * kw_row + g * 16 + w16] = packed_k, + } + } + } + } + } + n_base += p.n; + } +} + +pub const PackedBundle = struct { + n: usize, + k: usize, + layout: Layout, + w: []u32, + sb: []Float2, + input_scale: ?[]f32, + + pub fn deinit(b: *PackedBundle, a: std.mem.Allocator) void { + a.free(b.w); + a.free(b.sb); + if (b.input_scale) |is| a.free(is); + b.* = undefined; + } +}; + +/// Packs parts into 1 stacked bundle when input_scale matches across all parts, else per-part bundles (#1744). +pub fn packBundles(a: std.mem.Allocator, parts: []const Part, layout: Layout) ![]PackedBundle { + if (try canStack(parts)) { + const k = parts[0].k; + var n_total: usize = 0; + for (parts) |p| n_total += p.n; + const w = try a.alloc(u32, weightWords(n_total, k, layout)); + errdefer a.free(w); + const sb = try a.alloc(Float2, metaCount(n_total, k)); + errdefer a.free(sb); + try packParts(parts, layout, w, sb); + const is = if (parts[0].input_scale) |s| try a.dupe(f32, s) else null; + errdefer if (is) |s| a.free(s); + const out = try a.alloc(PackedBundle, 1); + out[0] = .{ .n = n_total, .k = k, .layout = layout, .w = w, .sb = sb, .input_scale = is }; + return out; + } + const out = try a.alloc(PackedBundle, parts.len); + var built: usize = 0; + errdefer { + for (out[0..built]) |*b| b.deinit(a); + a.free(out); + } + for (parts) |p| { + const w = try a.alloc(u32, weightWords(p.n, p.k, layout)); + errdefer a.free(w); + const sb = try a.alloc(Float2, metaCount(p.n, p.k)); + errdefer a.free(sb); + try packParts(&.{p}, layout, w, sb); + const is = if (p.input_scale) |s| try a.dupe(f32, s) else null; + errdefer if (is) |s| a.free(s); + out[built] = .{ .n = p.n, .k = p.k, .layout = layout, .w = w, .sb = sb, .input_scale = is }; + built += 1; + } + return out; +} + +/// Float64 reference dequantization [N_total, K] directly from raw AutoAWQ tensors. +pub fn dequantWeightsF64(parts: []const Part, out: []f64) !void { + if (parts.len == 0) return error.EmptyAwqParts; + const k = parts[0].k; + var n_total: usize = 0; + for (parts) |p| { + try validatePart(p); + if (p.k != k) return error.MismatchedAwqK; + n_total += p.n; + } + if (out.len != n_total * k) return error.InvalidAwqStorage; + var n_base: usize = 0; + for (parts) |p| { + const pn8 = p.n / 8; + for (0..p.n) |nl| { + const ng = n_base + nl; + for (0..k) |ki| { + const g = ki / group_size; + const q = unpackNibble(p.qweight[ki * pn8 + nl / 8], nl % 8); + const z = unpackNibble(p.qzeros[g * pn8 + nl / 8], nl % 8); + const sc = loadScale(p.scales_dtype, p.scales, g * p.n + nl); + out[ng * k + ki] = (@as(f64, @floatFromInt(q)) - @as(f64, @floatFromInt(z))) * @as(f64, sc); + } + } + n_base += p.n; + } +} + +/// Float64 dequantization [N, K] from repacked M5 or M3 layout via stored f32 scale and bias. +pub fn dequantPackedF64(n: usize, k: usize, layout: Layout, w: []const u32, sb: []const Float2, out: []f64) void { + const kg = k / group_size; + const kw_row = k / 8; + for (0..n) |ni| { + for (0..k) |ki| { + const g = ki / group_size; + const w16 = (ki % group_size) / 8; + const nib: u5 = @intCast(4 * (ki % 8)); + const word = switch (layout) { + .m5_tile => w[((ni / 32 * kg + g) * 32 + (ni % 32)) * 16 + w16], + .m3_row => w[ni * kw_row + g * 16 + w16], + }; + const q: u4 = @truncate(word >> nib); + const meta = switch (layout) { + .m5_tile => sb[g * n + ni], + .m3_row => sb[ni * kg + g], + }; + out[ni * k + ki] = @as(f64, @floatFromInt(q)) * @as(f64, meta.scale) + @as(f64, meta.bias); + } + } +} + +fn fillSyntheticAwq( + a: std.mem.Allocator, + n: usize, + k: usize, + dtype: ScaleDType, + seed: u64, + input_scale: ?[]const f32, +) !struct { p: Part, qw: []u32, qz: []u32, sc: []u8, ref: []f64 } { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const kg = k / group_size; + const n8 = n / 8; + const qw = try a.alloc(u32, k * n8); + const qz = try a.alloc(u32, kg * n8); + const sc = try a.alloc(u8, kg * n * dtype.byteSize()); + const ref = try a.alloc(f64, n * k); + const q_plain = try a.alloc(u4, k * n); + defer a.free(q_plain); + const z_plain = try a.alloc(u4, kg * n); + defer a.free(z_plain); + + for (0..kg) |g| { + for (0..n) |ni| { + z_plain[g * n + ni] = @intCast(rng.uintLessThan(u32, 16)); + const raw_s: f32 = (rng.float(f32) * 0.05 + 0.002) * (if (rng.boolean()) @as(f32, 1.0) else -1.0); + switch (dtype) { + .f16 => { + const h: f16 = @floatCast(raw_s); + std.mem.writeInt(u16, sc[2 * (g * n + ni) ..][0..2], @bitCast(h), .little); + }, + .bf16 => { + const u: u32 = @bitCast(raw_s); + const b: u16 = @truncate((u +% 0x7fff +% ((u >> 16) & 1)) >> 16); + std.mem.writeInt(u16, sc[2 * (g * n + ni) ..][0..2], b, .little); + }, + .f32 => std.mem.writeInt(u32, sc[4 * (g * n + ni) ..][0..4], @bitCast(raw_s), .little), + } + } + for (0..n8) |c8| { + var cols: [8]u4 = undefined; + for (0..8) |c| cols[c] = z_plain[g * n + c8 * 8 + c]; + qz[g * n8 + c8] = packAwqWord(cols); + } + } + for (0..k) |ki| { + for (0..n8) |c8| { + var cols: [8]u4 = undefined; + for (0..8) |c| { + const q: u4 = @intCast(rng.uintLessThan(u32, 16)); + q_plain[ki * n + c8 * 8 + c] = q; + cols[c] = q; + } + qw[ki * n8 + c8] = packAwqWord(cols); + } + } + for (0..n) |ni| { + for (0..k) |ki| { + const g = ki / group_size; + const sf = loadScale(dtype, sc, g * n + ni); + const q = q_plain[ki * n + ni]; + const z = z_plain[g * n + ni]; + ref[ni * k + ki] = (@as(f64, @floatFromInt(q)) - @as(f64, @floatFromInt(z))) * @as(f64, sf); + } + } + return .{ + .p = .{ + .n = n, + .k = k, + .qweight = qw, + .qzeros = qz, + .scales = sc, + .scales_dtype = dtype, + .input_scale = input_scale, + }, + .qw = qw, + .qz = qz, + .sc = sc, + .ref = ref, + }; +} + +test "test_awq: bit-exact unpack and repack for [0,2,4,6,1,3,5,7] with F16 and BF16 scales" { + const a = std.testing.allocator; + // Verify exact nibble shift inverse on explicit [0,2,4,6,1,3,5,7] packed word. + const cols = [8]u4{ 1, 2, 3, 4, 5, 6, 7, 8 }; + const word = packAwqWord(cols); + try std.testing.expectEqual(@as(u32, 0x8642_7531), word); + for (cols, 0..) |want, c| try std.testing.expectEqual(want, unpackNibble(word, c)); + + for ([_]ScaleDType{ .f16, .bf16 }) |dt| { + for ([_]usize{ 40, 64 }) |n| { + const k: usize = 256; + const syn = try fillSyntheticAwq(a, n, k, dt, 0xA11CE + n + @backingInt(dt), null); + defer { + a.free(syn.qw); + a.free(syn.qz); + a.free(syn.sc); + a.free(syn.ref); + } + const ref_parts = try a.alloc(f64, n * k); + defer a.free(ref_parts); + try dequantWeightsF64(&.{syn.p}, ref_parts); + try std.testing.expectEqualSlices(f64, syn.ref, ref_parts); + + for ([_]Layout{ .m5_tile, .m3_row }) |layout| { + const w = try a.alloc(u32, weightWords(n, k, layout)); + defer a.free(w); + const sb = try a.alloc(Float2, metaCount(n, k)); + defer a.free(sb); + try packParts(&.{syn.p}, layout, w, sb); + const got = try a.alloc(f64, n * k); + defer a.free(got); + dequantPackedF64(n, k, layout, w, sb, got); + // Every weight (q * s + (-z * s)) matches (q - z) * s within 0 ULP of exact f32 metadata. + for (got, syn.ref) |gv, wv| try std.testing.expectEqual(wv, gv); + } + } + } +} + +test "test_awq: stacking matching input_scale vs per-part split when input_scale differs" { + const a = std.testing.allocator; + const k: usize = 128; + const is_a = try a.alloc(f32, k); + defer a.free(is_a); + const is_b = try a.alloc(f32, k); + defer a.free(is_b); + for (is_a, is_b, 0..) |*pa, *pb, i| { + pa.* = 1.0 + @as(f32, @floatFromInt(i % 7)) * 0.125; + pb.* = pa.* + 0.5; + } + const p0 = try fillSyntheticAwq(a, 16, k, .f16, 101, is_a); + defer { + a.free(p0.qw); + a.free(p0.qz); + a.free(p0.sc); + a.free(p0.ref); + } + const p1_match = try fillSyntheticAwq(a, 24, k, .f16, 202, is_a); + defer { + a.free(p1_match.qw); + a.free(p1_match.qz); + a.free(p1_match.sc); + a.free(p1_match.ref); + } + const p1_diff = try fillSyntheticAwq(a, 24, k, .bf16, 303, is_b); + defer { + a.free(p1_diff.qw); + a.free(p1_diff.qz); + a.free(p1_diff.sc); + a.free(p1_diff.ref); + } + + const stacked = try packBundles(a, &.{ p0.p, p1_match.p }, .m5_tile); + defer { + for (stacked) |*b| b.deinit(a); + a.free(stacked); + } + try std.testing.expectEqual(@as(usize, 1), stacked.len); + try std.testing.expectEqual(@as(usize, 40), stacked[0].n); + + const ref_stack = try a.alloc(f64, 40 * k); + defer a.free(ref_stack); + try dequantWeightsF64(&.{ p0.p, p1_match.p }, ref_stack); + const got_stack = try a.alloc(f64, 40 * k); + defer a.free(got_stack); + dequantPackedF64(40, k, .m5_tile, stacked[0].w, stacked[0].sb, got_stack); + try std.testing.expectEqualSlices(f64, ref_stack, got_stack); + + const split = try packBundles(a, &.{ p0.p, p1_diff.p }, .m3_row); + defer { + for (split) |*b| b.deinit(a); + a.free(split); + } + try std.testing.expectEqual(@as(usize, 2), split.len); + try std.testing.expectEqual(@as(usize, 16), split[0].n); + try std.testing.expectEqual(@as(usize, 24), split[1].n); +} + +test "test_awq: quantization_config parsing and modules_to_not_convert matching" { + const a = std.testing.allocator; + const text = + \\{"quantization_config": {"quant_method": "awq", "bits": 4, "group_size": 128, + \\ "zero_point": true, "version": "gemm", "modules_to_not_convert": ["lm_head", "visual"]}} + ; + const parsed = try std.json.parseFromSlice(std.json.Value, a, text, .{}); + defer parsed.deinit(); + var cfg = (try parseConfig(a, parsed.value.object)).?; + defer cfg.deinit(a); + try std.testing.expectEqual(@as(u8, 4), cfg.bits); + try std.testing.expectEqual(@as(usize, 128), cfg.group_size); + try std.testing.expect(!cfg.isQuantized("lm_head")); + try std.testing.expect(!cfg.isQuantized("model.visual.blocks.0.attn.qkv")); + try std.testing.expect(cfg.isQuantized("model.layers.0.self_attn.q_proj")); + const legacy = try std.json.parseFromSlice(std.json.Value, a, "{\"loop_awq_config\":{\"quant_method\":\"loop_awq\"}}", .{}); + defer legacy.deinit(); + try std.testing.expect((try parseConfig(a, legacy.value.object)) == null); +} diff --git a/zig/src/families/sensenova_loop/config.zig b/zig/src/families/sensenova_loop/config.zig new file mode 100644 index 00000000000..b4ace145967 --- /dev/null +++ b/zig/src/families/sensenova_loop/config.zig @@ -0,0 +1,563 @@ +//! SenseNova-Loop config parsing, validation, 56-step execution plan and skipped-tensor policy. +const std = @import("std"); + +pub const max_layers: usize = 128; +pub const max_steps: usize = 128; +pub const max_eos: usize = 8; + +pub const MhcRole = enum { none, enter, inner, exit, both }; +pub const LoopSettings = struct { start: u8, end: u8, eval_count: u32 }; +pub const MhcConfig = struct { start: u8, end: u8, streams: u8, iterations: u32, fixed_identity: bool, pre_scale: f64 }; +pub const ExecutionStep = struct { exec: u8, phys: u8, state: u8, is_linear: bool, mhc_role: MhcRole }; + +pub const RopeConfig = struct { + rope_theta: f64, + partial_rotary_factor: f64, + rotary_dim: u32, + yarn_factor: f64, + original_max_position_embeddings: u32, + ceiling: u32, + mrope_interleaved: bool, + mrope_section: [3]u32, +}; + +pub const ExecutionPlan = struct { + steps: []const ExecutionStep, + linear_states: u8, + full_states: u8, + loops: u32, + + pub fn deinit(self: ExecutionPlan, gpa: std.mem.Allocator) void { + gpa.free(self.steps); + } +}; + +pub const Error = error{ + InvalidConfig, + UnsupportedModel, + MissingField, + BadLoopSettings, + BadMhcConfig, + MhcCrossesLoopBoundary, + BadLayerTypes, + MissingFullAttention, + BadRopeConfig, + MaxPositionExceedsCeiling, + BadTiedHead, + BadEos, + MissingEos, + TooManyEos, + InvalidLoopCount, + TooManyExecutionSteps, +} || @import("qwen35_layers").Error || std.mem.Allocator.Error || std.json.ParseError(std.json.Scanner); + +pub const Config = struct { + hidden_size: u32, + intermediate_size: u32, + num_hidden_layers: u8, + num_attention_heads: u32, + num_key_value_heads: u32, + head_dim: u32, + linear_num_key_heads: u32, + linear_num_value_heads: u32, + linear_key_head_dim: u32, + linear_value_head_dim: u32, + linear_conv_kernel_dim: u32, + vocab_size: u32, + rms_norm_eps: f32, + max_position_embeddings: u32, + tie_word_embeddings: bool, + mtp_num_hidden_layers: u32, + loop: LoopSettings, + mhc: ?MhcConfig, + rope: RopeConfig, + is_linear: [max_layers]bool, + eos_buf: [max_eos]u32, + eos_len: u8, + + pub fn eos(self: *const Config) []const u32 { + return self.eos_buf[0..self.eos_len]; + } + + pub fn isLinear(self: *const Config, phys: usize) bool { + return self.is_linear[phys]; + } + + pub fn mhcRole(self: *const Config, phys: u8) MhcRole { + const m = self.mhc orelse return .none; + if (phys < m.start or phys >= m.end) return .none; + if (m.end - m.start == 1) return .both; + if (phys == m.start) return .enter; + if (phys == m.end - 1) return .exit; + return .inner; + } + + /// Fill `buf` with the execution plan for `loops_override` (defaults to `loop.eval_count`). + pub fn fillPlan(self: *const Config, buf: *[max_steps]ExecutionStep, loops_override: ?u32) Error![]const ExecutionStep { + const loops = loops_override orelse self.loop.eval_count; + if (loops == 0) return error.InvalidLoopCount; + const body_len: usize = self.loop.end - self.loop.start; + const loop_steps = std.math.mul(usize, body_len, loops) catch return error.TooManyExecutionSteps; + const total = @as(usize, self.loop.start) + loop_steps + (self.num_hidden_layers - self.loop.end); + if (total > max_steps) return error.TooManyExecutionSteps; + + var exec: usize = 0; + var lin: u8 = 0; + var full: u8 = 0; + for (0..self.loop.start) |p| appendStep(self, buf, &exec, &lin, &full, @intCast(p)); + for (0..loops) |_| { + for (self.loop.start..self.loop.end) |p| appendStep(self, buf, &exec, &lin, &full, @intCast(p)); + } + for (self.loop.end..self.num_hidden_layers) |p| appendStep(self, buf, &exec, &lin, &full, @intCast(p)); + return buf[0..exec]; + } + + pub fn executionPlan(self: *const Config, gpa: std.mem.Allocator, loops_override: ?u32) Error!ExecutionPlan { + var tmp: [max_steps]ExecutionStep = undefined; + const view = try self.fillPlan(&tmp, loops_override); + const steps = try gpa.dupe(ExecutionStep, view); + var lin: u8 = 0; + var full: u8 = 0; + for (steps) |s| { + if (s.is_linear) lin += 1 else full += 1; + } + return .{ .steps = steps, .linear_states = lin, .full_states = full, .loops = loops_override orelse self.loop.eval_count }; + } + + pub fn parse(gpa: std.mem.Allocator, config_bytes: []const u8) Error!Config { + return parseWithGeneration(gpa, config_bytes, null); + } + + pub fn parseWithGeneration(gpa: std.mem.Allocator, config_bytes: []const u8, gen_bytes: ?[]const u8) Error!Config { + const doc = try std.json.parseFromSlice(std.json.Value, gpa, config_bytes, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.InvalidConfig; + const root = doc.value.object; + const mt = root.get("model_type") orelse return error.UnsupportedModel; + if (mt != .string or !std.mem.eql(u8, mt.string, "sensenova_loop")) return error.UnsupportedModel; + + const tower = try textTower(root); + if (tower.get("model_type")) |tmt| { + if (tmt != .string) return error.UnsupportedModel; + const ok = std.mem.eql(u8, tmt.string, "qwen3_5_text") or + std.mem.eql(u8, tmt.string, "sensenova_loop_text") or + std.mem.eql(u8, tmt.string, "sensenova_loop"); + if (!ok) return error.UnsupportedModel; + } + + var gen_doc: ?std.json.Parsed(std.json.Value) = null; + defer if (gen_doc) |*g| g.deinit(); + var gen_obj: ?std.json.ObjectMap = null; + if (gen_bytes) |gb| { + gen_doc = try std.json.parseFromSlice(std.json.Value, gpa, gb, .{}); + if (gen_doc.?.value != .object) return error.InvalidConfig; + gen_obj = gen_doc.?.value.object; + } + return parseObjects(root, tower, gen_obj); + } + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const cfg_path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(cfg_path); + const cfg_bytes = try std.Io.Dir.cwd().readFileAlloc(io, cfg_path, gpa, .limited(1 << 22)); + defer gpa.free(cfg_bytes); + + const gen_path = try std.fs.path.join(gpa, &.{ dir, "generation_config.json" }); + defer gpa.free(gen_path); + const gen_bytes = std.Io.Dir.cwd().readFileAlloc(io, gen_path, gpa, .limited(1 << 20)) catch |err| switch (err) { + error.FileNotFound => null, + else => return err, + }; + defer if (gen_bytes) |gb| gpa.free(gb); + return parseWithGeneration(gpa, cfg_bytes, gen_bytes); + } +}; + +/// Checkpoint tensors omitted by TensorFold's loader (unused gating logits). +pub fn isSkippedTensor(name: []const u8) bool { + return std.mem.eql(u8, name, "model.language_model.loop_gate.logits") or + std.mem.eql(u8, name, "language_model.loop_gate.logits") or + std.mem.eql(u8, name, "loop_gate.logits"); +} + +fn appendStep(cfg: *const Config, buf: *[max_steps]ExecutionStep, exec: *usize, lin: *u8, full: *u8, phys: u8) void { + const is_lin = cfg.is_linear[phys]; + const state = if (is_lin) lin.* else full.*; + if (is_lin) lin.* += 1 else full.* += 1; + buf[exec.*] = .{ .exec = @intCast(exec.*), .phys = phys, .state = state, .is_linear = is_lin, .mhc_role = cfg.mhcRole(phys) }; + exec.* += 1; +} + +fn textTower(root: std.json.ObjectMap) Error!std.json.ObjectMap { + const v = root.get("text_config") orelse return root; + return switch (v) { + .null => root, + .object => |o| o, + else => error.InvalidConfig, + }; +} + +fn parseObjects(root: std.json.ObjectMap, tower: std.json.ObjectMap, gen: ?std.json.ObjectMap) Error!Config { + const hidden = try reqPosU32(tower, root, "hidden_size"); + const intermediate = try reqPosU32(tower, root, "intermediate_size"); + const n_layers_u = try reqPosU32(tower, root, "num_hidden_layers"); + if (n_layers_u > max_layers) return error.InvalidConfig; + const n_layers: u8 = @intCast(n_layers_u); + const heads = try reqPosU32(tower, root, "num_attention_heads"); + const kv_heads = try reqPosU32(tower, root, "num_key_value_heads"); + if (heads % kv_heads != 0) return error.InvalidConfig; + const head_dim = if (optField(tower, root, "head_dim")) |v| try posU32Val(v) else hidden / heads; + if (head_dim == 0) return error.InvalidConfig; + const lin_k_heads = try reqPosU32(tower, root, "linear_num_key_heads"); + const lin_v_heads = try reqPosU32(tower, root, "linear_num_value_heads"); + if (lin_v_heads % lin_k_heads != 0) return error.InvalidConfig; + const eps_f64 = if (optField(tower, root, "rms_norm_eps")) |v| try finiteNum(v) else 1e-6; + if (eps_f64 <= 0) return error.InvalidConfig; + const max_pos = try reqPosU32(tower, root, "max_position_embeddings"); + + try checkModelFlags(tower); + var is_linear: [max_layers]bool = @splat(false); + try parseLayerTypes(tower, n_layers, &is_linear); + const loop = try parseLoop(root, n_layers); + const mhc = try parseMhc(root, n_layers, loop); + const rope = try parseRope(tower, root, head_dim, max_pos); + + var cfg = Config{ + .hidden_size = hidden, + .intermediate_size = intermediate, + .num_hidden_layers = n_layers, + .num_attention_heads = heads, + .num_key_value_heads = kv_heads, + .head_dim = head_dim, + .linear_num_key_heads = lin_k_heads, + .linear_num_value_heads = lin_v_heads, + .linear_key_head_dim = try reqPosU32(tower, root, "linear_key_head_dim"), + .linear_value_head_dim = try reqPosU32(tower, root, "linear_value_head_dim"), + .linear_conv_kernel_dim = try reqPosU32(tower, root, "linear_conv_kernel_dim"), + .vocab_size = try reqPosU32(tower, root, "vocab_size"), + .rms_norm_eps = @floatCast(eps_f64), + .max_position_embeddings = max_pos, + .tie_word_embeddings = try parseTied(root, tower), + .mtp_num_hidden_layers = if (optField(tower, root, "mtp_num_hidden_layers")) |v| try nonNegU32Val(v) else 0, + .loop = loop, + .mhc = mhc, + .rope = rope, + .is_linear = is_linear, + .eos_buf = @splat(0), + .eos_len = 0, + }; + try collectAllEos(&cfg, root, tower, gen); + return cfg; +} + +fn checkModelFlags(tower: std.json.ObjectMap) Error!void { + if (tower.get("hidden_act")) |v| if (v != .string or !std.mem.eql(u8, v.string, "silu")) return error.InvalidConfig; + if (tower.get("attn_output_gate")) |v| if (v != .bool or !v.bool) return error.InvalidConfig; + if (tower.get("attention_bias")) |v| if (v != .bool or v.bool) return error.InvalidConfig; + if (tower.get("mamba_ssm_dtype")) |v| { + if (v != .string or !std.mem.eql(u8, v.string, "float32")) return error.InvalidConfig; + } +} + +fn parseTied(root: std.json.ObjectMap, tower: std.json.ObjectMap) Error!bool { + const inner = try optBool(tower.get("tie_word_embeddings")); + const outer = try optBool(root.get("tie_word_embeddings")); + if (inner != null and outer != null and inner.? != outer.?) return error.BadTiedHead; + return inner orelse outer orelse false; +} + +fn optBool(v: ?std.json.Value) Error!?bool { + const x = v orelse return null; + return if (x == .bool) x.bool else error.BadTiedHead; +} + +fn parseLayerTypes(tower: std.json.ObjectMap, n_layers: u8, out: *[max_layers]bool) Error!void { + var full: [max_layers]bool = @splat(false); + try @import("qwen35_layers").read(full[0..n_layers], tower); + var has_full = false; + for (0..n_layers) |i| { + out[i] = !full[i]; + if (full[i]) has_full = true; + } + if (!has_full) return error.MissingFullAttention; +} + +fn parseLoop(root: std.json.ObjectMap, n_layers: u8) Error!LoopSettings { + const lv = root.get("loop_settings") orelse return error.BadLoopSettings; + if (lv != .object) return error.BadLoopSettings; + const o = lv.object; + if (o.get("use_gate")) |ug| if (ug != .bool or ug.bool) return error.BadLoopSettings; + const sv = o.get("start") orelse return error.BadLoopSettings; + const ev = o.get("end") orelse return error.BadLoopSettings; + const cv = o.get("eval_count") orelse return error.BadLoopSettings; + const csv = o.get("counts") orelse return error.BadLoopSettings; + if (sv != .integer or ev != .integer or cv != .integer) return error.BadLoopSettings; + if (sv.integer < 0 or ev.integer <= sv.integer or ev.integer > n_layers or cv.integer < 1) { + return error.BadLoopSettings; + } + if (csv != .array or csv.array.items.len != 1) return error.BadLoopSettings; + const c0 = csv.array.items[0]; + if (c0 != .integer or c0.integer != cv.integer) return error.BadLoopSettings; + const eval_count = std.math.cast(u32, cv.integer) orelse return error.BadLoopSettings; + return .{ .start = @intCast(sv.integer), .end = @intCast(ev.integer), .eval_count = eval_count }; +} + +fn parseMhc(root: std.json.ObjectMap, n_layers: u8, loop: LoopSettings) Error!?MhcConfig { + const mv = root.get("mhc") orelse return null; + if (mv == .null) return null; + if (mv != .object) return error.BadMhcConfig; + const o = mv.object; + var it = o.iterator(); + while (it.next()) |e| { + const k = e.key_ptr.*; + const known = std.mem.eql(u8, k, "start") or std.mem.eql(u8, k, "end") or + std.mem.eql(u8, k, "streams") or std.mem.eql(u8, k, "iterations") or + std.mem.eql(u8, k, "fixed_identity") or std.mem.eql(u8, k, "pre_scale"); + if (!known) return error.BadMhcConfig; + } + const sv = o.get("start") orelse return error.BadMhcConfig; + const ev = o.get("end") orelse return error.BadMhcConfig; + const stv = o.get("streams") orelse return error.BadMhcConfig; + const itv = o.get("iterations") orelse return error.BadMhcConfig; + const fiv = o.get("fixed_identity") orelse return error.BadMhcConfig; + if (sv != .integer or ev != .integer or stv != .integer or itv != .integer) return error.BadMhcConfig; + if (fiv != .bool) return error.BadMhcConfig; + if (sv.integer < 0 or ev.integer <= sv.integer or ev.integer > n_layers) return error.BadMhcConfig; + if (stv.integer != 2 and stv.integer != 4) return error.BadMhcConfig; + if (itv.integer < 1) return error.BadMhcConfig; + const pre_scale_f64 = if (o.get("pre_scale")) |pv| finiteNum(pv) catch return error.BadMhcConfig else 1.0; + if (pre_scale_f64 <= 0) return error.BadMhcConfig; + + const ms: u8 = @intCast(sv.integer); + const me: u8 = @intCast(ev.integer); + const valid_phase = (0 <= ms and me <= loop.start) or (loop.start <= ms and me <= loop.end) or + (loop.end <= ms and me <= n_layers); + if (!valid_phase) return error.MhcCrossesLoopBoundary; + return .{ + .start = ms, + .end = me, + .streams = @intCast(stv.integer), + .iterations = std.math.cast(u32, itv.integer) orelse return error.BadMhcConfig, + .fixed_identity = fiv.bool, + .pre_scale = pre_scale_f64, + }; +} + +fn parseRope(tower: std.json.ObjectMap, root: std.json.ObjectMap, head_dim: u32, max_pos: u32) Error!RopeConfig { + const rv = optField(tower, root, "rope_parameters") orelse optField(tower, root, "rope_scaling") orelse + return error.BadRopeConfig; + if (rv != .object) return error.BadRopeConfig; + const rope = rv.object; + const rt = rope.get("rope_type") orelse rope.get("type") orelse return error.BadRopeConfig; + if (rt != .string or !std.mem.eql(u8, rt.string, "yarn")) return error.BadRopeConfig; + + const factor = finiteNum(rope.get("factor") orelse return error.BadRopeConfig) catch return error.BadRopeConfig; + if (factor < 1.0) return error.BadRopeConfig; + const orig = posU32Val(rope.get("original_max_position_embeddings") orelse return error.BadRopeConfig) catch + return error.BadRopeConfig; + const ceil_f = @as(f64, @floatFromInt(orig)) * factor; + if (!std.math.isFinite(ceil_f) or ceil_f > @as(f64, std.math.maxInt(u32))) return error.BadRopeConfig; + const ceiling: u32 = @intFromFloat(@round(ceil_f)); + if (max_pos > ceiling) return error.MaxPositionExceedsCeiling; + + const theta = finiteNum(rope.get("rope_theta") orelse optField(tower, root, "rope_theta") orelse + return error.BadRopeConfig) catch return error.BadRopeConfig; + if (theta <= 0) return error.BadRopeConfig; + const prf = finiteNum(rope.get("partial_rotary_factor") orelse optField(tower, root, "partial_rotary_factor") orelse + return error.BadRopeConfig) catch return error.BadRopeConfig; + if (prf <= 0 or prf > 1.0) return error.BadRopeConfig; + const rotary_dim: u32 = @intFromFloat(@round(@as(f64, @floatFromInt(head_dim)) * prf)); + if (rotary_dim == 0 or rotary_dim > head_dim or rotary_dim % 2 != 0) return error.BadRopeConfig; + + const mi = rope.get("mrope_interleaved") orelse return error.BadRopeConfig; + if (mi != .bool or !mi.bool) return error.BadRopeConfig; + const ms = rope.get("mrope_section") orelse return error.BadRopeConfig; + if (ms != .array or ms.array.items.len != 3) return error.BadRopeConfig; + var sec: [3]u32 = undefined; + var sum: u32 = 0; + for (ms.array.items, &sec) |item, *dst| { + dst.* = nonNegU32Val(item) catch return error.BadRopeConfig; + sum += dst.*; + } + if (sum * 2 != rotary_dim) return error.BadRopeConfig; + return .{ + .rope_theta = theta, + .partial_rotary_factor = prf, + .rotary_dim = rotary_dim, + .yarn_factor = factor, + .original_max_position_embeddings = orig, + .ceiling = ceiling, + .mrope_interleaved = true, + .mrope_section = sec, + }; +} + +fn collectAllEos(cfg: *Config, root: std.json.ObjectMap, tower: std.json.ObjectMap, gen: ?std.json.ObjectMap) Error!void { + const holders = [_]?std.json.Value{ + tower.get("eos_token_id"), + root.get("eos_token_id"), + if (gen) |g| g.get("eos_token_id") else null, + }; + for (holders) |h| if (h) |v| try collectEos(cfg, v); + if (cfg.eos_len == 0) return error.MissingEos; +} + +fn collectEos(cfg: *Config, v: std.json.Value) Error!void { + switch (v) { + .null => {}, + .array => |arr| for (arr.items) |item| try collectEos(cfg, item), + .integer => |i| { + if (i < 0 or i >= cfg.vocab_size) return error.BadEos; + const id: u32 = @intCast(i); + if (std.mem.indexOfScalar(u32, cfg.eos(), id) != null) return; + if (cfg.eos_len == max_eos) return error.TooManyEos; + cfg.eos_buf[cfg.eos_len] = id; + cfg.eos_len += 1; + }, + else => return error.BadEos, + } +} + +fn optField(a: std.json.ObjectMap, b: std.json.ObjectMap, key: []const u8) ?std.json.Value { + return a.get(key) orelse b.get(key); +} + +fn reqPosU32(a: std.json.ObjectMap, b: std.json.ObjectMap, key: []const u8) Error!u32 { + return posU32Val(optField(a, b, key) orelse return error.MissingField); +} + +fn posU32Val(v: std.json.Value) Error!u32 { + if (v != .integer or v.integer <= 0) return error.InvalidConfig; + return std.math.cast(u32, v.integer) orelse error.InvalidConfig; +} + +fn nonNegU32Val(v: std.json.Value) Error!u32 { + if (v != .integer or v.integer < 0) return error.InvalidConfig; + return std.math.cast(u32, v.integer) orelse error.InvalidConfig; +} + +fn finiteNum(v: std.json.Value) Error!f64 { + const f: f64 = switch (v) { + .integer => |i| @floatFromInt(i), + .float => |x| x, + .number_string => |s| std.fmt.parseFloat(f64, s) catch return error.InvalidConfig, + else => return error.InvalidConfig, + }; + if (!std.math.isFinite(f)) return error.InvalidConfig; + return f; +} + +const sample_layers = + "[\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"," ++ + "\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"]"; + +const sample_cfg = + "{\"model_type\":\"sensenova_loop\",\"eos_token_id\":248046,\"tie_word_embeddings\":false," ++ + "\"loop_settings\":{\"start\":4,\"end\":28,\"eval_count\":2,\"counts\":[2]}," ++ + "\"mhc\":{\"start\":4,\"end\":28,\"streams\":2,\"iterations\":20,\"fixed_identity\":false,\"pre_scale\":1.0}," ++ + "\"text_config\":{\"model_type\":\"qwen3_5_text\",\"hidden_size\":4096,\"intermediate_size\":12288," ++ + "\"num_hidden_layers\":32,\"num_attention_heads\":16,\"num_key_value_heads\":4,\"head_dim\":256," ++ + "\"linear_num_key_heads\":16,\"linear_num_value_heads\":32,\"linear_key_head_dim\":128," ++ + "\"linear_value_head_dim\":128,\"linear_conv_kernel_dim\":4,\"vocab_size\":248320,\"rms_norm_eps\":1e-6," ++ + "\"max_position_embeddings\":524288,\"eos_token_id\":248044,\"mtp_num_hidden_layers\":0," ++ + "\"hidden_act\":\"silu\",\"attn_output_gate\":true,\"attention_bias\":false,\"mamba_ssm_dtype\":\"float32\"," ++ + "\"layer_types\":" ++ sample_layers ++ "," ++ + "\"rope_parameters\":{\"rope_type\":\"yarn\",\"factor\":2.0,\"original_max_position_embeddings\":262144," ++ + "\"rope_theta\":10000000,\"partial_rotary_factor\":0.25,\"mrope_interleaved\":true,\"mrope_section\":[11,11,10]}}}"; + +test "sensenova_loop config: parses 9B release config, yarn ceiling and 56-step plan" { + const a = std.testing.allocator; + const cfg = try Config.parseWithGeneration(a, sample_cfg, "{\"eos_token_id\":[248044,248046]}"); + try std.testing.expectEqual(@as(u32, 4096), cfg.hidden_size); + try std.testing.expectEqual(@as(u8, 32), cfg.num_hidden_layers); + try std.testing.expectEqual(@as(u32, 524288), cfg.rope.ceiling); + try std.testing.expectEqual(@as(u32, 64), cfg.rope.rotary_dim); + try std.testing.expectEqualSlices(u32, &.{ 248044, 248046 }, cfg.eos()); + try std.testing.expectEqual(@as(u32, 0), cfg.mtp_num_hidden_layers); + try std.testing.expect(!cfg.tie_word_embeddings); + + const plan = try cfg.executionPlan(a, null); + defer plan.deinit(a); + try std.testing.expectEqual(@as(usize, 56), plan.steps.len); + try std.testing.expectEqual(@as(u8, 42), plan.linear_states); + try std.testing.expectEqual(@as(u8, 14), plan.full_states); + try std.testing.expectEqual(MhcRole.none, plan.steps[3].mhc_role); + try std.testing.expectEqual(MhcRole.enter, plan.steps[4].mhc_role); + try std.testing.expectEqual(@as(u8, 4), plan.steps[4].phys); + try std.testing.expectEqual(MhcRole.inner, plan.steps[5].mhc_role); + try std.testing.expectEqual(MhcRole.exit, plan.steps[27].mhc_role); + try std.testing.expectEqual(MhcRole.enter, plan.steps[28].mhc_role); + try std.testing.expectEqual(@as(u8, 4), plan.steps[28].phys); + try std.testing.expectEqual(MhcRole.exit, plan.steps[51].mhc_role); + try std.testing.expectEqual(@as(u8, 27), plan.steps[51].phys); + try std.testing.expectEqual(MhcRole.none, plan.steps[52].mhc_role); + try std.testing.expect(!plan.steps[55].is_linear); + try std.testing.expectEqual(@as(u8, 13), plan.steps[55].state); +} + +test "sensenova_loop config: --loops override, boundary refusals, top-level fallback and skipped tensors" { + const a = std.testing.allocator; + const cfg = try Config.parse(a, sample_cfg); + const p1 = try cfg.executionPlan(a, 1); + defer p1.deinit(a); + try std.testing.expectEqual(@as(usize, 32), p1.steps.len); + const p4 = try cfg.executionPlan(a, 4); + defer p4.deinit(a); + try std.testing.expectEqual(@as(usize, 104), p4.steps.len); + try std.testing.expectError(error.InvalidLoopCount, cfg.executionPlan(a, 0)); + try std.testing.expectError(error.TooManyExecutionSteps, cfg.executionPlan(a, 6)); + + const cross = try std.mem.replaceOwned(u8, a, sample_cfg, "\"mhc\":{\"start\":4,\"end\":28", "\"mhc\":{\"start\":3,\"end\":28"); + defer a.free(cross); + try std.testing.expectError(error.MhcCrossesLoopBoundary, Config.parse(a, cross)); + + const gate_on = try std.mem.replaceOwned(u8, a, sample_cfg, "\"counts\":[2]", "\"counts\":[2],\"use_gate\":true"); + defer a.free(gate_on); + try std.testing.expectError(error.BadLoopSettings, Config.parse(a, gate_on)); + + const bad_ceil = try std.mem.replaceOwned(u8, a, sample_cfg, "524288", "524289"); + defer a.free(bad_ceil); + try std.testing.expectError(error.MaxPositionExceedsCeiling, Config.parse(a, bad_ceil)); + + const flat = + \\{"model_type":"sensenova_loop","hidden_size":1024,"intermediate_size":3072,"num_hidden_layers":8, + \\ "num_attention_heads":8,"num_key_value_heads":2,"head_dim":128,"linear_num_key_heads":8, + \\ "linear_num_value_heads":16,"linear_key_head_dim":64,"linear_value_head_dim":64,"linear_conv_kernel_dim":4, + \\ "vocab_size":32000,"max_position_embeddings":8192,"eos_token_id":[1,2],"mtp_num_hidden_layers":1, + \\ "loop_settings":{"start":2,"end":6,"eval_count":2,"counts":[2],"use_gate":false}, + \\ "mhc":{"start":2,"end":6,"streams":2,"iterations":20,"fixed_identity":false,"pre_scale":0.5}, + \\ "rope_parameters":{"rope_type":"yarn","factor":2.0,"original_max_position_embeddings":4096, + \\ "rope_theta":10000000,"partial_rotary_factor":0.25,"mrope_interleaved":true,"mrope_section":[5,5,6]}} + ; + const fc = try Config.parse(a, flat); + try std.testing.expectEqual(@as(u32, 1), fc.mtp_num_hidden_layers); + try std.testing.expectEqual(@as(f64, 0.5), fc.mhc.?.pre_scale); + try std.testing.expect(isSkippedTensor("model.language_model.loop_gate.logits")); + try std.testing.expect(isSkippedTensor("loop_gate.logits")); + try std.testing.expect(!isSkippedTensor("model.language_model.layers.4.mhc_attn.weight")); +} + +test "sensenova_loop config: one-layer mHC role is .both and fixed_identity/4-stream parse" { + const a = std.testing.allocator; + const one = try std.mem.replaceOwned(u8, a, sample_cfg, "\"mhc\":{\"start\":4,\"end\":28", "\"mhc\":{\"start\":4,\"end\":5"); + defer a.free(one); + const c1 = try Config.parse(a, one); + try std.testing.expectEqual(MhcRole.both, c1.mhcRole(4)); + const p1 = try c1.executionPlan(a, null); + defer p1.deinit(a); + try std.testing.expectEqual(MhcRole.both, p1.steps[4].mhc_role); + try std.testing.expectEqual(MhcRole.none, p1.steps[5].mhc_role); + try std.testing.expectEqual(MhcRole.both, p1.steps[28].mhc_role); + + const fi = try std.mem.replaceOwned(u8, a, sample_cfg, "\"streams\":2,\"iterations\":20,\"fixed_identity\":false", "\"streams\":4,\"iterations\":1001,\"fixed_identity\":true"); + defer a.free(fi); + const c2 = try Config.parse(a, fi); + try std.testing.expect(c2.mhc.?.fixed_identity); + try std.testing.expectEqual(@as(u8, 4), c2.mhc.?.streams); +} diff --git a/zig/src/families/sensenova_loop/linear_bench.zig b/zig/src/families/sensenova_loop/linear_bench.zig new file mode 100644 index 00000000000..ef82ba34f19 --- /dev/null +++ b/zig/src/families/sensenova_loop/linear_bench.zig @@ -0,0 +1,130 @@ +//! Standalone microbenchmark comparing BF16 and AWQ Metal linear kernels across SenseNova shapes. +const std = @import("std"); +const mtl = @import("metal"); +const awq = @import("awq.zig"); +const linear = @import("linear_gpu.zig"); + +const LinearGpu = linear.LinearGpu; +const AwqMatrix = linear.AwqMatrix; +const Bf16Matrix = linear.Bf16Matrix; + +const BenchJob = struct { + x: mtl.Buffer, + y: mtl.Buffer, + bf: []const mtl.Buffer, + aw: []const mtl.Buffer, + sb: []const mtl.Buffer, + n: u32, + k: u32, +}; + +fn benchRun(gpu: *LinearGpu, queue: mtl.Queue, j: BenchJob, m: u32, sk: ?u32, is_awq: bool, prompt: bool) !void { + const reps: usize = 8; + const m5 = gpu.tensor_units; + const layout: awq.Layout = if (m5) .m5_tile else .m3_row; + const awq_bytes = awq.weightWords(j.n, j.k, layout) * 4 + awq.metaCount(j.n, j.k) * 8; + const w_bytes = if (is_awq) awq_bytes else @as(usize, j.n) * j.k * 2; + var best_s: f64 = 1e9; + for (0..3) |_| { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const enc = cb.compute(.serial); + for (0..reps) |r| { + const c = r % j.bf.len; + if (is_awq) { + const mat = AwqMatrix{ .w = j.aw[c], .sb = j.sb[c], .n = j.n, .k = j.k, .m5_layout = m5 }; + try gpu.encodeAwq(enc, mat, .{ .buf = j.x }, null, .{ .buf = j.y }, m, j.n, prompt, sk); + } else { + const mat = Bf16Matrix{ .buf = j.bf[c], .n = j.n, .k = j.k }; + try gpu.encodeBf16(enc, mat, .{ .buf = j.x }, .{ .buf = j.y }, m, j.n, prompt, sk); + } + } + enc.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("bench gpu err: {s}\n", .{why}); + return error.GpuFailed; + } + const per = cb.gpuSeconds() / @as(f64, @floatFromInt(reps)); + if (per > 0 and per < best_s) best_s = per; + } + const bytes: f64 = @floatFromInt(w_bytes + @as(usize, m) * (j.k + j.n) * 2); + const flops = 2.0 * @as(f64, @floatFromInt(m)) * @as(f64, @floatFromInt(j.n)) * @as(f64, @floatFromInt(j.k)); + const tag = if (is_awq) "AWQ " else "BF16"; + std.debug.print( + " {s} ({d},{d}) M={d} {s}={d}: {d:.3} ms, {d:.1} GB/s, {d:.2} TF\n", + .{ tag, j.n, j.k, m, if (sk != null) "SK" else "pf", sk orelse 0, best_s * 1e3, bytes / best_s / 1e9, flops / best_s / 1e12 }, + ); +} + +fn allocCopies(device: mtl.Device, a: std.mem.Allocator, cnt: usize, bytes: usize, fill: u8) ![]mtl.Buffer { + const list = try a.alloc(mtl.Buffer, cnt); + var done: usize = 0; + errdefer { + for (list[0..done]) |b| b.deinit(); + a.free(list); + } + for (0..cnt) |i| { + list[i] = try device.buffer(bytes, mtl.ResourceOptions.shared); + @memset(list[i].contents()[0..bytes], fill); + done += 1; + } + return list; +} + +fn freeCopies(a: std.mem.Allocator, list: []const mtl.Buffer) void { + for (list) |b| b.deinit(); + a.free(list); +} + +/// Sweeps SK in {1,2,4,8} for decode (M=1,2,4,8,16,32) and prefill (M=128,512) on all SenseNova shapes. +pub fn bench(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !void { + var gpu = LinearGpu.init(a, device); + defer gpu.deinit(); + try gpu.reserve(512, true); + const shapes = [_][2]u32{ + .{ 248320, 4096 }, + .{ 24576, 4096 }, + .{ 4096, 12288 }, + .{ 12288, 4096 }, + .{ 10240, 4096 }, + .{ 8192, 4096 }, + .{ 4096, 4096 }, + .{ 2048, 4096 }, + }; + const copies: usize = 3; + const opts = mtl.ResourceOptions.shared; + std.debug.print("SenseNova microbench on {s} (tensor_units={}):\n", .{ device.name(), gpu.tensor_units }); + for (shapes) |sh| { + const n = sh[0]; + const k = sh[1]; + const layout: awq.Layout = if (gpu.tensor_units) .m5_tile else .m3_row; + const x_buf = try device.buffer(@as(usize, 512) * k * 2, opts); + const y_buf = try device.buffer(@as(usize, 512) * n * 2, opts); + defer x_buf.deinit(); + defer y_buf.deinit(); + @memset(x_buf.contents()[0 .. @as(usize, 512) * k * 2], 0x3f); + + const bf_copies = try allocCopies(device, a, copies, @as(usize, n) * k * 2, 0x3c); + defer freeCopies(a, bf_copies); + const awq_w = try allocCopies(device, a, copies, awq.weightWords(n, k, layout) * 4, 0x55); + defer freeCopies(a, awq_w); + const awq_sb = try allocCopies(device, a, copies, awq.metaCount(n, k) * 8, 0x3f); + defer freeCopies(a, awq_sb); + const job = BenchJob{ .x = x_buf, .y = y_buf, .bf = bf_copies, .aw = awq_w, .sb = awq_sb, .n = n, .k = k }; + for ([_]u32{ 1, 2, 4, 8, 16, 32 }) |m| { + for ([_]u32{ 1, 2, 4, 8 }) |sk| { + for ([_]bool{ false, true }) |is_awq| { + try benchRun(&gpu, queue, job, m, sk, is_awq, false); + } + } + } + for ([_]u32{ 1, 4, 8, 32, 128, 512 }) |m| { + for ([_]bool{ false, true }) |is_awq| { + try benchRun(&gpu, queue, job, m, null, is_awq, m > 32); + } + } + } +} diff --git a/zig/src/families/sensenova_loop/linear_gpu.zig b/zig/src/families/sensenova_loop/linear_gpu.zig new file mode 100644 index 00000000000..17c59a19976 --- /dev/null +++ b/zig/src/families/sensenova_loop/linear_gpu.zig @@ -0,0 +1,526 @@ +//! SenseNova-Loop BF16 and AWQ W4A16 g128 Metal linear wrapper, pipeline cache, and sweep benchmark. +const std = @import("std"); +const mtl = @import("metal"); +const ks = @import("kernel_sources"); +const frags = @import("core").frags; +const awq = @import("awq.zig"); + +const quant = @import("linear_quant.zig"); + +pub const Ref = struct { buf: mtl.Buffer, off: usize = 0 }; +pub const Sums = struct { ref: Ref, stride: u32 }; +pub const OutSplits = struct { + split1: u32 = 0, + y1: ?Ref = null, + ldy1: u32 = 0, + split2: u32 = 0, + y2: ?Ref = null, + ldy2: u32 = 0, +}; + +pub const Bf16Matrix = struct { + buf: mtl.Buffer, + off: usize = 0, + n: u32, + k: u32, +}; + +pub const AwqMatrix = struct { + w: mtl.Buffer, + w_off: usize = 0, + sb: mtl.Buffer, + sb_off: usize = 0, + input_scale: ?mtl.Buffer = null, + input_scale_off: usize = 0, + n: u32, + k: u32, + m5_layout: bool, + owns: bool = false, + + pub fn deinit(m: *AwqMatrix) void { + if (m.owns) { + m.w.deinit(); + m.sb.deinit(); + if (m.input_scale) |b| b.deinit(); + } + m.* = undefined; + } +}; + +pub const Kind = enum { + bf16_mv, + bf16_gemm, + bf16_splitk, + bf16_splitk_sum, + awq_m5_lane, + awq_m5_mv, + awq_m5_gemm, + awq_m3_mv, + awq_m3_qmm, + awq_xsum, + awq_scale_input, +}; + +pub const Key = struct { + kind: Kind, + n: u32 = 0, + k: u32 = 0, + sk: u32 = 1, + rows_tier: u32 = 1, + prompt: bool = false, + precompute_sums: bool = false, + edge_m: bool = false, + edge_n: bool = false, +}; + +pub const Bf16Args = extern struct { + rows: u32, + n: u32, + k: u32, + ldy: u32, + y1_addr: u64 = 0, + y2_addr: u64 = 0, + split1: u32 = 0, + ldy1: u32 = 0, + split2: u32 = 0, + ldy2: u32 = 0, +}; +pub const AwqArgs = extern struct { + m: i32, + n: i32, + k: i32, + mp: i32, + ldy: i32, + split1: u32 = 0, + y1_addr: u64 = 0, + y2_addr: u64 = 0, + ldy1: u32 = 0, + split2: u32 = 0, + ldy2: u32 = 0, + _pad: u32 = 0, +}; +pub const Bf16GemmArgs = extern struct { + p: [16]i32 = @splat(0), + y1_addr: u64 = 0, + y2_addr: u64 = 0, + split1: u32 = 0, + ldy1: u32 = 0, + split2: u32 = 0, + ldy2: u32 = 0, +}; +pub const Bf16SumArgs = extern struct { + p: [6]i32, + y1_addr: u64 = 0, + y2_addr: u64 = 0, + split1: u32 = 0, + ldy1: u32 = 0, + split2: u32 = 0, + ldy2: u32 = 0, +}; + +comptime { + std.debug.assert(@sizeOf(Bf16Args) == 48 and @offsetOf(Bf16Args, "y1_addr") == 16); + std.debug.assert(@sizeOf(AwqArgs) == 56 and @offsetOf(AwqArgs, "y1_addr") == 24); + std.debug.assert(@sizeOf(Bf16GemmArgs) == 96 and @offsetOf(Bf16GemmArgs, "y1_addr") == 64); + std.debug.assert(@sizeOf(Bf16SumArgs) == 56 and @offsetOf(Bf16SumArgs, "y1_addr") == 24); +} + +pub fn rowsTier(rows: u32) u32 { + if (rows <= 1) return 1; + if (rows <= 2) return 2; + if (rows <= 4) return 4; + if (rows <= 8) return 8; + if (rows <= 16) return 16; + return 32; +} + +pub fn bf16MvCols(tier: u32) u32 { + return if (tier == 1) 1 else if (tier <= 4) 2 else 1; +} + +pub fn awqM3MvCols(tier: u32) u32 { + return if (tier >= 2 and tier <= 8) 2 else 1; +} + +pub fn decodeSk(tensor_units: bool, is_awq: bool, n: u32, k: u32) u32 { + if (tensor_units and is_awq) { + if (k >= 8192) return 8; + if (n <= 4096) return 8; + if (n == 12288) return 2; + return 4; + } + if (is_awq) { + if (k >= 8192) return 4; + if (n >= 32768) return 1; + return 2; + } + if (n >= 32768) return 2; + return 4; +} + +pub const LinearGpu = struct { + allocator: std.mem.Allocator, + device: mtl.Device, + tensor_units: bool, + bf16_lib: ?mtl.Library = null, + awq_lib: ?mtl.Library = null, + cache: std.AutoHashMapUnmanaged(Key, mtl.Pipeline) = .empty, + xsum_ring: [2]?mtl.Buffer = .{ null, null }, + xsum_caps: [2]usize = .{ 0, 0 }, + xsum_turn: u1 = 0, + splitk_buf: ?mtl.Buffer = null, + splitk_cap: usize = 0, + scaled_buf: ?mtl.Buffer = null, + scaled_cap: usize = 0, + + pub fn init(a: std.mem.Allocator, device: mtl.Device) LinearGpu { + return .{ .allocator = a, .device = device, .tensor_units = device.tensorUnits() }; + } + + pub fn deinit(g: *LinearGpu) void { + var it = g.cache.valueIterator(); + while (it.next()) |p| p.deinit(); + g.cache.deinit(g.allocator); + if (g.bf16_lib) |l| l.deinit(); + if (g.awq_lib) |l| l.deinit(); + for (g.xsum_ring) |slot| if (slot) |b| b.deinit(); + if (g.splitk_buf) |b| b.deinit(); + if (g.scaled_buf) |b| b.deinit(); + g.* = undefined; + } + + /// Preallocate untracked scratch buffers up to `max_rows` before residency hold. + pub fn reserve(g: *LinearGpu, max_rows: u32, is_awq: bool) !void { + const stride = std.mem.alignForward(usize, max_rows, 16); + _ = try ensureScratch(g.device, &g.splitk_buf, &g.splitk_cap, 4 * @as(usize, max_rows) * 4160 * 4); + if (is_awq) { + const xb = @as(usize, 12288 / 128) * stride * 4; + for (&g.xsum_ring, &g.xsum_caps) |*slot, *cap| _ = try ensureScratch(g.device, slot, cap, xb); + _ = try ensureScratch(g.device, &g.scaled_buf, &g.scaled_cap, @as(usize, max_rows) * 12288 * 2); + } + } + + pub fn appendBuffers(g: *const LinearGpu, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + for (g.xsum_ring) |slot| if (slot) |b| try list.append(a, b); + if (g.splitk_buf) |b| try list.append(a, b); + if (g.scaled_buf) |b| try list.append(a, b); + } + + fn bf16Lib(g: *LinearGpu) !mtl.Library { + if (g.bf16_lib) |l| return l; + const text = try frags.source(g.device, g.allocator, ks.qwen27_bf16_linear); + defer g.allocator.free(text); + const l = try mtl.Library.fromSource(g.device, text, mtl.CompileOptions.mlx()); + g.bf16_lib = l; + return l; + } + + fn awqLib(g: *LinearGpu) !mtl.Library { + if (g.awq_lib) |l| return l; + const text = try frags.source(g.device, g.allocator, ks.qwen27_awq_w4a16); + defer g.allocator.free(text); + const l = try mtl.Library.fromSource(g.device, text, mtl.CompileOptions.mlx()); + g.awq_lib = l; + return l; + } + + pub fn pipeline(g: *LinearGpu, key: Key) !mtl.Pipeline { + if (g.cache.get(key)) |p| return p; + var buf: [96]u8 = undefined; + const fun: [:0]const u8 = switch (key.kind) { + .bf16_mv => try std.fmt.bufPrintSentinel(&buf, "sn_bf16_mv_r{d}_sk{d}", .{ key.rows_tier, key.sk }, 0), + .bf16_gemm => try std.fmt.bufPrintSentinel(&buf, "sn_bf16_gemm_{d}{d}", .{ @intFromBool(!key.edge_m), @intFromBool(!key.edge_n) }, 0), + .bf16_splitk => try std.fmt.bufPrintSentinel(&buf, "sn_bf16_gemm_splitk_{d}{d}", .{ @intFromBool(!key.edge_m), @intFromBool(!key.edge_n) }, 0), + .bf16_splitk_sum => "sn_bf16_gemm_splitk_sum", + .awq_m5_lane => try std.fmt.bufPrintSentinel(&buf, "sn_awq_lane_sk{d}_p{d}_r{d}", .{ key.sk, @intFromBool(key.precompute_sums), @intFromBool(key.prompt) }, 0), + .awq_m5_mv => try std.fmt.bufPrintSentinel(&buf, "sn_awq_m5_mv_r{d}_sk{d}", .{ key.rows_tier, key.sk }, 0), + .awq_m5_gemm => "sn_awq_gemm_m5", + .awq_m3_mv => try std.fmt.bufPrintSentinel(&buf, "sn_awq_row_mv_r{d}_sk{d}", .{ key.rows_tier, key.sk }, 0), + .awq_m3_qmm => "sn_awq_qmm_m3", + .awq_xsum => "sn_awq_xsum_128", + .awq_scale_input => "sn_awq_scale_input", + }; + const lib = switch (key.kind) { + .bf16_mv, .bf16_gemm, .bf16_splitk, .bf16_splitk_sum => try g.bf16Lib(), + else => try g.awqLib(), + }; + const p = try mtl.Pipeline.init(g.device, lib, fun, false); + errdefer p.deinit(); + try g.cache.put(g.allocator, key, p); + return p; + } + + fn ensureScratch(device: mtl.Device, slot: *?mtl.Buffer, cap: *usize, bytes: usize) !mtl.Buffer { + if (slot.* != null and cap.* >= bytes) return slot.*.?; + if (slot.*) |b| b.deinit(); + const alloc_bytes = @max(bytes, 256); + const b = try device.buffer(alloc_bytes, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + slot.* = b; + cap.* = alloc_bytes; + return b; + } + + pub fn prepareBf16(buf: mtl.Buffer, off: usize, n: u32, k: u32) !Bf16Matrix { + if (n == 0 or k == 0 or k % 8 != 0 or off % 16 != 0) return error.InvalidMatrix; + if (buf.length() < off + @as(usize, n) * k * 2) return error.BufferTooSmall; + return .{ .buf = buf, .off = off, .n = n, .k = k }; + } + + pub fn prepareAwqFromPacked(g: *const LinearGpu, b: awq.PackedBundle) !AwqMatrix { + return @import("linear_quant.zig").prepareAwqFromPacked(g, b); + } + + pub fn prepareAwq(g: *const LinearGpu, parts: []const awq.Part) ![]AwqMatrix { + return @import("linear_quant.zig").prepareAwq(g, parts); + } + + pub fn xsum128(g: *LinearGpu, e: mtl.ComputeEncoder, x: Ref, rows: u32, k: u32, stride: u32, xs: Ref) !void { + if (rows == 0 or k == 0 or k % 128 != 0 or stride < rows) return error.InvalidShape; + const p = try g.pipeline(.{ .kind = .awq_xsum }); + const kg = k / 128; + e.setPipeline(p); + e.setBuffer(x.buf, x.off, 0); + e.setValue([4]i32{ @intCast(rows), @intCast(stride), @intCast(k), 0 }, 1); + e.setBuffer(xs.buf, xs.off, 2); + e.dispatchThreads(mtl.Size.of(stride * kg, 1, 1), mtl.Size.of(256, 1, 1)); + } + + pub fn scaleInput(g: *LinearGpu, e: mtl.ComputeEncoder, x: Ref, scale: Ref, rows: u32, k: u32, out: Ref) !void { + if (rows == 0 or k == 0) return error.InvalidShape; + const p = try g.pipeline(.{ .kind = .awq_scale_input }); + e.setPipeline(p); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(scale.buf, scale.off, 1); + e.setValue([2]i32{ @intCast(rows), @intCast(k) }, 2); + e.setBuffer(out.buf, out.off, 3); + e.dispatchThreads(mtl.Size.of(k, rows, 1), mtl.Size.of(256, 1, 1)); + } + + pub const Dims = struct { rows: u32, n: u32, k: u32, ldy: u32 }; + + fn makeBf16Args(rows: u32, n: u32, k: u32, ldy: u32, splits: OutSplits, addrs: [2]u64, done: u32) Bf16Args { + return .{ + .rows = rows, + .n = n, + .k = k, + .ldy = ldy, + .y1_addr = if (addrs[0] != 0) addrs[0] + @as(u64, done) * splits.ldy1 * 2 else 0, + .y2_addr = if (addrs[1] != 0) addrs[1] + @as(u64, done) * splits.ldy2 * 2 else 0, + .split1 = splits.split1, + .ldy1 = splits.ldy1, + .split2 = splits.split2, + .ldy2 = splits.ldy2, + }; + } + + fn makeAwqArgs(m: u32, n: u32, k: u32, mp: u32, ldy: u32, splits: OutSplits, addrs: [2]u64, done: u32) AwqArgs { + return .{ + .m = @intCast(m), + .n = @intCast(n), + .k = @intCast(k), + .mp = @intCast(mp), + .ldy = @intCast(ldy), + .split1 = splits.split1, + .y1_addr = if (addrs[0] != 0) addrs[0] + @as(u64, done) * splits.ldy1 * 2 else 0, + .y2_addr = if (addrs[1] != 0) addrs[1] + @as(u64, done) * splits.ldy2 * 2 else 0, + .ldy1 = splits.ldy1, + .split2 = splits.split2, + .ldy2 = splits.ldy2, + }; + } + + pub fn dispatchBf16SplitK(kp: mtl.Pipeline, sp: mtl.Pipeline, e: mtl.ComputeEncoder, x: Ref, w: Ref, scratch: Ref, y: Ref, d: Dims, splits: u32) void { + quant.dispatchBf16SplitKSplit(kp, sp, e, x, w, scratch, y, d, splits, .{}); + } + + pub fn dispatchBf16Gemm(gp: mtl.Pipeline, e: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, d: Dims) void { + quant.dispatchBf16GemmSplit(gp, e, x, w, y, d, .{}); + } + + pub fn encodeBf16(g: *LinearGpu, e: mtl.ComputeEncoder, mat: Bf16Matrix, x: Ref, y: Ref, rows: u32, ldy: u32, prompt: bool, sk_override: ?u32) !void { + return g.encodeBf16Split(e, mat, x, y, rows, ldy, prompt, sk_override, .{}); + } + + pub fn encodeBf16Split( + g: *LinearGpu, + e: mtl.ComputeEncoder, + mat: Bf16Matrix, + x: Ref, + y: Ref, + rows: u32, + ldy: u32, + prompt: bool, + sk_override: ?u32, + splits: OutSplits, + ) !void { + if (rows == 0) return error.InvalidShape; + try quant.validateSplits(mat.n, ldy, splits); + const addrs = quant.splitAddrs(e, splits); + if (sk_override != null or !prompt) { + const sk = sk_override orelse decodeSk(g.tensor_units, false, mat.n, mat.k); + const max_take: u32 = if (sk_override != null) 32 else if (g.tensor_units) 16 else 8; + var done: u32 = 0; + while (done < rows) { + const take = @min(rows - done, max_take); + const tier: u32 = if (g.tensor_units and take < 4 and sk_override == null) 4 else rowsTier(take); + const p = try g.pipeline(.{ .kind = .bf16_mv, .n = mat.n, .k = mat.k, .sk = sk, .rows_tier = tier }); + const no = (8 / sk) * bf16MvCols(tier); + e.setPipeline(p); + e.setBuffer(x.buf, x.off + @as(usize, done) * mat.k * 2, 0); + e.setBuffer(mat.buf, mat.off, 1); + e.setValue(makeBf16Args(take, mat.n, mat.k, ldy, splits, addrs, done), 2); + e.setBuffer(y.buf, y.off + @as(usize, done) * ldy * 2, 3); + e.dispatchGroups(mtl.Size.of((mat.n + no - 1) / no, 1, 1), mtl.Size.of(256, 1, 1)); + done += take; + } + return; + } + if (!g.tensor_units and mat.n >= 512 and mat.n <= 8192) { + const k_splits: u32 = if (mat.n <= 4160 and mat.k >= 12288) 4 else 2; + const sc = try ensureScratch(g.device, &g.splitk_buf, &g.splitk_cap, @as(usize, k_splits) * rows * mat.n * 4); + const kp = try g.pipeline(.{ + .kind = .bf16_splitk, + .n = mat.n, + .k = mat.k, + .prompt = true, + .edge_m = rows % 64 != 0, + .edge_n = mat.n % 64 != 0, + }); + const sp = try g.pipeline(.{ .kind = .bf16_splitk_sum }); + quant.dispatchBf16SplitKSplit(kp, sp, e, x, .{ .buf = mat.buf, .off = mat.off }, .{ .buf = sc }, y, .{ .rows = rows, .n = mat.n, .k = mat.k, .ldy = ldy }, k_splits, splits); + return; + } + const gp = try g.pipeline(.{ + .kind = .bf16_gemm, + .n = mat.n, + .k = mat.k, + .prompt = true, + .edge_m = rows % 64 != 0, + .edge_n = mat.n % 128 != 0, + }); + quant.dispatchBf16GemmSplit(gp, e, x, .{ .buf = mat.buf, .off = mat.off }, y, .{ .rows = rows, .n = mat.n, .k = mat.k, .ldy = ldy }, splits); + } + + fn resolveXsum(g: *LinearGpu, e: mtl.ComputeEncoder, x: Ref, rows: u32, k: u32, eff_xs: ?Sums) !Sums { + if (eff_xs) |s| { + if (s.stride < rows) return error.InvalidShape; + return s; + } + const stride = std.mem.alignForward(u32, rows, 16); + const xs_bytes = @as(usize, k / 128) * stride * 4; + const turn = g.xsum_turn; + g.xsum_turn +%= 1; + const xb = try ensureScratch(g.device, &g.xsum_ring[turn], &g.xsum_caps[turn], xs_bytes); + const ref = Ref{ .buf = xb }; + try g.xsum128(e, x, rows, k, stride, ref); + e.barrier(); + return .{ .ref = ref, .stride = stride }; + } + + pub fn encodeAwq(g: *LinearGpu, e: mtl.ComputeEncoder, mat: AwqMatrix, x_in: Ref, xs_opt: ?Sums, y: Ref, rows: u32, ldy: u32, prompt: bool, sk_override: ?u32) !void { + return g.encodeAwqSplit(e, mat, x_in, xs_opt, y, rows, ldy, prompt, sk_override, .{}); + } + + pub fn encodeAwqSplit( + g: *LinearGpu, + e: mtl.ComputeEncoder, + mat: AwqMatrix, + x_in: Ref, + xs_opt: ?Sums, + y: Ref, + rows: u32, + ldy: u32, + prompt: bool, + sk_override: ?u32, + splits: OutSplits, + ) !void { + if (rows == 0) return error.InvalidShape; + try quant.validateSplits(mat.n, ldy, splits); + const addrs = quant.splitAddrs(e, splits); + var x = x_in; + if (mat.input_scale) |is_buf| { + const need = @as(usize, rows) * mat.k * 2; + const sc = try ensureScratch(g.device, &g.scaled_buf, &g.scaled_cap, need); + try g.scaleInput(e, x, .{ .buf = is_buf, .off = mat.input_scale_off }, rows, mat.k, .{ .buf = sc }); + e.barrier(); + x = .{ .buf = sc }; + } + if (mat.m5_layout and g.tensor_units) { + const eff_xs = if (mat.input_scale != null) null else xs_opt; + if ((sk_override != null or !prompt) and eff_xs == null and mat.n <= 24576 and rows <= 8) { + const sk = sk_override orelse decodeSk(true, true, mat.n, mat.k); + const p = try g.pipeline(.{ .kind = .awq_m5_lane, .n = mat.n, .k = mat.k, .sk = sk, .precompute_sums = false, .prompt = false }); + e.setPipeline(p); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(mat.w, mat.w_off, 1); + e.setBuffer(mat.sb, mat.sb_off, 2); + e.setValue(makeAwqArgs(rows, mat.n, mat.k, 0, ldy, splits, addrs, 0), 3); + e.setBuffer(y.buf, y.off, 4); + e.setBuffer(x.buf, x.off, 5); + e.dispatchGroups(mtl.Size.of((mat.n + 31) / 32, 1, 1), mtl.Size.of(sk * 32, 1, 1)); + return; + } + const sums = try g.resolveXsum(e, x, rows, mat.k, eff_xs); + const args = makeAwqArgs(rows, mat.n, mat.k, sums.stride, ldy, splits, addrs, 0); + if (sk_override != null or !prompt) { + const sk = sk_override orelse decodeSk(true, true, mat.n, mat.k); + const rb = rows > 16; + const p = try g.pipeline(.{ .kind = .awq_m5_lane, .n = mat.n, .k = mat.k, .sk = sk, .precompute_sums = true, .prompt = rb }); + e.setPipeline(p); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(mat.w, mat.w_off, 1); + e.setBuffer(mat.sb, mat.sb_off, 2); + e.setValue(args, 3); + e.setBuffer(y.buf, y.off, 4); + e.setBuffer(sums.ref.buf, sums.ref.off, 5); + e.dispatchGroups(mtl.Size.of((mat.n + 31) / 32, if (rb) (rows + 15) / 16 else 1, 1), mtl.Size.of(sk * 32, 1, 1)); + return; + } + const p = try g.pipeline(.{ .kind = .awq_m5_gemm, .n = mat.n, .k = mat.k, .prompt = true }); + const tn = (mat.n + 127) / 128; + const tm = (rows + 63) / 64; + e.setPipeline(p); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(mat.w, mat.w_off, 1); + e.setBuffer(mat.sb, mat.sb_off, 2); + e.setValue(args, 3); + e.setBuffer(y.buf, y.off, 4); + e.setBuffer(sums.ref.buf, sums.ref.off, 5); + e.dispatchGroups(mtl.Size.of(tn * 4, (tm + 3) / 4, 1), mtl.Size.of(256, 1, 1)); + return; + } + if (sk_override != null or !prompt) { + const sk = sk_override orelse decodeSk(g.tensor_units, true, mat.n, mat.k); + const max_take: u32 = if (sk_override != null) 32 else 8; + var done: u32 = 0; + while (done < rows) { + const take = @min(rows - done, max_take); + const tier = rowsTier(take); + const p = try g.pipeline(.{ .kind = .awq_m3_mv, .n = mat.n, .k = mat.k, .sk = sk, .rows_tier = tier }); + const no = (8 / sk) * awqM3MvCols(tier); + e.setPipeline(p); + e.setBuffer(x.buf, x.off + @as(usize, done) * mat.k * 2, 0); + e.setBuffer(mat.w, mat.w_off, 1); + e.setBuffer(mat.sb, mat.sb_off, 2); + e.setValue(makeAwqArgs(take, mat.n, mat.k, 0, ldy, splits, addrs, done), 3); + e.setBuffer(y.buf, y.off + @as(usize, done) * ldy * 2, 4); + e.dispatchGroups(mtl.Size.of((mat.n + no - 1) / no, 1, 1), mtl.Size.of(256, 1, 1)); + done += take; + } + return; + } + const p = try g.pipeline(.{ .kind = .awq_m3_qmm, .n = mat.n, .k = mat.k, .prompt = true }); + e.setPipeline(p); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(mat.w, mat.w_off, 1); + e.setBuffer(mat.sb, mat.sb_off, 2); + e.setValue(makeAwqArgs(rows, mat.n, mat.k, 0, ldy, splits, addrs, 0), 3); + e.setBuffer(y.buf, y.off, 4); + e.dispatchGroups(mtl.Size.of((mat.n + 63) / 64, (rows + 63) / 64, 1), mtl.Size.of(128, 1, 1)); + } + + /// Sweeps SK in {1,2,4,8} for decode and prefill across SenseNova shapes. + pub fn bench(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue) !void { + return @import("linear_bench.zig").bench(a, device, queue); + } +}; diff --git a/zig/src/families/sensenova_loop/linear_quant.zig b/zig/src/families/sensenova_loop/linear_quant.zig new file mode 100644 index 00000000000..d56c2734e1c --- /dev/null +++ b/zig/src/families/sensenova_loop/linear_quant.zig @@ -0,0 +1,150 @@ +//! Packed AWQ upload and split-output helpers. +const std = @import("std"); +const mtl = @import("metal"); +const awq = @import("awq.zig"); +const linear = @import("linear_gpu.zig"); + +const LinearGpu = linear.LinearGpu; +const AwqMatrix = linear.AwqMatrix; +const OutSplits = linear.OutSplits; +const Ref = linear.Ref; +const Dims = linear.LinearGpu.Dims; + +pub fn prepareAwqFromPacked(g: *const LinearGpu, b: awq.PackedBundle) !AwqMatrix { + const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + const w_bytes = b.w.len * 4; + const sb_bytes = b.sb.len * @sizeOf(awq.Float2); + const wb = try g.device.buffer(w_bytes, opts); + errdefer wb.deinit(); + @memcpy(wb.contents()[0..w_bytes], std.mem.sliceAsBytes(b.w)); + const sbb = try g.device.buffer(sb_bytes, opts); + errdefer sbb.deinit(); + @memcpy(sbb.contents()[0..sb_bytes], std.mem.sliceAsBytes(b.sb)); + var is_buf: ?mtl.Buffer = null; + if (b.input_scale) |is| { + const ib = try g.device.buffer(is.len * 4, opts); + errdefer ib.deinit(); + @memcpy(ib.contents()[0 .. is.len * 4], std.mem.sliceAsBytes(is)); + is_buf = ib; + } + return .{ + .w = wb, + .sb = sbb, + .input_scale = is_buf, + .n = @intCast(b.n), + .k = @intCast(b.k), + .m5_layout = b.layout == .m5_tile, + .owns = true, + }; +} + +pub fn prepareAwq(g: *const LinearGpu, parts: []const awq.Part) ![]AwqMatrix { + const layout: awq.Layout = if (g.tensor_units) .m5_tile else .m3_row; + const bundles = try awq.packBundles(g.allocator, parts, layout); + defer { + for (bundles) |*b| b.deinit(g.allocator); + g.allocator.free(bundles); + } + const out = try g.allocator.alloc(AwqMatrix, bundles.len); + var made: usize = 0; + errdefer { + for (out[0..made]) |*m| m.deinit(); + g.allocator.free(out); + } + for (bundles) |b| { + out[made] = try prepareAwqFromPacked(g, b); + made += 1; + } + return out; +} + +pub fn validateSplits(n: u32, ldy: u32, splits: OutSplits) !void { + if (splits.y1 != null) { + if (splits.split1 == 0 or splits.split1 >= n or splits.split1 % 128 != 0) return error.InvalidShape; + if (ldy < splits.split1) return error.InvalidShape; + const end1 = if (splits.y2 != null) splits.split2 else n; + if (splits.y2 != null) { + if (splits.split2 <= splits.split1 or splits.split2 >= n or splits.split2 % 128 != 0) return error.InvalidShape; + if (splits.ldy2 < n - splits.split2) return error.InvalidShape; + } + if (splits.ldy1 < end1 - splits.split1) return error.InvalidShape; + } else { + if (splits.y2 != null or splits.split1 != 0 or splits.split2 != 0) return error.InvalidShape; + if (ldy < n) return error.InvalidShape; + } +} + +pub fn splitAddrs(e: mtl.ComputeEncoder, splits: OutSplits) [2]u64 { + if (splits.y1) |y1| e.useResource(y1.buf, mtl.ResourceUsage.write); + if (splits.y2) |y2| e.useResource(y2.buf, mtl.ResourceUsage.write); + return .{ + if (splits.y1) |y1| y1.buf.gpuAddress() + y1.off else 0, + if (splits.y2) |y2| y2.buf.gpuAddress() + y2.off else 0, + }; +} + +pub fn dispatchBf16SplitKSplit( + kp: mtl.Pipeline, + sp: mtl.Pipeline, + e: mtl.ComputeEncoder, + x: Ref, + w: Ref, + scratch: Ref, + y: Ref, + d: Dims, + splits: u32, + out_splits: OutSplits, +) void { + const tn = (d.n + 63) / 64; + const tm = (d.rows + 63) / 64; + const kp_k = ((d.k / splits + 255) / 256) * 256; + var prm = [_]i32{ + @intCast(d.rows), @intCast(d.n), @intCast(d.k), @intCast(d.k), + @intCast(d.k), @intCast(d.n), @intCast(tn), @intCast(tm), + 0, @intCast(d.rows * d.n), @intCast(kp_k), 2, + 0, 0, 0, 0, + }; + e.setPipeline(kp); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + e.setBytes(std.mem.asBytes(&prm), 2); + e.setBuffer(scratch.buf, scratch.off, 3); + e.dispatchGroups(mtl.Size.of(splits * (tn << 2) * ((tm + 3) >> 2), 1, 1), mtl.Size.of(32, 2, 2)); + e.barrier(); + const addrs = splitAddrs(e, out_splits); + const sprm = linear.Bf16SumArgs{ + .p = .{ @intCast(splits), @intCast(d.rows * d.n), @intCast(d.n), @intCast(d.n), @intCast(d.rows), @intCast(d.ldy) }, + .y1_addr = addrs[0], + .y2_addr = addrs[1], + .split1 = out_splits.split1, + .ldy1 = out_splits.ldy1, + .split2 = out_splits.split2, + .ldy2 = out_splits.ldy2, + }; + e.setPipeline(sp); + e.setBuffer(scratch.buf, scratch.off, 0); + e.setValue(sprm, 1); + e.setBuffer(y.buf, y.off, 2); + e.dispatchGroups(mtl.Size.of((d.n + 31) / 32, (d.rows + 7) / 8, 1), mtl.Size.of(32, 8, 1)); +} + +pub fn dispatchBf16GemmSplit(gp: mtl.Pipeline, e: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, d: Dims, splits: OutSplits) void { + const tn = (d.n + 127) / 128; + const tm = (d.rows + 63) / 64; + const addrs = splitAddrs(e, splits); + var args = linear.Bf16GemmArgs{ + .y1_addr = addrs[0], + .y2_addr = addrs[1], + .split1 = splits.split1, + .ldy1 = splits.ldy1, + .split2 = splits.split2, + .ldy2 = splits.ldy2, + }; + for ([_]usize{ d.rows, d.n, d.k, d.k, d.k, d.ldy, tn, tm, 2, d.k / 256 }, 0..) |v, i| args.p[i] = @intCast(v); + e.setPipeline(gp); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(w.buf, w.off, 1); + e.setValue(args, 2); + e.setBuffer(y.buf, y.off, 3); + e.dispatchGroups(mtl.Size.of(tn * 4, (tm + 3) / 4, 1), mtl.Size.of(32, 4, 2)); +} diff --git a/zig/src/families/sensenova_loop/mhc_metal.zig b/zig/src/families/sensenova_loop/mhc_metal.zig new file mode 100644 index 00000000000..48627499ffd --- /dev/null +++ b/zig/src/families/sensenova_loop/mhc_metal.zig @@ -0,0 +1,233 @@ +//! Metal launch wrappers and ABI checks for SenseNova-Loop two-stream mHC kernels. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); + +pub const tg: u32 = 256; +pub const max_hidden: u32 = 4096; +pub const coeff_width: u32 = 6; + +pub const Ref = struct { + buf: mtl.Buffer, + off: usize = 0, +}; + +pub const Error = error{ + BadMhcShape, + BadMhcParams, +}; + +pub const EnterArgs = extern struct { + rows: u32, + hidden: u32, + has_pending: u32, + write_h: u32, +}; + +pub const PreNormArgs = extern struct { + rows: u32, + hidden: u32, + iters: u32, + shift_norm: u32, + xs_group: u32, + xs_stride: u32, + pre_scale: f32, + eps: f32, +}; + +pub const PostMergeArgs = extern struct { + rows: u32, + hidden: u32, + exit: u32, + pad0: u32 = 0, +}; + +comptime { + if (@sizeOf(EnterArgs) != 16 or @offsetOf(EnterArgs, "write_h") != 12) @compileError("EnterArgs ABI mismatch"); + if (@sizeOf(PreNormArgs) != 32 or @offsetOf(PreNormArgs, "eps") != 28) @compileError("PreNormArgs ABI mismatch"); + if (@sizeOf(PostMergeArgs) != 16 or @offsetOf(PostMergeArgs, "exit") != 8) @compileError("PostMergeArgs ABI mismatch"); +} + +pub const PreNormCall = struct { + iters: u32 = 20, + shift_norm: bool = true, + xs_group: u32 = 0, + xs_stride: u32 = 0, + pre_scale: f32 = 1.0, + eps: f32 = 1e-6, +}; + +pub const Pipelines = struct { + enter: mtl.Pipeline, + pre_norm: mtl.Pipeline, + post_merge: mtl.Pipeline, + post_and_pre_norm: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pipelines { + return loadSource(device, sources.core_sensenova_mhc); + } + + pub fn loadSource(device: mtl.Device, text: []const u8) !Pipelines { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var p: Pipelines = undefined; + p.enter = try mtl.Pipeline.init(device, lib, "sn_mhc_enter", false); + errdefer p.enter.deinit(); + p.pre_norm = try mtl.Pipeline.init(device, lib, "sn_mhc_pre_norm", false); + errdefer p.pre_norm.deinit(); + p.post_merge = try mtl.Pipeline.init(device, lib, "sn_mhc_post_merge", false); + errdefer p.post_merge.deinit(); + p.post_and_pre_norm = try mtl.Pipeline.init(device, lib, "sn_mhc_post_and_pre_norm", false); + return p; + } + + pub fn deinit(p: *Pipelines) void { + p.enter.deinit(); + p.pre_norm.deinit(); + p.post_merge.deinit(); + p.post_and_pre_norm.deinit(); + } +}; + +fn bind(e: mtl.ComputeEncoder, refs: []const Ref) void { + for (refs, 0..) |r, i| e.setBuffer(r.buf, r.off, i); +} + +pub fn checkShape(rows: u32, hidden: u32) Error!void { + if (rows == 0 or hidden == 0 or hidden > max_hidden) return error.BadMhcShape; +} + +pub fn checkPreNorm(rows: u32, hidden: u32, call: PreNormCall, has_xs: bool) Error!void { + try checkShape(rows, hidden); + if (call.iters == 0) return error.BadMhcParams; + if (!std.math.isFinite(call.pre_scale) or call.pre_scale <= 0) return error.BadMhcParams; + if (!std.math.isFinite(call.eps) or call.eps < 0) return error.BadMhcParams; + if (call.xs_group != 0 and call.xs_group != 64 and call.xs_group != 128) return error.BadMhcParams; + if (call.xs_group != 0) { + if (!has_xs or hidden % call.xs_group != 0 or call.xs_stride < rows) return error.BadMhcParams; + } +} + +/// Expand `[rows, H]` (optionally `bf16(h + pending)`) into `[rows, 2, H]` residual streams. +pub fn enter( + p: *const Pipelines, + e: mtl.ComputeEncoder, + h_in: Ref, + pending: ?Ref, + r_out: Ref, + h_out: ?Ref, + rows: u32, + hidden: u32, +) Error!void { + try checkShape(rows, hidden); + const elems = if (hidden % 8 == 0) hidden / 8 else hidden; + const grid_x = (elems + tg - 1) / tg; + e.setPipeline(p.enter); + bind(e, &.{ h_in, pending orelse h_in, r_out, h_out orelse r_out }); + e.setValue(EnterArgs{ + .rows = rows, + .hidden = hidden, + .has_pending = @intFromBool(pending != null), + .write_h = @intFromBool(h_out != null), + }, 4); + e.dispatchGroups(mtl.Size.of(grid_x, rows, 1), mtl.Size.of(tg, 1, 1)); +} + +/// Compute mHC routing coefficients, collapsed branch RMSNorm and optional group sums in one pass. +pub fn preNorm( + p: *const Pipelines, + e: mtl.ComputeEncoder, + r_in: Ref, + w: Ref, + b: Ref, + sub_w: Ref, + coeff_out: Ref, + norm_out: Ref, + xs_out: ?Ref, + rows: u32, + hidden: u32, + call: PreNormCall, +) Error!void { + try checkPreNorm(rows, hidden, call, xs_out != null); + e.setPipeline(p.pre_norm); + bind(e, &.{ r_in, w, b, sub_w, coeff_out, norm_out, xs_out orelse norm_out }); + e.setValue(PreNormArgs{ + .rows = rows, + .hidden = hidden, + .iters = call.iters, + .shift_norm = @intFromBool(call.shift_norm), + .xs_group = call.xs_group, + .xs_stride = call.xs_stride, + .pre_scale = call.pre_scale, + .eps = call.eps, + }, 7); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(tg, 1, 1)); +} + +/// Mix two residual streams with `coeff`, add branch update and optionally mean-collapse on exit. +pub fn postMerge( + p: *const Pipelines, + e: mtl.ComputeEncoder, + r_in: Ref, + y_in: Ref, + coeff_in: Ref, + out: Ref, + rows: u32, + hidden: u32, + exit: bool, +) Error!void { + try checkShape(rows, hidden); + const elems = if (hidden % 8 == 0) hidden / 8 else hidden; + const grid_x = (elems + tg - 1) / tg; + e.setPipeline(p.post_merge); + bind(e, &.{ r_in, y_in, coeff_in, out }); + e.setValue(PostMergeArgs{ .rows = rows, .hidden = hidden, .exit = @intFromBool(exit) }, 4); + e.dispatchGroups(mtl.Size.of(grid_x, rows, 1), mtl.Size.of(tg, 1, 1)); +} + +/// Fused post_merge + next pre_norm keeping `R_next` in threadgroup memory, bit-identical to sequential. +pub fn postAndPreNorm( + p: *const Pipelines, + e: mtl.ComputeEncoder, + r_in: Ref, + y_in: Ref, + coeff_in: Ref, + w_next: Ref, + b_next: Ref, + sub_w_next: Ref, + r_out: Ref, + coeff_out: Ref, + norm_out: Ref, + xs_out: ?Ref, + rows: u32, + hidden: u32, + call: PreNormCall, +) Error!void { + try checkPreNorm(rows, hidden, call, xs_out != null); + e.setPipeline(p.post_and_pre_norm); + bind(e, &.{ r_in, y_in, coeff_in, w_next, b_next, sub_w_next, r_out, coeff_out, norm_out, xs_out orelse norm_out }); + e.setValue(PreNormArgs{ + .rows = rows, + .hidden = hidden, + .iters = call.iters, + .shift_norm = @intFromBool(call.shift_norm), + .xs_group = call.xs_group, + .xs_stride = call.xs_stride, + .pre_scale = call.pre_scale, + .eps = call.eps, + }, 10); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(tg, 1, 1)); +} + +test "mhc_metal: validates shapes, pre_scale, xs_group and struct layout" { + try checkShape(1, 4096); + try checkPreNorm(4, 4096, .{ .xs_group = 64, .xs_stride = 4 }, true); + try std.testing.expectError(error.BadMhcShape, checkShape(0, 4096)); + try std.testing.expectError(error.BadMhcShape, checkShape(1, 0)); + try std.testing.expectError(error.BadMhcShape, checkShape(1, 4097)); + try std.testing.expectError(error.BadMhcParams, checkPreNorm(4, 4096, .{ .iters = 0 }, false)); + try std.testing.expectError(error.BadMhcParams, checkPreNorm(4, 4096, .{ .pre_scale = 0 }, false)); + try std.testing.expectError(error.BadMhcParams, checkPreNorm(4, 4096, .{ .xs_group = 32, .xs_stride = 4 }, true)); + try std.testing.expectError(error.BadMhcParams, checkPreNorm(4, 4096, .{ .xs_group = 64, .xs_stride = 3 }, true)); + try std.testing.expectError(error.BadMhcParams, checkPreNorm(4, 4096, .{ .xs_group = 64, .xs_stride = 4 }, false)); +} diff --git a/zig/src/families/sensenova_loop/mhc_ref.zig b/zig/src/families/sensenova_loop/mhc_ref.zig new file mode 100644 index 00000000000..e17ed548817 --- /dev/null +++ b/zig/src/families/sensenova_loop/mhc_ref.zig @@ -0,0 +1,561 @@ +//! IEEE-754 float64 reference and PyTorch BF16-rounded simulation for two-stream mHC (H <= 4096). +const std = @import("std"); + +pub const streams: usize = 2; +pub const max_hidden: usize = 4096; +pub const coeff_width: usize = 6; // { post0, post1, mix00, mix01, mix10, mix11 } + +pub const Accum = enum { none, f32, f16, bf16 }; +pub const Order = enum { sequential, pairwise, strided }; + +pub const Params = struct { + hidden: usize, + iterations: u32 = 20, + pre_scale: f32 = 1.0, + eps: f32 = 1e-6, + shift_norm: bool = true, + exit: bool = false, + xs_group: usize = 0, + xs_stride: usize = 0, +}; + +pub const PreIn = struct { + r_in: []const u16, + w: []const f32, + b: []const f32, + sub_w: []const u16, +}; + +pub const PreRefOut = struct { + coeff: []f64, + mag_coeff: []f64, + norm: []f64, + mag_norm: []f64, + xs: ?[]f64 = null, + mag_xs: ?[]f64 = null, +}; + +pub const PreSimOut = struct { + coeff: []u16, + norm: []u16, + xs: ?[]f32 = null, +}; + +/// fp32 to bf16 bits, round to nearest even (NaN stays NaN). +pub fn toBf16(v: f32) u16 { + const u: u32 = @bitCast(v); + if (std.math.isNan(v)) return @truncate((u >> 16) | 0x40); + return @truncate((u +% 0x7fff +% ((u >> 16) & 1)) >> 16); +} + +pub fn fromBf16(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +pub fn roundBf16(v: f32) f32 { + return fromBf16(toBf16(v)); +} + +/// Exact IEEE-754 float64 value rounded to nearest BF16 (ties to even), returned as float64. +pub fn bf64(v: f64) f64 { + if (!std.math.isFinite(v) or v == 0) return v; + const e = @max(std.math.frexp(v).exponent, -125); + const step = std.math.ldexp(@as(f64, 1), e - 8); + const q = v / step; + var t = @floor(q); + const d = q - t; + if (d > 0.5 or (d == 0.5 and @mod(t, 2) != 0)) t += 1; + const out = std.math.copysign(t * step, v); + return if (@abs(out) >= 0x1p128) std.math.copysign(std.math.inf(f64), v) else out; +} + +fn bfVal(h: u16) f64 { + return @as(f64, fromBf16(h)); +} + +fn roundIn(acc: Accum, v: f64) f64 { + return switch (acc) { + .f32 => @as(f32, @floatCast(v)), + .f16 => @as(f16, @floatCast(v)), + .bf16 => fromBf16(toBf16(@floatCast(v))), + .none => v, + }; +} + +fn chainSum(acc: Accum, t: []const f64, stride: usize, first: usize) f64 { + var s: f64 = 0; + var i = first; + while (i < t.len) : (i += stride) s = roundIn(acc, s + roundIn(acc, t[i])); + return s; +} + +fn halvesSum(acc: Accum, t: []const f64) f64 { + if (t.len == 0) return 0; + if (t.len == 1) return roundIn(acc, t[0]); + const mid = t.len / 2; + return roundIn(acc, halvesSum(acc, t[0..mid]) + halvesSum(acc, t[mid..])); +} + +pub fn sumIn(acc: Accum, order: Order, t: []const f64) f64 { + if (acc == .none) { + var s: f64 = 0; + for (t) |v| s += v; + return s; + } + return switch (order) { + .sequential => chainSum(acc, t, 1, 0), + .pairwise => halvesSum(acc, t), + .strided => blk: { + var lanes: [32]f64 = @splat(0); + for (&lanes, 0..) |*l, i| l.* = chainSum(acc, t, 32, i); + break :blk halvesSum(acc, &lanes); + }, + }; +} + +fn lse2(a: f64, b: f64) f64 { + if (std.math.isNan(a) or std.math.isNan(b)) return std.math.nan(f64); + const mx = @max(a, b); + if (std.math.isInf(mx) and mx < 0) return mx; + return mx + @log(1.0 + @exp(-@abs(a - b))); +} + +fn lse2F32(a: f32, b: f32) f32 { + if (std.math.isNan(a) or std.math.isNan(b)) return std.math.nan(f32); + const mx = @max(a, b); + if (std.math.isInf(mx) and mx < 0) return mx; + return mx + @log(1.0 + @exp(-@abs(a - b))); +} + +fn sinkhorn2x2(z: [4]f64, iters: u32) [4]f64 { + var l = z; + for (0..iters) |_| { + const r0 = lse2(l[0], l[1]); + l[0] -= r0; + l[1] -= r0; + const r1 = lse2(l[2], l[3]); + l[2] -= r1; + l[3] -= r1; + const c0 = lse2(l[0], l[2]); + l[0] -= c0; + l[2] -= c0; + const c1 = lse2(l[1], l[3]); + l[1] -= c1; + l[3] -= c1; + } + return .{ @exp(l[0]), @exp(l[1]), @exp(l[2]), @exp(l[3]) }; +} + +fn sinkhorn2x2F32(z: [4]f32, iters: u32) [4]f32 { + var l = z; + for (0..iters) |_| { + const r0 = lse2F32(l[0], l[1]); + l[0] -= r0; + l[1] -= r0; + const r1 = lse2F32(l[2], l[3]); + l[2] -= r1; + l[3] -= r1; + const c0 = lse2F32(l[0], l[2]); + l[0] -= c0; + l[2] -= c0; + const c1 = lse2F32(l[1], l[3]); + l[1] -= c1; + l[3] -= c1; + } + return .{ @exp(l[0]), @exp(l[1]), @exp(l[2]), @exp(l[3]) }; +} + +/// Float64 reference for `sn_mhc_enter`: expands `h` (optionally `bf16(h + pending)`) to two identical streams. +pub fn enterRef( + h_in: []const u16, + pending: ?[]const u16, + rows: usize, + hidden: usize, + r_out: []f64, + r_mag: []f64, + h_out: ?[]f64, + h_mag: ?[]f64, +) void { + for (0..rows) |r| { + for (0..hidden) |d| { + const hv = bfVal(h_in[r * hidden + d]); + const v = if (pending) |pend| bf64(hv + bfVal(pend[r * hidden + d])) else hv; + const mg = if (pending) |pend| @abs(hv) + @abs(bfVal(pend[r * hidden + d])) else 0; + r_out[(r * 2 + 0) * hidden + d] = v; + r_out[(r * 2 + 1) * hidden + d] = v; + r_mag[(r * 2 + 0) * hidden + d] = mg; + r_mag[(r * 2 + 1) * hidden + d] = mg; + if (h_out) |ho| ho[r * hidden + d] = v; + if (h_mag) |hm| hm[r * hidden + d] = mg; + } + } +} + +/// PyTorch BF16 simulation for `sn_mhc_enter`. +pub fn enterSim(h_in: []const u16, pending: ?[]const u16, rows: usize, hidden: usize, r_out: []u16, h_out: ?[]u16) void { + for (0..rows) |r| { + for (0..hidden) |d| { + const bits = if (pending) |pend| + toBf16(fromBf16(h_in[r * hidden + d]) + fromBf16(pend[r * hidden + d])) + else + h_in[r * hidden + d]; + r_out[(r * 2 + 0) * hidden + d] = bits; + r_out[(r * 2 + 1) * hidden + d] = bits; + if (h_out) |ho| ho[r * hidden + d] = bits; + } + } +} + +/// Float64 reference (and Gate 4 sum simulator) for `sn_mhc_pre_norm`. +pub fn preNormRef(a: std.mem.Allocator, in: PreIn, rows: usize, p: Params, acc: Accum, order: Order, out: PreRefOut) !void { + const h = p.hidden; + const two_h = 2 * h; + const scratch = try a.alloc(f64, two_h * 2 + h); + defer a.free(scratch); + const rv = scratch[0..two_h]; + const tmp = scratch[two_h .. 2 * two_h]; + const br = scratch[2 * two_h ..]; + + for (0..rows) |r| { + const rx = in.r_in[r * two_h ..][0..two_h]; + for (rv, rx, tmp) |*o, bits, *sq| { + const v = bfVal(bits); + o.* = v; + sq.* = v * v; + } + const ss = sumIn(acc, order, tmp); + const inv_rms = 1.0 / @sqrt(ss / @as(f64, @floatFromInt(two_h)) + @as(f64, p.eps)); + + var z: [8]f64 = undefined; + var dz: [8]f64 = undefined; + for (0..8) |m| { + const wm = in.w[m * two_h ..][0..two_h]; + var abs_dot: f64 = 0; + for (0..two_h) |j| { + const prod = rv[j] * @as(f64, wm[j]); + tmp[j] = prod; + abs_dot += @abs(prod); + } + const dot = sumIn(acc, order, tmp); + z[m] = dot * inv_rms + @as(f64, in.b[m]); + dz[m] = abs_dot * @abs(inv_rms) + 0.5 * @abs(dot * inv_rms); + } + + const pre0 = 1.0 / (1.0 + @exp(-z[0])); + const pre1 = 1.0 / (1.0 + @exp(-z[1])); + const post0 = 2.0 / (1.0 + @exp(-z[2])); + const post1 = 2.0 / (1.0 + @exp(-z[3])); + const mix = sinkhorn2x2(.{ z[4], z[5], z[6], z[7] }, p.iterations); + + const co = out.coeff[r * coeff_width ..][0..coeff_width]; + const cm = out.mag_coeff[r * coeff_width ..][0..coeff_width]; + co.* = .{ post0, post1, mix[0], mix[1], mix[2], mix[3] }; + cm[0] = dz[2] + @abs(post0) * (@abs(z[2]) + 3.0); + cm[1] = dz[3] + @abs(post1) * (@abs(z[3]) + 3.0); + const dz_max = @max(@max(dz[4], dz[5]), @max(dz[6], dz[7])); + const sk_scale: f64 = @as(f64, @floatFromInt(p.iterations)) * 4.0 + 6.0; + for (0..4) |k| cm[2 + k] = dz_max * sk_scale + @abs(mix[k]) * (@abs(z[4 + k]) + sk_scale); + + const p0 = bf64(pre0); + const p1 = bf64(pre1); + for (0..h) |d| { + const b_unscaled = bf64(p0 * rv[d] + p1 * rv[h + d]); + const bv = if (p.pre_scale != 1.0) bf64(@as(f64, p.pre_scale) * b_unscaled) else b_unscaled; + br[d] = bv; + tmp[d] = bv * bv; + } + const ss_b = sumIn(acc, order, tmp[0..h]); + const inv_b = 1.0 / @sqrt(ss_b / @as(f64, @floatFromInt(h)) + @as(f64, p.eps)); + for (0..h) |d| { + const sw = bfVal(in.sub_w[d]); + const w_eff = if (p.shift_norm) 1.0 + sw else sw; + const yv = (br[d] * inv_b) * w_eff; + out.norm[r * h + d] = yv; + out.mag_norm[r * h + d] = @abs(yv) * 0.5; + } + if (p.xs_group > 0) { + const xs_w = out.xs.?; + const xs_m = out.mag_xs.?; + const groups = h / p.xs_group; + for (0..groups) |g| { + const base = g * p.xs_group; + var ab: f64 = 0; + for (0..p.xs_group) |i| { + const oq = bf64(out.norm[r * h + base + i]); + tmp[i] = oq; + ab += @abs(oq); + } + xs_w[g * p.xs_stride + r] = sumIn(acc, order, tmp[0..p.xs_group]); + xs_m[g * p.xs_stride + r] = ab; + } + } + } +} + +/// Exact PyTorch BF16-rounded FP32 simulation for `sn_mhc_pre_norm`. +pub fn preNormSim(a: std.mem.Allocator, in: PreIn, rows: usize, p: Params, out: PreSimOut) !void { + const h = p.hidden; + const two_h = 2 * h; + const rv = try a.alloc(f32, two_h); + defer a.free(rv); + const br = try a.alloc(f32, h); + defer a.free(br); + + for (0..rows) |r| { + var ss: f32 = 0; + for (0..two_h) |j| { + const v = fromBf16(in.r_in[r * two_h + j]); + rv[j] = v; + ss += v * v; + } + const inv_rms = 1.0 / @sqrt(ss / @as(f32, @floatFromInt(two_h)) + p.eps); + + var z: [8]f32 = undefined; + for (0..8) |m| { + const wm = in.w[m * two_h ..][0..two_h]; + var dot: f32 = 0; + for (0..two_h) |j| dot += rv[j] * wm[j]; + z[m] = dot * inv_rms + in.b[m]; + } + + const pre0 = 1.0 / (1.0 + @exp(-z[0])); + const pre1 = 1.0 / (1.0 + @exp(-z[1])); + const post0 = 2.0 / (1.0 + @exp(-z[2])); + const post1 = 2.0 / (1.0 + @exp(-z[3])); + const mix = sinkhorn2x2F32(.{ z[4], z[5], z[6], z[7] }, p.iterations); + + const co = out.coeff[r * coeff_width ..][0..coeff_width]; + co.* = .{ toBf16(post0), toBf16(post1), toBf16(mix[0]), toBf16(mix[1]), toBf16(mix[2]), toBf16(mix[3]) }; + + const p0 = roundBf16(pre0); + const p1 = roundBf16(pre1); + var ss_b: f32 = 0; + for (0..h) |d| { + var bv = roundBf16(p0 * rv[d] + p1 * rv[h + d]); + if (p.pre_scale != 1.0) bv = roundBf16(p.pre_scale * bv); + br[d] = bv; + ss_b += bv * bv; + } + const inv_b = 1.0 / @sqrt(ss_b / @as(f32, @floatFromInt(h)) + p.eps); + for (0..h) |d| { + const sw = fromBf16(in.sub_w[d]); + const w_eff = if (p.shift_norm) 1.0 + sw else sw; + out.norm[r * h + d] = toBf16((br[d] * inv_b) * w_eff); + } + if (p.xs_group > 0) { + const xs = out.xs.?; + for (0..h / p.xs_group) |g| { + const base = g * p.xs_group; + var gs: f32 = 0; + for (0..p.xs_group) |i| gs += fromBf16(out.norm[r * h + base + i]); + xs[g * p.xs_stride + r] = gs; + } + } + } +} + +/// Float64 reference (and Gate 4 sum simulator) for `sn_mhc_post_merge` (exit or stream carry). +pub fn postMergeRef( + r_in: []const u16, + y_in: []const u16, + coeff: []const u16, + rows: usize, + hidden: usize, + exit: bool, + acc: Accum, + order: Order, + want: []f64, + mag: []f64, +) void { + for (0..rows) |r| { + const co = coeff[r * coeff_width ..][0..coeff_width]; + const post = [2]f64{ bfVal(co[0]), bfVal(co[1]) }; + const mix = [4]f64{ bfVal(co[2]), bfVal(co[3]), bfVal(co[4]), bfVal(co[5]) }; + for (0..hidden) |d| { + const r0 = bfVal(r_in[(r * 2 + 0) * hidden + d]); + const r1 = bfVal(r_in[(r * 2 + 1) * hidden + d]); + const yv = bfVal(y_in[r * hidden + d]); + var rn: [2]f64 = undefined; + var rm: [2]f64 = undefined; + for (0..2) |s| { + const mt = [2]f64{ mix[s * 2 + 0] * r0, mix[s * 2 + 1] * r1 }; + const mixed = bf64(sumIn(acc, order, &mt)); + const upd = bf64(post[s] * yv); + const add_t = [2]f64{ mixed, upd }; + rn[s] = sumIn(acc, order, &add_t); + rm[s] = @abs(mt[0]) + @abs(mt[1]) + @abs(upd); + } + if (exit) { + const b0 = bf64(rn[0]); + const b1 = bf64(rn[1]); + const et = [2]f64{ 0.5 * b0, 0.5 * b1 }; + want[r * hidden + d] = sumIn(acc, order, &et); + mag[r * hidden + d] = 0.5 * (@abs(b0) + @abs(b1)) + 0.5 * (rm[0] + rm[1]); + } else { + want[(r * 2 + 0) * hidden + d] = rn[0]; + want[(r * 2 + 1) * hidden + d] = rn[1]; + mag[(r * 2 + 0) * hidden + d] = rm[0]; + mag[(r * 2 + 1) * hidden + d] = rm[1]; + } + } + } +} + +/// Exact PyTorch BF16-rounded FP32 simulation for `sn_mhc_post_merge`. +pub fn postMergeSim( + r_in: []const u16, + y_in: []const u16, + coeff: []const u16, + rows: usize, + hidden: usize, + exit: bool, + out: []u16, +) void { + for (0..rows) |r| { + const co = coeff[r * coeff_width ..][0..coeff_width]; + const post = [2]f32{ fromBf16(co[0]), fromBf16(co[1]) }; + const mix = [4]f32{ fromBf16(co[2]), fromBf16(co[3]), fromBf16(co[4]), fromBf16(co[5]) }; + for (0..hidden) |d| { + const r0 = fromBf16(r_in[(r * 2 + 0) * hidden + d]); + const r1 = fromBf16(r_in[(r * 2 + 1) * hidden + d]); + const yv = fromBf16(y_in[r * hidden + d]); + var rn: [2]u16 = undefined; + for (0..2) |s| { + const mixed = roundBf16(mix[s * 2 + 0] * r0 + mix[s * 2 + 1] * r1); + const upd = roundBf16(post[s] * yv); + rn[s] = toBf16(mixed + upd); + } + if (exit) { + out[r * hidden + d] = toBf16(0.5 * (fromBf16(rn[0]) + fromBf16(rn[1]))); + } else { + out[(r * 2 + 0) * hidden + d] = rn[0]; + out[(r * 2 + 1) * hidden + d] = rn[1]; + } + } + } +} + +/// Float64 reference for fused `sn_mhc_post_and_pre_norm`, matching sequential `postMerge` -> `preNorm`. +pub fn postAndPreNormRef( + a: std.mem.Allocator, + r_in: []const u16, + y_in: []const u16, + coeff_in: []const u16, + w_next: []const f32, + b_next: []const f32, + sub_w_next: []const u16, + rows: usize, + p: Params, + acc: Accum, + order: Order, + want_r_next: []f64, + mag_r_next: []f64, + out: PreRefOut, +) !void { + postMergeRef(r_in, y_in, coeff_in, rows, p.hidden, false, acc, order, want_r_next, mag_r_next); + const r_bf = try a.alloc(u16, rows * 2 * p.hidden); + defer a.free(r_bf); + for (r_bf, want_r_next) |*dst, v| dst.* = toBf16(@floatCast(bf64(v))); + try preNormRef(a, .{ .r_in = r_bf, .w = w_next, .b = b_next, .sub_w = sub_w_next }, rows, p, acc, order, out); +} + +/// Exact PyTorch BF16 simulation for fused `sn_mhc_post_and_pre_norm`. +pub fn postAndPreNormSim( + a: std.mem.Allocator, + r_in: []const u16, + y_in: []const u16, + coeff_in: []const u16, + w_next: []const f32, + b_next: []const f32, + sub_w_next: []const u16, + rows: usize, + p: Params, + r_next_out: []u16, + out: PreSimOut, +) !void { + postMergeSim(r_in, y_in, coeff_in, rows, p.hidden, false, r_next_out); + try preNormSim(a, .{ .r_in = r_next_out, .w = w_next, .b = b_next, .sub_w = sub_w_next }, rows, p, out); +} + +test "mhc_ref: Sinkhorn produces doubly stochastic 2x2 matrix and preNorm/postMerge match" { + const a = std.testing.allocator; + const h: usize = 64; + const rows: usize = 2; + const r_in = try a.alloc(u16, rows * 2 * h); + defer a.free(r_in); + const w = try a.alloc(f32, 8 * 2 * h); + defer a.free(w); + const b = [_]f32{ -1.0986123, 1.0986123, 0.0, 0.0, 2.639057, 0.0, 0.0, 2.639057 }; + const sub_w = try a.alloc(u16, h); + defer a.free(sub_w); + const y_in = try a.alloc(u16, rows * h); + defer a.free(y_in); + + var prng = std.Random.DefaultPrng.init(42); + const rng = prng.random(); + for (r_in) |*v| v.* = toBf16((rng.float(f32) * 2 - 1) * 3.0); + for (w) |*v| v.* = (rng.float(f32) * 2 - 1) * 0.02; + for (sub_w) |*v| v.* = toBf16((rng.float(f32) * 2 - 1) * 0.1); + for (y_in) |*v| v.* = toBf16((rng.float(f32) * 2 - 1) * 2.0); + + const p = Params{ .hidden = h, .iterations = 20, .pre_scale = 0.5, .shift_norm = true, .xs_group = 64, .xs_stride = rows }; + const wc = try a.alloc(f64, rows * coeff_width); + defer a.free(wc); + const mc = try a.alloc(f64, rows * coeff_width); + defer a.free(mc); + const wn = try a.alloc(f64, rows * h); + defer a.free(wn); + const mn = try a.alloc(f64, rows * h); + defer a.free(mn); + const wxs = try a.alloc(f64, rows); + defer a.free(wxs); + const mxs = try a.alloc(f64, rows); + defer a.free(mxs); + + const pin = PreIn{ .r_in = r_in, .w = w, .b = &b, .sub_w = sub_w }; + try preNormRef(a, pin, rows, p, .none, .sequential, .{ .coeff = wc, .mag_coeff = mc, .norm = wn, .mag_norm = mn, .xs = wxs, .mag_xs = mxs }); + for (0..rows) |r| { + const c = wc[r * coeff_width ..]; + try std.testing.expectApproxEqAbs(@as(f64, 1.0), c[2] + c[3], 1e-3); + try std.testing.expectApproxEqAbs(@as(f64, 1.0), c[4] + c[5], 1e-3); + try std.testing.expectApproxEqAbs(@as(f64, 1.0), c[2] + c[4], 1e-12); + try std.testing.expectApproxEqAbs(@as(f64, 1.0), c[3] + c[5], 1e-12); + } + + const sc = try a.alloc(u16, rows * coeff_width); + defer a.free(sc); + const sn = try a.alloc(u16, rows * h); + defer a.free(sn); + const sxs = try a.alloc(f32, rows); + defer a.free(sxs); + try preNormSim(a, pin, rows, p, .{ .coeff = sc, .norm = sn, .xs = sxs }); + for (wn, sn) |ref_v, sim_bits| { + const sim_v: f64 = @as(f64, fromBf16(sim_bits)); + try std.testing.expect(@abs(ref_v - sim_v) <= @abs(ref_v) * 0x1p-6 + 0x1p-12); + } + + const r_fused = try a.alloc(u16, rows * 2 * h); + defer a.free(r_fused); + const c_fused = try a.alloc(u16, rows * coeff_width); + defer a.free(c_fused); + const n_fused = try a.alloc(u16, rows * h); + defer a.free(n_fused); + const xs_fused = try a.alloc(f32, rows); + defer a.free(xs_fused); + try postAndPreNormSim(a, r_in, y_in, sc, w, &b, sub_w, rows, p, r_fused, .{ .coeff = c_fused, .norm = n_fused, .xs = xs_fused }); + + const r_seq = try a.alloc(u16, rows * 2 * h); + defer a.free(r_seq); + const c_seq = try a.alloc(u16, rows * coeff_width); + defer a.free(c_seq); + const n_seq = try a.alloc(u16, rows * h); + defer a.free(n_seq); + const xs_seq = try a.alloc(f32, rows); + defer a.free(xs_seq); + postMergeSim(r_in, y_in, sc, rows, h, false, r_seq); + try preNormSim(a, .{ .r_in = r_seq, .w = w, .b = &b, .sub_w = sub_w }, rows, p, .{ .coeff = c_seq, .norm = n_seq, .xs = xs_seq }); + try std.testing.expectEqualSlices(u16, r_seq, r_fused); + try std.testing.expectEqualSlices(u16, c_seq, c_fused); + try std.testing.expectEqualSlices(u16, n_seq, n_fused); + try std.testing.expectEqualSlices(f32, xs_seq, xs_fused); +} diff --git a/zig/src/families/sensenova_loop/sensenova_loop.zig b/zig/src/families/sensenova_loop/sensenova_loop.zig new file mode 100644 index 00000000000..e8b1873fda8 --- /dev/null +++ b/zig/src/families/sensenova_loop/sensenova_loop.zig @@ -0,0 +1,14 @@ +//! SenseNova-Loop core family: config, 56-step looped plan, mHC kernels, AWQ W4A16 & BF16 linear ops. +pub const config = @import("config.zig"); +pub const mhc_ref = @import("mhc_ref.zig"); +pub const mhc_metal = @import("mhc_metal.zig"); +pub const awq = @import("awq.zig"); +pub const linear_gpu = @import("linear_gpu.zig"); + +test { + _ = config; + _ = mhc_ref; + _ = mhc_metal; + _ = awq; + _ = linear_gpu; +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index e8462e4915a..80016bf995e 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -8,6 +8,7 @@ const lanes = tf.lanes; const nemotron = tf.nemotron; const Allocator = std.mem.Allocator; const qwen27 = @import("qwen27_served.zig"); +const q27_eng = @import("qwen27_engine.zig"); const flashnext = @import("flashnext_host.zig"); const glm = @import("glm_host.zig"); const glm_dsa = @import("glm_dsa_host.zig"); @@ -53,6 +54,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "glm5_next", .formats = &.{"mlx-q4g64"} }, .{ .model_type = "qwen3_5", .formats = affine_widths }, .{ .model_type = "qwen3_5_moe", .formats = affine_widths }, + .{ .model_type = "sensenova_loop", .formats = &.{ "bf16", "awq" } }, .{ .model_type = "lfm3", .formats = &.{ "mlx-q4g32", "mlx-q4g64", "mlx-q6g64", "mlx-q8g64" } }, .{ .model_type = "lfm3_vl", .formats = &.{ "mlx-q4g32", "mlx-q4g64", "mlx-q6g64", "mlx-q8g64" } }, .{ .model_type = "lfm2_moe", .formats = &.{ "mlx-q4g64", "mlx-q6g64", "mlx-q8g64" } }, @@ -129,7 +131,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c const report = @import("sys").optional_libraries.atBoundary(); defer report.deinit(); if (fsr_options.refuse(o, problem)) return null; - if (o.prompt_int8 or o.rope_yarn != null) { + if (o.prompt_int8 or (o.rope_yarn != null and !q27_eng.isSenseNova(o.model_type))) { problem.* = if (o.prompt_int8) prompt_int8_refusal else "--rope-yarn: the Metal engine has no YaRN rope; serve without --rope-yarn"; return null; } @@ -144,7 +146,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (std.mem.eql(u8, o.model_type, "qwen4") or std.mem.eql(u8, o.model_type, "qwen4_text")) return @import("qwen4_metal.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen3")) return @import("qwen3_metal.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "hy_v4_flash")) return @import("hy4_metal.zig").open(a, gpa, io, o, problem); - const dense = ownsQwen27(a, io, o.model_type, o.dir); + const dense = q27_eng.isSenseNova(o.model_type) or q27_eng.ownsQwen27(a, io, o.model_type, o.dir); if (try refusal(a, o, dense)) |why| { problem.* = why; return null; @@ -291,52 +293,40 @@ const recall_refusal = "--recall drafts from a record in the lane engine's round /// Refused before any weights load: absent family learners and unsupported disk-state options. fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { const t = o.model_type; + const loop_sn = q27_eng.isSenseNova(t); if (o.kv8) return "--kv-cache fp8 keeps fp8 caches on CUDA; the Metal engines keep bf16: serve without it"; if (o.prompt_int8) return prompt_int8_refusal; if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; if (@import("qwen27_mtp.zig").refusal(o.mtp_drafts, o.mtp_confidence, o.drafter != null, std.mem.eql(u8, t, "qwen3_5") and dense)) |why| return why; - if (o.drafter != null and !dense and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop") and !std.mem.eql(u8, t, "ricursive")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark), Llama (a smaller Llama on the same tokenizer) and Ripple (its DFlash2 drafter)"; - const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; + if (o.drafter != null and (!dense or loop_sn) and !isGemma4(t) and !std.mem.eql(u8, t, "llama") and !std.mem.eql(u8, t, "qwen3_5_moe") and !std.mem.eql(u8, t, "flint") and !std.mem.eql(u8, t, "glm5_next") and !std.mem.eql(u8, t, "inkling2_loop") and !std.mem.eql(u8, t, "ricursive")) return "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head), Qwen3.5-MoE (qwen3_5_moe), GLM-5.3-Flash (glm5_next), Gemma 4 dense, Flint (DFlash2 on M5), Inkling 2 Mini (DSpark), Llama (a smaller Llama on the same tokenizer) and Ripple (its DFlash2 drafter)"; + const one_mac: ?[]const u8 = if (loop_sn) "SenseNova-Loop" else if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "nemotron_h_puzzle")) "Nemotron 3.5 Bolt" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; if (spill.refusal(o)) |why| return why; if (o.learn == null) return null; - // the 27B writes conversation states - if (o.learn_conversations and std.mem.eql(u8, t, "qwen3_5") and dense) return null; - const name: []const u8 = if (std.mem.eql(u8, t, "glm_moe_dsa")) "GLM-5.3 (EXLR8)" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) return null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; + // the 27B and SenseNova-Loop write conversation states + if (o.learn_conversations and (loop_sn or (std.mem.eql(u8, t, "qwen3_5") and dense))) return null; + const name: []const u8 = if (loop_sn) "SenseNova-Loop" else if (std.mem.eql(u8, t, "glm_moe_dsa")) "GLM-5.3 (EXLR8)" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (std.mem.eql(u8, t, "qwen3_5_moe")) "Qwen3.5-MoE" else if (std.mem.eql(u8, t, "llama")) "Llama" else if (std.mem.eql(u8, t, "flint")) "Flint" else if (std.mem.eql(u8, t, "unlimited-ocr")) "Unlimited-OCR-2" else if (std.mem.eql(u8, t, "ricursive")) "Ripple" else if (!std.mem.eql(u8, t, "qwen3_5")) return null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.learn_conversations) return try std.fmt.allocPrint(a, "{s} keeps conversation states on disk for Qwen3.8-27B, Nemotron, Flash Next and GLM-5.3-Flash: serve {s} without it", .{ spill.flag(o), name }); - const or_talks: []const u8 = if (dense and std.mem.eql(u8, t, "qwen3_5")) " (Qwen3.8-27B keeps conversation states on disk with --learn-conversations)" else ""; + const or_talks: []const u8 = if (loop_sn) " (keeps conversation states on disk with --learn-conversations)" else if (dense and std.mem.eql(u8, t, "qwen3_5")) " (Qwen3.8-27B keeps conversation states on disk with --learn-conversations)" else ""; return try std.fmt.allocPrint(a, "--learn learns prompt prefixes for Nemotron, Flash Next and GLM-5.3-Flash only{s}: serve {s} without --learn, --learn-dir or --learn-gib", .{ or_talks, name }); } -/// Whether `dir` opens on the Qwen3.8-27B-class engine: the 27B-class qwen3_5 checkpoints, and Qwen3.5-MoE. -fn ownsQwen27(a: Allocator, io: std.Io, t: []const u8, dir: []const u8) bool { - return (std.mem.eql(u8, t, "qwen3_5") and @import("qwen27_engine.zig").owns(a, io, dir, @import("sys").environment.read(bool, "TF_QWEN27_TIED_HEAD", false) catch false)) or std.mem.eql(u8, t, "qwen3_5_moe"); -} - -/// The context a Qwen3.8-27B-class start serves (--context, else 32,768); null with `problem` set past 1 to 262,144. -fn qwen27Context(a: Allocator, context: ?i64, problem: *[]const u8) !?u32 { - const n = context orelse 32768; - if (n <= 0 or n > 262144) { - problem.* = try std.fmt.allocPrint(a, "--context {d} is outside this Qwen checkpoint's 1 to 262,144 tokens", .{n}); - return null; - } - return @intCast(n); -} pub const Qwen27Budget = @import("qwen27_reserve.zig").Budget; /// What a Qwen3.8-27B-class start keeps free of its working set. pub const qwen27_margin = tf.qwen27.prompt_memory.margin; /// `serve`'s startup charge for a Qwen3.8-27B-class `dir` (no drafter or images); null for others or a refused context. pub fn qwen27Budget(a: Allocator, io: std.Io, t: []const u8, dir: []const u8, weights: u64, context: ?i64, streams: u32, fixed: bool, problem: *[]const u8) !?Qwen27Budget { - if (!ownsQwen27(a, io, t, dir)) return null; - const n = try qwen27Context(a, context, problem) orelse return null; + if (!q27_eng.ownsQwen27(a, io, t, dir)) return null; + const n = try q27_eng.qwen27Context(a, context, problem) orelse return null; return try @import("qwen27_reserve.zig").budget(a, io, dir, weights, n, streams, fixed); } -/// Qwen3.8-27B and Qwen3.5-MoE on the lane host: shared rounds, DFlash2 drafts for up to TF_Q27_DRAFT_SLOTS streams. +/// Qwen3.8-27B, Qwen3.5-MoE and SenseNova-Loop-9B on the lane host. fn openQwen27(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { - const context = try qwen27Context(a, o.context, problem) orelse return null; + const sn = q27_eng.isSenseNova(o.model_type); + const context = try q27_eng.laneContext(a, io, sn, o.dir, o.rope_yarn, o.context, problem) orelse return null; if (o.drafts and o.drafter != null and o.drafter_bits != 0 and o.drafter_bits != 4) { problem.* = "--drafter-bits takes 0 (bf16) or 4"; return null; @@ -344,8 +334,8 @@ fn openQwen27(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[ var why: []const u8 = ""; const drafter = if (o.drafts) o.drafter else null; const learn: ?@import("qwen27_disk.zig").Learn = if (o.learn_conversations) if (o.learn) |root| .{ .root = root, .dir = o.dir, .drafter = drafter, .cap = gibBytes(o.learn_gib), .floor = gibBytes(o.learn_min_free_gib), .daily = gibBytes(o.learn_daily_gib), .spill = o.spill, .slots = spill.slots(o) } else null else null; - const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .mtp_drafts = if (o.drafts) o.mtp_drafts else null, .mtp_confidence = o.mtp_confidence, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .learn = learn, .vision = o.vision }, a, &why) catch |err| { - problem.* = if (why.len > 0) why else try std.fmt.allocPrint(a, "the native Qwen engine (27B class) cannot load {s} ({s})", .{ o.dir, @errorName(err) }); + const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .mtp_drafts = if (o.drafts) o.mtp_drafts else null, .mtp_confidence = o.mtp_confidence, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .learn = learn, .vision = o.vision, .rope_yarn = if (sn) o.rope_yarn else null }, a, &why) catch |err| { + problem.* = if (why.len > 0) why else try std.fmt.allocPrint(a, "the native {s} engine cannot load {s} ({s})", .{ if (sn) "SenseNova" else "Qwen (27B class)", o.dir, @errorName(err) }); return null; }; return .{ .engine = h.engine(), .close = qwen27.close, .ctx = h }; @@ -598,3 +588,7 @@ test "plain sharing: Nemotron without a head shares streams without widening its try std.testing.expectEqual(@as(u32, 0), config.most_drafts); try std.testing.expect(!config.family_mtp); } + +test "qwen27 rope policy: --rope-yarn and resolved ceiling refusals" { + try @import("slide_open_test.zig").qwen27RopeChecks(open); +} diff --git a/zig/src/native/qwen27_disk.zig b/zig/src/native/qwen27_disk.zig index 422a056b81b..fa1d6fd6c04 100644 --- a/zig/src/native/qwen27_disk.zig +++ b/zig/src/native/qwen27_disk.zig @@ -89,7 +89,7 @@ pub fn identity(h: *Host, io: std.Io, a: Allocator, dir: []const u8, drafter: ?[ // a state written with the MTP head holds its keys and values too, so it is read only with the head @import("qwen27_mtp_flags.zig").identityWords(&w, &words, h.mtp != null); disk_identity.machine(&w, std.mem.span(h.model.device.name())); - disk_identity.profile(&w, .{ .family = if (h.model.config.moe()) "qwen3_5_moe" else "qwen3_5", .backend = "metal" }); + disk_identity.profile(&w, .{ .family = if (h.model.config.looped) "sensenova_loop" else if (h.model.config.moe()) "qwen3_5_moe" else "qwen3_5", .backend = "metal" }); return .{ .id = withPolicy(w.final(), h), .rate = p.rate }; } diff --git a/zig/src/native/qwen27_engine.zig b/zig/src/native/qwen27_engine.zig index 74f4e09f519..a987c9f2ffe 100644 --- a/zig/src/native/qwen27_engine.zig +++ b/zig/src/native/qwen27_engine.zig @@ -18,6 +18,52 @@ pub fn owns(a: Allocator, io: std.Io, dir: []const u8, tied_on: bool) bool { return !tied or tied_on; } +/// True for looped SenseNova checkpoints (`sensenova_loop`). +pub fn isSenseNova(model_type: []const u8) bool { + return std.mem.eql(u8, model_type, "sensenova_loop"); +} + +/// Whether `dir` opens on the Qwen3.8-27B-class engine: the 27B-class qwen3_5 checkpoints, and Qwen3.5-MoE. +pub fn ownsQwen27(a: Allocator, io: std.Io, t: []const u8, dir: []const u8) bool { + return (std.mem.eql(u8, t, "qwen3_5") and owns(a, io, dir, @import("sys").environment.read(bool, "TF_QWEN27_TIED_HEAD", false) catch false)) or std.mem.eql(u8, t, "qwen3_5_moe"); +} + +/// The context a Qwen3.8-27B-class start serves (--context, else 32,768); null with `problem` set past 1 to 262,144. +pub fn qwen27Context(a: Allocator, context: ?i64, problem: *[]const u8) !?u32 { + const n = context orelse 32768; + if (n <= 0 or n > 262144) { + problem.* = try std.fmt.allocPrint(a, "--context {d} is outside this Qwen checkpoint's 1 to 262,144 tokens", .{n}); + return null; + } + return @intCast(n); +} + +/// Validates and resolves `--context` for Qwen3.8-27B-class (`1..262144`) or `sensenova_loop` (config/YaRN ceiling). +pub fn laneContext(a: Allocator, io: std.Io, sn: bool, dir: []const u8, rope_yarn: ?f64, context: ?i64, problem: *[]const u8) !?u32 { + if (!sn) return qwen27Context(a, context, problem); + const n = context orelse 32768; + if (n <= 0) { + problem.* = try std.fmt.allocPrint(a, "--context {d} is outside this SenseNova checkpoint's context window", .{n}); + return null; + } + if (!try senseNovaContextOk(a, io, dir, rope_yarn, n, problem)) return null; + return @intCast(n); +} + +/// Validates a `sensenova_loop` context request against the checkpoint's resolved base or YaRN ceiling. +pub fn senseNovaContextOk(a: Allocator, io: std.Io, dir: []const u8, rope_yarn: ?f64, context: i64, problem: *[]const u8) !bool { + const max_ctx: i64 = @intCast(tf.qwen27.config.senseNovaMaxContext(a, io, dir, rope_yarn) catch |err| { + problem.* = switch (err) { + error.UnsupportedRopeScaling, error.RopeYarnFactor, error.RopeYarnConflict => "--rope-yarn / rope_parameters: static YaRN (factor > 1) is supported on looped SenseNova checkpoints without conflicting factors", + else => try std.fmt.allocPrint(a, "the native SenseNova engine cannot load {s} ({s})", .{ dir, @errorName(err) }), + }; + return false; + }); + if (context <= max_ctx) return true; + problem.* = try std.fmt.allocPrint(a, "--context {d} is outside this SenseNova checkpoint's 1 to {d} tokens", .{ context, max_ctx }); + return false; +} + test "a qwen3_5 checkpoint opens the 27B engine unless it has the 2B's geometry or a tied head" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/zig/src/native/qwen27_images.zig b/zig/src/native/qwen27_images.zig index c42c04b20de..6b76dfb6171 100644 --- a/zig/src/native/qwen27_images.zig +++ b/zig/src/native/qwen27_images.zig @@ -72,10 +72,14 @@ pub fn open(gpa: Allocator, io: std.Io, model: *const q.model.Model, dir: []cons v.* = .{ .gpa = gpa, .c = c, .tower = undefined, .rows = undefined, .capacity = o.image_tokens, .max_images = o.max_images, .markers = .{ c.vision_start, c.image_token, c.vision_end } }; // one image a pass: the tower's scratch holds the largest image the processor makes under the request's budget const largest: u32 = @intCast(@min(@as(u64, o.image_tokens), c.max_pixels / (@as(u64, c.factor()) * c.factor()))); - v.tower = try Tower.load(gpa, io, model.device, dir, c, largest); + const visual_prefixes = [_][]const u8{ tf.qwen_vl_tower.weights.prefix, "model.visual." }; + v.tower = if (mc.looped) + try Tower.loadWithPrefixes(gpa, io, model.device, dir, c, largest, model.device, &visual_prefixes) + else + try Tower.load(gpa, io, model.device, dir, c, largest); errdefer v.tower.deinit(); v.rows = try model.device.buffer(@as(usize, o.image_tokens) * mc.hidden * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); - std.log.info("Qwen3.8-27B: image tower loaded ({d:.2} GiB with scratch for {d} image tokens a request)", .{ @as(f64, @floatFromInt(v.tower.bytes + v.rows.length())) / (1 << 30), o.image_tokens }); + std.log.info("{s}: image tower loaded ({d:.2} GiB with scratch for {d} image tokens a request)", .{ if (mc.looped) "SenseNova-Loop" else "Qwen3.8-27B", @as(f64, @floatFromInt(v.tower.bytes + v.rows.length())) / (1 << 30), o.image_tokens }); return v; } diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index 43f840d7b98..9a56ebcea09 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -109,7 +109,8 @@ pub const Metal = struct { const device = runner.model.device; const tensor_units = device.tensorUnits(); const window = try windowRows(tensor_units); - const copies = try @import("qwen27_window.zig").copyPolicy(tensor_units, window, if (platform.c.getenv("TF_QWEN27_COPIES")) |v| std.mem.span(v) else null); + const copies_env = if (platform.c.getenv("TF_QWEN27_COPIES")) |v| std.mem.span(v) else null; + const copies = try @import("qwen27_window.zig").copyPolicy(tensor_units, window, copies_env orelse if (runner.model.config.looped) "1" else null); const ops = try tf.tree_round_gpu.Ops.init(device); errdefer ops.deinit(); const picks = try device.buffer(batch_rows * @sizeOf(contract.Pick), opts); @@ -178,7 +179,7 @@ pub const Metal = struct { const narrow: usize = @min(b.window, b.timed); // routed experts make a drafted window read most expert weights: plain rounds compete with drafted depths const routed = b.runner.model.config.moe(); - return .{ .exact_width = if (drafting or shared) b.window else 1, .mtp = drafting, .speculate = drafting, .speculate_early = false, .drafts = b.nodes, .draft_probabilities = true, .plain_guard = routed, .window_costs = b.costs[0..narrow], .shared_costs = b.costs[narrow..b.timed], .hidden_rows = shared, .streams_exact = true, .batch_rows = if (shared) batch_rows else b.window, .max_streams = b.runner.slots, .lone_copies = lone_copies, .context_copies = lone_copies, .allocate_shared_drafts = drafting, .draft_streams = drafting and b.draft_slots > 1 }; + return .{ .exact_width = if (drafting or shared or lone_copies) b.window else 1, .mtp = drafting, .speculate = drafting, .speculate_early = false, .drafts = b.nodes, .draft_probabilities = true, .plain_guard = routed, .window_costs = b.costs[0..narrow], .shared_costs = b.costs[narrow..b.timed], .hidden_rows = shared, .streams_exact = true, .batch_rows = if (shared) batch_rows else b.window, .max_streams = b.runner.slots, .lone_copies = lone_copies, .context_copies = lone_copies, .allocate_shared_drafts = drafting, .draft_streams = drafting and b.draft_slots > 1 }; } /// The slot holding `s`. @@ -279,21 +280,30 @@ pub const Metal = struct { pens.applyRow(row, logits); } + fn encodeArgmaxRange(b: *const Metal, e: mtl.ComputeEncoder, first: usize, rows: usize) !void { + const logits = b.runner.model.frame.get(.logits); + const vocab: u32 = @intCast(b.runner.model.config.vocab); + var at = first; + while (at < first + rows) : (at += contract.max_rows) { + const n = @min(first + rows - at, contract.max_rows); + try b.ops.argmax(e, .{ .buf = logits.buffer, .off = logits.offset + at * vocab * 2 }, .{ .buf = b.picks, .off = at * @sizeOf(contract.Pick) }, .{ .rows = @intCast(n), .vocab = vocab, .stride = vocab }); + } + } + + fn encodeArgmaxTail(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { + const b = self(ptr); + try b.encodeArgmaxRange(e, 0, b.rows); + } + /// Rows [first, first + rows)'s greedy picks into `picks` at the same rows: one command buffer and one wait. fn argmaxRows(b: *Metal, first: usize, rows: usize) !void { const metric = mtl.pass_metrics.phase(.sampling); defer metric.end(); - const logits = b.runner.model.frame.get(.logits); - const vocab: u32 = @intCast(b.runner.model.config.vocab); const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = b.runner.model.queue.commandBuffer(); const e = cb.compute(.serial); - var at = first; - while (at < first + rows) : (at += contract.max_rows) { - const n = @min(first + rows - at, contract.max_rows); - try b.ops.argmax(e, .{ .buf = logits.buffer, .off = logits.offset + at * vocab * 2 }, .{ .buf = b.picks, .off = at * @sizeOf(contract.Pick) }, .{ .rows = @intCast(n), .vocab = vocab, .stride = vocab }); - } + try b.encodeArgmaxRange(e, first, rows); e.end(); cb.commit(); cb.wait(); @@ -485,18 +495,23 @@ pub const Metal = struct { b.pens.clear(); // each penalized window's rows: the reply, its pending token, then the row's own path for (windows, b.round.?.firsts) |w, first| try b.pens.stageWindow(b.gpa, w, b.ids[first + 1 ..][0 .. w.rows() - 1], first); const fused = windows.len == 1 and b.windows[0] == 0 and b.draft != null and total > 1 and windows[0].stream.sampling == null and windows[0].masks.len == 0 and b.pens.len() == 0; + // every greedy window's rows from one argmax over the round; a sampled window draws on the host + var greedy = false; + for (windows) |w| greedy = greedy or (w.stream.sampling == null and w.masks.len == 0 and !w.stream.penalties.active()); + const tail_argmax = r.model.config.looped and !fused and greedy and r.reduce == null; std.debug.assert(r.tail == null); - if (fused) r.tail = .{ .ptr = b, .encode = @import("qwen27_keep.zig").encodeTail }; + if (fused) { + r.tail = .{ .ptr = b, .encode = @import("qwen27_keep.zig").encodeTail }; + } else if (tail_argmax) { + r.tail = .{ .ptr = b, .encode = encodeArgmaxTail }; + } defer r.tail = null; const before = r.gpu_seconds; if (plain) try r.advance(&b.round.?, .all) else try r.verifyHead(&b.round.?, .all); for (windows) |w| slots.charge(b, w.stream, before); // a shared round counts whole in each reply b.advanced = plain; b.rows = total; - // every greedy window's rows from one argmax over the round; a sampled window draws on the host - var greedy = false; - for (windows) |w| greedy = greedy or (w.stream.sampling == null and w.masks.len == 0 and !w.stream.penalties.active()); - if (fused) try @import("qwen27_keep.zig").finishPrefetch(b) else if (greedy) try b.argmaxRows(0, total); + if (fused) try @import("qwen27_keep.zig").finishPrefetch(b) else if (greedy and !tail_argmax) try b.argmaxRows(0, total); for (windows, out, b.round.?.firsts) |w, o, first| { const rows = w.rows(); const pens = w.stream.penalties.active(); diff --git a/zig/src/native/qwen27_reserve.zig b/zig/src/native/qwen27_reserve.zig index dfc16c21c15..137c04e36b2 100644 --- a/zig/src/native/qwen27_reserve.zig +++ b/zig/src/native/qwen27_reserve.zig @@ -30,10 +30,15 @@ pub fn requested(generation: u32, moe: bool) u32 { return q.prompt_rows.requested(generation, moe, rowsValue()); } +/// The prompt rows asked for on `c`: a valid TF_PROMPT_ROWS, else the chip and family default. +pub fn requestedFor(generation: u32, c: Config) u32 { + return q.prompt_rows.requestedModel(generation, c.moe(), c.looped, rowsValue()); +} + /// The prompt rows startup takes: the request when it fits (always when named), never under the window. pub fn rows(f: memory.Fit, generation: u32, window: u32) !u32 { const geometry = try q.attention_plan.Geometry.fromConfig(f.config, f.shared); - const wanted = q.prompt_rows.frameRequested(generation, f.config.moe(), rowsValue(), geometry); + const wanted = if (f.config.looped) requestedFor(generation, f.config) else q.prompt_rows.frameRequested(generation, f.config.moe(), rowsValue(), geometry); return @max(window, try f.choose(wanted, q.prompt_rows.override(rowsValue()) != null)); } diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 14f4c41f280..8e475e68682 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -41,6 +41,7 @@ pub const Options = struct { learn: ?disk.Learn = null, // --learn-conversations: kept states written behind to disk and read back vision: ?api.VisionOpen = null, // --vision: open loads the image tower, and requests may hold images images: ?*images.Vision = null, // the loaded tower attach serves (and the host then owns) + rope_yarn: ?f64 = null, }; pub const Host = struct { @@ -287,7 +288,12 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, o: Options, a: Allocato why.* = try drafterRefusal(a, dir, d, err); return err; }; - const model = try q.model.Model.loadDeferred(gpa, io, dir, reserve.loaded_rows); + const model = q.model.Model.loadDeferredOpts(gpa, io, dir, reserve.loaded_rows, .{ .rope_yarn = o.rope_yarn }) catch |err| { + if (err == error.UnsupportedRopeScaling or err == error.RopeYarnFactor or err == error.RopeYarnConflict) { + why.* = try std.fmt.allocPrint(a, "--rope-yarn / rope_parameters ({s}): YaRN requires valid factor and original_max_position_embeddings matching max_position_embeddings", .{@errorName(err)}); + } + return err; + }; errdefer model.deinit(); if (@import("qwen27_mtp_flags.zig").deviceRefusal(o.mtp_drafts, model.device.tensorUnits(), try q.decode_round.pagesOn())) |r| { why.* = r.why; @@ -390,7 +396,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.back = try lb.Metal.init(gpa, &h.runner, h.draft); errdefer h.back.deinit(); h.back.serial_copy_match = policy.serialCopyMatch(units, window, lanes_value); - h.back.chunk = h.runner.promptRows(@min(rows, reserve.requested(model.device.generation(), model.config.moe()))); + h.back.chunk = h.runner.promptRows(@min(rows, reserve.requestedFor(model.device.generation(), model.config))); h.back.grow = .{ .ctx = h, .room = Host.roomFor, .added = Host.added }; h.runner.grown = .{ .ctx = h, .added = Host.added }; h.back.vision = o.images; diff --git a/zig/src/native/qwen27_shared_policy_test.zig b/zig/src/native/qwen27_shared_policy_test.zig index a63c37596f4..2824df69852 100644 --- a/zig/src/native/qwen27_shared_policy_test.zig +++ b/zig/src/native/qwen27_shared_policy_test.zig @@ -20,7 +20,7 @@ const Counted = struct { test "qwen27 grants: native shared proposals do not spend nodes beyond the verified grants" { var model: tf.qwen27.model.Model = undefined; - model.config = std.mem.zeroes(@TypeOf(model.config)); + model.config = std.mem.zeroInit(@TypeOf(model.config), .{}); var runner: tf.qwen27.decode_round.Runner = undefined; runner.slots = 4; runner.model = &model; diff --git a/zig/src/native/slide_open_test.zig b/zig/src/native/slide_open_test.zig index fad7728770a..cc1c6d1f004 100644 --- a/zig/src/native/slide_open_test.zig +++ b/zig/src/native/slide_open_test.zig @@ -39,3 +39,36 @@ pub fn message(comptime open: anytype, model: []const u8, want: []const u8) !voi try std.testing.expect((try open(arena.allocator(), std.testing.allocator, std.testing.io, o, &why)) == null); try std.testing.expectEqualStrings(want, why); } + +pub fn qwen27RopeChecks(comptime open: anytype) !void { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var why: []const u8 = ""; + try std.testing.expect((try open(a, std.testing.allocator, io, .{ .dir = "d", .model_type = "qwen3_5", .rope_yarn = 2.0 }, &why)) == null); + try std.testing.expectEqualStrings("--rope-yarn: the Metal engine has no YaRN rope; serve without --rope-yarn", why); + try std.testing.expect((try open(a, std.testing.allocator, io, .{ .dir = "d", .model_type = "qwen3_5", .context = 300000 }, &why)) == null); + try std.testing.expectEqualStrings("--context 300000 is outside this Qwen checkpoint's 1 to 262,144 tokens", why); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const cfg_text = + \\{"model_type":"sensenova_loop","loop_settings":{"start":0,"end":4,"eval_count":2,"counts":[2]}, + \\"eos_token_id":1,"tie_word_embeddings":false,"text_config":{"hidden_size":64,"intermediate_size":128, + \\"num_hidden_layers":4,"num_attention_heads":4,"num_key_value_heads":2,"head_dim":32,"vocab_size":97, + \\"layer_types":["linear_attention","linear_attention","linear_attention","full_attention"], + \\"linear_num_key_heads":2,"linear_num_value_heads":4,"linear_key_head_dim":16, + \\"linear_value_head_dim":16,"linear_conv_kernel_dim":4,"max_position_embeddings":262144, + \\"partial_rotary_factor":0.5,"tie_word_embeddings":false,"rope_parameters":{"rope_type":"yarn","factor":1.0, + \\"original_max_position_embeddings":262144,"rope_theta":10000000,"partial_rotary_factor":0.5, + \\"mrope_interleaved":true,"mrope_section":[3,3,2]}}} + ; + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = cfg_text }); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + try std.testing.expect((try open(a, std.testing.allocator, io, .{ .dir = dir, .model_type = "sensenova_loop", .context = 300000 }, &why)) == null); + try std.testing.expectEqualStrings("--context 300000 is outside this SenseNova checkpoint's 1 to 262144 tokens", why); + why = ""; + if (try open(a, std.testing.allocator, io, .{ .dir = dir, .model_type = "sensenova_loop", .context = 300000, .rope_yarn = 2.0 }, &why)) |*o| o.close(o.ctx); + try std.testing.expect(std.mem.indexOf(u8, why, "outside this SenseNova checkpoint's") == null); + try std.testing.expect(std.mem.indexOf(u8, why, "no YaRN rope") == null); +} diff --git a/zig/src/qwen27_rows_test.zig b/zig/src/qwen27_rows_test.zig index 5c6f88bf6d3..aab9a8c4c80 100644 --- a/zig/src/qwen27_rows_test.zig +++ b/zig/src/qwen27_rows_test.zig @@ -62,6 +62,13 @@ const Device = struct { return d.units; } }; + +test "qwen27 rows: looped SenseNova-Loop widens its default from generation 15" { + for ([_]u32{ 0, 13, 14 }) |generation| try std.testing.expectEqual(@as(u32, 512), rows.requestedModel(generation, false, true, null)); + for ([_]u32{ 15, 16, 17, 18 }) |generation| try std.testing.expectEqual(@as(u32, 2048), rows.requestedModel(generation, false, true, null)); + for ([_]u32{ 0, 15, 17 }) |generation| try std.testing.expectEqual(@as(u32, 1024), rows.requestedModel(generation, true, true, null)); +} + const Backend = struct { runner: struct { slots: usize = 3, diff --git a/zig/src/qwen27_speed_test.zig b/zig/src/qwen27_speed_test.zig index baeaa3c700d..39fb26fc268 100644 --- a/zig/src/qwen27_speed_test.zig +++ b/zig/src/qwen27_speed_test.zig @@ -41,11 +41,11 @@ test "qwen27 speed: secondary tap chunks preserve source indices, guards, tails test "qwen27 speed: prompt parts fit the actual fused or unfused attention plan" { var parents: [2048]i32 = undefined; for (&parents, 0..) |*p, i| p.* = @as(i32, @intCast(i)) - 1; - for ([_]bool{ true, false }) |tensor| for ([_]bool{ true, false }) |fuse| { - const geometry = planning.Geometry{ .shared_prefix = tensor, .fuse_chain = fuse }; + for ([_]bool{ true, false }) |tensor| for ([_]bool{ true, false }) |fuse| for ([_]bool{ false, true }) |wide| { + const geometry = planning.Geometry{ .shared_prefix = tensor, .fuse_chain = fuse, .wide_prompt = wide }; for ([_]u32{ 16, 128, 129, 512, 2048 }) |requested| { const part = geometry.promptRows(requested); - const want = @min(requested, @as(u32, if (tensor and fuse) @import("families/qwen27/gpu_frame.zig").max_rows else planning.max_rows)); + const want = @min(requested, @as(u32, if (fuse and (tensor or wide)) @import("families/qwen27/gpu_frame.zig").max_rows else planning.max_rows)); try std.testing.expectEqual(want, part); for ([_]u32{ 128, 129, 512, 2051 }) |length| { var at: u32 = 0; diff --git a/zig/src/server/family_sampling.zig b/zig/src/server/family_sampling.zig index 91ee96ae425..3e1ffda5d1d 100644 --- a/zig/src/server/family_sampling.zig +++ b/zig/src/server/family_sampling.zig @@ -20,9 +20,9 @@ pub fn put(a: std.mem.Allocator, out: *json.Object, model_type: []const u8) !voi try out.put(a, "top_p", .{ .float = 1.0 }); } -/// Qwen 3.5, 3.6, Qwen3.8-27B and Flash-Next cards: a thinking set (generation_config.json) and an instruct set. +/// Qwen 3.5, 3.6, 27B, SenseNova-Loop and Flash-Next: thinking set (generation_config) and instruct set. pub fn hasInstruct(model_type: []const u8) bool { - for ([_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text", "qwen4_exp", "qwen4_exp_text" }) |t| { + for ([_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text", "qwen4_exp", "qwen4_exp_text", "sensenova_loop" }) |t| { if (std.mem.eql(u8, model_type, t)) return true; } return false; @@ -193,7 +193,7 @@ test "--instruct-sampling card serves the Qwen cards' instruct set under the fla defer arena.deinit(); const a = arena.allocator(); const cfg = "{\"do_sample\": true, \"temperature\": 1.0, \"top_k\": 20, \"top_p\": 0.95}"; - for ([_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text", "qwen4_exp", "qwen4_exp_text" }) |kind| { + for ([_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text", "qwen4_exp", "qwen4_exp_text", "sensenova_loop" }) |kind| { const thinking = (try resolve(a, kind, cfg, .{})).?; try std.testing.expectEqual(@as(f64, 1.0), thinking.get("temperature").?.float); try std.testing.expect(thinking.get("presence_penalty") == null); diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 14b23673d47..361eb32294b 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -41,6 +41,7 @@ pub const segments = @import("core/segments.zig"); pub const prompt_tail = @import("core/prompt_tail.zig"); pub const row_projection = @import("core/row_projection.zig"); pub const frags = @import("core/frags.zig"); +pub const rope_yarn = @import("core/rope_yarn.zig"); pub const affine_mm = @import("core/affine_mm.zig"); pub const moe_route = @import("core/moe_route.zig"); /// The checkpoint formats (MLX affine and its fp64 reader for the device checks, exact widen). @@ -93,6 +94,7 @@ pub const ricursive = @import("families/ricursive/ricursive.zig"); pub const lfm2_moe = @import("families/lfm2_moe/lfm2_moe.zig"); pub const flashnext_pack = @import("families/flashnext/pack.zig"); pub const lfm3 = @import("families/lfm3/lfm3.zig"); +pub const sensenova_loop = @import("families/sensenova_loop/sensenova_loop.zig"); test { std.testing.refAllDecls(@This()); diff --git a/zig/tests/contract/metal_limits_all.zig b/zig/tests/contract/metal_limits_all.zig index b2ee00e8539..38691d7acbc 100644 --- a/zig/tests/contract/metal_limits_all.zig +++ b/zig/tests/contract/metal_limits_all.zig @@ -8,6 +8,8 @@ pub fn gate(a: std.mem.Allocator, io: std.Io, device: mtl.Device, offline: ?[]co problems += try @import("metal_gemma4_embed.zig").limits(a, device, only); problems += try @import("metal_gemma4_mixed.zig").limits(a, device, only); problems += try @import("metal_llama_all.zig").limits(a, device, device.tensorUnits(), only); + problems += try @import("metal_sensenova_mhc.zig").limits(a, io, device, offline, only); + problems += try @import("metal_sensenova_linear.zig").limits(a, device, only); return problems; } diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index c78c29340ff..e4fe597a9aa 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -569,6 +569,11 @@ pub fn main(init: std.process.Init) !u8 { defer h3_image_suites.destroy(); var dsv41_suites = try @import("metal_dsv41_main.zig").Suites.create(a, device, queue, &kernels, o.only); defer dsv41_suites.destroy(); + const sn_mhc = try @import("metal_sensenova_mhc.zig").Suite.create(a, device, queue, &kernels, o.only); + defer sn_mhc.destroy(); + var sn_lin = @import("metal_sensenova_linear.zig").Suite{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; + defer sn_lin.deinit(); + try sn_lin.collect(o.only); const idol = try @import("metal_idol.zig").Suite.create(a, device, queue, &kernels, o.only); defer idol.destroy(); const idol_decoder = try @import("metal_idol_decoder.zig").Suite.create(a, device, queue, &kernels, o.only); @@ -585,6 +590,8 @@ pub fn main(init: std.process.Init) !u8 { try g.runAll(a, kernels.items, o.seed, &t); for (flash_list[0..flash_made]) |*probe| try probe.rowCountInvariant(); try dsv41_suites.gates(init.io, o.seed, &t); + if (try sn_mhc.invariance(o.seed) != 0) return 1; + if (wanted(o, "sensenova")) try sn_lin.rowCountInvariant(); } const t1 = std.Io.Clock.awake.now(init.io); var lim: usize = 0; diff --git a/zig/tests/contract/metal_sensenova_bf16.zig b/zig/tests/contract/metal_sensenova_bf16.zig new file mode 100644 index 00000000000..6034b4694dd --- /dev/null +++ b/zig/tests/contract/metal_sensenova_bf16.zig @@ -0,0 +1,513 @@ +//! SenseNova-Loop BF16 Metal linear contract probe (extracted from metal_sensenova_linear.zig). +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const dense_in = contract.dense; +const lgpu = tf.sensenova_loop.linear_gpu; + +pub fn ctlGate(ctl: u8) ?g.Gate { + return ([_]?g.Gate{ null, .nonfinite, .repeat, .shapes, .sums })[ctl]; +} + +pub fn injectNonFinite(buf: []u16, rows: usize, k: usize) void { + const at = [_][2]usize{ .{ 0, k / 3 }, .{ 1, k / 2 }, .{ 2, k - 1 }, .{ 3, 0 }, .{ 3, k - 1 } }; + const put = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (at, put) |pos, val| { + if (pos[0] < rows) buf[pos[0] * k + pos[1]] = c.toBf16(val); + } +} + +fn depthLinear(s: c.Shape) usize { + return s.k / 8 + 32; +} + +pub const Bf16Variant = enum { mv, gemm, splitk }; +pub const Bf16Cfg = struct { v: Bf16Variant, tier: u32 = 1, sk: u32 = 1, ctl: u8 = 0, name: []const u8 }; + +pub const Bf16Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + sum_pipe: ?mtl.Pipeline = null, + cfg: Bf16Cfg, + served_buf: [3]c.Shape = undefined, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + d: ?dense_in.Dense = null, + w16: []u16 = &.{}, + x: rig_.Ref = undefined, + w: rig_.Ref = undefined, + scratch: ?rig_.Ref = null, + y: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, dev: mtl.Device, q: mtl.Queue, lib: mtl.Library, cfg: Bf16Cfg) !Bf16Probe { + var buf: [64]u8 = undefined; + const fun: [:0]const u8 = switch (cfg.v) { + .mv => try std.fmt.bufPrintSentinel(&buf, "sn_bf16_mv_r{d}_sk{d}", .{ cfg.tier, cfg.sk }, 0), + .gemm => "sn_bf16_gemm_00", + .splitk => "sn_bf16_gemm_splitk_00", + }; + const pipe = try mtl.Pipeline.init(dev, lib, fun, false); + errdefer pipe.deinit(); + const sp = if (cfg.v == .splitk) try mtl.Pipeline.init(dev, lib, "sn_bf16_gemm_splitk_sum", false) else null; + return .{ .a = a, .rig = .{ .a = a, .device = dev, .queue = q }, .pipe = pipe, .sum_pipe = sp, .cfg = cfg }; + } + + pub fn deinit(p: *Bf16Probe) void { + if (p.d) |d| d.deinit(); + p.a.free(p.w16); + p.rig.deinit(); + p.pipe.deinit(); + if (p.sum_pipe) |sp| sp.deinit(); + } + + const vt = g.hooks(Bf16Probe); + + pub fn kernel(p: *Bf16Probe) g.Kernel { + const t = p.cfg.tier; + const v = p.cfg.v; + const ks: usize = if (v == .mv) 8 else 256; + p.served_buf = switch (v) { + .mv => .{ .{ .rows = t, .n = 64, .k = 4096 }, .{ .rows = t, .n = 4160, .k = 4096 }, .{ .rows = t, .n = 512, .k = 12288 } }, + .gemm => .{ .{ .rows = 96, .n = 192, .k = 4096 }, .{ .rows = 64, .n = 128, .k = 512 }, .{ .rows = 0, .n = 0, .k = 0 } }, + .splitk => .{ .{ .rows = 65, .n = 192, .k = 4096 }, .{ .rows = 64, .n = 128, .k = 512 }, .{ .rows = 0, .n = 0, .k = 0 } }, + }; + const n_srv: usize = if (v == .mv) 3 else 2; + return .{ + .spec = .{ + .name = p.cfg.name, + .accum = .f32, + .depth = depthLinear, + .out = .bf16, + .tiles = .{ + .{ .size = if (v == .mv) t else 64, .step = 1, .min = 1 }, + .{ .size = if (v == .mv) (8 / p.cfg.sk) * lgpu.bf16MvCols(t) else if (v == .gemm) 128 else 64, .step = 1, .min = 1 }, + .{ .size = if (v == .splitk) 1024 else 256, .step = ks, .min = ks }, + }, + .served = p.served_buf[0..n_srv], + }, + .ctx = p, + .vt = &vt, + .control = ctlGate(p.cfg.ctl), + }; + } + + pub fn prepare(p: *Bf16Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.n == 0 or s.k == 0 or s.k % 8 != 0) return false; + if (p.cfg.v == .mv and s.rows > 32) return false; + if (p.cfg.v != .mv and s.k % 256 != 0) return false; + if (p.cfg.v == .splitk and s.k < 512) return false; + if (p.d) |d| d.deinit(); + p.a.free(p.w16); + p.rig.reset(); + p.shape = s; + const d = try dense_in.Dense.init(p.a, s, 1); + p.d = d; + d.fillX(fill, seed, 2); + p.w16 = try p.a.alloc(u16, s.n * s.k); + var prng = std.Random.DefaultPrng.init(seed ^ 0x5151); + const h = s.k / 2; + for (0..s.n) |j| for (0..s.k) |i| { + const sv: f32 = if (i < h) @floatFromInt(1 + (i * 7 + j) % 6) else -@as(f32, @floatFromInt(1 + ((i - h) * 7 + j) % 6)); + p.w16[j * s.k + i] = c.toBf16(if (fill != .stress) prng.random().float(f32) * 2 - 1 else sv); + d.w[j * s.k + i] = c.fromBf16(p.w16[j * s.k + i]); + }; + p.x = try p.rig.input(std.mem.sliceAsBytes(d.x)); + p.w = try p.rig.input(std.mem.sliceAsBytes(p.w16)); + if (p.cfg.v == .splitk) p.scratch = try p.rig.scratch(4 * s.rows * s.n * 4); + p.y = try p.rig.output(d.outputs() * 2); + return true; + } + + pub fn count(p: *Bf16Probe) usize { + return p.d.?.outputs(); + } + + pub fn run(p: *Bf16Probe) !void { + const s = p.shape; + const pass = p.rig.begin(); + const e = pass.e; + const xr = lgpu.Ref{ .buf = p.x.buf, .off = p.x.off }; + const wr = lgpu.Ref{ .buf = p.w.buf, .off = p.w.off }; + const yr = lgpu.Ref{ .buf = p.y.buf, .off = p.y.off }; + const dims = lgpu.LinearGpu.Dims{ .rows = @intCast(s.rows), .n = @intCast(s.n), .k = @intCast(s.k), .ldy = @intCast(s.n) }; + switch (p.cfg.v) { + .mv => { + const no = (8 / p.cfg.sk) * lgpu.bf16MvCols(p.cfg.tier); + var r0: usize = 0; + while (r0 < s.rows) : (r0 += p.cfg.tier) { + const rm: u32 = @intCast(@min(p.cfg.tier, s.rows - r0)); + e.setPipeline(p.pipe); + e.setBuffer(p.x.buf, p.x.off + r0 * s.k * 2, 0); + e.setBuffer(p.w.buf, p.w.off, 1); + e.setValue(lgpu.Bf16Args{ .rows = rm, .n = dims.n, .k = dims.k, .ldy = dims.ldy }, 2); + e.setBuffer(p.y.buf, p.y.off + r0 * s.n * 2, 3); + e.dispatchGroups(mtl.Size.of((s.n + no - 1) / no, 1, 1), mtl.Size.of(256, 1, 1)); + } + }, + .gemm => lgpu.LinearGpu.dispatchBf16Gemm(p.pipe, e, xr, wr, yr, dims), + .splitk => lgpu.LinearGpu.dispatchBf16SplitK( + p.pipe, + p.sum_pipe.?, + e, + xr, + wr, + .{ .buf = p.scratch.?.buf, .off = p.scratch.?.off }, + yr, + dims, + 2, + ), + } + try p.rig.finish(pass); + } + + pub fn reference(p: *Bf16Probe, want: []f64, mag: []f64) !void { + return p.d.?.reference(want, mag); + } + + pub fn simulate(p: *Bf16Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + return p.d.?.simulate(acc, order, out); + } +}; + +fn fillRandomBf16(buf: mtl.Buffer, count: usize, seed: u64, scale: f32) void { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const dst = buf.slice(u16, count); + for (dst) |*d| d.* = c.toBf16((rng.float(f32) * 2.0 - 1.0) * scale); +} + +fn runBf16Once( + gpu: *lgpu.LinearGpu, + q: mtl.Queue, + mat: lgpu.Bf16Matrix, + x: lgpu.Ref, + y: lgpu.Ref, + rows: u32, + ldy: u32, + prompt: bool, + splits: lgpu.OutSplits, +) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = q.commandBuffer(); + const e = cb.compute(.serial); + try gpu.encodeBf16Split(e, mat, x, y, rows, ldy, prompt, null, splits); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("bf16 split gpu err: {s}\n", .{why}); + return error.GpuFailed; + } +} + +fn verifyBf16SplitCase( + gpu: *lgpu.LinearGpu, + q: mtl.Queue, + n: u32, + k: u32, + rows: u32, + prompt: bool, + split1: u32, + split2: u32, +) !void { + const opts = mtl.ResourceOptions.shared; + const x_buf = try gpu.device.buffer(@as(usize, rows) * k * 2, opts); + defer x_buf.deinit(); + const w_buf = try gpu.device.buffer(@as(usize, n) * k * 2, opts); + defer w_buf.deinit(); + fillRandomBf16(x_buf, @as(usize, rows) * k, 0x1111 + rows + n, 1.5); + fillRandomBf16(w_buf, @as(usize, n) * k, 0x2222 + split1 + split2, 0.25); + + const has2 = split2 > 0; + const w0 = split1; + const w1 = (if (has2) split2 else n) - split1; + const w2 = if (has2) n - split2 else 0; + const y_ref = try gpu.device.buffer(@as(usize, rows) * n * 2, opts); + defer y_ref.deinit(); + const y0 = try gpu.device.buffer(@as(usize, rows) * w0 * 2, opts); + defer y0.deinit(); + const y1 = try gpu.device.buffer(@as(usize, rows) * w1 * 2, opts); + defer y1.deinit(); + const y2 = if (has2) try gpu.device.buffer(@as(usize, rows) * w2 * 2, opts) else null; + defer if (y2) |b| b.deinit(); + const y_sep = try gpu.device.buffer(@as(usize, rows) * n * 2, opts); + defer y_sep.deinit(); + + const full_mat = try lgpu.LinearGpu.prepareBf16(w_buf, 0, n, k); + const xr = lgpu.Ref{ .buf = x_buf }; + try runBf16Once(gpu, q, full_mat, xr, .{ .buf = y_ref }, rows, n, prompt, .{}); + try runBf16Once(gpu, q, full_mat, xr, .{ .buf = y0 }, rows, w0, prompt, .{ + .split1 = split1, + .y1 = .{ .buf = y1 }, + .ldy1 = w1, + .split2 = split2, + .y2 = if (y2) |b| .{ .buf = b } else null, + .ldy2 = w2, + }); + + // Compare split outputs against full stacked output row by row. + const ref_s = y_ref.slice(u16, @as(usize, rows) * n); + const y0_s = y0.slice(u16, @as(usize, rows) * w0); + const y1_s = y1.slice(u16, @as(usize, rows) * w1); + const y2_s = if (y2) |b| b.slice(u16, @as(usize, rows) * w2) else &.{}; + for (0..rows) |r| { + if (!std.mem.eql(u16, ref_s[r * n ..][0..w0], y0_s[r * w0 ..][0..w0])) return error.SplitMismatch; + if (!std.mem.eql(u16, ref_s[r * n + split1 ..][0..w1], y1_s[r * w1 ..][0..w1])) return error.SplitMismatch; + if (has2 and !std.mem.eql(u16, ref_s[r * n + split2 ..][0..w2], y2_s[r * w2 ..][0..w2])) return error.SplitMismatch; + } + + // Also match separate slice matrices bit-for-bit when the same kernel path runs. + if (!prompt or gpu.tensor_units) { + const m0 = try lgpu.LinearGpu.prepareBf16(w_buf, 0, w0, k); + try runBf16Once(gpu, q, m0, xr, .{ .buf = y_sep }, rows, w0, prompt, .{}); + if (!std.mem.eql(u16, y_sep.slice(u16, @as(usize, rows) * w0), y0_s)) return error.SplitSeparateMismatch; + const m1 = try lgpu.LinearGpu.prepareBf16(w_buf, @as(usize, split1) * k * 2, w1, k); + try runBf16Once(gpu, q, m1, xr, .{ .buf = y_sep }, rows, w1, prompt, .{}); + if (!std.mem.eql(u16, y_sep.slice(u16, @as(usize, rows) * w1), y1_s)) return error.SplitSeparateMismatch; + if (has2) { + const m2 = try lgpu.LinearGpu.prepareBf16(w_buf, @as(usize, split2) * k * 2, w2, k); + try runBf16Once(gpu, q, m2, xr, .{ .buf = y_sep }, rows, w2, prompt, .{}); + if (!std.mem.eql(u16, y_sep.slice(u16, @as(usize, rows) * w2), y2_s)) return error.SplitSeparateMismatch; + } + } +} + +pub fn checkBf16Split(a: std.mem.Allocator, dev: mtl.Device, q: mtl.Queue) !void { + var gpu = lgpu.LinearGpu.init(a, dev); + defer gpu.deinit(); + try gpu.reserve(128, false); + for ([_]bool{ false, true }) |prompt| { + const rows: u32 = if (prompt) 65 else 12; + try verifyBf16SplitCase(&gpu, q, 10240, 4096, rows, prompt, 8192, 9216); + try verifyBf16SplitCase(&gpu, q, 12288, 4096, rows, prompt, 8192, 0); + if (prompt and !dev.tensorUnits()) { + try verifyBf16SplitCase(&gpu, q, 8192, 4096, rows, true, 4096, 0); + } + } + // Check OutSplits validation errors. + const opts = mtl.ResourceOptions.shared; + const dummy = try dev.buffer(4096 * 128 * 2, opts); + defer dummy.deinit(); + const mat = try lgpu.LinearGpu.prepareBf16(dummy, 0, 256, 128); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = q.commandBuffer(); + const e = cb.compute(.serial); + const ref = lgpu.Ref{ .buf = dummy }; + const bad = [_]lgpu.OutSplits{ + .{ .split1 = 0, .y1 = ref, .ldy1 = 256 }, + .{ .split1 = 64, .y1 = ref, .ldy1 = 192 }, + .{ .split1 = 128, .y1 = ref, .ldy1 = 64 }, + .{ .split1 = 128, .y1 = ref, .ldy1 = 128, .split2 = 128, .y2 = ref, .ldy2 = 128 }, + .{ .split1 = 128, .y1 = null, .y2 = ref, .ldy2 = 128 }, + }; + for (bad) |sp| { + const res = gpu.encodeBf16Split(e, mat, ref, ref, 1, 128, false, null, sp); + if (res) |_| return error.ExpectedInvalidShape else |err| if (err != error.InvalidShape) return err; + } + e.end(); + std.debug.print("PASS encodeBf16Split (10240,4096) & (12288,4096) bit-exact + OutSplits validation\n", .{}); +} + +fn runAwq( + gpu: *lgpu.LinearGpu, + q: mtl.Queue, + mat: lgpu.AwqMatrix, + x: lgpu.Ref, + xs: ?lgpu.Sums, + y: lgpu.Ref, + rows: u32, + ldy: u32, + prompt: bool, + sk: ?u32, + splits: lgpu.OutSplits, +) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = q.commandBuffer(); + const e = cb.compute(.serial); + try gpu.encodeAwqSplit(e, mat, x, xs, y, rows, ldy, prompt, sk, splits); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("awq gpu err: {s}\n", .{why}); + return error.GpuFailed; + } +} + +pub fn packBf16AsAwq(gpu: *const lgpu.LinearGpu, w_bf16: []const u16, n: u32, k: u32) !lgpu.AwqMatrix { + const awq = tf.sensenova_loop.awq; + const kg = k / 128; + const layout: awq.Layout = if (gpu.tensor_units) .m5_tile else .m3_row; + const w = try gpu.allocator.alloc(u32, awq.weightWords(n, k, layout)); + defer gpu.allocator.free(w); + @memset(w, 0); + const sb = try gpu.allocator.alloc(awq.Float2, awq.metaCount(n, k)); + defer gpu.allocator.free(sb); + for (0..n) |j| for (0..kg) |gi| { + const row = w_bf16[j * k + gi * 128 ..][0..128]; + var min_v: f32 = 0; + var max_v: f32 = 0; + for (row) |b| { + const v: f32 = @floatCast(c.fromBf16(b)); + min_v = @min(min_v, v); + max_v = @max(max_v, v); + } + const scale = (max_v - min_v) / 15.0; + const zp: f32 = if (scale != 0) @floatFromInt(@as(u32, @intFromFloat(std.math.clamp(@round(-min_v / scale), 0.0, 15.0)))) else 0; + const bias = if (scale != 0) -zp * scale else min_v; + sb[if (layout == .m5_tile) gi * n + j else j * kg + gi] = .{ .scale = scale, .bias = bias }; + for (0..16) |w16| { + var word: u32 = 0; + for (0..8) |ni| { + const vf: f32 = @floatCast(c.fromBf16(row[w16 * 8 + ni])); + const q_val: u32 = if (scale != 0) @intFromFloat(std.math.clamp(@round((vf - bias) / scale), 0.0, 15.0)) else 0; + word |= q_val << @intCast(ni * 4); + } + const w_idx = if (layout == .m5_tile) (((j / 32) * kg + gi) * 32 + (j % 32)) * 16 + w16 else j * (k / 8) + gi * 16 + w16; + w[w_idx] = word; + } + }; + return lgpu.LinearGpu.prepareAwqFromPacked(gpu, .{ .n = n, .k = k, .layout = layout, .w = w, .sb = sb, .input_scale = null }); +} + +fn verifyAwqSplitCase(gpu: *lgpu.LinearGpu, q: mtl.Queue, n: u32, k: u32, rows: u32, prompt: bool, split1: u32, split2: u32) !void { + const opts = mtl.ResourceOptions.shared; + const x_buf = try gpu.device.buffer(@as(usize, rows) * k * 2, opts); + defer x_buf.deinit(); + const w_buf = try gpu.device.buffer(@as(usize, n) * k * 2, opts); + defer w_buf.deinit(); + fillRandomBf16(x_buf, @as(usize, rows) * k, 0x5555 + rows + n, 1.5); + fillRandomBf16(w_buf, @as(usize, n) * k, 0x6666 + split1 + split2, 0.25); + + const has2 = split2 > 0; + const w0 = split1; + const w1 = (if (has2) split2 else n) - split1; + const w2 = if (has2) n - split2 else 0; + const w_all = w_buf.slice(u16, @as(usize, n) * k); + var full = try packBf16AsAwq(gpu, w_all, n, k); + defer full.deinit(); + const y_ref = try gpu.device.buffer(@as(usize, rows) * n * 2, opts); + defer y_ref.deinit(); + const y0 = try gpu.device.buffer(@as(usize, rows) * w0 * 2, opts); + defer y0.deinit(); + const y1 = try gpu.device.buffer(@as(usize, rows) * w1 * 2, opts); + defer y1.deinit(); + const y2 = if (has2) try gpu.device.buffer(@as(usize, rows) * w2 * 2, opts) else null; + defer if (y2) |b| b.deinit(); + const y_sep = try gpu.device.buffer(@as(usize, rows) * n * 2, opts); + defer y_sep.deinit(); + + const xr = lgpu.Ref{ .buf = x_buf }; + try runAwq(gpu, q, full, xr, null, .{ .buf = y_ref }, rows, n, prompt, null, .{}); + try runAwq(gpu, q, full, xr, null, .{ .buf = y0 }, rows, w0, prompt, null, .{ + .split1 = split1, + .y1 = .{ .buf = y1 }, + .ldy1 = w1, + .split2 = split2, + .y2 = if (y2) |b| .{ .buf = b } else null, + .ldy2 = w2, + }); + const ref_s = y_ref.slice(u16, @as(usize, rows) * n); + const y0_s = y0.slice(u16, @as(usize, rows) * w0); + const y1_s = y1.slice(u16, @as(usize, rows) * w1); + const y2_s = if (y2) |b| b.slice(u16, @as(usize, rows) * w2) else &.{}; + for (0..rows) |r| { + if (!std.mem.eql(u16, ref_s[r * n ..][0..w0], y0_s[r * w0 ..][0..w0])) return error.SplitMismatch; + if (!std.mem.eql(u16, ref_s[r * n + split1 ..][0..w1], y1_s[r * w1 ..][0..w1])) return error.SplitMismatch; + if (has2 and !std.mem.eql(u16, ref_s[r * n + split2 ..][0..w2], y2_s[r * w2 ..][0..w2])) return error.SplitMismatch; + } + + const sk_match: ?u32 = if (prompt) null else lgpu.decodeSk(gpu.tensor_units, true, n, k); + var m0 = try packBf16AsAwq(gpu, w_all[0 .. @as(usize, w0) * k], w0, k); + defer m0.deinit(); + try runAwq(gpu, q, m0, xr, null, .{ .buf = y_sep }, rows, w0, prompt, sk_match, .{}); + if (!std.mem.eql(u16, y_sep.slice(u16, @as(usize, rows) * w0), y0_s)) return error.SplitSeparateMismatch; + var m1 = try packBf16AsAwq(gpu, w_all[@as(usize, split1) * k ..][0 .. @as(usize, w1) * k], w1, k); + defer m1.deinit(); + try runAwq(gpu, q, m1, xr, null, .{ .buf = y_sep }, rows, w1, prompt, sk_match, .{}); + if (!std.mem.eql(u16, y_sep.slice(u16, @as(usize, rows) * w1), y1_s)) return error.SplitSeparateMismatch; + if (has2) { + var m2 = try packBf16AsAwq(gpu, w_all[@as(usize, split2) * k ..][0 .. @as(usize, w2) * k], w2, k); + defer m2.deinit(); + try runAwq(gpu, q, m2, xr, null, .{ .buf = y_sep }, rows, w2, prompt, sk_match, .{}); + if (!std.mem.eql(u16, y_sep.slice(u16, @as(usize, rows) * w2), y2_s)) return error.SplitSeparateMismatch; + } +} + +fn checkQuantRoundTrip(gpu: *lgpu.LinearGpu, q: mtl.Queue, n: u32, k: u32) !void { + const opts = mtl.ResourceOptions.shared; + const x_buf = try gpu.device.buffer(@as(usize, 65) * k * 2, opts); + defer x_buf.deinit(); + const w_buf = try gpu.device.buffer(@as(usize, n) * k * 2, opts); + defer w_buf.deinit(); + fillRandomBf16(x_buf, @as(usize, 65) * k, 0x7777 + n, 1.5); + // Use structured weights (16-level group grid + BF16 noise) plus an all-zero group for scale == 0 coverage. + var prng = std.Random.DefaultPrng.init(0x8888 + k); + const rng = prng.random(); + const w_s = w_buf.slice(u16, @as(usize, n) * k); + for (0..n) |j| { + for (0..k / 128) |g_idx| { + const gs: f32 = 0.02 + 0.04 * rng.float(f32); + const zp: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 14)); + for (0..128) |i| { + const val: f32 = if (j == 0 and g_idx == 0) 0.0 else blk: { + const qv: f32 = @floatFromInt(rng.uintLessThan(u32, 16)); + break :blk (qv - zp) * gs + (rng.float(f32) - 0.5) * gs * 0.25; + }; + w_s[j * k + g_idx * 128 + i] = c.toBf16(val); + } + } + } + const bf = try lgpu.LinearGpu.prepareBf16(w_buf, 0, n, k); + var aw = try packBf16AsAwq(gpu, w_s, n, k); + defer aw.deinit(); + const y_bf = try gpu.device.buffer(@as(usize, 65) * n * 2, opts); + defer y_bf.deinit(); + const y_aw = try gpu.device.buffer(@as(usize, 65) * n * 2, opts); + defer y_aw.deinit(); + for ([_]struct { rows: u32, prompt: bool }{ .{ .rows = 4, .prompt = false }, .{ .rows = 65, .prompt = true } }) |tc| { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = q.commandBuffer(); + const e = cb.compute(.serial); + try gpu.encodeBf16(e, bf, .{ .buf = x_buf }, .{ .buf = y_bf }, tc.rows, n, tc.prompt, null); + try gpu.encodeAwq(e, aw, .{ .buf = x_buf }, null, .{ .buf = y_aw }, tc.rows, n, tc.prompt, null); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |_| return error.GpuFailed; + var dot: f64 = 0; + var na: f64 = 0; + var nb: f64 = 0; + for (y_bf.slice(u16, tc.rows * n), y_aw.slice(u16, tc.rows * n)) |b, a| { + const fb = c.fromBf16(b); + const fa = c.fromBf16(a); + dot += fa * fb; + na += fa * fa; + nb += fb * fb; + } + const cos = dot / (@sqrt(na) * @sqrt(nb)); + if (!(cos > 0.999)) return error.QuantRoundTripCosTooLow; + } +} + +pub fn checkAwqSplitAndQuant(a: std.mem.Allocator, dev: mtl.Device, q: mtl.Queue) !void { + var gpu = lgpu.LinearGpu.init(a, dev); + defer gpu.deinit(); + try gpu.reserve(128, true); + for ([_]bool{ false, true }) |prompt| { + const rows: u32 = if (prompt) 65 else 12; + try verifyAwqSplitCase(&gpu, q, 10240, 4096, rows, prompt, 8192, 9216); + try verifyAwqSplitCase(&gpu, q, 12288, 4096, rows, prompt, 8192, 0); + } + try checkQuantRoundTrip(&gpu, q, 256, 1024); + try checkQuantRoundTrip(&gpu, q, 40, 256); +} diff --git a/zig/tests/contract/metal_sensenova_linear.zig b/zig/tests/contract/metal_sensenova_linear.zig new file mode 100644 index 00000000000..d663565ba7c --- /dev/null +++ b/zig/tests/contract/metal_sensenova_linear.zig @@ -0,0 +1,509 @@ +//! SenseNova-Loop BF16 and AWQ W4A16 g128 Metal kernels under Contract Gates 1-5 and row-invariance checks. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const limits_k = @import("metal_limits.zig"); +const bf16_k = @import("metal_sensenova_bf16.zig"); + +const c = contract.spec; +const g = contract.gates; +const rows_in = contract.rows; +const awq = tf.sensenova_loop.awq; +const lgpu = tf.sensenova_loop.linear_gpu; +const records = contract.sensenova_linear_records; + +pub const Bf16Variant = bf16_k.Bf16Variant; +pub const Bf16Cfg = bf16_k.Bf16Cfg; +pub const Bf16Probe = bf16_k.Bf16Probe; + +fn depthAwq(s: c.Shape) usize { + return 128 + s.k / 8 + 32; +} + +pub const AwqVariant = enum { m5_lane, m5_mv, m5_gemm, m3_mv, m3_qmm, xsum }; +pub const AwqCfg = struct { v: AwqVariant, tier: u32 = 1, sk: u32 = 1, pre: bool = false, rb: bool = false, ctl: u8 = 0, name: []const u8 }; + +fn isM5Variant(v: AwqVariant) bool { + return v == .m5_lane or v == .m5_mv or v == .m5_gemm; +} + +pub const AwqProbe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + xsum_pipe: ?mtl.Pipeline = null, + cfg: AwqCfg, + served_buf: [2]c.Shape = undefined, + shape: c.Shape = .{ .rows = 0, .n = 0, .k = 0 }, + x_host: []u16 = &.{}, + q_host: []u4 = &.{}, + sb_host: []awq.Float2 = &.{}, + x: rig_.Ref = undefined, + w: rig_.Ref = undefined, + sb: rig_.Ref = undefined, + xs: ?rig_.Ref = null, + y: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, dev: mtl.Device, q: mtl.Queue, lib: mtl.Library, cfg: AwqCfg) !AwqProbe { + var buf: [64]u8 = undefined; + const fun: [:0]const u8 = switch (cfg.v) { + .m5_lane => try std.fmt.bufPrintSentinel(&buf, "sn_awq_lane_sk{d}_p{d}_r{d}", .{ cfg.sk, @intFromBool(cfg.pre), @intFromBool(cfg.rb) }, 0), + .m5_mv => try std.fmt.bufPrintSentinel(&buf, "sn_awq_m5_mv_r{d}_sk{d}", .{ cfg.tier, cfg.sk }, 0), + .m5_gemm => "sn_awq_gemm_m5", + .m3_mv => try std.fmt.bufPrintSentinel(&buf, "sn_awq_row_mv_r{d}_sk{d}", .{ cfg.tier, cfg.sk }, 0), + .m3_qmm => "sn_awq_qmm_m3", + .xsum => "sn_awq_xsum_128", + }; + const pipe = try mtl.Pipeline.init(dev, lib, fun, false); + errdefer pipe.deinit(); + const xp = if ((cfg.v == .m5_lane and cfg.pre) or cfg.v == .m5_gemm) try mtl.Pipeline.init(dev, lib, "sn_awq_xsum_128", false) else null; + return .{ .a = a, .rig = .{ .a = a, .device = dev, .queue = q }, .pipe = pipe, .xsum_pipe = xp, .cfg = cfg }; + } + + pub fn deinit(p: *AwqProbe) void { + p.a.free(p.x_host); + p.a.free(p.q_host); + p.a.free(p.sb_host); + p.rig.deinit(); + p.pipe.deinit(); + if (p.xsum_pipe) |xp| xp.deinit(); + } + + const vt = g.hooks(AwqProbe); + + pub fn kernel(p: *AwqProbe) g.Kernel { + const rt: usize = switch (p.cfg.v) { + .m5_lane => if (p.cfg.rb) 32 else 16, + .m5_mv, .m3_mv => p.cfg.tier, + .m5_gemm, .m3_qmm => 64, + .xsum => 16, + }; + p.served_buf = switch (p.cfg.v) { + .m5_lane => .{ .{ .rows = if (p.cfg.rb) 24 else 8, .n = 64, .k = 4096 }, .{ .rows = if (p.cfg.rb) 33 else 16, .n = 128, .k = 12288 } }, + .m5_mv, .m3_mv => .{ .{ .rows = p.cfg.tier, .n = 64, .k = 4096 }, .{ .rows = p.cfg.tier, .n = 512, .k = 12288 } }, + .m5_gemm => .{ .{ .rows = 96, .n = 192, .k = 4096 }, .{ .rows = 65, .n = 40, .k = 512 } }, + .m3_qmm => .{ .{ .rows = 96, .n = 192, .k = 4096 }, .{ .rows = 64, .n = 128, .k = 512 } }, + .xsum => .{ .{ .rows = 8, .n = 1, .k = 4096 }, .{ .rows = 33, .n = 1, .k = 12288 } }, + }; + const nt: c.Tile = if (p.cfg.v == .xsum) .{} else .{ .size = 64, .step = 8, .min = 8 }; + const tiles: [3]c.Tile = .{ .{ .size = rt, .step = 1, .min = 1 }, nt, .{ .size = 256, .step = 128, .min = 128 } }; + return .{ + .spec = .{ .name = p.cfg.name, .accum = .f32, .depth = depthAwq, .out = if (p.cfg.v == .xsum) .f32 else .bf16, .tiles = tiles, .served = &p.served_buf }, + .ctx = p, + .vt = &vt, + .control = bf16_k.ctlGate(p.cfg.ctl), + }; + } + + pub fn prepare(p: *AwqProbe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (s.rows == 0 or s.k == 0 or s.k % 128 != 0) return false; + if (p.cfg.v != .xsum and (s.n == 0 or s.n % 8 != 0)) return false; + if (p.cfg.v == .m5_lane and !p.cfg.rb and s.rows > 16) return false; + if ((p.cfg.v == .m3_mv or p.cfg.v == .m5_mv) and s.rows > 32) return false; + p.a.free(p.x_host); + p.a.free(p.q_host); + p.a.free(p.sb_host); + p.q_host = &.{}; + p.sb_host = &.{}; + p.rig.reset(); + p.shape = s; + const kg = s.k / 128; + p.x_host = try p.a.alloc(u16, s.rows * s.k); + var prng = std.Random.DefaultPrng.init(seed ^ 0x4444); + const rng = prng.random(); + const h = s.k / 2; + const xmax: u64 = @min(32, ((1 << 24) - 1) / (16 * s.k)); + for (0..s.rows) |r| { + if (fill == .stress and p.cfg.v == .xsum) { + for (0..kg) |gi| { + const b = r * s.k + gi * 128; + @memset(p.x_host[b .. b + 63], c.toBf16(32768.0)); + p.x_host[b + 63] = c.toBf16(1.0); + @memset(p.x_host[b + 64 .. b + 128], c.toBf16(-32768.0)); + } + } else if (fill == .stress) { + for (0..h) |i| { + const v = 1 + rng.uintLessThan(u64, xmax); + p.x_host[r * s.k + i] = c.toBf16(@floatFromInt(v)); + p.x_host[r * s.k + h + i] = c.toBf16(@floatFromInt(v + @intFromBool(i < 8))); + } + } else for (0..s.k) |i| p.x_host[r * s.k + i] = if (i % 29 == 0) 0 else c.toBf16(rng.float(f32) * 4 - 2); + } + if (fill == .nonfinite) bf16_k.injectNonFinite(p.x_host, s.rows, s.k); + p.x = try p.rig.input(std.mem.sliceAsBytes(p.x_host)); + if (p.cfg.v == .xsum) { + p.y = try p.rig.output(kg * s.rows * 4); + return true; + } + const n8 = s.n / 8; + p.q_host = try p.a.alloc(u4, s.n * s.k); + const qw = try p.a.alloc(u32, s.k * n8); + const qz = try p.a.alloc(u32, kg * n8); + const dt: awq.ScaleDType = if (seed % 2 == 0) .f16 else .bf16; + const sc = try p.a.alloc(u8, kg * s.n * 2); + defer { + p.a.free(qw); + p.a.free(qz); + p.a.free(sc); + } + for (0..kg) |gi| for (0..n8) |c8| { + var zs: [8]u4 = undefined; + for (0..8) |ci| { + zs[ci] = if (fill == .stress) 8 else @intCast(1 + rng.uintLessThan(u32, 15)); + const sf: f32 = if (fill == .stress) 1.0 else (rng.float(f32) * 0.02 + 0.002); + const bits: u16 = if (dt == .f16) @bitCast(@as(f16, @floatCast(sf))) else c.toBf16(sf); + std.mem.writeInt(u16, sc[2 * (gi * s.n + c8 * 8 + ci) ..][0..2], bits, .little); + } + qz[gi * n8 + c8] = awq.packAwqWord(zs); + }; + for (0..s.k) |ki| for (0..n8) |c8| { + var cols: [8]u4 = undefined; + for (0..8) |ci| { + const ni = c8 * 8 + ci; + const sq: u4 = if (ki < h) @intCast(9 + (ki * 7 + ni) % 6) else @intCast(7 - ((ki - h) * 7 + ni) % 6); + cols[ci] = if (fill != .stress) @intCast(rng.uintLessThan(u32, 16)) else sq; + p.q_host[ni * s.k + ki] = cols[ci]; + } + qw[ki * n8 + c8] = awq.packAwqWord(cols); + }; + const part = awq.Part{ .n = s.n, .k = s.k, .qweight = qw, .qzeros = qz, .scales = sc, .scales_dtype = dt }; + const layout: awq.Layout = if (isM5Variant(p.cfg.v)) .m5_tile else .m3_row; + const pw = try p.a.alloc(u32, awq.weightWords(s.n, s.k, layout)); + defer p.a.free(pw); + p.sb_host = try p.a.alloc(awq.Float2, awq.metaCount(s.n, s.k)); + try awq.packParts(&.{part}, layout, pw, p.sb_host); + p.w = try p.rig.input(std.mem.sliceAsBytes(pw)); + p.sb = try p.rig.input(std.mem.sliceAsBytes(p.sb_host)); + if ((p.cfg.v == .m5_lane and p.cfg.pre) or p.cfg.v == .m5_gemm) { + p.xs = try p.rig.scratch(kg * std.mem.alignForward(usize, s.rows, 16) * 4); + } + p.y = try p.rig.output(s.rows * s.n * 2); + return true; + } + + pub fn count(p: *AwqProbe) usize { + return if (p.cfg.v == .xsum) (p.shape.k / 128) * p.shape.rows else p.shape.rows * p.shape.n; + } + + pub fn run(p: *AwqProbe) !void { + const s = p.shape; + const pass = p.rig.begin(); + const e = pass.e; + if (p.cfg.v == .xsum) { + e.setPipeline(p.pipe); + e.setBuffer(p.x.buf, p.x.off, 0); + e.setValue([4]i32{ @intCast(s.rows), @intCast(s.rows), @intCast(s.k), 0 }, 1); + e.setBuffer(p.y.buf, p.y.off, 2); + e.dispatchThreads(mtl.Size.of(p.count(), 1, 1), mtl.Size.of(256, 1, 1)); + } else { + const stride = std.mem.alignForward(usize, s.rows, 16); + if (p.xsum_pipe) |xp| { + e.setPipeline(xp); + e.setBuffer(p.x.buf, p.x.off, 0); + e.setValue([4]i32{ @intCast(s.rows), @intCast(stride), @intCast(s.k), 0 }, 1); + e.setBuffer(p.xs.?.buf, p.xs.?.off, 2); + e.dispatchThreads(mtl.Size.of(stride * (s.k / 128), 1, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); + } + const step: usize = if (p.cfg.v == .m3_mv or p.cfg.v == .m5_mv) p.cfg.tier else s.rows; + var r0: usize = 0; + while (r0 < s.rows) : (r0 += step) { + const rm: i32 = @intCast(@min(step, s.rows - r0)); + e.setPipeline(p.pipe); + e.setBuffer(p.x.buf, p.x.off + r0 * s.k * 2, 0); + e.setBuffer(p.w.buf, p.w.off, 1); + e.setBuffer(p.sb.buf, p.sb.off, 2); + e.setValue(lgpu.AwqArgs{ .m = rm, .n = @intCast(s.n), .k = @intCast(s.k), .mp = @intCast(stride), .ldy = @intCast(s.n) }, 3); + e.setBuffer(p.y.buf, p.y.off + r0 * s.n * 2, 4); + if (p.xs) |xs_ref| e.setBuffer(xs_ref.buf, xs_ref.off, 5); + switch (p.cfg.v) { + .m5_lane => e.dispatchGroups(mtl.Size.of((s.n + 31) / 32, if (p.cfg.rb) (s.rows + 15) / 16 else 1, 1), mtl.Size.of(p.cfg.sk * 32, 1, 1)), + .m5_mv => e.dispatchGroups(mtl.Size.of((s.n + 7) / 8, 1, 1), mtl.Size.of(p.cfg.sk * 32, 1, 1)), + .m5_gemm => e.dispatchGroups(mtl.Size.of(((s.n + 127) / 128) * 4, (((s.rows + 63) / 64) + 3) / 4, 1), mtl.Size.of(256, 1, 1)), + .m3_mv => blk: { + const no = (8 / p.cfg.sk) * lgpu.awqM3MvCols(p.cfg.tier); + e.dispatchGroups(mtl.Size.of((s.n + no - 1) / no, 1, 1), mtl.Size.of(256, 1, 1)); + break :blk; + }, + .m3_qmm => e.dispatchGroups(mtl.Size.of((s.n + 63) / 64, (s.rows + 63) / 64, 1), mtl.Size.of(128, 1, 1)), + .xsum => unreachable, + } + } + } + try p.rig.finish(pass); + } + + pub fn reference(p: *AwqProbe, want: []f64, mag: []f64) !void { + const s = p.shape; + const kg = s.k / 128; + if (p.cfg.v == .xsum) { + for (0..kg) |gi| for (0..s.rows) |r| { + var sum: f64 = 0; + var abs: f64 = 0; + for (0..128) |i| { + const v = @as(f64, c.fromBf16(p.x_host[r * s.k + gi * 128 + i])); + sum += v; + abs += @abs(v); + } + want[gi * s.rows + r] = sum; + mag[gi * s.rows + r] = abs; + }; + return; + } + const m5_math = isM5Variant(p.cfg.v); + for (0..s.rows) |r| for (0..s.n) |j| { + var y: f64 = 0; + var a: f64 = 0; + for (0..kg) |gi| { + const sb = if (m5_math) p.sb_host[gi * s.n + j] else p.sb_host[j * kg + gi]; + var qx: f64 = 0; + var xs: f64 = 0; + for (gi * 128..(gi + 1) * 128) |ki| { + const x = @as(f64, c.fromBf16(p.x_host[r * s.k + ki])); + const q: f64 = @floatFromInt(p.q_host[j * s.k + ki]); + const wv = q * @as(f64, sb.scale) + @as(f64, sb.bias); + qx += if (m5_math) q * x else wv * x; + xs += x; + a += if (m5_math) @abs(sb.scale) * @abs(q * x) + @abs(sb.bias) * @abs(x) else @abs(wv * x); + } + y += if (m5_math) @as(f64, sb.scale) * qx + @as(f64, sb.bias) * xs else qx; + } + want[r * s.n + j] = y; + mag[r * s.n + j] = a; + }; + } + + pub fn simulate(p: *AwqProbe, acc: c.Accum, order: g.Order, out: []f64) !void { + const s = p.shape; + const kg = s.k / 128; + if (p.cfg.v == .xsum) { + var t128: [128]f64 = undefined; + for (0..kg) |gi| for (0..s.rows) |r| { + for (0..128) |i| t128[i] = c.fromBf16(p.x_host[r * s.k + gi * 128 + i]); + out[gi * s.rows + r] = rows_in.sumIn(acc, order, &t128); + }; + return; + } + const m5_math = isM5Variant(p.cfg.v); + const buf = try p.a.alloc(f64, 2 * s.k + kg); + defer p.a.free(buf); + const t = buf[0 .. 2 * s.k]; + const gs = buf[2 * s.k ..]; + for (0..s.rows) |r| for (0..s.n) |j| { + for (0..s.k) |ki| { + const x = @as(f64, c.fromBf16(p.x_host[r * s.k + ki])); + const q: f64 = @floatFromInt(p.q_host[j * s.k + ki]); + const sb = if (m5_math) p.sb_host[(ki / 128) * s.n + j] else p.sb_host[j * kg + ki / 128]; + t[ki] = if (m5_math) q * x else (q * @as(f64, sb.scale) + @as(f64, sb.bias)) * x; + t[s.k + ki] = x; + } + if (m5_math) { + for (gs, 0..) |*gv, gi| { + const sb = p.sb_host[gi * s.n + j]; + gv.* = rows_in.sumIn(acc, .sequential, t[gi * 128 ..][0..128]) * @as(f64, sb.scale) + + rows_in.sumIn(acc, .sequential, t[s.k + gi * 128 ..][0..128]) * @as(f64, sb.bias); + } + out[r * s.n + j] = rows_in.sumIn(acc, order, gs); + } else out[r * s.n + j] = rows_in.sumIn(acc, order, t[0..s.k]); + }; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + libs: [2][5]?mtl.Library = @splat(@splat(null)), + bf16_list: std.ArrayList(*Bf16Probe) = .empty, + awq_list: std.ArrayList(*AwqProbe) = .empty, + + fn freeProbes(a: std.mem.Allocator, list: anytype) void { + for (list.items) |p| { + p.deinit(); + a.destroy(p); + } + list.deinit(a); + } + + pub fn deinit(s: *Suite) void { + freeProbes(s.a, &s.bf16_list); + freeProbes(s.a, &s.awq_list); + for (&s.libs) |*row| for (row) |*opt| if (opt.*) |lib| lib.deinit(); + } + + fn getLib(s: *Suite, is_awq: bool, ctl: u8) !mtl.Library { + const slot = &s.libs[@intFromBool(is_awq)][ctl]; + if (slot.*) |lib| return lib; + const prefix = try std.fmt.allocPrint(s.a, "#define TF_CTL {d}\n", .{ctl}); + defer s.a.free(prefix); + const raw = if (is_awq) @import("kernel_sources").qwen27_awq_w4a16 else @import("kernel_sources").qwen27_bf16_linear; + const body = try tf.frags.source(s.device, s.a, raw); + defer s.a.free(body); + const full = try std.mem.concat(s.a, u8, &.{ prefix, body }); + defer s.a.free(full); + slot.* = try mtl.Library.fromSource(s.device, full, mtl.CompileOptions.mlx()); + return slot.*.?; + } + + fn addProbe(s: *Suite, comptime T: type, list: *std.ArrayList(*T), comptime is_awq: bool, only: ?[]const u8, cfg: if (is_awq) AwqCfg else Bf16Cfg) !void { + if (is_awq and ((isM5Variant(cfg.v) and !s.device.tensorUnits()) or (cfg.v == .m3_qmm and s.device.tensorUnits()))) return; + if (only) |needle| if (std.mem.indexOf(u8, cfg.name, needle) == null) return; + const p = try s.a.create(T); + errdefer s.a.destroy(p); + p.* = try T.init(s.a, s.device, s.queue, try s.getLib(is_awq, cfg.ctl), cfg); + try list.append(s.a, p); + try s.kernels.append(s.a, p.kernel()); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]Bf16Cfg{ + .{ .v = .mv, .tier = 1, .sk = 1, .name = "sensenova linear sn_bf16_mv_r1_sk1" }, + .{ .v = .mv, .tier = 4, .sk = 2, .name = "sensenova linear sn_bf16_mv_r4_sk2" }, + .{ .v = .mv, .tier = 8, .sk = 4, .name = "sensenova linear sn_bf16_mv_r8_sk4" }, + .{ .v = .mv, .tier = 32, .sk = 8, .name = "sensenova linear sn_bf16_mv_r32_sk8" }, + .{ .v = .gemm, .tier = 64, .sk = 1, .name = "sensenova linear sn_bf16_gemm_00" }, + .{ .v = .splitk, .tier = 64, .sk = 2, .name = "sensenova linear sn_bf16_gemm_splitk_00" }, + }) |cs| try s.addProbe(Bf16Probe, &s.bf16_list, false, only, cs); + const ctags = [_][]const u8{ "nonfinite->0", "repeat", "tail skip", "fp16 sum" }; + inline for ([_]u8{ 1, 2, 3, 4 }, ctags) |ctl, tag| { + try s.addProbe(Bf16Probe, &s.bf16_list, false, only, .{ .v = .mv, .tier = 8, .sk = 2, .ctl = ctl, .name = "control: sensenova bf16_mv " ++ tag }); + if (ctl != 2) try s.addProbe(Bf16Probe, &s.bf16_list, false, only, .{ .v = .gemm, .tier = 64, .ctl = ctl, .name = "control: sensenova bf16_gemm " ++ tag }); + try s.addProbe(AwqProbe, &s.awq_list, true, only, .{ .v = .m5_lane, .tier = 16, .sk = 4, .pre = true, .ctl = ctl, .name = "control: sensenova awq_lane " ++ tag }); + try s.addProbe(AwqProbe, &s.awq_list, true, only, .{ .v = .m5_mv, .tier = 8, .sk = 2, .ctl = ctl, .name = "control: sensenova awq_m5_mv " ++ tag }); + if (ctl != 2) try s.addProbe(AwqProbe, &s.awq_list, true, only, .{ .v = .m5_gemm, .tier = 64, .ctl = ctl, .name = "control: sensenova awq_gemm_m5 " ++ tag }); + try s.addProbe(AwqProbe, &s.awq_list, true, only, .{ .v = .m3_mv, .tier = 8, .sk = 2, .ctl = ctl, .name = "control: sensenova awq_row_mv " ++ tag }); + if (ctl != 2) try s.addProbe(AwqProbe, &s.awq_list, true, only, .{ .v = .m3_qmm, .tier = 64, .ctl = ctl, .name = "control: sensenova awq_qmm " ++ tag }); + } + for ([_]AwqCfg{ + .{ .v = .m5_lane, .tier = 16, .sk = 1, .name = "sensenova awq-m5 sn_awq_lane_sk1_p0_r0" }, + .{ .v = .m5_lane, .tier = 16, .sk = 4, .pre = true, .name = "sensenova awq-m5 sn_awq_lane_sk4_p1_r0" }, + .{ .v = .m5_lane, .tier = 32, .sk = 8, .pre = true, .rb = true, .name = "sensenova awq-m5 sn_awq_lane_sk8_p1_r1" }, + .{ .v = .m5_mv, .tier = 1, .sk = 1, .name = "sensenova awq-m5 sn_awq_m5_mv_r1_sk1" }, + .{ .v = .m5_mv, .tier = 4, .sk = 2, .name = "sensenova awq-m5 sn_awq_m5_mv_r4_sk2" }, + .{ .v = .m5_mv, .tier = 8, .sk = 4, .name = "sensenova awq-m5 sn_awq_m5_mv_r8_sk4" }, + .{ .v = .m5_mv, .tier = 32, .sk = 8, .name = "sensenova awq-m5 sn_awq_m5_mv_r32_sk8" }, + .{ .v = .m5_gemm, .tier = 64, .sk = 1, .name = "sensenova awq-m5 sn_awq_gemm_m5" }, + .{ .v = .m3_mv, .tier = 1, .sk = 1, .name = "sensenova awq sn_awq_row_mv_r1_sk1" }, + .{ .v = .m3_mv, .tier = 4, .sk = 2, .name = "sensenova awq sn_awq_row_mv_r4_sk2" }, + .{ .v = .m3_mv, .tier = 8, .sk = 4, .name = "sensenova awq sn_awq_row_mv_r8_sk4" }, + .{ .v = .m3_mv, .tier = 32, .sk = 8, .name = "sensenova awq sn_awq_row_mv_r32_sk8" }, + .{ .v = .m3_qmm, .tier = 64, .sk = 1, .name = "sensenova awq sn_awq_qmm_m3" }, + .{ .v = .xsum, .tier = 16, .name = "sensenova awq sn_awq_xsum_128" }, + }) |cs| try s.addProbe(AwqProbe, &s.awq_list, true, only, cs); + } + + fn checkInv(s: *Suite, comptime P: type, lib: mtl.Library, v: anytype, sk: u32) !void { + const n: usize = 256; + const k: usize = 1024; + const pre = if (P == AwqProbe) (v == .m5_lane or v == .m5_gemm) else false; + const is_m5_m = if (P == AwqProbe) isM5Variant(v) else false; + const tier7: u32 = if (v == .m5_lane) 16 else if (v == .m5_gemm) 64 else 8; + const c7 = if (P == Bf16Probe) Bf16Cfg{ .v = .mv, .tier = 8, .sk = sk, .name = "i" } else AwqCfg{ .v = v, .tier = tier7, .sk = sk, .pre = pre, .name = "i" }; + var p7 = try P.init(s.a, s.device, s.queue, lib, c7); + defer p7.deinit(); + _ = try p7.prepare(.{ .rows = 7, .n = n, .k = k }, .random, 99 + sk); + try p7.run(); + const ref = try s.a.dupe(u8, p7.rig.bytes(p7.y, 7 * n * 2)); + defer s.a.free(ref); + for ([_]usize{ 1, 3 }) |rows| { + const tier: u32 = if (v == .m5_lane) 16 else if (v == .m5_gemm) 64 else if (rows == 1) 1 else 4; + const c1 = if (P == Bf16Probe) Bf16Cfg{ .v = .mv, .tier = tier, .sk = sk, .name = "s" } else AwqCfg{ .v = v, .tier = tier, .sk = sk, .pre = pre, .name = "s" }; + var p1 = try P.init(s.a, s.device, s.queue, lib, c1); + defer p1.deinit(); + _ = try p1.prepare(.{ .rows = rows, .n = n, .k = k }, .random, 99 + sk); + @memcpy(p1.rig.bytes(p1.x, rows * k * 2), p7.rig.bytes(p7.x, rows * k * 2)); + if (P == Bf16Probe) { + @memcpy(p1.rig.bytes(p1.w, n * k * 2), p7.rig.bytes(p7.w, n * k * 2)); + } else { + const wb = awq.weightWords(n, k, if (is_m5_m) .m5_tile else .m3_row) * 4; + @memcpy(p1.rig.bytes(p1.w, wb), p7.rig.bytes(p7.w, wb)); + @memcpy(p1.rig.bytes(p1.sb, awq.metaCount(n, k) * 8), p7.rig.bytes(p7.sb, awq.metaCount(n, k) * 8)); + } + try p1.run(); + if (!std.mem.eql(u8, ref[0 .. rows * n * 2], p1.rig.bytes(p1.y, rows * n * 2))) return error.RowInvarianceFailed; + } + } + + fn checkEncodeAwqInv(s: *Suite) !void { + var gpu = lgpu.LinearGpu.init(s.a, s.device); + defer gpu.deinit(); + try gpu.reserve(64, true); + const n: u32 = 256; + const k: u32 = 1024; + const opts = mtl.ResourceOptions.shared; + const w_buf = try s.device.buffer(@as(usize, n) * k * 2, opts); + defer w_buf.deinit(); + const x_buf = try s.device.buffer(@as(usize, 33) * k * 2, opts); + defer x_buf.deinit(); + const y_ref = try s.device.buffer(@as(usize, 33) * n * 2, opts); + defer y_ref.deinit(); + const y_cur = try s.device.buffer(@as(usize, 16) * n * 2, opts); + defer y_cur.deinit(); + var prng = std.Random.DefaultPrng.init(0x3333); + for (w_buf.slice(u16, @as(usize, n) * k)) |*d| d.* = c.toBf16((prng.random().float(f32) * 2.0 - 1.0) * 0.25); + for (x_buf.slice(u16, @as(usize, 33) * k)) |*d| d.* = c.toBf16((prng.random().float(f32) * 2.0 - 1.0) * 1.5); + var mat = try bf16_k.packBf16AsAwq(&gpu, w_buf.slice(u16, @as(usize, n) * k), n, k); + defer mat.deinit(); + for ([_]u32{ 33, 1, 4, 8, 16 }) |rows| { + const dst = if (rows == 33) y_ref else y_cur; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = s.queue.commandBuffer(); + const e = cb.compute(.serial); + try gpu.encodeAwq(e, mat, .{ .buf = x_buf }, null, .{ .buf = dst }, rows, n, false, null); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |_| return error.GpuFailed; + if (rows != 33 and !std.mem.eql(u16, y_ref.slice(u16, rows * n), y_cur.slice(u16, rows * n))) { + return error.RowInvarianceFailed; + } + } + } + + /// Gate 3 row-invariance: 1, 3, 7 rows per launch produce identical row bytes to single-row launches. + pub fn rowCountInvariant(s: *Suite) !void { + const bf_lib = try s.getLib(false, 0); + const awq_lib = try s.getLib(true, 0); + for ([_]u32{ 1, 2, 4, 8 }) |sk| { + try s.checkInv(Bf16Probe, bf_lib, .mv, sk); + try s.checkInv(AwqProbe, awq_lib, AwqVariant.m3_mv, sk); + if (s.device.tensorUnits()) { + try s.checkInv(AwqProbe, awq_lib, AwqVariant.m5_mv, sk); + try s.checkInv(AwqProbe, awq_lib, AwqVariant.m5_lane, sk); + } + } + if (s.device.tensorUnits()) try s.checkInv(AwqProbe, awq_lib, AwqVariant.m5_gemm, 1); + try s.checkEncodeAwqInv(); + try bf16_k.checkBf16Split(s.a, s.device, s.queue); + try bf16_k.checkAwqSplitAndQuant(s.a, s.device, s.queue); + std.debug.print("PASS row-invariance sensenova bf16_mv, awq_row_mv{s}, encodeAwq (1,4,8,16,33), awq split + quant\n", .{if (s.device.tensorUnits()) ", awq_m5_mv, awq_lane, awq_gemm_m5" else ""}); + } +}; + +pub fn limits(a: std.mem.Allocator, device: mtl.Device, only: ?[]const u8) !usize { + const tensor = device.tensorUnits(); + var list: std.ArrayList(contract.limits.MetalLaunch) = .empty; + defer list.deinit(a); + for (records.records) |d| { + if (only) |needle| if (std.mem.indexOf(u8, d.name, needle) == null) continue; + if (records.isM5Only(d.name) and !tensor) continue; + try list.append(a, d); + } + var probs = try contract.registry.checkMetal(a, list.items, false); + const bf_src = try tf.frags.source(device, a, @import("kernel_sources").qwen27_bf16_linear); + defer a.free(bf_src); + const awq_src = try tf.frags.source(device, a, @import("kernel_sources").qwen27_awq_w4a16); + defer a.free(awq_src); + for (list.items) |d| { + const fun = d.name[std.mem.lastIndexOfScalar(u8, d.name, ' ').? + 1 ..]; + const src = if (std.mem.startsWith(u8, d.name, "sensenova linear ")) bf_src else awq_src; + probs += try limits_k.onThisGpu(a, device, .{ .decl = d, .function = fun, .here = src, .pre_m5 = src }, false); + } + const bad = contract.limits.MetalLaunch{ .name = "control: sensenova 40 KiB tg", .threads = 256, .tg_memory = 40 * 1024 }; + if (try contract.registry.checkMetal(a, &.{bad}, true) == 0) probs += 1; + return probs; +} diff --git a/zig/tests/contract/metal_sensenova_mhc.zig b/zig/tests/contract/metal_sensenova_mhc.zig new file mode 100644 index 00000000000..1110458acd9 --- /dev/null +++ b/zig/tests/contract/metal_sensenova_mhc.zig @@ -0,0 +1,592 @@ +//! Two-stream mHC contract suite for SenseNova-Loop: Gates 1-5, planted controls, row invariance and xsum parity. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const sources = @import("kernel_sources"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); +const limits_mod = @import("metal_limits.zig"); +const offline_mod = @import("metal_offline.zig"); + +const c = contract.spec; +const g = contract.gates; +const mhc = tf.sensenova_loop.mhc_metal; +const ref = tf.sensenova_loop.mhc_ref; +const base = "sensenova mhc "; + +pub const Kind = enum { enter, pre_norm, post_merge, post_merge_exit, post_and_pre_norm }; + +const hidden_max = ref.max_hidden; +const served_shapes = [_]c.Shape{ + .{ .rows = 16, .n = 1, .k = hidden_max }, + .{ .rows = 1, .n = 1, .k = hidden_max }, + .{ .rows = 7, .n = 1, .k = hidden_max }, +}; + +fn oneDepth(_: c.Shape) usize { + return 1; +} + +fn postDepth(_: c.Shape) usize { + return 4; +} + +fn preNormDepth(s: c.Shape) usize { + return 2 * s.k / 256 + 16; +} + +pub fn spec(k: Kind, name: []const u8) c.Spec { + const t = [_]c.Tile{ .{ .size = 8, .step = 1, .min = 1 }, .{}, .{ .size = 256, .step = 1, .min = 1 } }; + return switch (k) { + .enter => .{ .name = name, .accum = .none, .depth = oneDepth, .out = .bf16, .tiles = t, .served = &served_shapes, .sums = .{ .f16 = 0, .bf16 = 0, .why = "elementwise stream expansion has no reduction sum" } }, + .pre_norm => .{ .name = name, .accum = .f32, .depth = preNormDepth, .ops = 260, .mids = 2, .out = .bf16, .tiles = t, .served = &served_shapes, .sums = .{ .why = "fp32 sqrsum, matvec and branch RMSNorm" } }, + .post_merge => .{ .name = name, .accum = .f32, .depth = postDepth, .ops = 2, .mids = 1, .out = .bf16, .tiles = t, .served = &served_shapes, .sums = .{ .why = "fp32 residual stream mix and post-weighted branch sum" } }, + .post_merge_exit => .{ .name = name, .accum = .f32, .depth = postDepth, .ops = 2, .mids = 2, .out = .bf16, .tiles = t, .served = &served_shapes, .sums = .{ .why = "fp32 residual mix, branch sum and exit stream mean" } }, + .post_and_pre_norm => .{ .name = name, .accum = .f32, .depth = preNormDepth, .ops = 260, .mids = 2, .out = .bf16, .tiles = t, .served = &served_shapes, .sums = .{ .why = "fused fp32 post-merge + log-Sinkhorn + collapsed RMSNorm" }, .replaces = "sn_mhc_post_merge + sn_mhc_pre_norm" }, + }; +} + +fn mRef(r: rig_.Ref, extra: usize) mhc.Ref { + return .{ .buf = r.buf, .off = r.off + extra }; +} + +fn hasPre(k: Kind) bool { + return k == .pre_norm or k == .post_and_pre_norm; +} + +fn hasPost(k: Kind) bool { + return k == .post_merge or k == .post_merge_exit or k == .post_and_pre_norm; +} + +const vt = g.hooks(Proj); +const plain_vt = blk: { + var v = g.hooks(Proj); + v.replaced = null; + break :blk v; +}; + +pub const Proj = struct { + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + kind: Kind, + ctl: u8, + name: []const u8, + pipes: mhc.Pipelines, + shape: c.Shape = undefined, + h_in: []u16 = &.{}, + r_in: []u16 = &.{}, + y_in: []u16 = &.{}, + coeff_in: []u16 = &.{}, + w: []f32 = &.{}, + b: []f32 = &.{}, + sub_w: []u16 = &.{}, + in_a: rig_.Ref = undefined, + in_b: rig_.Ref = undefined, + in_c: rig_.Ref = undefined, + in_w: rig_.Ref = undefined, + in_bias: rig_.Ref = undefined, + in_sub: rig_.Ref = undefined, + out: [3]rig_.Ref = undefined, + out_len: [3]usize = .{ 0, 0, 0 }, + n_outs: usize = 0, + xs_group: u32 = 0, + xs_stride: u32 = 0, + shift_norm: bool = true, + pre_scale: f32 = 1.0, + has_pending: bool = false, + write_h: bool = false, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, k: Kind, ctl: u8, name: []const u8) !Proj { + const pipes = if (ctl == 0) try mhc.Pipelines.load(device) else blk: { + const text = try std.fmt.allocPrint(a, "#define TF_CTL {d}\n{s}", .{ ctl, sources.core_sensenova_mhc }); + defer a.free(text); + break :blk try mhc.Pipelines.loadSource(device, text); + }; + return .{ .a = a, .arena = std.heap.ArenaAllocator.init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .kind = k, .ctl = ctl, .name = name, .pipes = pipes }; + } + + pub fn deinit(p: *Proj) void { + p.pipes.deinit(); + p.rig.deinit(); + p.arena.deinit(); + } + + pub fn kernel(p: *Proj) g.Kernel { + const control: ?g.Gate = switch (p.ctl) { + 1 => .nonfinite, + 3 => .sums, + 2, 4, 5 => .shapes, + else => null, + }; + var s = spec(p.kind, p.name); + if (p.ctl == 0) return .{ .spec = s, .ctx = p, .vt = &vt, .control = null }; + s.replaces = null; + return .{ .spec = s, .ctx = p, .vt = &plain_vt, .control = control }; + } + + pub fn count(p: *Proj) usize { + const rows = p.shape.rows; + const h = p.shape.k; + return switch (p.kind) { + .enter => rows * (2 * h + if (p.write_h) h else 0), + .pre_norm => rows * (ref.coeff_width + h), + .post_merge => rows * 2 * h, + .post_merge_exit => rows * h, + .post_and_pre_norm => rows * (2 * h + ref.coeff_width + h), + }; + } + + fn allocHost(p: *Proj, rows: usize, h: usize) !void { + const aa = p.arena.allocator(); + p.h_in = if (p.kind == .enter) try aa.alloc(u16, rows * h) else &.{}; + p.r_in = if (p.kind != .enter) try aa.alloc(u16, rows * 2 * h) else &.{}; + p.y_in = if (hasPost(p.kind) or p.has_pending) try aa.alloc(u16, rows * h) else &.{}; + p.coeff_in = if (hasPost(p.kind)) try aa.alloc(u16, rows * ref.coeff_width) else &.{}; + p.w = if (hasPre(p.kind)) try aa.alloc(f32, 8 * 2 * h) else &.{}; + p.b = if (hasPre(p.kind)) try aa.alloc(f32, 8) else &.{}; + p.sub_w = if (hasPre(p.kind)) try aa.alloc(u16, h) else &.{}; + } + + fn fillRandom(p: *Proj, rows: usize, seed: u64) void { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (p.h_in) |*v| v.* = ref.toBf16((rng.float(f32) * 2 - 1) * 4); + for (p.r_in) |*v| v.* = ref.toBf16((rng.float(f32) * 2 - 1) * 4); + for (p.y_in) |*v| v.* = ref.toBf16((rng.float(f32) * 2 - 1) * 4); + for (p.w) |*v| v.* = (rng.float(f32) * 2 - 1) * 0.04; + for (p.b) |*v| v.* = (rng.float(f32) * 2 - 1) * 0.5; + for (p.sub_w) |*v| v.* = ref.toBf16((rng.float(f32) * 2 - 1) * 0.5); + for (0..if (hasPost(p.kind)) rows else 0) |r| { + for (p.coeff_in[r * ref.coeff_width ..][0..ref.coeff_width]) |*v| v.* = ref.toBf16(0.25 + rng.float(f32)); + } + } + + fn fillNonfinite(p: *Proj, rows: usize, h: usize) void { + const nan16 = ref.toBf16(std.math.nan(f32)); + const pinf16 = ref.toBf16(std.math.inf(f32)); + const ninf16 = ref.toBf16(-std.math.inf(f32)); + @memset(p.h_in, ref.toBf16(1.0)); + @memset(p.r_in, ref.toBf16(1.0)); + @memset(p.y_in, ref.toBf16(1.0)); + @memset(p.w, 0.01); + @memset(p.b, 0.0); + @memset(p.sub_w, ref.toBf16(0.5)); + for (0..if (hasPost(p.kind)) rows else 0) |r| { + p.coeff_in[r * ref.coeff_width ..][0..ref.coeff_width].* = .{ ref.toBf16(1.0), ref.toBf16(1.0), ref.toBf16(0.5), ref.toBf16(0.5), ref.toBf16(0.5), ref.toBf16(0.5) }; + } + switch (p.kind) { + .enter => { + p.h_in[0] = nan16; + if (rows > 1) p.h_in[h] = pinf16; + if (rows > 2) p.h_in[2 * h] = ninf16; + }, + .pre_norm => { + p.r_in[0] = nan16; + p.sub_w[0] = pinf16; + if (h > 1) p.sub_w[1] = ninf16; + }, + .post_merge, .post_merge_exit => { + p.y_in[0] = nan16; + if (rows > 1) p.y_in[h] = pinf16; + if (rows > 2) p.y_in[2 * h] = ninf16; + }, + .post_and_pre_norm => { + p.y_in[0] = nan16; + if (rows > 1) p.y_in[h + @intFromBool(h > 1)] = pinf16; + if (rows > 2) p.y_in[2 * h + (if (h > 2) @as(usize, 2) else 0)] = ninf16; + if (h > 3) p.sub_w[3] = pinf16; + if (h > 4) p.sub_w[4] = ninf16; + }, + } + } + + fn fillStressPre(p: *Proj, rows: usize, h: usize) void { + const two_h = 2 * h; + const half_h = h / 2; + var ss: f64 = 0; + for (0..h) |d| { + const v: f32 = @floatFromInt(16 + (d % 8)); + const vb = ref.toBf16(v); + const v1 = if (d < half_h) ref.toBf16(-v) else vb; + for (0..rows) |r| { + p.r_in[(r * 2 + 0) * h + d] = vb; + p.r_in[(r * 2 + 1) * h + d] = v1; + } + ss += 2.0 * @as(f64, ref.fromBf16(vb)) * @as(f64, ref.fromBf16(vb)); + } + const inv_rms = 1.0 / @sqrt(ss / @as(f64, @floatFromInt(two_h)) + 1e-6); + var nudge: f64 = 0; + for (0..@min(@as(usize, 8), h)) |d| { + const v: f64 = @floatFromInt(16 + (d % 8)); + nudge += if (d < half_h) -v else v; + } + for (0..8) |m| { + const wm = p.w[m * two_h ..][0..two_h]; + for (0..h) |d| { + const bw: f32 = @floatFromInt(1 + ((d + m) % 7)); + wm[d] = bw; + wm[h + d] = (if (d < half_h) bw else -bw) + @as(f32, @floatFromInt(@intFromBool(d < 8))); + } + p.b[m] = @floatCast(-nudge * inv_rms + if (m == 2) @as(f64, -8.0) else 0.0); + } + for (0..two_h) |j| p.w[two_h + j] = -p.w[j]; + p.b[1] = -p.b[0]; + @memset(p.sub_w, ref.toBf16(0.5)); + } + + fn fillStressPost(p: *Proj, rows: usize, h: usize, fused: bool) void { + for (0..rows) |r| { + p.coeff_in[r * ref.coeff_width ..][0..ref.coeff_width].* = .{ ref.toBf16(1.0), ref.toBf16(1.0), ref.toBf16(19.0 / 16.0), ref.toBf16(-1.0), ref.toBf16(19.0 / 16.0), ref.toBf16(-1.0) }; + for (0..h) |d| { + p.r_in[(r * 2 + 0) * h + d] = ref.toBf16(16768.0); + p.r_in[(r * 2 + 1) * h + d] = ref.toBf16(19840.0); + const target: f32 = if (!fused or d == 0) 0.5 else @floatFromInt(16 + (d % 8)); + p.y_in[r * h + d] = ref.toBf16(-(72.0 - target)); + } + } + if (fused) { + const two_h = 2 * h; + var ss: f64 = 0.25 * 2.0; + for (1..h) |d| { + const v: f64 = @floatFromInt(16 + (d % 8)); + ss += 2.0 * v * v; + } + const inv_rms = 1.0 / @sqrt(ss / @as(f64, @floatFromInt(two_h)) + 1e-6); + var nudge: f64 = 0; + for (1..@min(@as(usize, 9), h)) |d| nudge += @floatFromInt(16 + (d % 8)); + for (0..8) |m| { + const wm = p.w[m * two_h ..][0..two_h]; + for (0..h) |d| { + const bw: f32 = @floatFromInt(1 + ((d + m) % 7)); + wm[d] = bw; + wm[h + d] = -bw + @as(f32, @floatFromInt(@intFromBool(d >= 1 and d < 9))); + } + p.b[m] = @floatCast(-nudge * inv_rms + if (m == 2) @as(f64, -8.0) else 0.0); + } + @memset(p.sub_w, ref.toBf16(0.5)); + } + } + + pub fn prepare(p: *Proj, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.k > hidden_max) return false; + if (p.xs_group != 0 and ((p.xs_group != 64 and p.xs_group != 128) or shape.k % p.xs_group != 0)) return false; + p.rig.reset(); + _ = p.arena.reset(.retain_capacity); + p.shape = shape; + const n = shape.rows; + const h = shape.k; + try p.allocHost(n, h); + switch (fill) { + .random => p.fillRandom(n, seed), + .nonfinite => p.fillNonfinite(n, h), + .stress => switch (p.kind) { + .enter => p.fillRandom(n, seed), + .pre_norm => p.fillStressPre(n, h), + .post_merge, .post_merge_exit => p.fillStressPost(n, h, false), + .post_and_pre_norm => p.fillStressPost(n, h, true), + }, + } + try p.bindBuffers(n, h); + return true; + } + + fn bindBuffers(p: *Proj, n: usize, h: usize) !void { + p.in_a = try p.rig.input(std.mem.sliceAsBytes(if (p.kind == .enter) p.h_in else p.r_in)); + p.in_b = if (hasPost(p.kind) or p.has_pending) try p.rig.input(std.mem.sliceAsBytes(p.y_in)) else p.in_a; + p.in_c = if (hasPost(p.kind)) try p.rig.input(std.mem.sliceAsBytes(p.coeff_in)) else p.in_a; + p.in_w = if (hasPre(p.kind)) try p.rig.input(std.mem.sliceAsBytes(p.w)) else p.in_a; + p.in_bias = if (hasPre(p.kind)) try p.rig.input(std.mem.sliceAsBytes(p.b)) else p.in_a; + p.in_sub = if (hasPre(p.kind)) try p.rig.input(std.mem.sliceAsBytes(p.sub_w)) else p.in_a; + const lens: [3]usize = switch (p.kind) { + .enter => .{ n * 2 * h * 2, if (p.write_h) n * h * 2 else 0, 0 }, + .pre_norm => .{ n * ref.coeff_width * 2, n * h * 2, 0 }, + .post_merge => .{ n * 2 * h * 2, 0, 0 }, + .post_merge_exit => .{ n * h * 2, 0, 0 }, + .post_and_pre_norm => .{ n * 2 * h * 2, n * ref.coeff_width * 2, n * h * 2 }, + }; + p.out_len = lens; + p.n_outs = 0; + for (lens, 0..) |len, i| if (len > 0) { + p.out[i] = try p.rig.output(len); + p.n_outs = i + 1; + }; + } + + pub fn encode(p: *Proj, e: anytype, r0: usize, n: usize, xs_out: ?rig_.Ref) void { + const rows: u32 = @intCast(n); + const h: u32 = @intCast(p.shape.k); + const call = mhc.PreNormCall{ .iters = 20, .shift_norm = p.shift_norm, .xs_group = p.xs_group, .xs_stride = if (p.xs_group != 0) p.xs_stride else 0, .pre_scale = p.pre_scale, .eps = 1e-6 }; + const xs_ref: ?mhc.Ref = if (xs_out) |xr| mRef(xr, r0 * 4) else null; + switch (p.kind) { + .enter => mhc.enter(&p.pipes, e, mRef(p.in_a, r0 * h * 2), if (p.has_pending) mRef(p.in_b, r0 * h * 2) else null, mRef(p.out[0], r0 * 2 * h * 2), if (p.write_h) mRef(p.out[1], r0 * h * 2) else null, rows, h) catch unreachable, + .pre_norm => mhc.preNorm(&p.pipes, e, mRef(p.in_a, r0 * 2 * h * 2), mRef(p.in_w, 0), mRef(p.in_bias, 0), mRef(p.in_sub, 0), mRef(p.out[0], r0 * ref.coeff_width * 2), mRef(p.out[1], r0 * h * 2), xs_ref, rows, h, call) catch unreachable, + .post_merge, .post_merge_exit => mhc.postMerge(&p.pipes, e, mRef(p.in_a, r0 * 2 * h * 2), mRef(p.in_b, r0 * h * 2), mRef(p.in_c, r0 * ref.coeff_width * 2), mRef(p.out[0], r0 * (if (p.kind == .post_merge_exit) h else 2 * h) * 2), rows, h, p.kind == .post_merge_exit) catch unreachable, + .post_and_pre_norm => mhc.postAndPreNorm(&p.pipes, e, mRef(p.in_a, r0 * 2 * h * 2), mRef(p.in_b, r0 * h * 2), mRef(p.in_c, r0 * ref.coeff_width * 2), mRef(p.in_w, 0), mRef(p.in_bias, 0), mRef(p.in_sub, 0), mRef(p.out[0], r0 * 2 * h * 2), mRef(p.out[1], r0 * ref.coeff_width * 2), mRef(p.out[2], r0 * h * 2), xs_ref, rows, h, call) catch unreachable, + } + } + + pub fn run(p: *Proj) !void { + const pass = p.rig.begin(); + p.encode(pass.e, 0, p.shape.rows, null); + try p.rig.finish(pass); + } + + pub fn replaced(p: *Proj) ![]const u8 { + const rows: u32 = @intCast(p.shape.rows); + const h: u32 = @intCast(p.shape.k); + const call = mhc.PreNormCall{ .shift_norm = p.shift_norm, .pre_scale = p.pre_scale, .eps = 1e-6 }; + const pass = p.rig.begin(); + try mhc.postMerge(&p.pipes, pass.e, mRef(p.in_a, 0), mRef(p.in_b, 0), mRef(p.in_c, 0), mRef(p.out[0], 0), rows, h, false); + try mhc.preNorm(&p.pipes, pass.e, mRef(p.out[0], 0), mRef(p.in_w, 0), mRef(p.in_bias, 0), mRef(p.in_sub, 0), mRef(p.out[1], 0), mRef(p.out[2], 0), null, rows, h, call); + try p.rig.finish(pass); + return p.rig.outputBytes(); + } + + fn computeModel(p: *Proj, acc: ref.Accum, order: ref.Order, want: []f64, mag: []f64) !void { + const rows = p.shape.rows; + const h = p.shape.k; + const params = ref.Params{ .hidden = h, .iterations = 20, .pre_scale = p.pre_scale, .eps = 1e-6, .shift_norm = p.shift_norm }; + const aa = p.arena.allocator(); + switch (p.kind) { + .enter => ref.enterRef(p.h_in, if (p.has_pending) p.y_in else null, rows, h, want[0 .. rows * 2 * h], mag[0 .. rows * 2 * h], if (p.write_h) want[rows * 2 * h ..] else null, if (p.write_h) mag[rows * 2 * h ..] else null), + .pre_norm => { + const c_n = rows * ref.coeff_width; + try ref.preNormRef(aa, .{ .r_in = p.r_in, .w = p.w, .b = p.b, .sub_w = p.sub_w }, rows, params, acc, order, .{ .coeff = want[0..c_n], .mag_coeff = mag[0..c_n], .norm = want[c_n..], .mag_norm = mag[c_n..] }); + }, + .post_merge, .post_merge_exit => ref.postMergeRef(p.r_in, p.y_in, p.coeff_in, rows, h, p.kind == .post_merge_exit, acc, order, want, mag), + .post_and_pre_norm => { + const r_n = rows * 2 * h; + const c_n = rows * ref.coeff_width; + try ref.postAndPreNormRef(aa, p.r_in, p.y_in, p.coeff_in, p.w, p.b, p.sub_w, rows, params, acc, order, want[0..r_n], mag[0..r_n], .{ .coeff = want[r_n .. r_n + c_n], .mag_coeff = mag[r_n .. r_n + c_n], .norm = want[r_n + c_n ..], .mag_norm = mag[r_n + c_n ..] }); + }, + } + } + + pub fn reference(p: *Proj, want: []f64, mag: []f64) !void { + try p.computeModel(.none, .sequential, want, mag); + } + + pub fn simulate(p: *Proj, acc: c.Accum, order: g.Order, out: []f64) !void { + const m_acc: ref.Accum = switch (acc) { + .f32 => .f32, + .f16 => .f16, + .bf16 => .bf16, + .none => .none, + }; + const m_ord: ref.Order = switch (order) { + .sequential => .sequential, + .pairwise => .pairwise, + .strided => .strided, + }; + const mag = try p.arena.allocator().alloc(f64, p.count()); + try p.computeModel(m_acc, m_ord, out, mag); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + probes: std.ArrayList(*Proj) = .empty, + + const E = struct { k: Kind, ctl: u8, name: []const u8 }; + const list = [_]E{ + .{ .k = .enter, .ctl = 0, .name = base ++ "enter sn_mhc_enter" }, + .{ .k = .pre_norm, .ctl = 0, .name = base ++ "pre_norm sn_mhc_pre_norm" }, + .{ .k = .post_merge, .ctl = 0, .name = base ++ "post_merge sn_mhc_post_merge" }, + .{ .k = .post_merge_exit, .ctl = 0, .name = base ++ "post_merge_exit sn_mhc_post_merge" }, + .{ .k = .post_and_pre_norm, .ctl = 0, .name = base ++ "post_and_pre_norm sn_mhc_post_and_pre_norm" }, + .{ .k = .enter, .ctl = 1, .name = base ++ "control: enter non-finite flushed to zero" }, + .{ .k = .enter, .ctl = 2, .name = base ++ "control: enter zeroes second stream" }, + .{ .k = .enter, .ctl = 4, .name = base ++ "control: enter skips tail element" }, + .{ .k = .pre_norm, .ctl = 1, .name = base ++ "control: pre_norm non-finite flushed to zero" }, + .{ .k = .pre_norm, .ctl = 2, .name = base ++ "control: pre_norm skips Sinkhorn" }, + .{ .k = .pre_norm, .ctl = 3, .name = base ++ "control: pre_norm fp16 sum" }, + .{ .k = .pre_norm, .ctl = 4, .name = base ++ "control: pre_norm skips tail element" }, + .{ .k = .pre_norm, .ctl = 5, .name = base ++ "control: pre_norm transposes W" }, + .{ .k = .post_merge, .ctl = 1, .name = base ++ "control: post_merge non-finite flushed to zero" }, + .{ .k = .post_merge, .ctl = 2, .name = base ++ "control: post_merge drops post weight" }, + .{ .k = .post_merge, .ctl = 3, .name = base ++ "control: post_merge fp16 sum" }, + .{ .k = .post_merge, .ctl = 4, .name = base ++ "control: post_merge skips tail element" }, + .{ .k = .post_merge, .ctl = 5, .name = base ++ "control: post_merge transposes mix" }, + .{ .k = .post_merge_exit, .ctl = 1, .name = base ++ "control: post_merge_exit non-finite flushed to zero" }, + .{ .k = .post_merge_exit, .ctl = 2, .name = base ++ "control: post_merge_exit drops post weight" }, + .{ .k = .post_merge_exit, .ctl = 3, .name = base ++ "control: post_merge_exit fp16 sum" }, + .{ .k = .post_merge_exit, .ctl = 4, .name = base ++ "control: post_merge_exit skips tail element" }, + .{ .k = .post_merge_exit, .ctl = 5, .name = base ++ "control: post_merge_exit transposes mix" }, + .{ .k = .post_and_pre_norm, .ctl = 1, .name = base ++ "control: post_and_pre_norm non-finite flushed to zero" }, + .{ .k = .post_and_pre_norm, .ctl = 2, .name = base ++ "control: post_and_pre_norm drops post or Sinkhorn" }, + .{ .k = .post_and_pre_norm, .ctl = 3, .name = base ++ "control: post_and_pre_norm fp16 sum" }, + .{ .k = .post_and_pre_norm, .ctl = 4, .name = base ++ "control: post_and_pre_norm skips tail element" }, + .{ .k = .post_and_pre_norm, .ctl = 5, .name = base ++ "control: post_and_pre_norm transposes mix" }, + }; + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a, .device = device, .queue = queue }; + for (list) |entry| { + if (only) |text| if (std.mem.indexOf(u8, entry.name, text) == null) continue; + const p = try a.create(Proj); + p.* = try Proj.init(a, device, queue, entry.k, entry.ctl, entry.name); + try s.probes.append(a, p); + try kernels.append(a, p.kernel()); + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + s.a.destroy(s); + } + + /// Launches of 1, 7 and 11 rows/launch equal one launch at rows = 33, plus xs_group and pending checks. + pub fn invariance(s: *Suite, seed: u64) !usize { + var bad: usize = 0; + var launches: usize = 0; + var kernels: usize = 0; + for (s.probes.items) |p| { + if (p.ctl != 0) continue; + kernels += 1; + const shape = c.Shape{ .rows = 33, .n = 1, .k = hidden_max }; + if (!try p.prepare(shape, .random, seed)) return error.Refused; + try p.run(); + const whole = try s.a.dupe(u8, try p.rig.outputBytes()); + defer s.a.free(whole); + for ([_]usize{ 1, 7, 11 }) |step| { + for (p.out[0..p.n_outs], p.out_len[0..p.n_outs]) |o, len| @memset(p.rig.bytes(o, len), 0x55); + const pass = p.rig.begin(); + var r0: usize = 0; + while (r0 < shape.rows) : (r0 += step) { + p.encode(pass.e, r0, @min(step, shape.rows - r0), null); + launches += 1; + } + try p.rig.finish(pass); + if (!std.mem.eql(u8, whole, try p.rig.outputBytes())) { + bad += 1; + std.debug.print("FAIL row invariance {s}: {d} rows/launch differs\n", .{ p.name, step }); + } + } + } + if (kernels > 0) bad += try s.checkExtras(seed); + if (kernels == 0) return 0; + std.debug.print("{s} row invariance {s}: {d} kernels at 1, 7 and 11 rows ({d} launches) + xsum/pending, {d} differ\n", .{ if (bad == 0) "PASS" else "FAIL", base, kernels, launches, bad }); + return bad; + } + + fn checkExtras(s: *Suite, seed: u64) !usize { + var bad: usize = 0; + var ep = try Proj.init(s.a, s.device, s.queue, .enter, 0, base ++ "enter_pending"); + defer ep.deinit(); + ep.has_pending = true; + ep.write_h = true; + if (!try ep.prepare(.{ .rows = 9, .n = 1, .k = 257 }, .random, seed + 1)) return 1; + try ep.run(); + const e_sim = try s.a.alloc(u16, ep.count()); + defer s.a.free(e_sim); + ref.enterSim(ep.h_in, ep.y_in, 9, 257, e_sim[0 .. 9 * 2 * 257], e_sim[9 * 2 * 257 ..]); + if (!std.mem.eql(u8, try ep.rig.outputBytes(), std.mem.sliceAsBytes(e_sim))) bad += 1; + for ([_]u32{ 64, 128 }) |xg| bad += try s.checkXsumAndFused(xg, seed); + return bad; + } + + fn checkXsumAndFused(s: *Suite, xs_group: u32, seed: u64) !usize { + var bad: usize = 0; + const rows: usize = 5; + const h: usize = hidden_max; + const groups = h / xs_group; + var fp = try Proj.init(s.a, s.device, s.queue, .post_and_pre_norm, 0, base ++ "xs_fused"); + defer fp.deinit(); + fp.shift_norm = false; + fp.pre_scale = 0.5; + fp.xs_group = xs_group; + fp.xs_stride = rows; + if (!try fp.prepare(.{ .rows = rows, .n = 1, .k = h }, .random, seed + xs_group)) return 1; + const xs_bytes = groups * rows * 4; + const xs_fused = try fp.rig.scratch(xs_bytes); + const xs_seq = try fp.rig.scratch(xs_bytes); + const pass1 = fp.rig.begin(); + fp.encode(pass1.e, 0, rows, xs_fused); + try fp.rig.finish(pass1); + const fused_out = try s.a.dupe(u8, try fp.rig.outputBytes()); + defer s.a.free(fused_out); + const fused_xs = try s.a.dupe(u8, fp.rig.bytes(xs_fused, xs_bytes)); + defer s.a.free(fused_xs); + + const call = mhc.PreNormCall{ .shift_norm = false, .xs_group = xs_group, .xs_stride = rows, .pre_scale = 0.5, .eps = 1e-6 }; + const pass2 = fp.rig.begin(); + try mhc.postMerge(&fp.pipes, pass2.e, mRef(fp.in_a, 0), mRef(fp.in_b, 0), mRef(fp.in_c, 0), mRef(fp.out[0], 0), rows, h, false); + try mhc.preNorm(&fp.pipes, pass2.e, mRef(fp.out[0], 0), mRef(fp.in_w, 0), mRef(fp.in_bias, 0), mRef(fp.in_sub, 0), mRef(fp.out[1], 0), mRef(fp.out[2], 0), mRef(xs_seq, 0), rows, h, call); + try fp.rig.finish(pass2); + if (!std.mem.eql(u8, fused_out, try fp.rig.outputBytes())) { + std.debug.print("FAIL xsum fused_out != seq_out (xg={d})\n", .{xs_group}); + bad += 1; + } + if (!std.mem.eql(u8, fused_xs, fp.rig.bytes(xs_seq, xs_bytes))) { + std.debug.print("FAIL xsum fused_xs != seq_xs (xg={d})\n", .{xs_group}); + bad += 1; + } + + const norm_bytes = fp.rig.bytes(fp.out[2], rows * h * 2); + for (0..groups) |g_idx| { + for (0..rows) |r_idx| { + var sum_gpu: f32 = 0; + var sum_abs: f32 = 0; + for (0..xs_group) |i| { + const b16 = std.mem.readInt(u16, norm_bytes[2 * (r_idx * h + g_idx * xs_group + i) ..][0..2], .little); + const fv = ref.fromBf16(b16); + sum_gpu += fv; + sum_abs += @abs(fv); + } + const xs_idx = g_idx * rows + r_idx; + const g_v: f32 = @bitCast(std.mem.readInt(u32, fused_xs[4 * xs_idx ..][0..4], .little)); + if (@abs(g_v - sum_gpu) > sum_abs * 1e-5 + 1e-6) { + std.debug.print("FAIL xsum sum mismatch xg={d} g={d} r={d}\n", .{ xs_group, g_idx, r_idx }); + bad += 1; + } + } + } + + const r_sim = try s.a.alloc(u16, rows * 2 * h); + defer s.a.free(r_sim); + const c_sim = try s.a.alloc(u16, rows * ref.coeff_width); + defer s.a.free(c_sim); + const n_sim = try s.a.alloc(u16, rows * h); + defer s.a.free(n_sim); + const xs_sim = try s.a.alloc(f32, groups * rows); + defer s.a.free(xs_sim); + const params = ref.Params{ .hidden = h, .pre_scale = 0.5, .shift_norm = false, .xs_group = xs_group, .xs_stride = rows }; + try ref.postAndPreNormSim(s.a, fp.r_in, fp.y_in, fp.coeff_in, fp.w, fp.b, fp.sub_w, rows, params, r_sim, .{ .coeff = c_sim, .norm = n_sim, .xs = xs_sim }); + for (0..groups * rows) |i| { + const g_v: f32 = @bitCast(std.mem.readInt(u32, fused_xs[4 * i ..][0..4], .little)); + if (@abs(g_v - xs_sim[i]) > 0.05) { + std.debug.print("FAIL xsum sim mismatch xg={d} i={d} gpu={d} sim={d}\n", .{ xs_group, i, g_v, xs_sim[i] }); + bad += 1; + } + } + return bad; + } +}; + +fn launchOf(_: std.mem.Allocator, _: mtl.Device, d: contract.limits.MetalLaunch) !limits_mod.Launch { + const fun = d.name[std.mem.lastIndexOfScalar(u8, d.name, ' ').? + 1 ..]; + return .{ .decl = d, .function = fun, .here = sources.core_sensenova_mhc, .pre_m5 = sources.core_sensenova_mhc }; +} + +pub fn limits(a: std.mem.Allocator, io: std.Io, device: mtl.Device, offline: ?[]const u8, only: ?[]const u8) !usize { + var list: std.ArrayList(contract.limits.MetalLaunch) = .empty; + defer list.deinit(a); + for (contract.registry.sensenova_mhc.records) |d| { + if (only) |needle| if (std.mem.indexOf(u8, d.name, needle) == null) continue; + try list.append(a, d); + } + if (list.items.len == 0) return 0; + var n = try contract.registry.checkMetal(a, list.items, false); + for (list.items) |d| n += try limits_mod.onThisGpu(a, device, try launchOf(a, device, d), false); + if (offline) |dir| n += try offline_mod.run(a, io, dir, list.items, launchOf, device); + return n; +} diff --git a/zig/tests/fixtures/sensenova_loop_config.json b/zig/tests/fixtures/sensenova_loop_config.json new file mode 100644 index 00000000000..279d50ebac1 --- /dev/null +++ b/zig/tests/fixtures/sensenova_loop_config.json @@ -0,0 +1,90 @@ +{ +"base": {"attn_implementation":"sdpa","bos_token_id":null,"dtype":"bfloat16","eos_token_id":248046,"hidden_size":4096,"image_token_id":248056,"loop_settings":{"counts":[2],"end":28,"eval_count":2,"start":4},"model_type":"sensenova_loop","pad_token_id":248044,"patch_conv3d":true,"text_config":{"attention_bias":false,"attention_dropout":0.0,"attn_output_gate":true,"bos_token_id":null,"dtype":"bfloat16","eos_token_id":248044,"full_attention_interval":4,"head_dim":256,"hidden_act":"silu","hidden_size":4096,"initializer_range":0.02,"intermediate_size":12288,"layer_types":["linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention"],"linear_conv_kernel_dim":4,"linear_key_head_dim":128,"linear_num_key_heads":16,"linear_num_value_heads":32,"linear_value_head_dim":128,"mamba_ssm_dtype":"float32","max_position_embeddings":524288,"mlp_only_layers":[],"model_type":"qwen3_5_text","mtp_num_hidden_layers":0,"mtp_use_dedicated_embeddings":false,"num_attention_heads":16,"num_hidden_layers":32,"num_key_value_heads":4,"pad_token_id":248044,"partial_rotary_factor":0.25,"rms_norm_eps":1e-06,"rope_parameters":{"mrope_interleaved":true,"mrope_section":[11,11,10],"partial_rotary_factor":0.25,"rope_theta":10000000,"rope_type":"yarn","factor":2.0,"original_max_position_embeddings":262144},"tie_word_embeddings":false,"use_cache":true,"vocab_size":248320},"tie_word_embeddings":false,"use_cache":true,"video_token_id":248057,"vision_end_token_id":248054,"vision_start_token_id":248053,"mhc":{"end":28,"fixed_identity":false,"iterations":20,"pre_scale":1.0,"start":4,"streams":2},"model_name":"SenseNova-Loop-9B"}, +"cases": [ +{"name":"release config","expect":"accept"}, +{"name":"loop_settings only under text_config","set":{"text_config":{"loop_settings":{"counts":[2],"end":28,"eval_count":2,"start":4}}},"remove":["loop_settings"],"expect":"config"}, +{"name":"loop_settings missing","remove":["loop_settings"],"expect":"config"}, +{"name":"loop_settings not an object","set":{"loop_settings":[2]},"expect":"config"}, +{"name":"mhc only under text_config is ignored","set":{"text_config":{"mhc":{"end":28,"fixed_identity":false,"iterations":20,"pre_scale":1.0,"start":4,"streams":2}}},"remove":["mhc"],"expect":"accept"}, +{"name":"loop_settings.start missing","remove":["loop_settings.start"],"expect":"config"}, +{"name":"loop_settings.end missing","remove":["loop_settings.end"],"expect":"config"}, +{"name":"loop_settings.eval_count missing","remove":["loop_settings.eval_count"],"expect":"config"}, +{"name":"loop_settings.counts missing","remove":["loop_settings.counts"],"expect":"config"}, +{"name":"start equals end","set":{"loop_settings":{"start":28,"end":28}},"expect":"config"}, +{"name":"start after end","set":{"loop_settings":{"start":29,"end":28}},"expect":"config"}, +{"name":"start negative","set":{"loop_settings":{"start":-1}},"expect":"config"}, +{"name":"start zero","set":{"loop_settings":{"start":0}},"expect":"accept"}, +{"name":"end past the layer count","set":{"loop_settings":{"end":33}},"expect":"config"}, +{"name":"end at the layer count","set":{"loop_settings":{"end":32,"counts":[2]}},"expect":"accept"}, +{"name":"eval_count zero","set":{"loop_settings":{"eval_count":0,"counts":[0]}},"expect":"config"}, +{"name":"eval_count one","set":{"loop_settings":{"eval_count":1,"counts":[1]}},"expect":"accept"}, +{"name":"eval_count not an integer","set":{"loop_settings":{"eval_count":2.5,"counts":[2]}},"expect":"config"}, +{"name":"counts differ from eval_count","set":{"loop_settings":{"counts":[3]}},"expect":"config"}, +{"name":"counts has two entries","set":{"loop_settings":{"counts":[2,2]}},"expect":"config"}, +{"name":"counts not a list","set":{"loop_settings":{"counts":2}},"expect":"config"}, +{"name":"use_gate absent","expect":"accept"}, +{"name":"use_gate false","set":{"loop_settings":{"use_gate":false}},"expect":"accept"}, +{"name":"use_gate true","set":{"loop_settings":{"use_gate":true}},"expect":"config"}, +{"name":"use_gate null","set":{"loop_settings":{"use_gate":null}},"expect":"config"}, +{"name":"use_gate a string","set":{"loop_settings":{"use_gate":"false"}},"expect":"config"}, +{"name":"use_gate an integer","set":{"loop_settings":{"use_gate":0}},"expect":"config"}, +{"name":"unknown loop_settings key is ignored","set":{"loop_settings":{"extra":1}},"expect":"accept"}, +{"name":"unknown loop_settings key of another type is ignored","set":{"loop_settings":{"note":"x","nested":{"a":[1]}}},"expect":"accept"}, +{"name":"mhc null","set":{"mhc":null},"expect":"accept"}, +{"name":"mhc absent","remove":["mhc"],"expect":"accept"}, +{"name":"mhc not an object","set":{"mhc":[1]},"expect":"config"}, +{"name":"unknown mhc key","set":{"mhc":{"extra":1}},"expect":"config"}, +{"name":"mhc.start missing","remove":["mhc.start"],"expect":"config"}, +{"name":"mhc.end missing","remove":["mhc.end"],"expect":"config"}, +{"name":"mhc.streams missing","remove":["mhc.streams"],"expect":"config"}, +{"name":"mhc.iterations missing","remove":["mhc.iterations"],"expect":"config"}, +{"name":"mhc.fixed_identity missing","remove":["mhc.fixed_identity"],"expect":"config"}, +{"name":"mhc.pre_scale missing","remove":["mhc.pre_scale"],"expect":"accept"}, +{"name":"mhc range crossing the loop start","set":{"mhc":{"start":3,"end":5}},"expect":"config"}, +{"name":"mhc range crossing the loop end","set":{"mhc":{"start":27,"end":29}},"expect":"config"}, +{"name":"mhc range across the whole loop and more","set":{"mhc":{"start":0,"end":32}},"expect":"config"}, +{"name":"mhc range inside the first phase","set":{"mhc":{"start":0,"end":4}},"expect":"accept"}, +{"name":"mhc range inside the last phase","set":{"mhc":{"start":28,"end":32}},"expect":"accept"}, +{"name":"mhc range of one layer","set":{"mhc":{"start":4,"end":5}},"expect":"accept"}, +{"name":"mhc range of one layer at the loop end","set":{"mhc":{"start":27,"end":28}},"expect":"accept"}, +{"name":"mhc start equals end","set":{"mhc":{"start":6,"end":6}},"expect":"config"}, +{"name":"mhc start after end","set":{"mhc":{"start":7,"end":6}},"expect":"config"}, +{"name":"mhc end past the layer count","set":{"mhc":{"start":28,"end":33}},"expect":"config"}, +{"name":"mhc start negative","set":{"mhc":{"start":-1,"end":4}},"expect":"config"}, +{"name":"mhc streams 2","set":{"mhc":{"streams":2}},"expect":"accept"}, +{"name":"mhc streams 4 is an engine limit","set":{"mhc":{"streams":4}},"expect":"admission"}, +{"name":"mhc streams 3","set":{"mhc":{"streams":3}},"expect":"config"}, +{"name":"mhc streams 1","set":{"mhc":{"streams":1}},"expect":"config"}, +{"name":"mhc fixed_identity true is an engine limit","set":{"mhc":{"fixed_identity":true}},"expect":"admission"}, +{"name":"mhc fixed_identity not a boolean","set":{"mhc":{"fixed_identity":0}},"expect":"config"}, +{"name":"iterations 1","set":{"mhc":{"iterations":1}},"expect":"accept"}, +{"name":"iterations 19","set":{"mhc":{"iterations":19}},"expect":"accept"}, +{"name":"iterations 50","set":{"mhc":{"iterations":50}},"expect":"accept"}, +{"name":"iterations 1000","set":{"mhc":{"iterations":1000}},"expect":"accept"}, +{"name":"iterations 1001 is an engine limit","set":{"mhc":{"iterations":1001}},"expect":"admission"}, +{"name":"iterations 0","set":{"mhc":{"iterations":0}},"expect":"config"}, +{"name":"iterations negative","set":{"mhc":{"iterations":-1}},"expect":"config"}, +{"name":"iterations a float","set":{"mhc":{"iterations":20.5}},"expect":"config"}, +{"name":"iterations a string","set":{"mhc":{"iterations":"20"}},"expect":"config"}, +{"name":"pre_scale 0.5","set":{"mhc":{"pre_scale":0.5}},"expect":"accept"}, +{"name":"pre_scale 2","set":{"mhc":{"pre_scale":2}},"expect":"accept"}, +{"name":"pre_scale 1.75","set":{"mhc":{"pre_scale":1.75}},"expect":"accept"}, +{"name":"pre_scale 0","set":{"mhc":{"pre_scale":0}},"expect":"config"}, +{"name":"pre_scale negative","set":{"mhc":{"pre_scale":-1.0}},"expect":"config"}, +{"name":"pre_scale a string","set":{"mhc":{"pre_scale":"1"}},"expect":"config"}, +{"name":"pre_scale null","set":{"mhc":{"pre_scale":null}},"expect":"config"}, +{"name":"layer_types absent","remove":["text_config.layer_types"],"expect":"accept"}, +{"name":"layer_types null","set":{"text_config":{"layer_types":null}},"expect":"accept"}, +{"name":"layer_types absent with interval 2","set":{"text_config":{"full_attention_interval":2}},"remove":["text_config.layer_types"],"expect":"accept"}, +{"name":"layer_types and interval both absent","remove":["text_config.layer_types","text_config.full_attention_interval"],"expect":"accept"}, +{"name":"layer_types absent with an unset interval","set":{"text_config":{"full_attention_interval":null}},"remove":["text_config.layer_types"],"expect":"config"}, +{"name":"layer_types one entry short","set":{"text_config":{"layer_types":["linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention"]}},"expect":"config"}, +{"name":"layer_types one entry long","set":{"text_config":{"layer_types":["linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention"]}},"expect":"config"}, +{"name":"layer_types names an unknown type","set":{"text_config":{"layer_types":["linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","full_attention","linear_attention","linear_attention","linear_attention","sliding_attention"]}},"expect":"config"}, +{"name":"layer_types contradicts the interval","set":{"text_config":{"full_attention_interval":2}},"expect":"config"}, +{"name":"tied head in both places is an engine limit","set":{"tie_word_embeddings":true,"text_config":{"tie_word_embeddings":true}},"expect":"admission"}, +{"name":"tied head at the root alone contradicts text_config","set":{"tie_word_embeddings":true},"expect":"config"}, +{"name":"tied head in text_config alone contradicts the root","set":{"text_config":{"tie_word_embeddings":true}},"expect":"config"}, +{"name":"untied head","set":{"tie_word_embeddings":false},"expect":"accept"} +] +} diff --git a/zig/tests/qwen27/classes.zig b/zig/tests/qwen27/classes.zig index 869f7d58368..45282dde032 100644 --- a/zig/tests/qwen27/classes.zig +++ b/zig/tests/qwen27/classes.zig @@ -40,16 +40,32 @@ fn linears(w: q.gpu_weights.Weights, c: Class, out: []Linear) []Linear { }, .head => unreachable, }; - if (x) |v| { + if (x) |v| if (v.n > 0) { out[n] = v; n += 1; - } + }; } return out[0..n]; } /// Weight bytes a call reads (codes, bf16 scales and biases), and its n*k by code width. -fn bytes(l: Linear, by_bits: *[9]usize) usize { +fn bytes(l: Linear, by_bits: *[17]usize) usize { + if (comptime @hasField(Linear, "sn")) { + if (l.sn) |s| { + var sum: usize = 0; + for (s.runs) |run| switch (run.mat) { + .bf16 => |m| { + by_bits[16] += @as(usize, m.n) * m.k; + sum += @as(usize, m.n) * m.k * 2; + }, + .awq => |m| { + by_bits[4] += @as(usize, m.n) * m.k; + sum += m.w.length() + m.sb.length(); + }, + }; + return sum; + } + } if (l.runs.len > 0) { var sum: usize = 0; for (l.runs) |r| sum += bytes(r.linear, by_bits); @@ -111,7 +127,8 @@ pub fn main(init: std.process.Init) !void { var total_bytes: usize = 0; for (std.enums.values(Class)) |c| { const ls = linears(m.weights, c, &store); - var by_bits: [9]usize = @splat(0); + if (ls.len == 0) continue; + var by_bits: [17]usize = @splat(0); var b: usize = 0; for (ls) |l| b += bytes(l, &by_bits); _ = try time(m, c, ls, rows, 1); // pipelines and clocks diff --git a/zig/tests/qwen27/sensenova_oracle.zig b/zig/tests/qwen27/sensenova_oracle.zig new file mode 100644 index 00000000000..a84f7dc0cf7 --- /dev/null +++ b/zig/tests/qwen27/sensenova_oracle.zig @@ -0,0 +1,207 @@ +//! SenseNova-Loop-9B HF PyTorch oracle trace/generation parity verifier and LinearGpu microbench. +const std = @import("std"); +const mtl = @import("metal"); +const q = @import("qwen27"); +const core = @import("core"); + +fn bf16ToF64(bits: u16) f64 { + return @floatCast(@as(f32, @bitCast(@as(u32, bits) << 16))); +} + +const Stats = struct { cos: f64, max_abs: f64 }; + +fn compareTensor(got: []const u16, st_bytes: []const u8, st_hdr: std.json.ObjectMap, st_base: usize, name: []const u8) !Stats { + const ent = (st_hdr.get(name) orelse return error.MissingOracleTensor).object; + const dtype = ent.get("dtype").?.string; + const offs = ent.get("data_offsets").?.array.items; + const raw = st_bytes[st_base + @as(usize, @intCast(offs[0].integer)) .. st_base + @as(usize, @intCast(offs[1].integer))]; + var dot: f64 = 0; + var na: f64 = 0; + var nb: f64 = 0; + var max_abs: f64 = 0; + if (std.mem.eql(u8, dtype, "BF16")) { + if (raw.len != got.len * 2) return error.OracleShapeMismatch; + for (got, 0..) |g, i| { + const a = bf16ToF64(g); + const b = bf16ToF64(std.mem.readInt(u16, raw[i * 2 ..][0..2], .little)); + dot += a * b; + na += a * a; + nb += b * b; + max_abs = @max(max_abs, @abs(a - b)); + } + } else if (std.mem.eql(u8, dtype, "F32")) { + if (raw.len != got.len * 4) return error.OracleShapeMismatch; + for (got, 0..) |g, i| { + const a = bf16ToF64(g); + const b: f64 = @floatCast(@as(f32, @bitCast(std.mem.readInt(u32, raw[i * 4 ..][0..4], .little)))); + dot += a * b; + na += a * a; + nb += b * b; + max_abs = @max(max_abs, @abs(a - b)); + } + } else return error.BadOracleDType; + const denom = @sqrt(na) * @sqrt(nb); + return .{ .cos = if (denom > 0) dot / denom else 0, .max_abs = max_abs }; +} + +fn oracleLogitsRow(st_bytes: []const u8, st_hdr: std.json.ObjectMap, st_base: usize, name: []const u8, pos: usize, vocab: usize, out: []u16) !void { + const ent = st_hdr.get(name).?.object; + const offs = ent.get("data_offsets").?.array.items; + const raw = st_bytes[st_base + @as(usize, @intCast(offs[0].integer)) .. st_base + @as(usize, @intCast(offs[1].integer))]; + const base = pos * vocab * 2; + for (out, 0..) |*d, i| d.* = std.mem.readInt(u16, raw[base + i * 2 ..][0..2], .little); +} + +fn top16Overlap(a_row: []const u16, b_row: []const u16, alloc: std.mem.Allocator) !usize { + const n = a_row.len; + const a_idx = try alloc.alloc(u32, n); + defer alloc.free(a_idx); + const b_idx = try alloc.alloc(u32, n); + defer alloc.free(b_idx); + for (0..n) |i| { + a_idx[i] = @intCast(i); + b_idx[i] = @intCast(i); + } + const Ctx = struct { + vals: []const u16, + pub fn lessThan(ctx: @This(), x: u32, y: u32) bool { + return bf16ToF64(ctx.vals[x]) > bf16ToF64(ctx.vals[y]); + } + }; + std.mem.sort(u32, a_idx, Ctx{ .vals = a_row }, Ctx.lessThan); + std.mem.sort(u32, b_idx, Ctx{ .vals = b_row }, Ctx.lessThan); + var hits: usize = 0; + for (a_idx[0..16]) |id| if (std.mem.indexOfScalar(u32, b_idx[0..16], id) != null) { + hits += 1; + }; + return hits; +} + +fn ptrU16(r: q.projection.Ref, n: usize) []const u16 { + const p: [*]const u16 = @ptrCast(@alignCast(r.buffer.contents() + r.offset)); + return p[0..n]; +} + +fn verifyTrace(a: std.mem.Allocator, gpa: std.mem.Allocator, m: *q.model.Model, runner: *q.decode_round.Runner, st_bytes: []const u8, st_hdr: std.json.ObjectMap, st_base: usize, trace_ids: []const u32, is_awq: bool) !void { + const hidden = m.config.hidden; + const vocab = m.config.vocab; + const rows = trace_ids.len; + const emb = m.weights.embed_bf16 orelse return error.MissingEmbedBf16; + const emb_src = ptrU16(.{ .buffer = emb.buffer, .offset = emb.offset }, vocab * hidden); + const emb_rows = try a.alloc(u16, rows * hidden); + for (trace_ids, 0..) |id, ri| @memcpy(emb_rows[ri * hidden ..][0..hidden], emb_src[id * hidden ..][0..hidden]); + + try runner.taps.use(m.device, &.{ 3, 27, 51, 55 }); + runner.capture_taps = true; + var round = try q.round_plan.Round.init(gpa, &.{.{ .slot = 0, .start = 0, .capacity = runner.capacity, .ids = trace_ids }}, @intCast(m.config.conv_kernel), runner.slots, @intCast(m.shard.global.vocab)); + defer round.deinit(); + m.kernels.prompt = true; + try runner.advance(&round, .all); + m.kernels.prompt = false; + + const checks = [_]struct { label: []const u8, got: []const u16, min_cos: f64 }{ + .{ .label = "embed_tokens", .got = emb_rows, .min_cos = 0.99999 }, + .{ .label = "exec3_out", .got = ptrU16(try runner.taps.plane(0), rows * hidden), .min_cos = 0.9995 }, + .{ .label = "exec27_h_after_collapse", .got = ptrU16(try runner.taps.plane(1), rows * hidden), .min_cos = 0.9995 }, + .{ .label = "exec51_h_after_collapse", .got = ptrU16(try runner.taps.plane(2), rows * hidden), .min_cos = 0.999 }, + .{ .label = "exec55_out", .got = ptrU16(try runner.taps.plane(3), rows * hidden), .min_cos = 0.999 }, + .{ .label = "final_norm", .got = ptrU16(m.frame.get(.input), rows * hidden), .min_cos = 0.999 }, + .{ .label = "logits_bf16", .got = ptrU16(m.frame.get(.logits), rows * vocab), .min_cos = if (is_awq) 0.9985 else 0.999 }, + }; + for (checks) |ck| { + const st = try compareTensor(ck.got, st_bytes, st_hdr, st_base, ck.label); + std.debug.print("TRACE {s:<24} cos={d:.7} max_abs={d:.5} min={d:.5}\n", .{ ck.label, st.cos, st.max_abs, ck.min_cos }); + if (st.cos < ck.min_cos or !std.math.isFinite(st.cos)) return error.OracleTraceCosineTooLow; + } + + const metal_logits = ptrU16(m.frame.get(.logits), rows * vocab); + const o_row = try a.alloc(u16, vocab); + for (0..rows) |pos| { + const m_row = metal_logits[pos * vocab ..][0..vocab]; + try oracleLogitsRow(st_bytes, st_hdr, st_base, "logits_bf16", pos, vocab, o_row); + const m_top = try q.session.argmax(m_row); + const o_top = try q.session.argmax(o_row); + std.debug.print("TOP1 pos={d}: metal={d} oracle={d} match={}\n", .{ pos, m_top, o_top, m_top == o_top }); + if (m_top != o_top) return error.Top1Mismatch; + } + try oracleLogitsRow(st_bytes, st_hdr, st_base, "logits_bf16", rows - 1, vocab, o_row); + const ov = try top16Overlap(metal_logits[(rows - 1) * vocab ..][0..vocab], o_row, a); + std.debug.print("TOP16 overlap pos={d}: {d}/16\n", .{ rows - 1, ov }); + if (ov < 12) return error.Top16OverlapTooLow; +} + +pub fn main(init: std.process.Init) !void { + const gpa = init.gpa; + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + if (args.len == 2 and std.mem.eql(u8, args[1], "--microbench")) { + const dev = try mtl.Device.init(); + defer dev.deinit(); + const queue = try dev.queue(); + defer queue.deinit(); + return core.sensenova_loop.linear_gpu.LinearGpu.bench(gpa, dev, queue); + } + var model_dir: ?[]const u8 = null; + var json_path: ?[]const u8 = null; + var st_path: ?[]const u8 = null; + var i: usize = 1; + while (i < args.len) : (i += 1) { + if (i + 1 >= args.len) return error.MissingValue; + if (std.mem.eql(u8, args[i], "--model")) model_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--oracle-json")) json_path = args[i + 1] else if (std.mem.eql(u8, args[i], "--oracle-st")) st_path = args[i + 1] else return error.UnknownOption; + i += 1; + } + const dir = model_dir orelse return error.MissingModel; + const m = try q.model.Model.load(gpa, io, dir, 128, null); + defer m.deinit(); + const is_awq = m.weights.head.bits == 4; + const oj_raw = try std.Io.Dir.cwd().readFileAlloc(io, json_path orelse return error.MissingOracleJson, a, .limited(32 << 20)); + const oj = try std.json.parseFromSlice(std.json.Value, a, oj_raw, .{}); + const st_bytes = try std.Io.Dir.cwd().readFileAlloc(io, st_path orelse return error.MissingOracleSt, a, .limited(64 << 20)); + const hlen: usize = @intCast(std.mem.readInt(u64, st_bytes[0..8], .little)); + const st_hdr = try std.json.parseFromSlice(std.json.Value, a, st_bytes[8 .. 8 + hlen], .{}); + const trace_ids: []const u32 = if (oj.value.object.get("trace_prompt_ids")) |v| blk: { + const t_arr = v.array.items; + const buf = try a.alloc(u32, t_arr.len); + for (t_arr, buf) |x, *d| d.* = @intCast(x.integer); + break :blk buf; + } else &.{ 9707, 11, 1268, 527 }; + + var runner = try q.decode_round.Runner.init(gpa, m, 1, 512); + defer runner.deinit(); + try verifyTrace(a, gpa, m, &runner, st_bytes, st_hdr.value.object, 8 + hlen, trace_ids, is_awq); + + runner.capture_taps = false; + const gen_val = oj.value.object.get("generations_greedy_64") orelse oj.value.object.get("generations_greedy") orelse return error.MissingGenerations; + var it = gen_val.object.iterator(); + const s = q.session.Session{ .runner = &runner }; + while (it.next()) |kv| { + if (kv.value_ptr.* != .object) continue; + const p_items = kv.value_ptr.object.get("input_ids").?.array.items; + const g_items = kv.value_ptr.object.get("generated_ids").?.array.items; + const pids = try a.alloc(u32, p_items.len); + const gids = try a.alloc(u32, g_items.len); + for (p_items, pids) |v, *d| d.* = @intCast(v.integer); + for (g_items, gids) |v, *d| d.* = @intCast(v.integer); + try runner.reset(0); + try s.prefill(pids, 128); + var match: usize = 0; + var exact = true; + var first_got: u32 = 0; + var first_exp: u32 = 0; + for (gids, 0..) |exp, step| { + const tok = try s.greedy(); + if (tok == exp and exact) match += 1 else if (exact) { + exact = false; + first_got = tok; + first_exp = exp; + } + if (m.config.isEos(tok) or step + 1 == gids.len) break; + try s.step(tok); + } + std.debug.print("GREEDY {s}: match={d}/{d} exact={} first_diff_pos={d} got={d} exp={d}\n", .{ kv.key_ptr.*, match, gids.len, exact, match, first_got, first_exp }); + if (match == 0) return error.GreedyDivergedImmediately; + } +} From 294f7d00c56aa6244a2191c4e4a341dab5f64a92 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:42:43 +0000 Subject: [PATCH 346/361] qwen27: follow main 881e224d's prompt-tail layout within the file limit Main 881e224d911cefd609fa26cdfc9b15599cced2d9 added the prompt-tail slices retained by the rebase. Move the unchanged round fingerprint into its own module so the combined runner remains below 600 lines. --- zig/src/families/qwen27/decode_round.zig | 19 +---------------- zig/src/families/qwen27/round_fingerprint.zig | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 18 deletions(-) create mode 100644 zig/src/families/qwen27/round_fingerprint.zig diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 4f5e80c2276..431f036fc36 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -14,6 +14,7 @@ const GdnPool = @import("gdn_pool_gpu.zig").Pool; const GdnHook = @import("gdn_hook.zig").Hook; const GdnPlan = @import("gdn_plan.zig").Plan; const Round = @import("round_plan.zig").Round; +const fingerprint = @import("round_fingerprint.zig").fingerprint; const Taps = @import("taps.zig").Taps; const image_rows = @import("image_rows.zig"); const mrope = @import("core").qwen_vl.rope; @@ -591,21 +592,3 @@ pub const Runner = struct { try r.taps.record(r.model.glue, e, layer, hidden, rows); } }; - -fn fingerprint(round: *const Round) [32]u8 { - var hash = std.crypto.hash.sha2.Sha256.init(.{}); - hash.update(std.mem.sliceAsBytes(round.ids)); - hash.update(std.mem.sliceAsBytes(round.slots)); - hash.update(std.mem.sliceAsBytes(round.feed_positions)); - hash.update(std.mem.sliceAsBytes(round.draw_positions)); - hash.update(std.mem.sliceAsBytes(round.firsts)); - for (round.windows) |window| { - hash.update(std.mem.asBytes(&window.start)); - hash.update(std.mem.asBytes(&window.taps)); - hash.update(std.mem.sliceAsBytes(window.parents)); - hash.update(std.mem.sliceAsBytes(window.conv)); - } - var out: [32]u8 = undefined; - hash.final(&out); - return out; -} diff --git a/zig/src/families/qwen27/round_fingerprint.zig b/zig/src/families/qwen27/round_fingerprint.zig new file mode 100644 index 00000000000..842dc21d227 --- /dev/null +++ b/zig/src/families/qwen27/round_fingerprint.zig @@ -0,0 +1,21 @@ +//! Identity of the exact row plan held between verify and keep. +const std = @import("std"); +const Round = @import("round_plan.zig").Round; + +pub fn fingerprint(round: *const Round) [32]u8 { + var hash = std.crypto.hash.sha2.Sha256.init(.{}); + hash.update(std.mem.sliceAsBytes(round.ids)); + hash.update(std.mem.sliceAsBytes(round.slots)); + hash.update(std.mem.sliceAsBytes(round.feed_positions)); + hash.update(std.mem.sliceAsBytes(round.draw_positions)); + hash.update(std.mem.sliceAsBytes(round.firsts)); + for (round.windows) |window| { + hash.update(std.mem.asBytes(&window.start)); + hash.update(std.mem.asBytes(&window.taps)); + hash.update(std.mem.sliceAsBytes(window.parents)); + hash.update(std.mem.sliceAsBytes(window.conv)); + } + var out: [32]u8 = undefined; + hash.final(&out); + return out; +} From 467d1e5e0f4d5232f7aa84015c43a67073ac80ad Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:16:49 +0000 Subject: [PATCH 347/361] qwen27: extract routed Metal contract probes for file limit --- zig/tests/contract/metal_main.zig | 61 +-------------------------- zig/tests/contract/metal_moe.zig | 69 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 59 deletions(-) create mode 100644 zig/tests/contract/metal_moe.zig diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index e4fe597a9aa..74030eca792 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -20,8 +20,6 @@ const drama_cfg = @import("metal_drama_cfg.zig"); const glm_eh_k = @import("metal_glm_eh.zig"); const pair_k = @import("metal_pair.zig"); const minimax_k = @import("metal_minimax.zig"); -const q27_moe = @import("metal_qwen27_moe.zig"); -const q27_rows = @import("metal_qwen27_moe_rows.zig"); const flash_pool = @import("metal_flashnext_pool.zig"); const flash = @import("metal_flashnext.zig"); const fsr = @import("metal_fsr.zig"); @@ -80,62 +78,7 @@ const common = [_]Reg{ /// The lane kernel takes every format on the M5's tensor units, and 6-bit groups of 32 alone before them. const m5_only = @import("metal_lane_variants.zig").m5; -/// Ornith-1.5-122B's routed block: the experts' decode rows with an extra matrix, then moe.metal's kernels. -const Moe = struct { - extra: std.ArrayList(*q27_moe.Extra) = .empty, - route: ?*q27_moe.Route = null, - sort: ?*q27_rows.Sort = null, - gather: ?*q27_rows.Gather = null, - glu: ?*q27_rows.Glu = null, - combine: std.ArrayList(*q27_rows.Combine) = .empty, - - fn collect(m: *Moe, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, o: Opts, kernels: *std.ArrayList(g.Kernel)) !void { - for ([_]u8{ 4, 8 }, [_][]const u8{ "metal qwen27 q27_rows_extra q4 g64", "metal qwen27 q27_rows_extra q8 g64" }) |bits, name| { - if (!wanted(o, name)) continue; - const x = try a.create(q27_moe.Extra); - x.* = try q27_moe.Extra.init(a, device, queue, bits, name); - try m.extra.append(a, x); - try kernels.append(a, x.kernel()); - } - if (wanted(o, q27_moe.Route.spec().name)) { - m.route = try a.create(q27_moe.Route); - m.route.?.* = try q27_moe.Route.init(a, device, queue); - try kernels.append(a, m.route.?.kernel()); - } - if (wanted(o, q27_rows.Sort.spec().name)) { - m.sort = try a.create(q27_rows.Sort); - m.sort.?.* = try q27_rows.Sort.init(a, device, queue); - try kernels.append(a, m.sort.?.kernel()); - } - if (wanted(o, q27_rows.Gather.spec().name)) { - m.gather = try a.create(q27_rows.Gather); - m.gather.?.* = try q27_rows.Gather.init(a, device, queue); - try kernels.append(a, m.gather.?.kernel()); - } - if (wanted(o, q27_rows.Glu.spec().name)) { - m.glu = try a.create(q27_rows.Glu); - m.glu.?.* = try q27_rows.Glu.init(a, device, queue); - try kernels.append(a, m.glu.?.kernel()); - } - for ([_]bool{ true, false }) |in_out| { - if (!wanted(o, q27_rows.Combine.spec(in_out).name)) continue; - const x = try a.create(q27_rows.Combine); - x.* = try q27_rows.Combine.init(a, device, queue, in_out); - try m.combine.append(a, x); - try kernels.append(a, x.kernel()); - } - } - fn deinit(m: *Moe, a: std.mem.Allocator) void { - for (m.extra.items) |x| x.deinit(); - m.extra.deinit(a); - if (m.route) |x| x.deinit(); - if (m.sort) |x| x.deinit(); - if (m.gather) |x| x.deinit(); - if (m.glu) |x| x.deinit(); - for (m.combine.items) |x| x.deinit(); - m.combine.deinit(a); - } -}; +const Moe = @import("metal_moe.zig").Moe; fn wanted(o: Opts, name: []const u8) bool { const only = o.only orelse return true; return std.mem.indexOf(u8, name, only) != null; @@ -422,7 +365,7 @@ pub fn main(init: std.process.Init) !u8 { for (tiles[0..ntiles]) |*x| try kernels.append(a, x.kernel()); var moe: Moe = .{}; defer moe.deinit(a); - try moe.collect(a, device, queue, o, &kernels); + try moe.collect(a, device, queue, o.only, &kernels); var row_wide: @import("metal_row_wide.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer row_wide.deinit(); try row_wide.collect(o.only); diff --git a/zig/tests/contract/metal_moe.zig b/zig/tests/contract/metal_moe.zig new file mode 100644 index 00000000000..3aea83d23aa --- /dev/null +++ b/zig/tests/contract/metal_moe.zig @@ -0,0 +1,69 @@ +//! Ornith-1.5-122B's routed contract probes: experts' decode rows, routing and combining. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const q27_moe = @import("metal_qwen27_moe.zig"); +const q27_rows = @import("metal_qwen27_moe_rows.zig"); +const g = contract.gates; + +pub const Moe = struct { + extra: std.ArrayList(*q27_moe.Extra) = .empty, + route: ?*q27_moe.Route = null, + sort: ?*q27_rows.Sort = null, + gather: ?*q27_rows.Gather = null, + glu: ?*q27_rows.Glu = null, + combine: std.ArrayList(*q27_rows.Combine) = .empty, + + pub fn collect(m: *Moe, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, only: ?[]const u8, kernels: *std.ArrayList(g.Kernel)) !void { + for ([_]u8{ 4, 8 }, [_][]const u8{ "metal qwen27 q27_rows_extra q4 g64", "metal qwen27 q27_rows_extra q8 g64" }) |bits, name| { + if (!wanted(only, name)) continue; + const x = try a.create(q27_moe.Extra); + x.* = try q27_moe.Extra.init(a, device, queue, bits, name); + try m.extra.append(a, x); + try kernels.append(a, x.kernel()); + } + if (wanted(only, q27_moe.Route.spec().name)) { + m.route = try a.create(q27_moe.Route); + m.route.?.* = try q27_moe.Route.init(a, device, queue); + try kernels.append(a, m.route.?.kernel()); + } + if (wanted(only, q27_rows.Sort.spec().name)) { + m.sort = try a.create(q27_rows.Sort); + m.sort.?.* = try q27_rows.Sort.init(a, device, queue); + try kernels.append(a, m.sort.?.kernel()); + } + if (wanted(only, q27_rows.Gather.spec().name)) { + m.gather = try a.create(q27_rows.Gather); + m.gather.?.* = try q27_rows.Gather.init(a, device, queue); + try kernels.append(a, m.gather.?.kernel()); + } + if (wanted(only, q27_rows.Glu.spec().name)) { + m.glu = try a.create(q27_rows.Glu); + m.glu.?.* = try q27_rows.Glu.init(a, device, queue); + try kernels.append(a, m.glu.?.kernel()); + } + for ([_]bool{ true, false }) |in_out| { + if (!wanted(only, q27_rows.Combine.spec(in_out).name)) continue; + const x = try a.create(q27_rows.Combine); + x.* = try q27_rows.Combine.init(a, device, queue, in_out); + try m.combine.append(a, x); + try kernels.append(a, x.kernel()); + } + } + + pub fn deinit(m: *Moe, a: std.mem.Allocator) void { + for (m.extra.items) |x| x.deinit(); + m.extra.deinit(a); + if (m.route) |x| x.deinit(); + if (m.sort) |x| x.deinit(); + if (m.gather) |x| x.deinit(); + if (m.glu) |x| x.deinit(); + for (m.combine.items) |x| x.deinit(); + m.combine.deinit(a); + } +}; + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const prefix = only orelse return true; + return std.mem.indexOf(u8, name, prefix) != null; +} From d4e78a2555b4ae003a32bb68ec4725c9f47b6f1e Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:25:49 +0100 Subject: [PATCH 348/361] residency_owner_tests: export sensenova_loop for #3859 --- zig/residency_owner_tests.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/residency_owner_tests.zig b/zig/residency_owner_tests.zig index 8c3ae6385c5..de19dd68199 100644 --- a/zig/residency_owner_tests.zig +++ b/zig/residency_owner_tests.zig @@ -25,6 +25,7 @@ pub const bf16_topk = @import("bf16_topk"); /// The core pool and its Metal pages, which qwen27/kv_pages.zig reads through core. pub const kv_pool = @import("src/core/kv_pool.zig"); pub const metal_kv_pages = @import("src/core/metal_kv_pages.zig"); +pub const sensenova_loop = @import("src/families/sensenova_loop/sensenova_loop.zig"); const a = std.testing.allocator; test "residency owner GLM: actual arena slots tower and snapshots match live unique allocations" { From 6b4c3d96349bf115f1b68a2b7511b5f17976c9f5 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:14:07 +0000 Subject: [PATCH 349/361] qwen27: main's moved keysForward passes shift and rope Main moved keysForward to prompt_tail.zig. This PR's copy passed the shifted norm and YaRN rope, so the moved one must too. Both default to the plain path, so other Qwen models are unchanged. --- zig/src/families/qwen27/prompt_tail.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/src/families/qwen27/prompt_tail.zig b/zig/src/families/qwen27/prompt_tail.zig index 4c59060a6f4..5feef363f50 100644 --- a/zig/src/families/qwen27/prompt_tail.zig +++ b/zig/src/families/qwen27/prompt_tail.zig @@ -95,7 +95,7 @@ pub fn keysForward(ptr: *anyopaque, e: mtl.ComputeEncoder, attn_block: usize, we try r.model.glue.unstack(e, f.get(.mixed), f.get(.key), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = 0 }); try r.model.glue.unstack(e, f.get(.mixed), f.get(.value), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = kv }); e.barrier(); - try r.attention.keysOnly(e, &r.scratch, &r.bindings[layer], plan, .{ .qg = f.get(.q_gate), .key = f.get(.key), .q_gain = wts.ref(weights.q_norm), .k_gain = wts.ref(weights.k_norm), .norm_q = f.get(.norm_query), .norm_k = f.get(.norm_key), .query = f.get(.query), .rotated_key = f.get(.rotated_key), .positions = f.get(.positions), .rows = rows, .eps = r.model.config.eps, .theta = r.model.config.rope_theta, .h_end = r.current_placed.h_end, .w_end = r.current_placed.w_end, .plane = f.capacity, .geometry = r.geometry }, f.get(.value), caches); + try r.attention.keysOnly(e, &r.scratch, &r.bindings[layer], plan, .{ .qg = f.get(.q_gate), .key = f.get(.key), .q_gain = wts.ref(weights.q_norm), .k_gain = wts.ref(weights.k_norm), .norm_q = f.get(.norm_query), .norm_k = f.get(.norm_key), .query = f.get(.query), .rotated_key = f.get(.rotated_key), .positions = f.get(.positions), .rows = rows, .eps = r.model.config.eps, .theta = r.model.config.rope_theta, .h_end = r.current_placed.h_end, .w_end = r.current_placed.w_end, .plane = f.capacity, .geometry = r.geometry, .shift = r.model.config.shift_norms, .rope = r.model.config.rope }, f.get(.value), caches); } test "qwen27 prompt tail: each planted reader of the last layer's rows refuses it" { From 9bf0962d78b4daf8fc0a1ee47a5ea0562e992dfb Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:35:59 +0100 Subject: [PATCH 350/361] qwen27 metal: serve SenseNova-Loop-9B natively (BF16 and AWQ g128) The net change of #3859 at c07419f1f8 over its merge base 685851076f, carried as one commit because four of the branch's merge commits hold changes of their own. --- zig/src/families/qwen27/decode_round.zig | 1 - 1 file changed, 1 deletion(-) diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index 431f036fc36..d3b0a7a986c 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -24,7 +24,6 @@ const slot_pages = @import("slot_pages.zig"); pub const pagesOn = kv_pages.on; pub const KvPages = kv_pages.KvPages; pub const KvSpan = kv_pages.KvSpan; -const kvp = kv_pages.kvp; const kv_grow = @import("kv_grow.zig"); const kv_slots = @import("kv_slots.zig"); From 09c2c24db47730962fbca210bec9093c38861e6e Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:16:24 +0100 Subject: [PATCH 351/361] lanes: fuse drafter absorb and hold via draft_round --- zig/src/core/lanes/drafted.zig | 75 ++++++++++++++++++++++++++++++++++ zig/src/core/lanes/drafter.zig | 1 + 2 files changed, 76 insertions(+) diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index a5f98256654..b5c4bf12a10 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -337,6 +337,13 @@ pub const Drafted = struct { } try x.holds.append(x.gpa, .{ .stream = r.stream, .pending = pending, .position = r.position, .depth = r.depth, .plan = r.plan, .lanes = r.lanes, .tokens = r.stream.context.items, .sampling = r.stream.sampling }); } + if (x.drafter.vtable.draft_round) |f| { + if ((x.drafter.proposal_head == null or x.drafter.proposal_head.?.mode == .legacy) and + (x.absorbs.items.len > 0 or x.holds.items.len > 0)) + { + return f(x.drafter.ptr, x.absorbs.items, x.holds.items); + } + } if (x.absorbs.items.len > 0) try x.drafter.absorb(x.absorbs.items); if (x.holds.items.len > 0) try x.drafter.hold(x.holds.items); } @@ -376,3 +383,71 @@ pub const Drafted = struct { self(ptr).dropStream(s); } }; + +test "draft_round fuses absorb and hold" { + const gpa = std.testing.allocator; + const Mock = struct { + rounds: u32 = 0, + absorbs: u32 = 0, + holds: u32 = 0, + rows: [4]u32 = .{ 1, 2, 3, 4 }, + fn cast(ptr: *anyopaque) *@This() { + return @ptrCast(@alignCast(ptr)); + } + fn taps(_: *anyopaque) []const u32 { + return &.{0}; + } + fn facts(_: *anyopaque) dr.Facts { + return .{ .depth = 2, .step_ms = 0.5 }; + } + fn open(_: *anyopaque, _: *Stream) anyerror!void {} + fn absorb(ptr: *anyopaque, _: []const dr.Absorb) anyerror!void { + cast(ptr).absorbs += 1; + } + fn hold(ptr: *anyopaque, _: []const dr.Hold) anyerror!void { + cast(ptr).holds += 1; + } + fn draftRound(ptr: *anyopaque, absorbs: []const dr.Absorb, holds: []const dr.Hold) anyerror!void { + const m = cast(ptr); + m.rounds += 1; + try std.testing.expectEqual(@as(usize, 1), absorbs.len); + try std.testing.expectEqual(@as(usize, 1), holds.len); + } + fn held(_: *anyopaque, _: []const *Stream, _: []const []u32) anyerror!void {} + fn release(_: *anyopaque, _: *Stream) void {} + fn prefill(_: *anyopaque, _: *Stream) anyerror!void {} + fn prefillFeatures(ptr: *anyopaque, s: *Stream, _: []const u32, sink: be.FeatureSink) anyerror!void { + const m = cast(ptr); + try sink.take(sink.ptr, s, .{ .buffer = @intFromPtr(&m.rows), .rows = 4, .row_bytes = 4, .space = .host, .dtype = .u32 }, 0); + } + fn features(ptr: *anyopaque, _: *Stream, _: []const u32, _: u64, n: u32) anyerror!be.Features { + return .{ .buffer = @intFromPtr(&cast(ptr).rows), .rows = n, .row_bytes = 4, .space = .host, .dtype = .u32 }; + } + fn first(_: *anyopaque, _: *Stream, _: u64) anyerror!u64 { + return 0; + } + fn queue(_: *anyopaque, _: *Stream, _: be.Feed, _: u64) anyerror!u64 { + return 0; + } + fn read(_: *anyopaque, _: u64) anyerror!u32 { + return 7; + } + fn verify(_: *anyopaque, _: []const be.Window, _: []be.Verified) anyerror!void {} + fn keep(_: *anyopaque, _: []const be.Window, _: []const []const u32) anyerror!void {} + fn draftFn(_: *anyopaque, _: []const be.DraftRequest) anyerror!void {} + }; + var mock: Mock = .{}; + const target: be.Backend = .{ .ptr = &mock, .vtable = &.{ .prefill = Mock.prefill, .prefill_features = Mock.prefillFeatures, .features = Mock.features, .first = Mock.first, .queue = Mock.queue, .read = Mock.read, .verify = Mock.verify, .keep = Mock.keep, .draft = Mock.draftFn, .release = Mock.release } }; + const drafter: dr.Drafter = .{ .ptr = &mock, .vtable = &.{ .taps = Mock.taps, .facts = Mock.facts, .open = Mock.open, .absorb = Mock.absorb, .hold = Mock.hold, .draft_round = Mock.draftRound, .held = Mock.held, .release = Mock.release } }; + var x = try Drafted.init(gpa, target, drafter); + defer x.deinit(); + var s = try Stream.init(gpa, .{ .id = "dr", .prompt = &.{ 10, 20, 30, 40 }, .max_new = 4 }); + defer s.deinit(gpa); + try x.backend().prefill(&s); + defer x.backend().release(&s); + try std.testing.expectEqual(@as(u32, 1), mock.absorbs); + try x.backend().draft(&.{.{ .stream = &s, .follow = &.{}, .first = .{ .value = 50 }, .rows = null, .start = 4, .position = 5, .depth = 2 }}); + try std.testing.expectEqual(@as(u32, 1), mock.rounds); + try std.testing.expectEqual(@as(u32, 1), mock.absorbs); + try std.testing.expectEqual(@as(u32, 0), mock.holds); +} diff --git a/zig/src/core/lanes/drafter.zig b/zig/src/core/lanes/drafter.zig index 66628bc77fd..3a0b5dd8305 100644 --- a/zig/src/core/lanes/drafter.zig +++ b/zig/src/core/lanes/drafter.zig @@ -57,6 +57,7 @@ pub const Drafter = struct { open: *const fn (ptr: *anyopaque, s: *Stream) anyerror!void, absorb: *const fn (ptr: *anyopaque, items: []const Absorb) anyerror!void, hold: *const fn (ptr: *anyopaque, items: []const Hold) anyerror!void, + draft_round: ?*const fn (ptr: *anyopaque, absorbs: []const Absorb, holds: []const Hold) anyerror!void = null, hold_planned: ?*const fn (*anyopaque, []const Hold) anyerror!void = null, clear_proposals: ?*const fn (*anyopaque, *Stream) void = null, /// out[i] gets streams[i]'s first out[i].len held drafts (error if fewer); a hold holds exactly its depth. From 1db7595a09830d8e7b6eea76e459eb7063460c24 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:16:25 +0100 Subject: [PATCH 352/361] qwen27 metal: SenseNova-Loop native MTP drafter --- zig/src/families/qwen27/qwen27.zig | 2 + zig/src/families/qwen27/residency.zig | 3 + zig/src/families/qwen27/sn_mtp.zig | 598 ++++++++++++++++++ zig/src/families/qwen27/sn_mtp_batch.zig | 252 ++++++++ zig/src/families/qwen27/sn_mtp_scratch.zig | 363 +++++++++++ .../families/sensenova_loop/mtp_weights.zig | 327 ++++++++++ .../sensenova_loop/sensenova_loop.zig | 2 + zig/src/native/metal.zig | 2 +- zig/src/native/qwen27_lanes.zig | 16 +- zig/src/native/qwen27_served.zig | 121 ++-- zig/src/native/qwen27_served_test.zig | 124 ++++ zig/src/native/qwen27_slots.zig | 1 + zig/src/native/sensenova_features.zig | 155 +++++ zig/src/native/sensenova_mtp_drafter.zig | 135 ++++ zig/src/platform/environment.zig | 4 +- zig/src/platform/environment_test.zig | 5 + zig/tests/qwen27/sensenova_oracle.zig | 156 ++++- 17 files changed, 2176 insertions(+), 90 deletions(-) create mode 100644 zig/src/families/qwen27/sn_mtp.zig create mode 100644 zig/src/families/qwen27/sn_mtp_batch.zig create mode 100644 zig/src/families/qwen27/sn_mtp_scratch.zig create mode 100644 zig/src/families/sensenova_loop/mtp_weights.zig create mode 100644 zig/src/native/qwen27_served_test.zig create mode 100644 zig/src/native/sensenova_features.zig create mode 100644 zig/src/native/sensenova_mtp_drafter.zig diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index b523d55dfbb..fe89ee8fe68 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -53,6 +53,7 @@ pub const tap_gather = @import("tap_gather.zig"); pub const tap_ring = @import("tap_ring.zig"); /// Staged references: a round's stage rows copied to their planes (tf-qwen27-run --stages). pub const stage_planes = @import("stage_planes.zig"); +pub const sn_mtp = @import("sn_mtp.zig"); /// The 27B's Metal sources by name (the kernel contract compiles them as the engine does). pub const runtime_sources = @import("qwen_runtime_sources"); test { @@ -89,6 +90,7 @@ test { _ = @import("mtp_step_test.zig"); _ = @import("geometry_test.zig"); _ = @import("slot_pages_test.zig"); + _ = sn_mtp; } pub const residency = @import("residency.zig"); diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index 70a8452e424..b4bc9e5e94f 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -145,6 +145,7 @@ pub fn hold(h: anytype, io: std.Io) !void { try list.append(h.gpa, d.model.pending); try appendDraft(&d.model.backend, h.gpa, &list); } + if (h.mtp) |m| try m.appendBuffers(h.gpa, &list); if (h.back.vision) |v| { const held = v.buffers(); try list.appendSlice(h.gpa, &held); @@ -155,6 +156,7 @@ pub fn hold(h: anytype, io: std.Io) !void { h.runner.setResident(r.follow()); setBack(h.back, r.follow()); if (h.draft) |d| d.model.backend.setResident(r.follow()); + if (h.mtp) |m| m.setResident(r.follow()); } h.warm = if (h.resident) |*r| r.target() else .{ .queue = h.model.queue }; } @@ -164,6 +166,7 @@ pub fn drop(h: anytype) void { h.runner.setResident(null); setBack(h.back, null); if (h.draft) |d| d.model.backend.setResident(null); + if (h.mtp) |m| m.setResident(null); if (h.resident) |*r| r.deinit(); h.resident = null; h.warm = .{ .queue = h.model.queue }; diff --git a/zig/src/families/qwen27/sn_mtp.zig b/zig/src/families/qwen27/sn_mtp.zig new file mode 100644 index 00000000000..c4a148a73c7 --- /dev/null +++ b/zig/src/families/qwen27/sn_mtp.zig @@ -0,0 +1,598 @@ +//! Native Metal single-layer MTP drafter for SenseNova-Loop-9B (BF16 and AWQ checkpoints). +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const attn = @import("attention.zig"); +const wts = @import("gpu_weights.zig"); +const loop = @import("loop.zig"); +const projection = @import("projection.zig"); +const scratch_mod = @import("sn_mtp_scratch.zig"); +const Config = @import("config.zig").Config; +const Model = @import("model.zig").Model; +const mtp_weights = core.sensenova_loop.mtp_weights; +const round_contract = core.tree_round; +const round_gpu = core.tree_round_gpu; +const lref = scratch_mod.lref; +const buf_opts = scratch_mod.buf_opts; +const scratch_count = scratch_mod.scratch_count; +const ScratchField = scratch_mod.ScratchField; +const batch = @import("sn_mtp_batch.zig"); + +pub const max_depth = scratch_mod.max_depth; +pub const batch_cap = scratch_mod.batch_cap; +pub const batch_streams = scratch_mod.batch_streams; +pub const Features = scratch_mod.Features; +pub const AbsorbItem = scratch_mod.AbsorbItem; +pub const HoldItem = scratch_mod.HoldItem; +pub const StreamCtx = scratch_mod.StreamCtx; + +pub const Mtp = struct { + gpa: std.mem.Allocator, + model: *Model, + weights: mtp_weights.Weights, + attention: attn.Attention, + ops: round_gpu.Ops, + geometry: attn.planning.Geometry, + abs_scratch: attn.Scratch, + abs_binding: attn.Binding, + chain_scratch: [max_depth - 1]attn.Scratch, + chain_binding: [max_depth - 1]attn.Binding, + bufs: [scratch_count]mtl.Buffer, + parents_storage: [batch_cap]i32, + kept_storage: [batch_cap]u32, + ctxs: []?StreamCtx, + capacity: usize, + hidden: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + kv_dim: usize, + intermediate: usize, + vocab: usize, + abs_rows: u32, + bits: u32 = 16, + draft_head: ?core.sensenova_loop.linear_gpu.AwqMatrix = null, + depth: u32, + plain_guard: bool, + step_ms: f64 = 0.5, + tap_layer: [1]u32, + residency: ?mtl.ResidencySet.Follow = null, + + /// True when this SenseNova-Loop checkpoint has a companion `mtp.safetensors`. + pub fn available(io: std.Io, dir: []const u8, cfg: Config) bool { + return cfg.looped and cfg.mhc_iterations > 0 and mtp_weights.Weights.hasFile(io, dir); + } + + /// Per-stream device KV and speculative chain bytes (capacity tokens). + pub fn kvSlotBytes(cfg: Config, capacity: usize) usize { + return 2 * cfg.kvDim() * capacity * 2 + max_depth * 16 + (max_depth + 1) * cfg.hidden * 2; + } + + pub fn slotBytes(m: *const Mtp) usize { + return 2 * m.kv_dim * m.capacity * 2 + max_depth * 16 + (max_depth + 1) * m.hidden * 2; + } + + pub fn loadWeights(gpa: std.mem.Allocator, io: std.Io, model: *Model, dir: []const u8) !mtp_weights.Weights { + const c = model.config; + return mtp_weights.Weights.load(gpa, io, model.device, model.queue, dir, c.hidden, c.heads, c.kv_heads, c.head_dim, c.intermediate); + } + + pub fn init(gpa: std.mem.Allocator, io: std.Io, model: *Model, dir: []const u8, slots: u32, capacity: usize) !*Mtp { + var weights = try loadWeights(gpa, io, model, dir); + errdefer weights.deinit(); + return initFromWeights(gpa, model, weights, slots, capacity); + } + + pub fn initFromWeights(gpa: std.mem.Allocator, model: *Model, weights: mtp_weights.Weights, slots: u32, capacity: usize) !*Mtp { + if (slots == 0 or capacity < 16 or model.kernels.sn == null or model.weights.head.sn == null or model.weights.embed_bf16 == null) { + return error.MissingSenseNovaMtpPrereqs; + } + var w_owned = weights; + errdefer w_owned.deinit(); + const cfg = model.config; + const dev = model.device; + const units = dev.tensorUnits(); + const geometry = try attn.planning.Geometry.fromConfig(cfg, units); + var attention = try scratch_mod.buildAttention(gpa, dev, geometry, units); + errdefer attention.deinit(); + const ops = try round_gpu.Ops.init(dev); + errdefer ops.deinit(); + const kv_dim = cfg.kvDim(); + const eff_batch = geometry.promptRows(@intCast(@min(batch_cap, capacity))); + const abs_limits = attn.Limits{ .rows = eff_batch, .streams = batch_streams, .keys = @intCast(capacity), .shared_prefix = geometry.shared_prefix, .geometry = geometry }; + var abs_scratch = try attn.Scratch.init(dev, abs_limits); + errdefer abs_scratch.deinit(); + var abs_binding = try attn.Binding.init(dev, abs_limits); + errdefer abs_binding.deinit(); + const chain_limits = attn.Limits{ .rows = batch_streams, .streams = batch_streams, .keys = @intCast(capacity), .shared_prefix = geometry.shared_prefix, .geometry = geometry }; + var chain_scratch: [max_depth - 1]attn.Scratch = undefined; + var chain_binding: [max_depth - 1]attn.Binding = undefined; + var made_chain: usize = 0; + errdefer for (0..made_chain) |i| { + chain_scratch[i].deinit(); + chain_binding[i].deinit(); + }; + for (0..max_depth - 1) |i| { + chain_scratch[i] = try attn.Scratch.init(dev, chain_limits); + errdefer chain_scratch[i].deinit(); + chain_binding[i] = try attn.Binding.init(dev, chain_limits); + made_chain += 1; + } + const sizes = scratch_mod.scratchSizes(cfg, eff_batch); + var bufs: [scratch_count]mtl.Buffer = undefined; + var made_bufs: usize = 0; + errdefer for (bufs[0..made_bufs]) |b| b.deinit(); + for (sizes, &bufs) |bytes, *b| { + b.* = try dev.buffer(@max(bytes, 16), buf_opts); + made_bufs += 1; + } + var draft_head: ?core.sensenova_loop.linear_gpu.AwqMatrix = null; + errdefer if (draft_head) |*dh| dh.deinit(); + if (w_owned.bits == 4 and model.weights.head.bits == 16) { + const runs = model.weights.head.sn.?.runs; + if (runs.len == 1 and runs[0].mat == .bf16) { + draft_head = try mtp_weights.quantizeMat(&model.kernels.sn.?, model.queue, runs[0].mat.bf16); + } + } + if (w_owned.bits == 4 or draft_head != null) { + try model.kernels.sn.?.reserve(@import("gpu_frame.zig").max_rows, true); + } + const ctxs = try gpa.alloc(?StreamCtx, slots); + @memset(ctxs, null); + errdefer { + for (ctxs) |*slot_opt| if (slot_opt.*) |*sc| sc.deinit(); + gpa.free(ctxs); + } + ctxs[0] = try StreamCtx.init(dev, capacity, kv_dim, cfg.hidden); + const depth = std.math.clamp(try @import("sys").environment.read(u32, "TF_MTP_DRAFTS", 3), 1, max_depth); + const plain_guard = try @import("sys").environment.read(bool, "TF_MTP_PLAIN_GUARD", true); + const m = try gpa.create(Mtp); + m.* = .{ + .gpa = gpa, + .model = model, + .weights = w_owned, + .attention = attention, + .ops = ops, + .geometry = geometry, + .abs_scratch = abs_scratch, + .abs_binding = abs_binding, + .chain_scratch = chain_scratch, + .chain_binding = chain_binding, + .bufs = bufs, + .parents_storage = undefined, + .kept_storage = undefined, + .ctxs = ctxs, + .capacity = capacity, + .hidden = cfg.hidden, + .heads = cfg.heads, + .kv_heads = cfg.kv_heads, + .head_dim = cfg.head_dim, + .kv_dim = kv_dim, + .intermediate = cfg.intermediate, + .vocab = cfg.vocab, + .abs_rows = eff_batch, + .bits = w_owned.bits, + .draft_head = draft_head, + .depth = depth, + .plain_guard = plain_guard, + .tap_layer = .{@intCast(cfg.layers - 1)}, + }; + for (&m.parents_storage, 0..) |*p, r| p.* = @as(i32, @intCast(r)) - 1; + for (&m.kept_storage, 0..) |*k, r| k.* = @intCast(r); + @memcpy(m.buf(.kept).slice(u32, eff_batch), m.kept_storage[0..eff_batch]); + return m; + } + + pub fn deinit(m: *Mtp) void { + m.setResident(null); + for (m.ctxs) |*slot_opt| if (slot_opt.*) |*sc| sc.deinit(); + m.gpa.free(m.ctxs); + for (m.bufs) |b| b.deinit(); + for (&m.chain_scratch, &m.chain_binding) |*s, *b| { + s.deinit(); + b.deinit(); + } + m.abs_scratch.deinit(); + m.abs_binding.deinit(); + m.ops.deinit(); + m.attention.deinit(); + if (m.draft_head) |*dh| dh.deinit(); + m.weights.deinit(); + m.gpa.destroy(m); + } + + pub fn appendBuffers(m: *const Mtp, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + return scratch_mod.appendMtpBuffers(m, a, list); + } + + pub fn setResident(m: *Mtp, hook: ?mtl.ResidencySet.Follow) void { + if (m.residency) |old| m.applyResident(old, false); + m.residency = hook; + if (hook) |f| m.applyResident(f, true); + } + + fn applyResident(m: *Mtp, f: mtl.ResidencySet.Follow, joining: bool) void { + scratch_mod.applyMtpResident(m, f, joining); + } + + pub fn openStream(m: *Mtp, s: usize) !void { + if (s == 0) return error.BadMtpStream; + for (m.ctxs) |slot_opt| if (slot_opt) |sc| if (sc.in_use and sc.owner == s) return error.DuplicateMtpStream; + for (m.ctxs) |*slot_opt| if (slot_opt.*) |*sc| if (!sc.in_use) { + sc.reset(s); + return; + }; + for (m.ctxs) |*slot_opt| if (slot_opt.* == null) { + var sc = try StreamCtx.init(m.model.device, m.capacity, m.kv_dim, m.hidden); + sc.reset(s); + slot_opt.* = sc; + if (m.residency) |f| { + for ([_]mtl.Buffer{ sc.keys, sc.values, sc.picks_buf, sc.chain_out_buf }) |b| mtl.resident.fields.one(b, f, true); + } + return; + }; + return error.NoFreeMtpSlot; + } + + pub fn releaseStream(m: *Mtp, s: usize) void { + for (m.ctxs) |*slot_opt| if (slot_opt.*) |*sc| if (sc.in_use and sc.owner == s) { + sc.reset(0); + return; + }; + } + + pub fn ctxOf(m: *const Mtp, s: usize) !*StreamCtx { + for (m.ctxs) |*slot_opt| if (slot_opt.*) |*sc| if (sc.in_use and sc.owner == s) return sc; + return error.UnknownMtpStream; + } + + pub fn absorb(m: *Mtp, items: []const AbsorbItem) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + for (items) |it| { + const ctx = try m.ctxOf(it.stream); + const total = it.follow.len; + if (total == 0) continue; + if (it.rows) |sel| if (sel.len != total) return error.BadMtpAbsorb; + if (it.features.row_bytes != m.hidden * 2) return error.BadMtpFeatures; + if (ctx.len == 0 and it.start > 0) { + ctx.begin = it.start; + ctx.len = it.start; + } + if (it.start != ctx.len or (it.start - ctx.begin) + total > m.capacity) return error.BadMtpPosition; + var done: usize = 0; + while (done < total) { + const take: u32 = @intCast(@min(m.abs_rows, total - done)); + const last_chunk = done + take == total; + const pos = it.start + done; + const raw_ref = try scratch_mod.stageRawFeatures(m, it.features, it.rows, done, take); + @memcpy(m.buf(.ids).slice(u32, take), it.follow[done..][0..take]); + const pos_dst = m.buf(.pos).slice(u32, take); + for (pos_dst, 0..) |*p, r| p.* = @intCast(pos + r); + const cache_view = m.cacheView(ctx); + var plan = try attn.Plan.init(m.gpa, &.{.{ .parents = m.parents_storage[0..take], .start = @intCast(pos - ctx.begin), .capacity = cache_view.capacity }}, m.geometry); + defer plan.deinit(); + try m.abs_scratch.upload(plan); + try m.abs_binding.upload(plan, &.{cache_view}); + const cb = m.model.queue.commandBuffer(); + const e = cb.compute(.serial); + var ended = false; + errdefer if (!ended) e.end(); + try m.encodeStep(e, &m.abs_scratch, &m.abs_binding, plan, cache_view, take, raw_ref, m.ref(.ids), m.ref(.pos), true, if (last_chunk and !it.prompt_only) ctx else null, it.propose and last_chunk and !it.prompt_only, 0); + e.end(); + ended = true; + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("sensenova mtp absorb GPU failure: {s}", .{msg}); + return error.GpuFailed; + } + ctx.len += take; + done += take; + } + ctx.has_out = !it.prompt_only; + ctx.has_pick0 = it.propose and !it.prompt_only; + } + } + + pub fn hold(m: *Mtp, items: []const HoldItem) !void { + if (items.len > 1 and batch.canBatch(m, &.{}, items)) return batch.run(m, &.{}, items); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + for (items) |it| { + const ctx = try m.ctxOf(it.stream); + const depth = @min(it.depth, max_depth); + if (depth == 0) { + ctx.held_count = 0; + continue; + } + if (!ctx.has_out) { + for (ctx.held_tokens[0..depth]) |*t| t.* = it.pending; + ctx.held_count = depth; + continue; + } + const chain_steps: usize = if (depth > 1) depth - 1 else 0; + const need_gpu = !ctx.has_pick0 or chain_steps > 0; + if (need_gpu) { + if (ctx.len < ctx.begin or (ctx.len - ctx.begin) + chain_steps > m.capacity) return error.BadMtpPosition; + const cache_view = m.cacheView(ctx); + var plans: [max_depth - 1]attn.Plan = undefined; + var built: usize = 0; + defer for (plans[0..built]) |*p| p.deinit(); + try m.stageChain(cache_view, ctx.begin, ctx.len, chain_steps, &plans, &built); + const cb = m.model.queue.commandBuffer(); + const e = cb.compute(.serial); + var ended = false; + errdefer if (!ended) e.end(); + if (!ctx.has_pick0) { + try m.encodeHeadPick(e, ctx, 0); + ctx.has_pick0 = true; + } + try m.encodeChain(e, ctx, cache_view, &plans, chain_steps); + e.end(); + ended = true; + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("sensenova mtp hold GPU failure: {s}", .{msg}); + return error.GpuFailed; + } + } + scratch_mod.populateHeld(ctx, it.pending, depth, m.vocab); + } + } + + pub fn draftRound(m: *Mtp, absorbs: []const AbsorbItem, holds: []const HoldItem) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const depth = if (holds.len == 1) @min(holds[0].depth, max_depth) else 0; + if (absorbs.len == 1 and holds.len == 1 and absorbs[0].stream == holds[0].stream and + !absorbs[0].prompt_only and absorbs[0].follow.len > 0 and absorbs[0].follow.len <= m.abs_rows and depth > 0) + { + const it = absorbs[0]; + const hit = holds[0]; + const ctx = try m.ctxOf(it.stream); + const take: u32 = @intCast(it.follow.len); + if (it.rows) |sel| if (sel.len != take) return error.BadMtpAbsorb; + if (it.features.row_bytes != m.hidden * 2) return error.BadMtpFeatures; + const start_begin = if (ctx.len == 0 and it.start > 0) it.start else ctx.begin; + const start_len = if (ctx.len == 0 and it.start > 0) it.start else ctx.len; + const chain_steps: usize = depth - 1; + if (it.start != start_len or (it.start - start_begin) + take + chain_steps > m.capacity) { + return error.BadMtpPosition; + } + const raw_ref = try scratch_mod.stageRawFeatures(m, it.features, it.rows, 0, take); + @memcpy(m.buf(.ids).slice(u32, take), it.follow); + const pos_dst = m.buf(.pos).slice(u32, take); + for (pos_dst, 0..) |*p, r| p.* = @intCast(it.start + r); + const cache_view = m.cacheViewAt(ctx, start_begin); + var abs_plan = try attn.Plan.init(m.gpa, &.{.{ .parents = m.parents_storage[0..take], .start = @intCast(it.start - start_begin), .capacity = cache_view.capacity }}, m.geometry); + defer abs_plan.deinit(); + try m.abs_scratch.upload(abs_plan); + try m.abs_binding.upload(abs_plan, &.{cache_view}); + var plans: [max_depth - 1]attn.Plan = undefined; + var built: usize = 0; + defer for (plans[0..built]) |*p| p.deinit(); + try m.stageChain(cache_view, start_begin, it.start + take, chain_steps, &plans, &built); + const cb = m.model.queue.commandBuffer(); + const e = cb.compute(.serial); + var ended = false; + errdefer if (!ended) e.end(); + try m.encodeStep(e, &m.abs_scratch, &m.abs_binding, abs_plan, cache_view, take, raw_ref, m.ref(.ids), m.ref(.pos), true, ctx, it.propose, 0); + e.barrier(); + if (!it.propose) try m.encodeHeadPick(e, ctx, 0); + try m.encodeChain(e, ctx, cache_view, &plans, chain_steps); + e.end(); + ended = true; + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("sensenova mtp draftRound GPU failure: {s}", .{msg}); + return error.GpuFailed; + } + ctx.begin = start_begin; + ctx.len = it.start + take; + ctx.has_out = true; + ctx.has_pick0 = true; + scratch_mod.populateHeld(ctx, hit.pending, depth, m.vocab); + return; + } + if ((absorbs.len > 1 or holds.len > 1) and batch.canBatch(m, absorbs, holds)) { + return batch.run(m, absorbs, holds); + } + if (absorbs.len > 0) try m.absorb(absorbs); + if (holds.len > 0) try m.hold(holds); + } + + pub fn held(m: *const Mtp, streams: []const usize, outs: []const []u32) !void { + for (streams, outs) |s, out| { + const ctx = try m.ctxOf(s); + if (out.len > ctx.held_count) return error.TooFewMtpDrafts; + @memcpy(out, ctx.held_tokens[0..out.len]); + } + } + + /// Warm GEMM/splitK/attention pipelines before residency lock and time single-step `hold`. + pub fn warmup(m: *Mtp, io: std.Io) !void { + return scratch_mod.warmup(m, io); + } + + fn stageChain(m: *Mtp, cache_view: attn.Cache, start_begin: u64, base_pos: u64, chain_steps: usize, plans: *[max_depth - 1]attn.Plan, built: *usize) !void { + const cpos_ptr: [*]u32 = @ptrCast(@alignCast(m.buf(.chain_pos).contents())); + for (0..chain_steps) |s| { + const pos_k = base_pos + s; + cpos_ptr[s * batch_streams] = @intCast(pos_k); + plans[s] = try attn.Plan.init(m.gpa, &.{.{ .parents = m.parents_storage[0..1], .start = @intCast(pos_k - start_begin), .capacity = cache_view.capacity }}, m.geometry); + built.* += 1; + try m.chain_scratch[s].upload(plans[s]); + try m.chain_binding[s].upload(plans[s], &.{cache_view}); + } + } + + fn encodeChain(m: *Mtp, e: mtl.ComputeEncoder, ctx: *StreamCtx, cache_view: attn.Cache, plans: *const [max_depth - 1]attn.Plan, chain_steps: usize) !void { + for (0..chain_steps) |s| { + const hin = ctx.chainOutRef(s, m.hidden); + const ids_ref = projection.Ref{ .buffer = ctx.picks_buf, .offset = s * 16 }; + const pos_ref = projection.Ref{ .buffer = m.buf(.chain_pos), .offset = s * batch_streams * 4 }; + try m.encodeStep(e, &m.chain_scratch[s], &m.chain_binding[s], plans[s], cache_view, 1, hin, ids_ref, pos_ref, false, ctx, true, s + 1); + } + } + + pub fn encodeHeadBatch(m: *Mtp, e: mtl.ComputeEncoder, in_ref: projection.Ref, ctxs: []const *StreamCtx, slot_idx: usize) !void { + const rows: u32 = @intCast(ctxs.len); + const sn = &m.model.kernels.sn.?; + if (m.draft_head) |dh| { + try sn.encodeAwq(e, dh, lref(in_ref), null, lref(m.ref(.logits)), rows, @intCast(m.vocab), false, null); + } else { + const head_sn = m.model.weights.head.sn.?; + try loop.encodeSn(sn, null, e, head_sn, in_ref, null, m.ref(.logits), rows, false); + } + e.barrier(); + for (ctxs, 0..) |ctx, i| { + try m.ops.argmax(e, .{ .buf = m.buf(.logits), .off = i * m.vocab * 2 }, ctx.pickRef(slot_idx), .{ .rows = 1, .vocab = @intCast(m.vocab), .stride = @intCast(m.vocab) }); + } + e.barrier(); + } + + fn encodeHeadPick(m: *Mtp, e: mtl.ComputeEncoder, ctx: *StreamCtx, slot_idx: usize) !void { + return m.encodeHeadBatch(e, ctx.chainOutRef(slot_idx, m.hidden), &.{ctx}, slot_idx); + } + + pub fn encodeTransformer( + m: *Mtp, + e: mtl.ComputeEncoder, + scratch: *const attn.Scratch, + binding: *const attn.Binding, + plan: attn.Plan, + caches: []const attn.Cache, + rows: u32, + raw_hin: projection.Ref, + embed_ids: ?projection.Ref, + pos_ref: projection.Ref, + norm_target_hin: bool, + keys_only: bool, + dims_slot: usize, + ) !void { + const cfg = m.model.config; + const glue = m.model.glue; + const sn = &m.model.kernels.sn.?; + const w = &m.weights; + const hidden_u32: u32 = @intCast(m.hidden); + const kv_dim_u32: u32 = @intCast(m.kv_dim); + const prompt_lin = rows >= 16 and caches.len == 1; + const hin_norm_src = if (norm_target_hin) blk: { + try glue.headNormWith(e, raw_hin, wts.ref(m.model.weights.norm), m.ref(.hin), hidden_u32, rows, cfg.eps, cfg.shift_norms); + break :blk m.ref(.hin); + } else raw_hin; + if (embed_ids) |ids_ref| { + try glue.embeddingBf16(e, m.hidden, m.vocab, wts.ref(m.model.weights.embed_bf16.?), ids_ref, m.ref(.h), rows); + } + e.barrier(); + const en_plane = m.ref(.planes); + const hn_plane = projection.Ref{ .buffer = m.buf(.planes), .offset = @as(usize, m.abs_rows) * m.hidden * 2 }; + try glue.headNormWith(e, m.ref(.h), wts.ref(w.norm_e), en_plane, hidden_u32, rows, cfg.eps, true); + try glue.headNormWith(e, hin_norm_src, wts.ref(w.norm_h), hn_plane, hidden_u32, rows, cfg.eps, true); + e.barrier(); + try glue.tapRows(e, m.ref(.planes), m.ref(.kept), m.ref(.cat), .{ .rows = rows, .width = hidden_u32, .capacity = m.abs_rows, .planes = 2 }); + e.barrier(); + try scratch_mod.encodeMat(sn, e, w.fc, m.ref(.cat), m.ref(.h), rows, hidden_u32, prompt_lin, null); + e.barrier(); + try glue.headNormWith(e, m.ref(.h), wts.ref(w.input_norm), m.ref(.x), hidden_u32, rows, cfg.eps, true); + e.barrier(); + const q_dim_u32: u32 = @intCast(2 * m.heads * m.head_dim); + try scratch_mod.encodeMatSplit(sn, e, w.qkv, m.ref(.x), m.ref(.qg), rows, q_dim_u32, prompt_lin, null, .{ + .split1 = q_dim_u32, + .y1 = .{ .buf = m.buf(.k) }, + .ldy1 = kv_dim_u32, + .split2 = q_dim_u32 + kv_dim_u32, + .y2 = .{ .buf = m.buf(.v) }, + .ldy2 = kv_dim_u32, + }); + e.barrier(); + const prep: attn.Preprocess = .{ .qg = m.ref(.qg), .key = m.ref(.k), .q_gain = wts.ref(w.q_norm), .k_gain = wts.ref(w.k_norm), .norm_q = m.ref(.norm_q), .norm_k = m.ref(.norm_k), .query = m.ref(.query), .rotated_key = m.ref(.rot_k), .positions = pos_ref, .rows = rows, .eps = cfg.eps, .theta = cfg.rope_theta, .geometry = m.geometry, .shift = true, .rope = cfg.rope }; + if (keys_only) { + try m.attention.keysOnly(e, scratch, binding, plan, prep, m.ref(.v), caches); + return; + } + try m.attention.preprocess(e, prep); + try m.attention.encode(e, scratch, binding, plan, m.ref(.query), m.ref(.rot_k), m.ref(.v), m.ref(.attn_out), caches, m.ref(.qg), prompt_lin, false); + e.barrier(); + try scratch_mod.encodeMat(sn, e, w.o, m.ref(.attn_out), m.ref(.r), rows, hidden_u32, prompt_lin, null); + e.barrier(); + glue.residual(e, m.ref(.h), m.ref(.r), m.ref(.hin), hidden_u32, rows); + e.barrier(); + try glue.headNormWith(e, m.ref(.hin), wts.ref(w.post_norm), m.ref(.x), hidden_u32, rows, cfg.eps, true); + e.barrier(); + try scratch_mod.encodeMat(sn, e, w.gate_up, m.ref(.x), m.ref(.gu), rows, @intCast(2 * m.intermediate), prompt_lin, null); + e.barrier(); + const gu_ref = m.ref(.gu); + const up_ref = projection.Ref{ .buffer = gu_ref.buffer, .offset = gu_ref.offset + m.intermediate * 2 }; + std.debug.assert(dims_slot <= max_depth); + const dims_slice = m.buf(.dummy_dims).slice(i32, (max_depth + 1) * 4); + dims_slice[dims_slot * 4] = @intCast(rows); + dims_slice[dims_slot * 4 + 1] = @intCast(16 * ((rows + 15) / 16)); + const dims_ref = projection.Ref{ .buffer = m.buf(.dummy_dims), .offset = dims_slot * 16 }; + try m.model.kernels.mlp(e, gu_ref, up_ref, dims_ref, m.ref(.act), m.ref(.dummy_sums), @intCast(m.intermediate), rows); + const down_xs = if (comptime @hasDecl(@import("core"), "sensenova_loop")) blk: { + const v = if (m.model.kernels.sn_xs128) |xs128| xs128.sums else null; + m.model.kernels.sn_xs128 = null; + break :blk v; + } else null; + e.barrier(); + try scratch_mod.encodeMat(sn, e, w.down, m.ref(.act), m.ref(.r), rows, hidden_u32, prompt_lin, down_xs); + e.barrier(); + glue.residual(e, m.ref(.hin), m.ref(.r), m.ref(.h), hidden_u32, rows); + e.barrier(); + try glue.headNormWith(e, m.ref(.h), wts.ref(w.norm), m.ref(.x), hidden_u32, rows, cfg.eps, true); + e.barrier(); + } + + pub fn encodeStep( + m: *Mtp, + e: mtl.ComputeEncoder, + scratch: *const attn.Scratch, + binding: *const attn.Binding, + plan: attn.Plan, + cache_view: attn.Cache, + rows: u32, + raw_hin: projection.Ref, + ids_ref: projection.Ref, + pos_ref: projection.Ref, + norm_target_hin: bool, + ctx_out: ?*StreamCtx, + predict_pick: bool, + slot_idx: usize, + ) !void { + const dims_slot = if (ctx_out != null) slot_idx else 0; + try m.encodeTransformer(e, scratch, binding, plan, &.{cache_view}, rows, raw_hin, ids_ref, pos_ref, norm_target_hin, ctx_out == null, dims_slot); + if (ctx_out) |ctx| { + const hidden_u32: u32 = @intCast(m.hidden); + const src = projection.Ref{ .buffer = m.buf(.x), .offset = @as(usize, rows - 1) * m.hidden * 2 }; + try m.model.glue.unstack(e, src, ctx.chainOutRef(slot_idx, m.hidden), .{ .rows = 1, .width = hidden_u32, .stride = hidden_u32, .offset = 0 }); + e.barrier(); + if (predict_pick) try m.encodeHeadPick(e, ctx, slot_idx); + } + } + + pub fn cacheView(m: *const Mtp, ctx: *const StreamCtx) attn.Cache { + return m.cacheViewAt(ctx, ctx.begin); + } + + pub fn cacheViewAt(m: *const Mtp, ctx: *const StreamCtx, begin: u64) attn.Cache { + return .{ + .keys = .{ .buffer = ctx.keys, .offset = begin * m.head_dim * 2 }, + .values = .{ .buffer = ctx.values, .offset = begin * m.head_dim * 2 }, + .capacity = @intCast(m.capacity - begin), + .key_stride = @intCast(m.capacity * m.head_dim), + .value_stride = @intCast(m.capacity * m.head_dim), + }; + } + + pub fn buf(m: *const Mtp, f: ScratchField) mtl.Buffer { + return m.bufs[@backingInt(f)]; + } + + pub fn ref(m: *const Mtp, f: ScratchField) projection.Ref { + return .{ .buffer = m.buf(f) }; + } +}; diff --git a/zig/src/families/qwen27/sn_mtp_batch.zig b/zig/src/families/qwen27/sn_mtp_batch.zig new file mode 100644 index 00000000000..808c7d7b284 --- /dev/null +++ b/zig/src/families/qwen27/sn_mtp_batch.zig @@ -0,0 +1,252 @@ +//! Multi-stream batched absorb, head pick, and chain steps for SenseNova MTP. +const std = @import("std"); +const mtl = @import("metal"); +const attn = @import("attention.zig"); +const wts = @import("gpu_weights.zig"); +const projection = @import("projection.zig"); +const scratch_mod = @import("sn_mtp_scratch.zig"); + +const AbsorbItem = scratch_mod.AbsorbItem; +const HoldItem = scratch_mod.HoldItem; +const StreamCtx = scratch_mod.StreamCtx; +const max_streams: usize = scratch_mod.batch_streams; +const chain_cap: usize = scratch_mod.max_depth - 1; + +pub fn canBatch(m: anytype, absorbs: []const AbsorbItem, holds: []const HoldItem) bool { + if (absorbs.len == 0 and holds.len == 0) return false; + if (absorbs.len > max_streams or holds.len > max_streams) return false; + const row_cap = @min(m.abs_rows, attn.planning.max_rows); + var total_rows: usize = 0; + for (absorbs, 0..) |ab, i| { + if (ab.prompt_only or ab.follow.len == 0) return false; + total_rows += ab.follow.len; + for (absorbs[0..i]) |prev| if (prev.stream == ab.stream) return false; + } + if (total_rows > row_cap) return false; + for (holds, 0..) |hit, i| { + for (holds[0..i]) |prev| if (prev.stream == hit.stream) return false; + } + return true; +} + +pub fn run(m: anytype, absorbs: []const AbsorbItem, holds: []const HoldItem) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + var abs_ctxs: [max_streams]*StreamCtx = undefined; + var abs_begin: [max_streams]u64 = undefined; + var abs_new_len: [max_streams]u64 = undefined; + var abs_end_row: [max_streams]u32 = undefined; + var abs_caches: [max_streams]attn.Cache = undefined; + var abs_windows: [max_streams]attn.planning.Window = undefined; + var abs_pick0: [max_streams]bool = @splat(false); + + var hold_ctxs: [max_streams]*StreamCtx = undefined; + var hold_abs_idx: [max_streams]?usize = @splat(null); + var hold_has_out: [max_streams]bool = @splat(false); + var hold_begin: [max_streams]u64 = undefined; + var hold_len: [max_streams]u64 = undefined; + var hold_depth: [max_streams]u32 = undefined; + + for (absorbs, 0..) |ab, a| { + const ctx = try m.ctxOf(ab.stream); + const take = ab.follow.len; + if (ab.rows) |sel| if (sel.len != take) return error.BadMtpAbsorb; + if (ab.features.row_bytes != m.hidden * 2) return error.BadMtpFeatures; + const start_begin = if (ctx.len == 0 and ab.start > 0) ab.start else ctx.begin; + const start_len = if (ctx.len == 0 and ab.start > 0) ab.start else ctx.len; + if (ab.start != start_len) return error.BadMtpPosition; + var extra_chain: usize = 0; + for (holds) |hit| if (hit.stream == ab.stream) { + const d = @min(hit.depth, scratch_mod.max_depth); + if (d > 1) extra_chain = d - 1; + break; + }; + if ((ab.start - start_begin) + take + extra_chain > m.capacity) return error.BadMtpPosition; + abs_ctxs[a] = ctx; + abs_begin[a] = start_begin; + abs_new_len[a] = ab.start + take; + } + + var pick_ctxs: [max_streams]*StreamCtx = undefined; + var pick_count: usize = 0; + var max_chain: usize = 0; + + for (holds, 0..) |hit, j| { + const ctx = try m.ctxOf(hit.stream); + hold_ctxs[j] = ctx; + var ai: ?usize = null; + for (absorbs, 0..) |ab, a| if (ab.stream == hit.stream) { + ai = a; + break; + }; + hold_abs_idx[j] = ai; + const has_out = (ai != null) or ctx.has_out; + const base_begin = if (ai) |a| abs_begin[a] else ctx.begin; + const base_len = if (ai) |a| abs_new_len[a] else ctx.len; + const d = @min(hit.depth, scratch_mod.max_depth); + if (has_out and d > 1) { + if (base_len < base_begin or (base_len - base_begin) + (d - 1) > m.capacity) return error.BadMtpPosition; + max_chain = @max(max_chain, d - 1); + } + hold_has_out[j] = has_out; + hold_begin[j] = base_begin; + hold_len[j] = base_len; + hold_depth[j] = d; + } + + for (absorbs, 0..) |ab, a| { + var held_pos = false; + for (holds, 0..) |hit, j| if (hit.stream == ab.stream) { + held_pos = hold_depth[j] > 0; + break; + }; + abs_pick0[a] = ab.propose or held_pos; + if (abs_pick0[a]) { + pick_ctxs[pick_count] = abs_ctxs[a]; + pick_count += 1; + } + } + for (holds, 0..) |_, j| { + if (hold_abs_idx[j] == null and hold_depth[j] > 0 and hold_has_out[j] and !hold_ctxs[j].has_pick0) { + pick_ctxs[pick_count] = hold_ctxs[j]; + pick_count += 1; + } + } + + if (absorbs.len == 0 and pick_count == 0 and max_chain == 0) { + for (holds, 0..) |hit, j| { + const ctx = hold_ctxs[j]; + if (hold_depth[j] == 0) { + ctx.held_count = 0; + continue; + } + for (ctx.held_tokens[0..hold_depth[j]]) |*t| t.* = hit.pending; + ctx.held_count = hold_depth[j]; + } + return; + } + + var abs_plan: ?attn.Plan = null; + defer if (abs_plan) |*p| p.deinit(); + var total_rows: u32 = 0; + if (absorbs.len > 0) { + const ids_slice = m.buf(.ids).slice(u32, m.abs_rows); + const pos_slice = m.buf(.pos).slice(u32, m.abs_rows); + var row_off: u32 = 0; + for (absorbs, 0..) |ab, a| { + const take: u32 = @intCast(ab.follow.len); + try scratch_mod.stageFeaturesAt(m, ab.features, ab.rows, 0, take, row_off); + @memcpy(ids_slice[row_off..][0..take], ab.follow); + for (pos_slice[row_off..][0..take], 0..) |*p, r| p.* = @intCast(ab.start + r); + abs_caches[a] = m.cacheViewAt(abs_ctxs[a], abs_begin[a]); + abs_windows[a] = .{ .parents = m.parents_storage[0..take], .start = @intCast(ab.start - abs_begin[a]), .capacity = abs_caches[a].capacity }; + row_off += take; + abs_end_row[a] = row_off; + } + total_rows = row_off; + abs_plan = try attn.Plan.init(m.gpa, abs_windows[0..absorbs.len], m.geometry); + try m.abs_scratch.upload(abs_plan.?); + try m.abs_binding.upload(abs_plan.?, abs_caches[0..absorbs.len]); + } + + var plans: [chain_cap]attn.Plan = undefined; + var built: usize = 0; + defer for (plans[0..built]) |*p| p.deinit(); + var ch_ctxs: [chain_cap][max_streams]*StreamCtx = undefined; + var ch_caches: [chain_cap][max_streams]attn.Cache = undefined; + var ch_counts: [chain_cap]usize = @splat(0); + const cpos_ptr: [*]u32 = @ptrCast(@alignCast(m.buf(.chain_pos).contents())); + for (0..max_chain) |s| { + var ch_windows: [max_streams]attn.planning.Window = undefined; + var k: usize = 0; + for (0..holds.len) |j| { + if (!hold_has_out[j] or hold_depth[j] <= s + 1) continue; + const pos_k = hold_len[j] + s; + cpos_ptr[s * max_streams + k] = @intCast(pos_k); + ch_ctxs[s][k] = hold_ctxs[j]; + ch_caches[s][k] = m.cacheViewAt(hold_ctxs[j], hold_begin[j]); + ch_windows[k] = .{ .parents = m.parents_storage[0..1], .start = @intCast(pos_k - hold_begin[j]), .capacity = ch_caches[s][k].capacity }; + k += 1; + } + ch_counts[s] = k; + plans[s] = try attn.Plan.init(m.gpa, ch_windows[0..k], m.geometry); + built += 1; + try m.chain_scratch[s].upload(plans[s]); + try m.chain_binding[s].upload(plans[s], ch_caches[s][0..k]); + } + + const cb = m.model.queue.commandBuffer(); + const e = cb.compute(.serial); + var ended = false; + errdefer if (!ended) e.end(); + const hidden_u32: u32 = @intCast(m.hidden); + const glue = m.model.glue; + + if (absorbs.len > 0) { + try m.encodeTransformer(e, &m.abs_scratch, &m.abs_binding, abs_plan.?, abs_caches[0..absorbs.len], total_rows, m.ref(.gather), m.ref(.ids), m.ref(.pos), true, false, 0); + for (0..absorbs.len) |a| { + const src = projection.Ref{ .buffer = m.buf(.x), .offset = @as(usize, abs_end_row[a] - 1) * m.hidden * 2 }; + try glue.unstack(e, src, abs_ctxs[a].chainOutRef(0, m.hidden), .{ .rows = 1, .width = hidden_u32, .stride = hidden_u32, .offset = 0 }); + } + e.barrier(); + } + + if (pick_count > 0) { + for (pick_ctxs[0..pick_count], 0..) |ctx, i| { + const dst = projection.Ref{ .buffer = m.buf(.cat), .offset = i * m.hidden * 2 }; + try glue.unstack(e, ctx.chainOutRef(0, m.hidden), dst, .{ .rows = 1, .width = hidden_u32, .stride = hidden_u32, .offset = 0 }); + } + e.barrier(); + try m.encodeHeadBatch(e, m.ref(.cat), pick_ctxs[0..pick_count], 0); + } + + for (0..max_chain) |s| { + const k = ch_counts[s]; + const k_u32: u32 = @intCast(k); + for (ch_ctxs[s][0..k], 0..) |ctx, i| { + const hin_dst = projection.Ref{ .buffer = m.buf(.gather), .offset = i * m.hidden * 2 }; + try glue.unstack(e, ctx.chainOutRef(s, m.hidden), hin_dst, .{ .rows = 1, .width = hidden_u32, .stride = hidden_u32, .offset = 0 }); + const ids_ref = projection.Ref{ .buffer = ctx.picks_buf, .offset = s * 16 }; + const h_dst = projection.Ref{ .buffer = m.buf(.h), .offset = i * m.hidden * 2 }; + try glue.embeddingBf16(e, m.hidden, m.vocab, wts.ref(m.model.weights.embed_bf16.?), ids_ref, h_dst, 1); + } + const pos_ref = projection.Ref{ .buffer = m.buf(.chain_pos), .offset = s * max_streams * 4 }; + try m.encodeTransformer(e, &m.chain_scratch[s], &m.chain_binding[s], plans[s], ch_caches[s][0..k], k_u32, m.ref(.gather), null, pos_ref, false, false, s + 1); + for (ch_ctxs[s][0..k], 0..) |ctx, i| { + const src = projection.Ref{ .buffer = m.buf(.x), .offset = i * m.hidden * 2 }; + try glue.unstack(e, src, ctx.chainOutRef(s + 1, m.hidden), .{ .rows = 1, .width = hidden_u32, .stride = hidden_u32, .offset = 0 }); + } + e.barrier(); + try m.encodeHeadBatch(e, m.ref(.x), ch_ctxs[s][0..k], s + 1); + } + + e.end(); + ended = true; + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("sensenova mtp batch draftRound GPU failure: {s}", .{msg}); + return error.GpuFailed; + } + + for (0..absorbs.len) |a| { + abs_ctxs[a].begin = abs_begin[a]; + abs_ctxs[a].len = abs_new_len[a]; + abs_ctxs[a].has_out = true; + abs_ctxs[a].has_pick0 = abs_pick0[a]; + } + for (holds, 0..) |hit, j| { + const ctx = hold_ctxs[j]; + if (hold_depth[j] == 0) { + ctx.held_count = 0; + continue; + } + if (!hold_has_out[j]) { + for (ctx.held_tokens[0..hold_depth[j]]) |*t| t.* = hit.pending; + ctx.held_count = hold_depth[j]; + continue; + } + ctx.has_pick0 = true; + scratch_mod.populateHeld(ctx, hit.pending, hold_depth[j], m.vocab); + } +} diff --git a/zig/src/families/qwen27/sn_mtp_scratch.zig b/zig/src/families/qwen27/sn_mtp_scratch.zig new file mode 100644 index 00000000000..752d8aa2f78 --- /dev/null +++ b/zig/src/families/qwen27/sn_mtp_scratch.zig @@ -0,0 +1,363 @@ +//! Scratch buffer layout, stream KV context, and attention builder for SenseNova MTP. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const attn = @import("attention.zig"); +const projection = @import("projection.zig"); +const simd_attention = @import("simd_attention.zig"); +const Config = @import("config.zig").Config; +const linear_gpu = core.sensenova_loop.linear_gpu; +const round_gpu = core.tree_round_gpu; + +pub const max_depth: u32 = 4; +pub const batch_cap: u32 = 2048; +pub const batch_streams: u32 = 16; +pub const buf_opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + +/// Input hidden states slice passed to `Mtp.absorb` (layer `layers - 1` pre-final-norm output). +pub const Features = struct { + buffer: usize, + offset: usize, + rows: u32, + row_bytes: u32, + host: bool = false, +}; + +pub const AbsorbItem = struct { + stream: usize, + features: Features, + start: u64, + follow: []const u32, + rows: ?[]const u32 = null, + propose: bool = true, + prompt_only: bool = false, +}; + +pub const HoldItem = struct { + stream: usize, + pending: u32, + position: u64, + depth: u32, +}; + +/// Per-stream MTP KV cache and speculative state. +pub const StreamCtx = struct { + keys: mtl.Buffer, + values: mtl.Buffer, + picks_buf: mtl.Buffer, + chain_out_buf: mtl.Buffer, + begin: u64 = 0, + len: u64 = 0, + has_out: bool = false, + has_pick0: bool = false, + in_use: bool = false, + owner: usize = 0, + held_tokens: [max_depth]u32 = @splat(0), + held_count: u32 = 0, + + pub fn init(device: mtl.Device, capacity: usize, kv_dim: usize, hidden: usize) !StreamCtx { + const kv_bytes = kv_dim * capacity * 2; + const keys = try device.buffer(kv_bytes, buf_opts); + errdefer keys.deinit(); + const values = try device.buffer(kv_bytes, buf_opts); + errdefer values.deinit(); + const picks_buf = try device.buffer(max_depth * 16, buf_opts); + errdefer picks_buf.deinit(); + const chain_out_buf = try device.buffer((max_depth + 1) * hidden * 2, buf_opts); + return .{ .keys = keys, .values = values, .picks_buf = picks_buf, .chain_out_buf = chain_out_buf }; + } + + pub fn deinit(c: *StreamCtx) void { + c.keys.deinit(); + c.values.deinit(); + c.picks_buf.deinit(); + c.chain_out_buf.deinit(); + } + + pub fn reset(c: *StreamCtx, owner: usize) void { + c.begin = 0; + c.len = 0; + c.has_out = false; + c.has_pick0 = false; + c.in_use = owner != 0; + c.owner = owner; + c.held_count = 0; + } + + pub fn chainOutRef(c: *const StreamCtx, slot_idx: usize, hidden: usize) projection.Ref { + return .{ .buffer = c.chain_out_buf, .offset = slot_idx * hidden * 2 }; + } + + pub fn pickRef(c: *const StreamCtx, idx: usize) round_gpu.Ref { + return .{ .buf = c.picks_buf, .off = idx * 16 }; + } +}; + +pub const ScratchField = enum(usize) { + ids, + pos, + kept, + hin, + planes, + cat, + h, + x, + qg, + kv_raw, + k, + v, + norm_q, + query, + norm_k, + rot_k, + attn_out, + r, + gu, + act, + dummy_dims, + dummy_sums, + logits, + chain_pos, + gather, +}; + +pub const scratch_count: usize = 25; + +pub fn lref(r: projection.Ref) linear_gpu.Ref { + return .{ .buf = r.buffer, .off = r.offset }; +} + +pub fn scratchSizes(c: Config, rows: u32) [scratch_count]usize { + const r: usize = rows; + const h = c.hidden; + const kv = c.kvDim(); + const qd = c.heads * c.head_dim; + const inter = c.intermediate; + return .{ + r * 4, + r * 4, + r * 4, + r * h * 2, + 2 * r * h * 2, + r * 2 * h * 2, + r * h * 2, + r * h * 2, + r * 2 * qd * 2, + 16, + r * kv * 2, + r * kv * 2, + r * qd * 2, + r * qd * 2, + r * kv * 2, + r * kv * 2, + r * qd * 2, + r * h * 2, + r * 2 * inter * 2, + r * inter * 2, + (max_depth + 1) * 16, + @max(r, 16) * ((inter + 63) / 64) * 4, + @as(usize, batch_streams) * c.vocab * 2, + @as(usize, max_depth) * batch_streams * 4, + r * h * 2, + }; +} + +pub fn buildAttention(a: std.mem.Allocator, dev: mtl.Device, g: attn.planning.Geometry, units: bool) !attn.Attention { + const text = try simd_attention.grouped(a, units, true, g.group(), g.kv_heads, false); + defer a.free(text); + const lib = mtl.Library.fromSource(dev, text, mtl.CompileOptions.mlx()) catch |err| blk: { + if (units) return err; + const base = try simd_attention.grouped(a, units, false, g.group(), g.kv_heads, false); + defer a.free(base); + break :blk try mtl.Library.fromSource(dev, base, mtl.CompileOptions.mlx()); + }; + defer lib.deinit(); + return attn.Attention.init(dev, lib); +} + +pub fn encodeMat( + sn: *linear_gpu.LinearGpu, + e: mtl.ComputeEncoder, + mat: core.sensenova_loop.mtp_weights.MtpMat, + x: projection.Ref, + y: projection.Ref, + rows: u32, + ldy: u32, + prompt: bool, + xs_opt: ?linear_gpu.Sums, +) !void { + return encodeMatSplit(sn, e, mat, x, y, rows, ldy, prompt, xs_opt, .{}); +} + +pub fn encodeMatSplit( + sn: *linear_gpu.LinearGpu, + e: mtl.ComputeEncoder, + mat: core.sensenova_loop.mtp_weights.MtpMat, + x: projection.Ref, + y: projection.Ref, + rows: u32, + ldy: u32, + prompt: bool, + xs_opt: ?linear_gpu.Sums, + splits: linear_gpu.OutSplits, +) !void { + switch (mat) { + .bf16 => |m| try sn.encodeBf16Split(e, m, lref(x), lref(y), rows, ldy, prompt, null, splits), + .awq => |m| try sn.encodeAwqSplit(e, m, lref(x), xs_opt, lref(y), rows, ldy, prompt, null, splits), + } +} + +pub fn populateHeld(ctx: *StreamCtx, pending: u32, depth: u32, vocab: usize) void { + var prev = pending; + for (0..depth) |d| { + const p: *const round_gpu.contract.Pick = @ptrCast(@alignCast(ctx.picks_buf.contents() + d * 16)); + const tok = if (p.nonfinite == 0 and p.token < vocab) p.token else prev; + ctx.held_tokens[d] = tok; + prev = tok; + } + ctx.held_count = depth; +} + +/// Copy `count` feature rows (selected or contiguous) into `gather` at `dst_row`. +pub fn stageFeaturesAt(m: anytype, feat: Features, rows: ?[]const u32, start_idx: usize, count: u32, dst_row: usize) !void { + const rb = m.hidden * 2; + const dst = m.buf(.gather).contents()[dst_row * rb ..][0 .. @as(usize, count) * rb]; + const src_ptr: [*]const u8 = if (!feat.host) (mtl.Buffer{ .id = @ptrFromInt(feat.buffer) }).contents() else @ptrFromInt(feat.buffer); + if (rows) |sel| { + for (0..count) |i| { + const r = sel[start_idx + i]; + if (r >= feat.rows) return error.BadMtpFeatures; + @memcpy(dst[i * rb ..][0..rb], src_ptr[feat.offset + @as(usize, r) * rb ..][0..rb]); + } + } else { + @memcpy(dst, src_ptr[feat.offset + start_idx * rb ..][0 .. @as(usize, count) * rb]); + } +} + +pub fn stageRawFeatures(m: anytype, feat: Features, rows: ?[]const u32, start_idx: usize, count: u32) !projection.Ref { + const rb = m.hidden * 2; + if (rows == null and !feat.host and feat.offset % 16 == 0 and feat.buffer != 0) { + return .{ .buffer = .{ .id = @ptrFromInt(feat.buffer) }, .offset = feat.offset + start_idx * rb }; + } + try stageFeaturesAt(m, feat, rows, start_idx, count, 0); + return m.ref(.gather); +} + +pub fn appendMtpBuffers(m: anytype, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + try m.weights.appendBuffers(a, list); + if (m.draft_head) |dh| { + try list.appendSlice(a, &.{ dh.w, dh.sb }); + if (dh.input_scale) |ib| try list.append(a, ib); + } + try list.appendSlice(a, &m.abs_scratch.buffers); + try list.appendSlice(a, &m.abs_binding.buffers); + for (m.chain_scratch, m.chain_binding) |s, b| { + try list.appendSlice(a, &s.buffers); + try list.appendSlice(a, &b.buffers); + } + try list.appendSlice(a, &m.bufs); + for (m.ctxs) |slot_opt| if (slot_opt) |sc| { + try list.appendSlice(a, &.{ sc.keys, sc.values, sc.picks_buf, sc.chain_out_buf }); + }; +} + +pub fn applyMtpResident(m: anytype, f: mtl.ResidencySet.Follow, joining: bool) void { + m.weights.applyResident(f, joining); + if (m.draft_head) |dh| { + mtl.resident.fields.one(dh.w, f, joining); + mtl.resident.fields.one(dh.sb, f, joining); + if (dh.input_scale) |ib| mtl.resident.fields.one(ib, f, joining); + } + for (m.abs_scratch.buffers) |b| mtl.resident.fields.one(b, f, joining); + for (m.abs_binding.buffers) |b| mtl.resident.fields.one(b, f, joining); + for (m.chain_scratch, m.chain_binding) |s, b| { + for (s.buffers) |sb| mtl.resident.fields.one(sb, f, joining); + for (b.buffers) |bb| mtl.resident.fields.one(bb, f, joining); + } + for (m.bufs) |b| mtl.resident.fields.one(b, f, joining); + for (m.ctxs) |slot_opt| if (slot_opt) |sc| { + for ([_]mtl.Buffer{ sc.keys, sc.values, sc.picks_buf, sc.chain_out_buf }) |b| mtl.resident.fields.one(b, f, joining); + }; +} + +/// Warm GEMM/splitK/attention pipelines before residency lock and time single-step `hold`. +pub fn warmup(m: anytype, io: std.Io) !void { + const ctx = &(m.ctxs[0] orelse return error.MissingMtpSlot); + ctx.reset(0); + ctx.in_use = true; + defer ctx.reset(0); + const prompt_rows: u32 = @min(m.abs_rows, @min(512, @as(u32, @intCast(m.capacity - 8)))); + @memset(m.buf(.gather).slice(u16, prompt_rows * m.hidden), 0x3c00); + const cache_view = m.cacheView(ctx); + for (0..3) |pass| { + ctx.begin = 0; + ctx.len = 0; + const rows: u32 = switch (pass) { + 0 => prompt_rows, + 1 => 2, + else => 1, + }; + const pos_dst = m.buf(.pos).slice(u32, rows); + const id_dst = m.buf(.ids).slice(u32, rows); + for (pos_dst, id_dst, 0..) |*p, *id, r| { + p.* = @intCast(r); + id.* = @intCast((r * 17 + 5) % m.vocab); + } + var plan = try attn.Plan.init(m.gpa, &.{.{ .parents = m.parents_storage[0..rows], .start = 0, .capacity = cache_view.capacity }}, m.geometry); + defer plan.deinit(); + try m.abs_scratch.upload(plan); + try m.abs_binding.upload(plan, &.{cache_view}); + const cb = m.model.queue.commandBuffer(); + const e = cb.compute(.serial); + var ended = false; + errdefer if (!ended) e.end(); + try m.encodeStep(e, &m.abs_scratch, &m.abs_binding, plan, cache_view, rows, m.ref(.gather), m.ref(.ids), m.ref(.pos), true, ctx, true, 0); + e.end(); + ended = true; + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("sensenova mtp warmup failure: {s}", .{msg}); + return error.GpuFailed; + } + ctx.len = rows; + } + var best: f64 = std.math.floatMax(f64); + const cpos_ptr: [*]u32 = @ptrCast(@alignCast(m.buf(.chain_pos).contents())); + for (0..8) |iter| { + cpos_ptr[0] = @intCast(ctx.len); + var plan = try attn.Plan.init(m.gpa, &.{.{ .parents = m.parents_storage[0..1], .start = @intCast(ctx.len), .capacity = cache_view.capacity }}, m.geometry); + defer plan.deinit(); + try m.chain_scratch[0].upload(plan); + try m.chain_binding[0].upload(plan, &.{cache_view}); + const t0 = std.Io.Clock.awake.now(io); + const cb = m.model.queue.commandBuffer(); + const e = cb.compute(.serial); + var ended = false; + errdefer if (!ended) e.end(); + try m.encodeStep(e, &m.chain_scratch[0], &m.chain_binding[0], plan, cache_view, 1, ctx.chainOutRef(0, m.hidden), .{ .buffer = ctx.picks_buf, .offset = 0 }, .{ .buffer = m.buf(.chain_pos), .offset = 0 }, false, ctx, true, 1); + e.end(); + ended = true; + cb.commit(); + cb.wait(); + const ns = t0.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds(); + if (iter >= 3) best = @min(best, @as(f64, @floatFromInt(ns)) / 1e6); + } + m.step_ms = best; + std.log.info("sensenova mtp: bits={d} depth={d} abs_rows={d} step_ms={d:.2} plain_guard={} slot_bytes={d}", .{ m.bits, m.depth, m.abs_rows, m.step_ms, m.plain_guard, m.slotBytes() }); +} + +test "mtp scratch batch cap and row sizing" { + try std.testing.expectEqual(@as(u32, 2048), batch_cap); + var cfg = std.mem.zeroes(Config); + cfg.hidden = 4096; + cfg.heads = 16; + cfg.kv_heads = 4; + cfg.head_dim = 256; + cfg.intermediate = 12288; + cfg.vocab = 248320; + const s128 = scratchSizes(cfg, 128); + const s2048 = scratchSizes(cfg, 2048); + try std.testing.expectEqual(s128[@backingInt(ScratchField.ids)] * 16, s2048[@backingInt(ScratchField.ids)]); + try std.testing.expectEqual(s128[@backingInt(ScratchField.planes)] * 16, s2048[@backingInt(ScratchField.planes)]); +} diff --git a/zig/src/families/sensenova_loop/mtp_weights.zig b/zig/src/families/sensenova_loop/mtp_weights.zig new file mode 100644 index 00000000000..4e656bad5f8 --- /dev/null +++ b/zig/src/families/sensenova_loop/mtp_weights.zig @@ -0,0 +1,327 @@ +//! Official SenseNova-Loop MTP safetensors weight loader (`mtp.safetensors` beside checkpoint). +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const cp = core.checkpoint_metal; +const awq = @import("awq.zig"); +const linear_gpu = @import("linear_gpu.zig"); + +pub const file = "mtp.safetensors"; + +pub const MtpMat = union(enum) { + bf16: linear_gpu.Bf16Matrix, + awq: linear_gpu.AwqMatrix, + + pub fn deinit(m: *MtpMat) void { + switch (m.*) { + .awq => |*a| a.deinit(), + .bf16 => {}, + } + } +}; + +pub const Weights = struct { + allocator: std.mem.Allocator, + ck: ?cp.Checkpoint = null, + owned: std.ArrayList(mtl.Buffer) = .empty, + bits: u32 = 16, + norm_e: cp.Tensor, + norm_h: cp.Tensor, + input_norm: cp.Tensor, + post_norm: cp.Tensor, + q_norm: cp.Tensor, + k_norm: cp.Tensor, + norm: cp.Tensor, + fc: MtpMat, + qkv: MtpMat, + o: MtpMat, + gate_up: MtpMat, + down: MtpMat, + + /// True when `{dir}/mtp.safetensors` exists and can be opened. + pub fn hasFile(io: std.Io, dir: []const u8) bool { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = std.fmt.bufPrint(&buf, "{s}/{s}", .{ dir, file }) catch return false; + std.Io.Dir.cwd().access(io, path, .{}) catch return false; + return true; + } + + pub fn load( + gpa: std.mem.Allocator, + io: std.Io, + device: mtl.Device, + queue: mtl.Queue, + dir: []const u8, + hidden: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + intermediate: usize, + ) !Weights { + _ = io; + const bits = try @import("sys").environment.read(u32, "TF_MTP_BITS", 4); + if (bits != 4 and bits != 16) return error.BadMtpBits; + const path = try std.fs.path.joinZ(gpa, &.{ dir, file }); + defer gpa.free(path); + var ck = cp.Checkpoint.init(gpa); + var keep_ck = true; + errdefer if (keep_ck) ck.deinit(); + try ck.addFile(device, path, ""); + var temp_owned: std.ArrayList(mtl.Buffer) = .empty; + var keep_temp = true; + errdefer if (keep_temp) { + for (temp_owned.items) |b| b.deinit(); + temp_owned.deinit(gpa); + }; + const m = try resolvePrefix(&ck); + const p = if (std.mem.eql(u8, m, "mtp.")) "mtp.layers.0." else "language_model.mtp.layers.0."; + const q_rows = 2 * heads * head_dim; + const kv_rows = kv_heads * head_dim; + const o_cols = heads * head_dim; + var norm_e = try normTensor(gpa, &ck, m, "pre_fc_norm_embedding.weight", hidden); + var norm_h = try normTensor(gpa, &ck, m, "pre_fc_norm_hidden.weight", hidden); + var norm = try normTensor(gpa, &ck, m, "norm.weight", hidden); + var input_norm = try normTensor(gpa, &ck, p, "input_layernorm.weight", hidden); + var post_norm = try normTensor(gpa, &ck, p, "post_attention_layernorm.weight", hidden); + var q_norm = try normTensor(gpa, &ck, p, "self_attn.q_norm.weight", head_dim); + var k_norm = try normTensor(gpa, &ck, p, "self_attn.k_norm.weight", head_dim); + const bf_fc = try singleMatrix(gpa, device, &ck, &temp_owned, m, "fc.weight", hidden, 2 * hidden); + const bf_qkv = try stackMatrices(gpa, device, &ck, &temp_owned, p, &.{ + .{ .suffix = "self_attn.q_proj.weight", .n = q_rows }, + .{ .suffix = "self_attn.k_proj.weight", .n = kv_rows }, + .{ .suffix = "self_attn.v_proj.weight", .n = kv_rows }, + }, hidden); + const bf_o = try singleMatrix(gpa, device, &ck, &temp_owned, p, "self_attn.o_proj.weight", hidden, o_cols); + const bf_gu = try stackMatrices(gpa, device, &ck, &temp_owned, p, &.{ + .{ .suffix = "mlp.gate_proj.weight", .n = intermediate }, + .{ .suffix = "mlp.up_proj.weight", .n = intermediate }, + }, hidden); + const bf_down = try singleMatrix(gpa, device, &ck, &temp_owned, p, "mlp.down_proj.weight", hidden, intermediate); + + if (bits == 4) { + var owned: std.ArrayList(mtl.Buffer) = .empty; + errdefer { + for (owned.items) |b| b.deinit(); + owned.deinit(gpa); + } + try packNorms(gpa, device, &owned, .{ &norm_e, &norm_h, &norm, &input_norm, &post_norm, &q_norm, &k_norm }); + var sn_gpu = linear_gpu.LinearGpu.init(gpa, device); + defer sn_gpu.deinit(); + const src = [5]linear_gpu.Bf16Matrix{ bf_fc, bf_qkv, bf_o, bf_gu, bf_down }; + var q_mats: [5]?linear_gpu.AwqMatrix = @splat(null); + errdefer for (&q_mats) |*qm| if (qm.*) |*am| am.deinit(); + for (src, &q_mats) |mat, *dst| dst.* = try quantizeMat(&sn_gpu, queue, mat); + for (temp_owned.items) |b| b.deinit(); + temp_owned.deinit(gpa); + keep_temp = false; + ck.deinit(); + keep_ck = false; + return .{ + .allocator = gpa, + .ck = null, + .owned = owned, + .bits = 4, + .norm_e = norm_e, + .norm_h = norm_h, + .norm = norm, + .input_norm = input_norm, + .post_norm = post_norm, + .q_norm = q_norm, + .k_norm = k_norm, + .fc = .{ .awq = q_mats[0].? }, + .qkv = .{ .awq = q_mats[1].? }, + .o = .{ .awq = q_mats[2].? }, + .gate_up = .{ .awq = q_mats[3].? }, + .down = .{ .awq = q_mats[4].? }, + }; + } + keep_ck = false; + keep_temp = false; + return .{ + .allocator = gpa, + .ck = ck, + .owned = temp_owned, + .bits = 16, + .norm_e = norm_e, + .norm_h = norm_h, + .norm = norm, + .input_norm = input_norm, + .post_norm = post_norm, + .q_norm = q_norm, + .k_norm = k_norm, + .fc = .{ .bf16 = bf_fc }, + .qkv = .{ .bf16 = bf_qkv }, + .o = .{ .bf16 = bf_o }, + .gate_up = .{ .bf16 = bf_gu }, + .down = .{ .bf16 = bf_down }, + }; + } + + pub fn appendBuffers(w: *const Weights, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + if (w.ck) |*ck| for (ck.shards.items) |s| try list.append(a, s.buffer); + try list.appendSlice(a, w.owned.items); + for ([_]MtpMat{ w.fc, w.qkv, w.o, w.gate_up, w.down }) |mat| switch (mat) { + .awq => |awq_m| { + try list.appendSlice(a, &.{ awq_m.w, awq_m.sb }); + if (awq_m.input_scale) |ib| try list.append(a, ib); + }, + .bf16 => {}, + }; + } + + pub fn applyResident(w: *const Weights, f: mtl.ResidencySet.Follow, joining: bool) void { + if (w.ck) |*ck| for (ck.shards.items) |s| mtl.resident.fields.one(s.buffer, f, joining); + for (w.owned.items) |b| mtl.resident.fields.one(b, f, joining); + for ([_]MtpMat{ w.fc, w.qkv, w.o, w.gate_up, w.down }) |mat| switch (mat) { + .awq => |awq_m| { + mtl.resident.fields.one(awq_m.w, f, joining); + mtl.resident.fields.one(awq_m.sb, f, joining); + if (awq_m.input_scale) |ib| mtl.resident.fields.one(ib, f, joining); + }, + .bf16 => {}, + }; + } + + pub fn deinit(w: *Weights) void { + for ([_]*MtpMat{ &w.fc, &w.qkv, &w.o, &w.gate_up, &w.down }) |mat| mat.deinit(); + for (w.owned.items) |b| b.deinit(); + w.owned.deinit(w.allocator); + if (w.ck) |*ck| ck.deinit(); + } +}; + +fn bf16ToF32(b: u16) f32 { + return @bitCast(@as(u32, b) << 16); +} + +fn roundEven(x: f32) f32 { + if (!std.math.isFinite(x)) return 0.0; + const clamped = std.math.clamp(x, -1.0e9, 1.0e9); + const f = @floor(clamped); + const d = clamped - f; + if (d > 0.5) return f + 1.0; + if (d < 0.5) return f; + return if (@mod(@as(i64, @intFromFloat(f)), 2) != 0) f + 1.0 else f; +} + +pub fn quantizeMat(sn: *linear_gpu.LinearGpu, queue: mtl.Queue, mat: linear_gpu.Bf16Matrix) !linear_gpu.AwqMatrix { + _ = queue; + if (mat.k == 0 or mat.k % 128 != 0) return error.BadMtpTensor; + const raw = mat.buf.contents()[mat.off..][0 .. @as(usize, mat.n) * mat.k * 2]; + const kg = mat.k / 128; + const layout: awq.Layout = if (sn.tensor_units) .m5_tile else .m3_row; + const w = try sn.allocator.alloc(u32, awq.weightWords(mat.n, mat.k, layout)); + defer sn.allocator.free(w); + @memset(w, 0); + const sb = try sn.allocator.alloc(awq.Float2, awq.metaCount(mat.n, mat.k)); + defer sn.allocator.free(sb); + for (0..mat.n) |j| for (0..kg) |gi| { + const base = (j * mat.k + gi * 128) * 2; + var min_v: f32 = 0.0; + var max_v: f32 = 0.0; + for (0..128) |c_idx| { + const v = bf16ToF32(std.mem.readInt(u16, raw[base + c_idx * 2 ..][0..2], .little)); + min_v = @min(min_v, v); + max_v = @max(max_v, v); + } + const scale = (max_v - min_v) / 15.0; + const zp: u32 = if (scale != 0.0) @intFromFloat(std.math.clamp(roundEven(-min_v / scale), 0.0, 15.0)) else 0; + const eff_scale: f32 = if (scale != 0.0) scale else 0.0; + const bias: f32 = if (eff_scale != 0.0) -@as(f32, @floatFromInt(zp)) * eff_scale else min_v; + sb[if (layout == .m5_tile) gi * mat.n + j else j * kg + gi] = .{ .scale = eff_scale, .bias = bias }; + for (0..16) |w16| { + var word: u32 = 0; + for (0..8) |ni| { + const v = bf16ToF32(std.mem.readInt(u16, raw[base + (w16 * 8 + ni) * 2 ..][0..2], .little)); + const q_val: u32 = if (eff_scale != 0.0) @intFromFloat(std.math.clamp(roundEven((v - bias) / eff_scale), 0.0, 15.0)) else 0; + word |= q_val << @intCast(ni * 4); + } + const w_idx = if (layout == .m5_tile) (((j / 32) * kg + gi) * 32 + (j % 32)) * 16 + w16 else j * (mat.k / 8) + gi * 16 + w16; + w[w_idx] = word; + } + }; + return linear_gpu.LinearGpu.prepareAwqFromPacked(sn, .{ .n = mat.n, .k = mat.k, .layout = layout, .w = w, .sb = sb, .input_scale = null }); +} + +fn packNorms(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), norms: [7]*cp.Tensor) !void { + var total: usize = 0; + for (norms) |t| total += std.mem.alignForward(usize, t.bytes, 16); + const buf = try ownBuffer(a, device, owned, total); + var off: usize = 0; + for (norms) |t| { + @memcpy(buf.contents()[off..][0..t.bytes], t.buffer.contents()[t.offset..][0..t.bytes]); + t.buffer = buf; + t.offset = off; + off += std.mem.alignForward(usize, t.bytes, 16); + } +} + +fn resolvePrefix(ck: *const cp.Checkpoint) ![]const u8 { + if (ck.has("mtp.fc.weight")) return "mtp."; + if (ck.has("language_model.mtp.fc.weight")) return "language_model.mtp."; + return error.MissingMtpWeights; +} + +fn checked(t: cp.Tensor, shape: []const usize) !cp.Tensor { + if (t.dtype != .bf16 or t.rank != shape.len or !std.mem.eql(usize, t.shape[0..t.rank], shape)) return error.BadMtpTensor; + return t; +} + +fn normTensor(a: std.mem.Allocator, ck: *const cp.Checkpoint, prefix: []const u8, suffix: []const u8, n: usize) !cp.Tensor { + const name = try std.mem.concat(a, u8, &.{ prefix, suffix }); + defer a.free(name); + return checked(try ck.get(name), &.{n}); +} + +fn ownBuffer(a: std.mem.Allocator, device: mtl.Device, owned: *std.ArrayList(mtl.Buffer), bytes: usize) !mtl.Buffer { + const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + const b = try device.buffer(bytes, opts); + owned.append(a, b) catch |err| { + b.deinit(); + return err; + }; + return b; +} + +fn singleMatrix( + a: std.mem.Allocator, + device: mtl.Device, + ck: *const cp.Checkpoint, + owned: *std.ArrayList(mtl.Buffer), + prefix: []const u8, + suffix: []const u8, + n: usize, + k: usize, +) !linear_gpu.Bf16Matrix { + const name = try std.mem.concat(a, u8, &.{ prefix, suffix }); + defer a.free(name); + const t = try checked(try ck.get(name), &.{ n, k }); + if (t.offset % 16 == 0) return linear_gpu.LinearGpu.prepareBf16(t.buffer, t.offset, @intCast(n), @intCast(k)); + const buf = try ownBuffer(a, device, owned, n * k * 2); + @memcpy(buf.contents()[0 .. n * k * 2], t.buffer.contents()[t.offset..][0 .. n * k * 2]); + return linear_gpu.LinearGpu.prepareBf16(buf, 0, @intCast(n), @intCast(k)); +} + +fn stackMatrices( + a: std.mem.Allocator, + device: mtl.Device, + ck: *const cp.Checkpoint, + owned: *std.ArrayList(mtl.Buffer), + prefix: []const u8, + parts: []const struct { suffix: []const u8, n: usize }, + k: usize, +) !linear_gpu.Bf16Matrix { + var total_n: usize = 0; + for (parts) |part| total_n += part.n; + const buf = try ownBuffer(a, device, owned, total_n * k * 2); + var dst_bytes: usize = 0; + for (parts) |part| { + const name = try std.mem.concat(a, u8, &.{ prefix, part.suffix }); + defer a.free(name); + const t = try checked(try ck.get(name), &.{ part.n, k }); + const row_bytes = part.n * k * 2; + @memcpy(buf.contents()[dst_bytes..][0..row_bytes], t.buffer.contents()[t.offset..][0..row_bytes]); + dst_bytes += row_bytes; + } + return linear_gpu.LinearGpu.prepareBf16(buf, 0, @intCast(total_n), @intCast(k)); +} diff --git a/zig/src/families/sensenova_loop/sensenova_loop.zig b/zig/src/families/sensenova_loop/sensenova_loop.zig index e8b1873fda8..3833b7461b5 100644 --- a/zig/src/families/sensenova_loop/sensenova_loop.zig +++ b/zig/src/families/sensenova_loop/sensenova_loop.zig @@ -4,6 +4,7 @@ pub const mhc_ref = @import("mhc_ref.zig"); pub const mhc_metal = @import("mhc_metal.zig"); pub const awq = @import("awq.zig"); pub const linear_gpu = @import("linear_gpu.zig"); +pub const mtp_weights = @import("mtp_weights.zig"); test { _ = config; @@ -11,4 +12,5 @@ test { _ = mhc_metal; _ = awq; _ = linear_gpu; + _ = mtp_weights; } diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 80016bf995e..336b24fad4a 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -334,7 +334,7 @@ fn openQwen27(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[ var why: []const u8 = ""; const drafter = if (o.drafts) o.drafter else null; const learn: ?@import("qwen27_disk.zig").Learn = if (o.learn_conversations) if (o.learn) |root| .{ .root = root, .dir = o.dir, .drafter = drafter, .cap = gibBytes(o.learn_gib), .floor = gibBytes(o.learn_min_free_gib), .daily = gibBytes(o.learn_daily_gib), .spill = o.spill, .slots = spill.slots(o) } else null else null; - const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .mtp_drafts = if (o.drafts) o.mtp_drafts else null, .mtp_confidence = o.mtp_confidence, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .learn = learn, .vision = o.vision, .rope_yarn = if (sn) o.rope_yarn else null }, a, &why) catch |err| { + const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafts = if (sn) o.drafts else true, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .mtp_drafts = if (o.drafts) o.mtp_drafts else null, .mtp_confidence = o.mtp_confidence, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .learn = learn, .vision = o.vision, .rope_yarn = if (sn) o.rope_yarn else null }, a, &why) catch |err| { problem.* = if (why.len > 0) why else try std.fmt.allocPrint(a, "the native {s} engine cannot load {s} ({s})", .{ if (sn) "SenseNova" else "Qwen (27B class)", o.dir, @errorName(err) }); return null; }; diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index 9a56ebcea09..db495dc6717 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -97,6 +97,8 @@ pub const Metal = struct { slot_resume: bool = true, // TF_QWEN27_SLOT_RESUME: a later prompt resumes where slot 0 stands (0: off) give_back: [max_streams]bool = @splat(false), // a free slot's grown K/V and ring wait to go back (slots.giveBack) draft_block: @import("qwen27_draft_block.zig").Lone = .{}, // TF_Q27_DFLASH_ADAPTIVE_BLOCK: a lone stream's block rows + held_taps: ?mtl.Buffer = null, + features_state: @import("sensenova_features.zig").State = .{}, pub fn init(gpa: std.mem.Allocator, runner: *q.decode_round.Runner, draft: ?*Draft) !*Metal { if (runner.slots == 0 or runner.slots > max_streams) return error.TargetBinding; @@ -147,6 +149,7 @@ pub const Metal = struct { q.residency.setBack(b, null); b.standing.deinit(b.gpa); if (b.rewind) |x| x.deinit(); + if (b.held_taps) |x| x.deinit(); b.dropRound(); b.dropTree(); b.freeContexts(); @@ -167,12 +170,13 @@ pub const Metal = struct { pub const refill = slots.refill; pub fn backend(b: *Metal) be.Backend { - return .{ .ptr = b, .defer_lone_draft = b.runner.slots == 1, .first_before_draft = b.tensor_units, .penalties = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = slots.prefillStep, .cancel_prefill = slots.cancelPrefill, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draft_fns.draftFn, .prepare_features = features.prepare, .features = features.rows, .draft_capacity = draft_fns.capacityFn, .probabilities = draft_fns.probabilitiesFn, .tree = draft_fns.treeFn, .release = releaseFn, .reports_fill = true } }; + const feat = @import("sensenova_features.zig"); + return .{ .ptr = b, .defer_lone_draft = b.runner.slots == 1, .first_before_draft = b.tensor_units, .penalties = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = slots.prefillStep, .cancel_prefill = slots.cancelPrefill, .prefill_features = feat.prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draft_fns.draftFn, .prepare_features = features.prepare, .features = features.rows, .draft_capacity = draft_fns.capacityFn, .probabilities = draft_fns.probabilitiesFn, .tree = draft_fns.treeFn, .release = releaseFn, .reports_fill = true } }; } /// What the round loop reads at setup: up to TF_Q27_DRAFT_SLOTS streams draft trees; every stream verifies copies. pub fn facts(b: *const Metal) lanes.Model { - const drafting = b.draft != null or b.external; + const drafting = b.draft != null or b.features_state.enabled or b.external; const shared = b.runner.slots > 1; // Context copies remain opt-in until their served cost is qualified. const lone_copies = b.copies; @@ -508,6 +512,7 @@ pub const Metal = struct { defer r.tail = null; const before = r.gpu_seconds; if (plain) try r.advance(&b.round.?, .all) else try r.verifyHead(&b.round.?, .all); + try @import("sensenova_features.zig").recordVerify(b, windows, inputs[0..windows.len]); for (windows) |w| slots.charge(b, w.stream, before); // a shared round counts whole in each reply b.advanced = plain; b.rows = total; @@ -583,11 +588,14 @@ pub const Metal = struct { if (b.round == null or windows.len != b.count) return error.NothingToKeep; for (windows, paths, b.windows[0..b.count]) |w, path, slot| if (path.len == 0 or path[0] != 0 or b.slotOf(w.stream) != slot) return error.NothingToKeep; try b.keepPaths(paths); + @import("sensenova_features.zig").recordKeep(b, windows, paths); } fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { - slots.endFill(self(ptr), s); - self(ptr).unbind(s); + const b = self(ptr); + if (b.slotOf(s)) |slot| b.features_state.clearSlot(slot); + slots.endFill(b, s); + b.unbind(s); } }; diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 8e475e68682..de34f027439 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -30,11 +30,13 @@ pub const Options = struct { context: u32, streams: u32, // --parallel: slots at most, fewer when their caches do not fit streams_fixed: bool = false, // --parallel named a number: every slot fits, or the server refuses + drafts: bool = true, drafter: ?[]const u8 = null, drafter_name: ?[]const u8 = null, drafter_bits: u8 = 0, mtp_drafts: ?u32 = null, // --mtp-drafts N: the MTP head beside the checkpoint drafts every stream's chains (0: off) mtp_confidence: ?f64 = null, // --mtp-confidence: a chain stops where its cumulative chance falls below it + mtp_dir: ?[]const u8 = null, // SenseNova-Loop: the checkpoint directory its own mtp.safetensors is read from cache_gib: ?f64 = null, cache_over_cap: bool = false, decode_share: ?f64 = null, // --decode-share: the reply's share of a fill step's wall time beside live decoders @@ -52,6 +54,7 @@ pub const Host = struct { runner: q.decode_round.Runner, trace: ?tf.gpu_profile.Trace = null, // TF_Q27_PROFILE: rounds' class GPU times to the log, gpu_seconds in replies draft: ?*lb.Draft = null, + sn_mtp: ?*q.sn_mtp.Mtp = null, // SenseNova-Loop's own MTP head (mtp.safetensors), the core's drafter back: *lb.Metal, mtp: ?*Mtp = null, // --mtp-drafts: the MTP head, the core's drafter in front of `back` wrap: ?lanes.drafted.Drafted = null, @@ -114,7 +117,7 @@ pub const Host = struct { }; /// The reply-end snapshot, retaining a matching pre-reply cache state too when both fit. -fn keepEnd(store: *pc.Store, gpa: Allocator, s: *lanes.Stream, stands: u32) void { +pub fn keepEnd(store: *pc.Store, gpa: Allocator, s: *lanes.Stream, stands: u32) void { const prompt: u32 = @intCast(s.prompt_len); const tokens = s.context.items; if (tokens.len == prompt or stands + 1 < tokens.len or stands > tokens.len) return; @@ -208,7 +211,7 @@ fn shareRoom(h: *const Host, why: *[]const u8) !u64 { const cap = reserve.cap; /// Whether a new slot's `bytes` fit in `free`, once kept prompt states (never the one `restoring`) give theirs back. -fn takeRoom(cache: ?*pc.Store, free: usize, bytes: usize, restoring: ?pc.Saved, prompt: []const u32) bool { +pub fn takeRoom(cache: ?*pc.Store, free: usize, bytes: usize, restoring: ?pc.Saved, prompt: []const u32) bool { const held = if (cache) |c| c.held else 0; const ok = if (cache) |c| c.giveBack(restoring, prompt, Left{ .room = free, .store = c, .held = held, .bytes = bytes }) else free >= bytes; const freed = held - (if (cache) |c| c.held else 0); @@ -228,55 +231,9 @@ const Left = struct { } }; -/// Kept states of a fake family whose bytes grow as the 27B's K/V rows (64 KiB a token); `saved` is never read. -const FakeStates = struct { - live: usize = 0, - fn bytes(_: *anyopaque, at: u32) u64 { - return @as(u64, at) << 16; - } - fn save(ptr: *anyopaque, _: ?*anyopaque, at: u32) anyerror!pc.Saved { - const f: *FakeStates = @ptrCast(@alignCast(ptr)); - f.live += 1; - return @ptrFromInt(@as(usize, at) << 4); - } - fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void {} - fn drop(ptr: *anyopaque, _: pc.Saved) void { - const f: *FakeStates = @ptrCast(@alignCast(ptr)); - f.live -= 1; - } -}; - -test "--prompt-cache-gib 40: a later 192k-token slot takes its room back from kept states, never the one it restores" { - const gpa = std.testing.allocator; - const g: u64 = 1 << 30; - var fake: FakeStates = .{}; - var store = pc.Store.init(gpa, .{ .ptr = &fake, .vtable = &.{ .bytes = FakeStates.bytes, .save = FakeStates.save, .restore = FakeStates.restore, .drop = FakeStates.drop } }, .{}, 40 * g); - defer store.deinit(); - const tokens = try gpa.alloc(u32, 200_000); - defer gpa.free(tokens); - for ([_]u32{ 100_000, 150_000, 190_000 }, 0..) |at, k| { // three conversations' histories: 6.1, 9.2 and 11.6 GiB - for (tokens, 0..) |*t, i| t.* = @intCast(k * 1_000_000 + i); - try std.testing.expect(store.keep(tokens[0 .. at + 1], at, null, &.{}, &.{})); - } - const restoring = store.entries.items[2].saved; // the newest conversation's next turn resumes its state - const slot: u64 = 12_900_000_000; // a --context 196608 slot's K/V rows, taps ring and scratch - try std.testing.expect(!takeRoom(null, 4 * g, slot, null, tokens)); // without a cache to give back: LaneMemory - try std.testing.expect(takeRoom(&store, 4 * g, slot, restoring, tokens)); // 4 GiB free + 6.1 + 9.2 freed - try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); - try std.testing.expect(store.entries.items[0].saved == restoring); - try std.testing.expect(!takeRoom(&store, 0, 2 * slot, restoring, tokens)); // its own state never goes - try std.testing.expectEqual(@as(usize, 1), fake.live); -} - -test "a reply's end keeps its prompt's born: newest conversations precede redundant history under pressure" { - var fake: FakeStates = .{}; - const snapshots: pc.Snapshots = .{ .ptr = &fake, .vtable = &.{ .bytes = FakeStates.bytes, .save = FakeStates.save, .restore = FakeStates.restore, .drop = FakeStates.drop } }; - try @import("qwen27_reply_cache_test.zig").replyBorn(keepEnd, snapshots, &fake.live); -} - /// Memory the slots past the ready ones take on first use: their K/V rows and taps rings. fn laterBytes(h: *const Host) u64 { - const ring_bytes: usize = if (h.draft) |d| @as(usize, d.model.ring().window) * d.model.ring().stride else 0; + const ring_bytes: usize = if (h.draft) |d| @as(usize, d.model.ring().window) * d.model.ring().stride else if (h.sn_mtp) |m| m.slotBytes() else 0; return (h.runner.slots - h.runner.ready) * (h.runner.slotBytes() + ring_bytes) + h.runner.gdn.missingBeforeBytes(); } @@ -304,6 +261,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, o: Options, a: Allocato return err; }; var with = o; // the tower before the slots: their room and the cache's budget count it as taken + with.mtp_dir = dir; if (o.vision) |v| with.images = try images.open(gpa, io, model, dir, v, a, why); errdefer if (with.images) |v| v.deinit(); const h = try attach(gpa, io, model, null, with, a, why); @@ -326,7 +284,8 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q why.* = policy.problem(err) orelse why.*; return err; }; - _ = policy.copyPolicy(units, window, if (platform.c.getenv("TF_QWEN27_COPIES")) |v| std.mem.span(v) else null) catch |err| { + const copies_value = if (platform.c.getenv("TF_QWEN27_COPIES")) |v| std.mem.span(v) else null; + _ = policy.copyPolicy(units, window, copies_value) catch |err| { why.* = policy.problem(err) orelse why.*; return err; }; @@ -348,12 +307,21 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q }; var draft_owned = owns_draft; errdefer if (draft_owned) draft_model.?.deinit(); + var sn_w = if (o.drafts and drafter == null and o.drafter == null and (o.mtp_drafts orelse 0) == 0) blk: { + if (o.mtp_dir) |mdir| if (q.sn_mtp.Mtp.available(io, mdir, model.config)) { + break :blk try q.sn_mtp.Mtp.loadWeights(gpa, io, model, mdir); + }; + break :blk null; + } else null; + errdefer if (sn_w) |*mw| mw.deinit(); + const sn_on = sn_w != null; const memory = q.prompt_memory; const mtp_on = model.weights.mtp != null and (o.mtp_drafts orelse 0) > 0; const shared = try q.simd_attention.sharedPrefix(model.device.tensorUnits()); // the MTP head's keys and values: one more attention layer a slot, beside the drafter's ring when there is one const head_kv: usize = if (mtp_on) @as(usize, capacity + window) * model.config.kvDim() * 2 * 2 else 0; - var fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, head_kv + if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, if (draft_model) |d| d.graph.config.tap_count else q.taps.layers.len, model.frame.capacity, room(model)); + const sn_ring: usize = if (sn_on) q.sn_mtp.Mtp.kvSlotBytes(model.config, capacity + window) else 0; // in a ring's place + var fit_prompt = reserve.fit(model.config, capacity, window, o.streams, shared, head_kv + if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else sn_ring, if (draft_model) |d| d.graph.config.tap_count else if (sn_on) 1 else q.taps.layers.len, model.frame.capacity, room(model)); if (draft_model) |d| fit_prompt.tap_row = memory.tapRowBytes(model.config.hidden, d.graph.config.tap_count, d.graph.config.variant == .v1); const rows = try reserve.rows(fit_prompt, model.device.generation(), window); const slots = fit_prompt.streams(rows, o.streams_fixed) catch |err| { @@ -373,6 +341,9 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.model = model; h.owns_model = false; h.draft = null; + h.mtp = null; + h.sn_mtp = null; + h.wrap = null; h.cache = null; h.resident = null; h.disk_stage = null; @@ -393,6 +364,11 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q if (draft_model) |d| h.draft = try lb.Draft.attach(gpa, &h.runner, d, owns_draft); draft_owned = false; errdefer if (h.draft) |d| d.deinit(); + if (sn_w) |mw| { + h.sn_mtp = try q.sn_mtp.Mtp.initFromWeights(gpa, model, mw, slots, capacity + window); + sn_w = null; + } + errdefer if (h.sn_mtp) |m| m.deinit(); h.back = try lb.Metal.init(gpa, &h.runner, h.draft); errdefer h.back.deinit(); h.back.serial_copy_match = policy.serialCopyMatch(units, window, lanes_value); @@ -405,9 +381,13 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q holdResident(h, io) catch |err| std.log.warn("qwen27: no residency set ({s}); the first request after an idle second re-wires the weights", .{@errorName(err)}); residency.end(); errdefer q.residency.drop(h); // decided before cache sizing and the worker starts - if (h.draft != null or mtp_on) try h.back.measure(io); - h.mtp = null; - h.wrap = null; + if ((h.sn_mtp != null or !o.drafts) and copies_value == null) h.back.copies = false; + if (h.sn_mtp) |m| { + try m.warmup(io); + h.wrap = try lanes.drafted.Drafted.init(gpa, h.back.backend(), @import("sensenova_mtp_drafter.zig").drafter(m)); + } + errdefer if (h.wrap) |*w| w.deinit(); + if (h.draft != null or mtp_on or h.sn_mtp != null) try h.back.measure(io); if (mtp_on) { const x = try Mtp.init(gpa, h.back, .{ .cap = o.mtp_drafts, .floor = o.mtp_confidence }); h.mtp = x; @@ -415,7 +395,6 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q std.log.info("qwen27: the MTP head drafts chains of {d} at most, a step {d:.2} ms", .{ x.depth(), x.step_ms }); } errdefer if (h.mtp) |x| x.deinit(); - errdefer if (h.wrap) |*w| w.deinit(); h.cfg = try lanes.Config.init(gpa, if (h.wrap) |*w| w.facts(h.back.facts()) else h.back.facts(), window, h.back.nodes); errdefer h.cfg.deinit(gpa); h.clock = .{ .io = io }; @@ -431,7 +410,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q // a reply that ends soon goes first beside a long prompt; a share someone set stays as they set it if (o.decode_share == null and std.c.getenv("TENSORFOLD_PREFILL_SHARE") == null) h.host.srpt = .withDefault(true); var loop_text: [160]u8 = undefined; - std.log.info("qwen27: {s}", .{try policy.describe(&loop_text, serial, window, h.draft != null, h.back.copies)}); + std.log.info("qwen27: {s}", .{try policy.describe(&loop_text, serial, window, h.draft != null or h.sn_mtp != null, h.back.copies)}); const ane = tf.startup_receipt.span(.optional_ane); if (model.share_pending) { const before = cache_fit.footprint(); @@ -453,7 +432,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q if (h.trace) |*t| t.enabled = true; // serving rounds count from here: measure() timed whole, unsplit buffers try h.host.start(); tf.startup_receipt.span(.model_ready).end(); - std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else 0, .drafter = if (h.draft) |d| d.model.graph.config.kind() else "DFlash2", .images = o.images != null }}); + std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else if (h.sn_mtp != null) slots else 0, .drafter = if (h.draft) |d| d.model.graph.config.kind() else "DFlash2", .images = o.images != null }}); return h; } test "qwen27 startup: draft stream count, singular text and optional suffixes" { @@ -554,6 +533,7 @@ pub fn close(ptr: *anyopaque) void { if (h.mtp) |x| x.deinit(); h.back.deinit(); if (h.draft) |d| d.deinit(); + if (h.sn_mtp) |m| m.deinit(); if (h.trace) |*t| t.reportRest(); h.runner.deinit(); if (h.vision) |v| v.deinit(); @@ -571,30 +551,5 @@ test { _ = @import("qwen27_draft_block.zig"); _ = @import("qwen27_share_fit.zig"); _ = @import("qwen27_startup_line.zig"); -} - -test "Qwen27 interior state uses a guaranteed cold request cut" { - const gpa = std.testing.allocator; - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const a = arena.allocator(); - const tokens = try a.alloc(u32, 128 * 1024 + 64); - @memset(tokens, 7); - var fake: FakeStates = .{}; - var store = pc.Store.init(gpa, .{ .ptr = &fake, .vtable = &.{ .bytes = FakeStates.bytes, .save = FakeStates.save, .restore = FakeStates.restore, .drop = FakeStates.drop } }, cacheRules(2048), 32 << 30); - defer store.deinit(); - var starts: std.ArrayList(u32) = .empty; - var at: u32 = 2048; - while (at < tokens.len) : (at += 2048) try starts.append(a, at); - const p = try store.beginUser(a, tokens, @intCast(tokens.len - 8), 16, @intCast(tokens.len - 8), &.{}, starts.items, null, &.{}); - try std.testing.expectEqualSlices(u32, &.{ 16, 129024, @intCast(tokens.len - 8) }, p.marks); - for (p.marks) |m| try std.testing.expect(store.keep(tokens, m, null, starts.items, &.{})); - tokens[tokens.len - 512] += 1; - const followup = try store.beginUser(a, tokens, @intCast(tokens.len - 8), 16, @intCast(tokens.len - 8), &.{}, starts.items, null, &.{}); - try std.testing.expectEqual(@as(u32, 129024), followup.from); - try std.testing.expect(store.held <= store.budget); -} - -test "qwen27 reply cache: warm work preserves both client histories within rounded budgets" { - try @import("qwen27_reply_cache_test.zig").exercise(keepEnd, slot_state.opening); + _ = @import("qwen27_served_test.zig"); } diff --git a/zig/src/native/qwen27_served_test.zig b/zig/src/native/qwen27_served_test.zig new file mode 100644 index 00000000000..78416f0559f --- /dev/null +++ b/zig/src/native/qwen27_served_test.zig @@ -0,0 +1,124 @@ +//! Prompt-cache, startup wording, and reply-cache unit tests extracted from qwen27_served.zig. +const std = @import("std"); +const platform = @import("sys"); +const api = @import("engine_api"); +const tf = @import("tensorfold"); +const lanes = tf.lanes; +const pc = api.prompt_cache; +const lb = @import("qwen27_lanes.zig"); +const served = @import("qwen27_served.zig"); +const startup = @import("qwen27_startup.zig"); +const slot_state = @import("qwen27_slots.zig"); + +const FakeStates = struct { + live: usize = 0, + fn bytes(_: *anyopaque, at: u32) u64 { + return @as(u64, at) << 16; + } + fn save(ptr: *anyopaque, _: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f: *FakeStates = @ptrCast(@alignCast(ptr)); + f.live += 1; + return @ptrFromInt(@as(usize, at) << 4); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void {} + fn drop(ptr: *anyopaque, _: pc.Saved) void { + const f: *FakeStates = @ptrCast(@alignCast(ptr)); + f.live -= 1; + } +}; + +test "--prompt-cache-gib 40: a later 192k-token slot takes its room back from kept states, never the one it restores" { + const gpa = std.testing.allocator; + const g: u64 = 1 << 30; + var fake: FakeStates = .{}; + var store = pc.Store.init(gpa, .{ .ptr = &fake, .vtable = &.{ .bytes = FakeStates.bytes, .save = FakeStates.save, .restore = FakeStates.restore, .drop = FakeStates.drop } }, .{}, 40 * g); + defer store.deinit(); + const tokens = try gpa.alloc(u32, 200_000); + defer gpa.free(tokens); + for ([_]u32{ 100_000, 150_000, 190_000 }, 0..) |at, k| { // three conversations' histories: 6.1, 9.2 and 11.6 GiB + for (tokens, 0..) |*t, i| t.* = @intCast(k * 1_000_000 + i); + try std.testing.expect(store.keep(tokens[0 .. at + 1], at, null, &.{}, &.{})); + } + const restoring = store.entries.items[2].saved; // the newest conversation's next turn resumes its state + const slot: u64 = 12_900_000_000; // a --context 196608 slot's K/V rows, taps ring and scratch + try std.testing.expect(!served.takeRoom(null, 4 * g, slot, null, tokens)); // without a cache to give back: LaneMemory + try std.testing.expect(served.takeRoom(&store, 4 * g, slot, restoring, tokens)); // 4 GiB free + 6.1 + 9.2 freed + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); + try std.testing.expect(store.entries.items[0].saved == restoring); + try std.testing.expect(!served.takeRoom(&store, 0, 2 * slot, restoring, tokens)); // its own state never goes + try std.testing.expectEqual(@as(usize, 1), fake.live); +} + +test "a reply's end keeps its prompt's born: newest conversations precede redundant history under pressure" { + var fake: FakeStates = .{}; + const snapshots: pc.Snapshots = .{ .ptr = &fake, .vtable = &.{ .bytes = FakeStates.bytes, .save = FakeStates.save, .restore = FakeStates.restore, .drop = FakeStates.drop } }; + try @import("qwen27_reply_cache_test.zig").replyBorn(served.keepEnd, snapshots, &fake.live); +} + +test "qwen27 startup: draft stream count, singular text and optional suffixes" { + const limit = try lb.draftSlots(); + const limited = platform.c.getenv("TF_Q27_DRAFT_SLOTS") != null; + try std.testing.expectEqual(@as(u32, if (limited) 1 else 8), limit); + // the wording: the smaller of the stream count and the draft-slot setting + const wording = [_]struct { streams: u32, slots: u32, want: []const u8 }{ + .{ .streams = 1, .slots = 0, .want = "" }, + .{ .streams = 1, .slots = 1, .want = "DFlash2 drafts for the only stream" }, + .{ .streams = 1, .slots = 8, .want = "DFlash2 drafts for the only stream" }, + .{ .streams = 1, .slots = 99, .want = "DFlash2 drafts for the only stream" }, + .{ .streams = 2, .slots = 0, .want = "" }, + .{ .streams = 2, .slots = 1, .want = "DFlash2 drafts for 1 of 2 streams" }, + .{ .streams = 2, .slots = 8, .want = "DFlash2 drafts for both streams" }, + .{ .streams = 2, .slots = 99, .want = "DFlash2 drafts for both streams" }, + .{ .streams = 4, .slots = 1, .want = "DFlash2 drafts for 1 of 4 streams" }, + .{ .streams = 4, .slots = 8, .want = "DFlash2 drafts for all 4 streams" }, + .{ .streams = 4, .slots = 99, .want = "DFlash2 drafts for all 4 streams" }, + .{ .streams = 16, .slots = 1, .want = "DFlash2 drafts for 1 of 16 streams" }, + .{ .streams = 16, .slots = 8, .want = "DFlash2 drafts for 8 of 16 streams" }, + .{ .streams = 16, .slots = 99, .want = "DFlash2 drafts for all 16 streams" }, + }; + var buf: [64]u8 = undefined; + for (wording) |case| try std.testing.expectEqualStrings(case.want, try startup.draftWording(&buf, case.streams, case.slots)); + // the whole line: the wording, a drafter's absence and the optional suffixes + const lines = [_]struct { streams: u32, slots: u32, images: bool, want: []const u8 }{ + .{ .streams = 1, .slots = 8, .images = false, .want = "Qwen3.8-27B: 1 stream of 4096 tokens, DFlash2 drafts for the only stream" }, + .{ .streams = 2, .slots = 8, .images = true, .want = "Qwen3.8-27B: 2 streams of 4096 tokens, DFlash2 drafts for both streams, images read" }, + .{ .streams = 4, .slots = 8, .images = false, .want = "Qwen3.8-27B: 4 streams of 4096 tokens, DFlash2 drafts for all 4 streams" }, + .{ .streams = 16, .slots = 8, .images = false, .want = "Qwen3.8-27B: 16 streams of 4096 tokens, DFlash2 drafts for 8 of 16 streams" }, + .{ .streams = 2, .slots = 0, .images = false, .want = "Qwen3.8-27B: 2 streams of 4096 tokens" }, + }; + var actual: [192]u8 = undefined; + for (lines) |case| { + const got = try std.fmt.bufPrint(&actual, "{f}", .{startup.StartupLine{ .streams = case.streams, .context = 4096, .draft_slots = case.slots, .images = case.images }}); + try std.testing.expectEqualStrings(case.want, got); + } +} + +test { + _ = @import("qwen27_share_fit.zig"); +} + +test "Qwen27 interior state uses a guaranteed cold request cut" { + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const tokens = try a.alloc(u32, 128 * 1024 + 64); + @memset(tokens, 7); + var fake: FakeStates = .{}; + var store = pc.Store.init(gpa, .{ .ptr = &fake, .vtable = &.{ .bytes = FakeStates.bytes, .save = FakeStates.save, .restore = FakeStates.restore, .drop = FakeStates.drop } }, served.cacheRules(2048), 32 << 30); + defer store.deinit(); + var starts: std.ArrayList(u32) = .empty; + var at: u32 = 2048; + while (at < tokens.len) : (at += 2048) try starts.append(a, at); + const p = try store.beginUser(a, tokens, @intCast(tokens.len - 8), 16, @intCast(tokens.len - 8), &.{}, starts.items, null, &.{}); + try std.testing.expectEqualSlices(u32, &.{ 16, 129024, @intCast(tokens.len - 8) }, p.marks); + for (p.marks) |m| try std.testing.expect(store.keep(tokens, m, null, starts.items, &.{})); + tokens[tokens.len - 512] += 1; + const followup = try store.beginUser(a, tokens, @intCast(tokens.len - 8), 16, @intCast(tokens.len - 8), &.{}, starts.items, null, &.{}); + try std.testing.expectEqual(@as(u32, 129024), followup.from); + try std.testing.expect(store.held <= store.budget); +} + +test "qwen27 reply cache: warm work preserves both client histories within rounded budgets" { + try @import("qwen27_reply_cache_test.zig").exercise(served.keepEnd, slot_state.opening); +} diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index 27d2dcd3702..b29163aa688 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -139,6 +139,7 @@ pub fn chunk(b: *Metal, s: *lanes.Stream, f: *Fill, _: u32) !bool { const session = q.session.Session{ .runner = b.runner, .slot = slot }; if (decoded) try session.decodeChunk(part, last) else try session.promptChunk(part, last); if (b.ringOf(slot)) |g| try ringChunk(b, g, part.len); + try @import("sensenova_features.zig").recordChunk(b, s, slot, at, part.len, last); } charge(b, s, before); lanes.prefill_widths.completed(b.gpa, s, part.len); diff --git a/zig/src/native/sensenova_features.zig b/zig/src/native/sensenova_features.zig new file mode 100644 index 00000000000..16c9385315b --- /dev/null +++ b/zig/src/native/sensenova_features.zig @@ -0,0 +1,155 @@ +//! Target tap feature capture and slice lookup for external drafters (e.g. SenseNova MTP). +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const lanes = tf.lanes; +const be = lanes.backend; +const lb = @import("qwen27_lanes.zig"); +const Metal = lb.Metal; + +pub const State = struct { + enabled: bool = false, + taps: [q.taps.max_planes]u32 = @splat(0), + tap_count: usize = 0, + sink: ?be.FeatureSink = null, + chunk_slot: u32 = 0, + chunk_start: u64 = 0, + chunk_rows: u32 = 0, + chunk_valid: bool = false, + held_start: [lb.max_streams]u64 = @splat(0), + held_rows: [lb.max_streams]u32 = @splat(0), + + pub fn clearSlot(st: *State, slot: u32) void { + if (slot < lb.max_streams) st.held_rows[slot] = 0; + if (st.chunk_valid and st.chunk_slot == slot) st.chunk_valid = false; + } + + fn matchesTaps(st: *const State, wanted: []const u32) bool { + return st.enabled and wanted.len == st.tap_count and std.mem.eql(u32, wanted, st.taps[0..st.tap_count]); + } +}; + +fn rowBytes(b: *const Metal) usize { + return @as(usize, b.runner.taps.width) * b.features_state.tap_count * 2; +} + +fn slotOffset(b: *const Metal, slot: u32, row: usize) usize { + return (@as(usize, slot) * lb.max_rows + row) * rowBytes(b); +} + +pub fn prepareFeaturesFn(ptr: *anyopaque, taps: []const u32) anyerror!void { + const b = Metal.self(ptr); + if (b.features_state.enabled) { + if (b.features_state.matchesTaps(taps)) return; + return error.TapsNotPrepared; + } + for (b.owners[0..b.runner.slots]) |o| if (o != null) return error.TapsAfterStreams; + try b.runner.taps.use(b.runner.model.device, taps); + b.runner.capture_taps = true; + const per_row = @as(usize, b.runner.taps.width) * taps.len * 2; + const need = lb.max_streams * lb.max_rows * per_row; + if (b.held_taps == null) { + b.held_taps = try b.runner.model.device.buffer(need, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + } + @memcpy(b.features_state.taps[0..taps.len], taps); + b.features_state.tap_count = taps.len; + b.features_state.enabled = true; +} + +pub fn prefillFeaturesFn(ptr: *anyopaque, s: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) anyerror!void { + const b = Metal.self(ptr); + if (!b.features_state.matchesTaps(taps)) return error.TapsNotPrepared; + b.features_state.sink = sink; + defer b.features_state.sink = null; + return b.backend().prefill(s); +} + +pub fn recordChunk(b: *Metal, s: *lanes.Stream, slot: u32, start: usize, count: usize, last: bool) !void { + const st = &b.features_state; + if (!st.enabled or count == 0) return; + try b.runner.taps.complete(); + st.chunk_slot = slot; + st.chunk_start = start; + st.chunk_rows = @intCast(count); + st.chunk_valid = true; + st.held_rows[slot] = 0; + if (st.sink) |sink| { + const rb = rowBytes(b); + try sink.take(sink.ptr, s, .{ + .buffer = @intFromPtr(b.runner.taps.buffer.id), + .offset = 0, + .rows = @intCast(count), + .row_bytes = @intCast(rb), + .space = .device, + .dtype = .bf16, + }, start); + } + if (last) { + copyRows(b, slot, 0, count - 1, 1); + st.held_start[slot] = start + count - 1; + st.held_rows[slot] = 1; + } +} + +pub fn recordVerify(b: *Metal, windows: []const be.Window, inputs: []const q.round_plan.Input) !void { + const st = &b.features_state; + if (!st.enabled) return; + try b.runner.taps.complete(); + st.chunk_valid = false; + for (windows, inputs, 0..) |w, in, i| { + const rows: u32 = @intCast(w.rows()); + const first = b.round.?.firsts[i]; + copyRows(b, in.slot, 0, first, rows); + st.held_start[in.slot] = in.start; + st.held_rows[in.slot] = rows; + } +} + +pub fn recordKeep(b: *Metal, windows: []const be.Window, paths: []const []const u32) void { + const st = &b.features_state; + if (!st.enabled or b.advanced) return; + for (windows, paths) |w, path| { + const slot = b.slotOf(w.stream) orelse continue; + var highest: u32 = 0; + for (path) |row| highest = @max(highest, row); + st.held_rows[slot] = @min(st.held_rows[slot], highest + 1); + } +} + +pub fn featuresFn(ptr: *anyopaque, s: *lanes.Stream, taps: []const u32, start: u64, count: u32) anyerror!be.Features { + const b = Metal.self(ptr); + const st = &b.features_state; + if (!st.matchesTaps(taps)) return error.TapsNotPrepared; + const slot = try b.slotFor(s); + const rb = rowBytes(b); + if (count == 0) { + return .{ .buffer = @intFromPtr(b.held_taps.?.id), .offset = slotOffset(b, slot, 0), .rows = 0, .row_bytes = @intCast(rb), .space = .device, .dtype = .bf16 }; + } + if (st.held_rows[slot] > 0 and start >= st.held_start[slot] and start + count <= st.held_start[slot] + st.held_rows[slot]) { + const rel: usize = @intCast(start - st.held_start[slot]); + return .{ .buffer = @intFromPtr(b.held_taps.?.id), .offset = slotOffset(b, slot, rel), .rows = count, .row_bytes = @intCast(rb), .space = .device, .dtype = .bf16 }; + } + if (st.chunk_valid and st.chunk_slot == slot and st.tap_count == 1 and start >= st.chunk_start and start + count <= st.chunk_start + st.chunk_rows) { + const rel: usize = @intCast(start - st.chunk_start); + return .{ .buffer = @intFromPtr(b.runner.taps.buffer.id), .offset = rel * rb, .rows = count, .row_bytes = @intCast(rb), .space = .device, .dtype = .bf16 }; + } + return error.RowsNotHeld; +} + +fn copyRows(b: *Metal, dst_slot: u32, dst_row: usize, src_row: usize, rows: usize) void { + const t = &b.runner.taps; + const w_bytes = @as(usize, t.width) * 2; + const plane_bytes = @as(usize, t.capacity) * w_bytes; + const src_base = t.buffer.contents(); + const dst_base = b.held_taps.?.contents() + slotOffset(b, dst_slot, dst_row); + if (t.count == 1) { + @memcpy(dst_base[0 .. rows * w_bytes], src_base[src_row * w_bytes ..][0 .. rows * w_bytes]); + return; + } + for (0..rows) |r| { + for (0..t.count) |p| { + @memcpy(dst_base[(r * t.count + p) * w_bytes ..][0..w_bytes], src_base[p * plane_bytes + (src_row + r) * w_bytes ..][0..w_bytes]); + } + } +} diff --git a/zig/src/native/sensenova_mtp_drafter.zig b/zig/src/native/sensenova_mtp_drafter.zig new file mode 100644 index 00000000000..a19e93e0290 --- /dev/null +++ b/zig/src/native/sensenova_mtp_drafter.zig @@ -0,0 +1,135 @@ +//! Lanes Drafter vtable wrapper over SenseNova-Loop-9B native Metal MTP. +const std = @import("std"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const lanes = tf.lanes; +const Mtp = q.sn_mtp.Mtp; +const Stream = lanes.Stream; +const dr = lanes.drafter; + +const default_prior = [_]f64{ 0.80, 0.62, 0.48, 0.36 }; +const max_batch = 16; + +fn cast(ptr: *anyopaque) *Mtp { + return @ptrCast(@alignCast(ptr)); +} + +fn tapsFn(ptr: *anyopaque) []const u32 { + return &cast(ptr).tap_layer; +} + +fn factsFn(ptr: *anyopaque) dr.Facts { + const m = cast(ptr); + return .{ + .limit_shared_drafts = true, + .depth = m.depth, + .step_ms = m.step_ms, + .prior = default_prior[0..@min(m.depth, default_prior.len)], + .plain_guard = m.plain_guard, + .batched = true, + .stream_bytes = m.slotBytes(), + .copy_first = true, + }; +} + +fn openFn(ptr: *anyopaque, s: *Stream) anyerror!void { + return cast(ptr).openStream(@intFromPtr(s)); +} + +fn toAbsorbItem(it: dr.Absorb) !q.sn_mtp.AbsorbItem { + if (it.features.dtype != .bf16) return error.BadMtpFeatures; + // Skip intermediate prompt-chunk draft proposals (rows strictly before the prompt's last token). + const prompt_chunk = it.rows == null and it.features.rows > 0 and it.start + it.features.rows < it.stream.prompt_len; + return .{ + .stream = @intFromPtr(it.stream), + .features = .{ + .buffer = it.features.buffer, + .offset = it.features.offset, + .rows = it.features.rows, + .row_bytes = it.features.row_bytes, + .host = it.features.space == .host, + }, + .start = it.start, + .follow = it.follow, + .rows = it.rows, + .propose = it.propose and !prompt_chunk, + .prompt_only = prompt_chunk, + }; +} + +fn toHoldItem(it: dr.Hold) q.sn_mtp.HoldItem { + return .{ .stream = @intFromPtr(it.stream), .pending = it.pending, .position = it.position, .depth = it.depth }; +} + +fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const m = cast(ptr); + var buf: [max_batch]q.sn_mtp.AbsorbItem = undefined; + var at: usize = 0; + while (at < items.len) { + const take = @min(buf.len, items.len - at); + for (items[at..][0..take], buf[0..take]) |it, *dst| dst.* = try toAbsorbItem(it); + try m.absorb(buf[0..take]); + at += take; + } +} + +fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const m = cast(ptr); + var buf: [max_batch]q.sn_mtp.HoldItem = undefined; + var at: usize = 0; + while (at < items.len) { + const take = @min(buf.len, items.len - at); + for (items[at..][0..take], buf[0..take]) |it, *dst| dst.* = toHoldItem(it); + try m.hold(buf[0..take]); + at += take; + } +} + +fn draftRoundFn(ptr: *anyopaque, absorbs: []const dr.Absorb, holds: []const dr.Hold) anyerror!void { + if (absorbs.len > max_batch or holds.len > max_batch) { + if (absorbs.len > 0) try absorbFn(ptr, absorbs); + if (holds.len > 0) try holdFn(ptr, holds); + return; + } + const m = cast(ptr); + var ab: [max_batch]q.sn_mtp.AbsorbItem = undefined; + var hb: [max_batch]q.sn_mtp.HoldItem = undefined; + for (absorbs, ab[0..absorbs.len]) |it, *dst| dst.* = try toAbsorbItem(it); + for (holds, hb[0..holds.len]) |it, *dst| dst.* = toHoldItem(it); + try m.draftRound(ab[0..absorbs.len], hb[0..holds.len]); +} + +fn heldFn(ptr: *anyopaque, streams: []const *Stream, outs: []const []u32) anyerror!void { + const m = cast(ptr); + var ids: [max_batch]usize = undefined; + var at: usize = 0; + while (at < streams.len) { + const take = @min(ids.len, streams.len - at); + for (streams[at..][0..take], ids[0..take]) |s, *id| id.* = @intFromPtr(s); + try m.held(ids[0..take], outs[at..][0..take]); + at += take; + } +} + +fn releaseFn(ptr: *anyopaque, s: *Stream) void { + cast(ptr).releaseStream(@intFromPtr(s)); +} + +const vtable: dr.Drafter.VTable = .{ + .taps = tapsFn, + .facts = factsFn, + .open = openFn, + .absorb = absorbFn, + .hold = holdFn, + .draft_round = draftRoundFn, + .held = heldFn, + .release = releaseFn, +}; + +pub fn drafter(m: *Mtp) dr.Drafter { + return .{ + .kind = "MTP", + .ptr = m, + .vtable = &vtable, + }; +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index f8ad555e12a..b2e287bdd65 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -68,7 +68,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_CUDA_SEGMENTS", .scope = .cuda, .kind = .segments, .trim = " ", .forms = "a whole number from 1 to 4, or empty for the default" }, .{ .name = "TF_CUDA_CARVEOUT", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_CUDA_CARVEOUT_MIB", .scope = .cuda, .kind = .mib, .forms = "a positive whole MiB count fitting a native byte size, or empty for 1792 MiB" }, - .{ .name = "TF_MTP_DRAFTS", .scope = .cuda, .kind = .u32, .forms = "a whole number from 0 to 4294967295 (clamped to the drafter's window)" }, + .{ .name = "TF_MTP_DRAFTS", .scope = .common, .kind = .u32, .forms = "a whole number from 0 to 4294967295 (clamped to the drafter's window)" }, .{ .name = "TF_DSPINE_WINDOW", .scope = .cuda, .kind = .size, .min = 16, .max = 8192, .forms = "a whole row count from 16 to 8192, at most the DSpine drafter's own sliding_window" }, .{ .name = "TF_DRAFT_NODES", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size node count (capped by the drafter's window)" }, .{ .name = "TF_QMMF_HALF_BELOW", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size block count (0 disables half tiles)" }, @@ -129,6 +129,8 @@ pub const rules = [_]Rule{ .{ .name = "TF_Q27_MTP_GPU_PICK", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 fuses the 27B MTP absorb and picks drafts on the GPU; unset or blank is 0)" }, .{ .name = "TF_QWEN27_JOIN", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 runs a window's rows in pairs in the 27B's decode tail before M5; unset or blank is 1)" }, .{ .name = "TF_QWEN27_TIED_HEAD", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 lets a dense Qwen with a tied head load, its head read from the embedding; unset or blank is 0)" }, + .{ .name = "TF_MTP_PLAIN_GUARD", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 enables plain-round guard alongside MTP; unset or blank is 1)" }, + .{ .name = "TF_MTP_BITS", .scope = .metal, .kind = .u32, .only = &.{ 4, 16 }, .first_digit = true, .forms = "4 or 16 (MTP weight bits; unset or blank defaults to 4)" }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 puts the streams' keys and values in core-pool pages; unset or blank is 0)" }, .{ .name = "TF_QWEN35_CHUNK", .scope = .metal, .kind = .size, .min = 1, .forms = "whole prompt rows a prefill pass, 1 to the served context window (default 128)" }, .{ .name = "TF_DSV41_SMALL", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 reads a DeepSeek-V4.1 Metal checkpoint's config at its own small shapes)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 85a3af31b3e..f5b3c277b66 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -195,6 +195,10 @@ const valid = [_]Case{ .{ .name = "TF_QWEN27_JOIN", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN27_TIED_HEAD", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN27_TIED_HEAD", .raw = "1", .n = 1 }, + .{ .name = "TF_MTP_DRAFTS", .raw = "3", .n = 3 }, + .{ .name = "TF_MTP_PLAIN_GUARD", .raw = "1", .n = 1 }, + .{ .name = "TF_MTP_BITS", .raw = "4", .n = 4 }, + .{ .name = "TF_MTP_BITS", .raw = "16", .n = 16 }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN35_METAL_KV_PAGES", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN35_CHUNK", .raw = "128", .n = 128 }, @@ -331,6 +335,7 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "GLM_POOL_TOKENS", "4294967232" }, .{ "GLM_POOL_TOKENS", "2k" }, .{ "GLM_POOL_TOKENS", "+2000000" }, .{ "GLM_POOL_TOKENS", "-1" }, .{ "GLM_POOL_TOKENS", "1e6" }, .{ "GLM_POOL_TOKENS", "lots" }, + .{ "TF_MTP_BITS", "8" }, }) |c| try t.expectError(error.InvalidEnvironment, e.parse(c[0], c[1])); try t.expectEqual(@as(?u64, null), try e.parse("TF_CUDA_DEVICE", " ")); try t.expectEqual(@as(?u64, 0), try e.parse("TF_Q27_COPY_ROWS", "+0")); diff --git a/zig/tests/qwen27/sensenova_oracle.zig b/zig/tests/qwen27/sensenova_oracle.zig index a84f7dc0cf7..b44a87e2cba 100644 --- a/zig/tests/qwen27/sensenova_oracle.zig +++ b/zig/tests/qwen27/sensenova_oracle.zig @@ -130,6 +130,155 @@ fn verifyTrace(a: std.mem.Allocator, gpa: std.mem.Allocator, m: *q.model.Model, if (ov < 12) return error.Top16OverlapTooLow; } +fn readTensorU32(a: std.mem.Allocator, st_bytes: []const u8, st_hdr: std.json.ObjectMap, st_base: usize, name: []const u8) ![]u32 { + const ent = (st_hdr.get(name) orelse return error.MissingOracleTensor).object; + const dtype = ent.get("dtype").?.string; + if (!std.mem.eql(u8, dtype, "I32")) return error.BadOracleDType; + const offs = ent.get("data_offsets").?.array.items; + const raw = st_bytes[st_base + @as(usize, @intCast(offs[0].integer)) .. st_base + @as(usize, @intCast(offs[1].integer))]; + const out = try a.alloc(u32, raw.len / 4); + for (out, 0..) |*d, i| d.* = std.mem.readInt(u32, raw[i * 4 ..][0..4], .little); + return out; +} + +fn compareRow(got: []const u16, st_bytes: []const u8, st_hdr: std.json.ObjectMap, st_base: usize, name: []const u8, row: usize) !Stats { + const ent = (st_hdr.get(name) orelse return error.MissingOracleTensor).object; + const dtype = ent.get("dtype").?.string; + if (!std.mem.eql(u8, dtype, "BF16")) return error.BadOracleDType; + const offs = ent.get("data_offsets").?.array.items; + const raw = st_bytes[st_base + @as(usize, @intCast(offs[0].integer)) .. st_base + @as(usize, @intCast(offs[1].integer))]; + const rb = got.len * 2; + if ((row + 1) * rb > raw.len) return error.OracleShapeMismatch; + const src = raw[row * rb ..][0..rb]; + var dot: f64 = 0; + var na: f64 = 0; + var nb: f64 = 0; + var max_abs: f64 = 0; + for (got, 0..) |g, i| { + const a = bf16ToF64(g); + const b = bf16ToF64(std.mem.readInt(u16, src[i * 2 ..][0..2], .little)); + dot += a * b; + na += a * a; + nb += b * b; + max_abs = @max(max_abs, @abs(a - b)); + } + const denom = @sqrt(na) * @sqrt(nb); + return .{ .cos = if (denom > 0) dot / denom else 0, .max_abs = max_abs }; +} + +fn verifyMtpOracle(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, m: *q.model.Model, model_dir: []const u8, path: []const u8, is_awq: bool) !void { + const raw_bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(64 << 20)); + const hlen: usize = @intCast(std.mem.readInt(u64, raw_bytes[0..8], .little)); + const hdr = try std.json.parseFromSlice(std.json.Value, a, raw_bytes[8 .. 8 + hlen], .{}); + const st_hdr = hdr.value.object; + const st_base = 8 + hlen; + + const follow_ids = try readTensorU32(a, raw_bytes, st_hdr, st_base, "follow_ids"); + const chain_preds = try readTensorU32(a, raw_bytes, st_hdr, st_base, "chain_preds"); + const rows = follow_ids.len; + const hidden = m.config.hidden; + const ent_r55 = st_hdr.get("r55_raw").?.object; + const offs = ent_r55.get("data_offsets").?.array.items; + const r55_raw = raw_bytes[st_base + @as(usize, @intCast(offs[0].integer)) .. st_base + @as(usize, @intCast(offs[1].integer))]; + const r55_buf = try m.device.buffer(r55_raw.len, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + defer r55_buf.deinit(); + @memcpy(r55_buf.contents()[0..r55_raw.len], r55_raw); + + const mtp = try q.sn_mtp.Mtp.init(gpa, io, m, model_dir, 4, 256); + defer mtp.deinit(); + const sid: usize = 1; + try mtp.openStream(sid); + defer mtp.releaseStream(sid); + + try mtp.absorb(&.{.{ + .stream = sid, + .features = .{ .buffer = @intFromPtr(r55_buf.id), .offset = 0, .rows = @intCast(rows), .row_bytes = @intCast(hidden * 2) }, + .start = 0, + .follow = follow_ids, + .propose = true, + }}); + const ctx = try mtp.ctxOf(sid); + const out0 = ptrU16(.{ .buffer = ctx.chainOutRef(0, hidden).buffer, .offset = ctx.chainOutRef(0, hidden).offset }, hidden); + const st_abs = try compareRow(out0, raw_bytes, st_hdr, st_base, "absorb_out", rows - 1); + const mtp_q4 = mtp.draft_head != null or mtp.weights.bits == 4; + const q4_any = is_awq or mtp_q4; + std.debug.print("MTP(bits={d},head_q4={}) absorb_out last cos={d:.7} max_abs={d:.5}\n", .{ mtp.weights.bits, mtp.draft_head != null, st_abs.cos, st_abs.max_abs }); + const min_abs_cos: f64 = if (mtp_q4) 0.98 else if (is_awq) 0.998 else 0.999; + const min_chain_cos: f64 = if (mtp_q4) 0.88 else if (is_awq) 0.98 else 0.998; + if (st_abs.cos < min_abs_cos or !std.math.isFinite(st_abs.cos)) return error.MtpOracleCosineTooLow; + + try mtp.hold(&.{.{ .stream = sid, .pending = follow_ids[rows - 1], .position = rows, .depth = 3 }}); + var held_toks: [3]u32 = undefined; + try mtp.held(&.{sid}, &.{held_toks[0..3]}); + for (0..3) |k| { + const ck_ref = ctx.chainOutRef(k, hidden); + const ck_out = ptrU16(.{ .buffer = ck_ref.buffer, .offset = ck_ref.offset }, hidden); + const st_ck = try compareRow(ck_out, raw_bytes, st_hdr, st_base, "chain_outs", k); + std.debug.print("MTP chain[{d}] cos={d:.7} got={d} exp={d}\n", .{ k, st_ck.cos, held_toks[k], chain_preds[k] }); + if (st_ck.cos < min_chain_cos or !std.math.isFinite(st_ck.cos)) return error.MtpChainCosineTooLow; + if (!q4_any and held_toks[k] != chain_preds[k]) return error.MtpChainTokenMismatch; + } + if (q4_any and held_toks[0] != chain_preds[0]) return error.MtpAwqTop1Mismatch; + + const sid2: usize = 2; + try mtp.openStream(sid2); + defer mtp.releaseStream(sid2); + try mtp.draftRound( + &.{.{ + .stream = sid2, + .features = .{ .buffer = @intFromPtr(r55_buf.id), .offset = 0, .rows = @intCast(rows), .row_bytes = @intCast(hidden * 2) }, + .start = 0, + .follow = follow_ids, + .propose = false, + }}, + &.{.{ .stream = sid2, .pending = follow_ids[rows - 1], .position = rows, .depth = 3 }}, + ); + var round_toks: [3]u32 = undefined; + try mtp.held(&.{sid2}, &.{round_toks[0..3]}); + if (!std.mem.eql(u32, &round_toks, &held_toks)) return error.MtpDraftRoundMismatch; + + const sid3: usize = 3; + const sid4: usize = 4; + try mtp.openStream(sid3); + defer mtp.releaseStream(sid3); + try mtp.openStream(sid4); + defer mtp.releaseStream(sid4); + if (rows > 1) { + try mtp.absorb(&.{.{ + .stream = sid4, + .features = .{ .buffer = @intFromPtr(r55_buf.id), .offset = 0, .rows = @intCast(rows - 1), .row_bytes = @intCast(hidden * 2) }, + .start = 0, + .follow = follow_ids[0 .. rows - 1], + .propose = false, + .prompt_only = true, + }}); + } + const off4 = if (rows > 1) (rows - 1) * hidden * 2 else 0; + const ab3: q.sn_mtp.AbsorbItem = .{ + .stream = sid3, + .features = .{ .buffer = @intFromPtr(r55_buf.id), .offset = 0, .rows = @intCast(rows), .row_bytes = @intCast(hidden * 2) }, + .start = 0, + .follow = follow_ids, + .propose = false, + }; + const ab4: q.sn_mtp.AbsorbItem = .{ + .stream = sid4, + .features = .{ .buffer = @intFromPtr(r55_buf.id), .offset = off4, .rows = 1, .row_bytes = @intCast(hidden * 2) }, + .start = if (rows > 1) rows - 1 else 0, + .follow = follow_ids[if (rows > 1) rows - 1 else 0..], + .propose = false, + }; + const h3: q.sn_mtp.HoldItem = .{ .stream = sid3, .pending = follow_ids[rows - 1], .position = rows, .depth = 3 }; + const h4: q.sn_mtp.HoldItem = .{ .stream = sid4, .pending = follow_ids[rows - 1], .position = rows, .depth = 3 }; + try mtp.draftRound(&.{ ab3, ab4 }, &.{ h3, h4 }); + var b3_toks: [3]u32 = undefined; + var b4_toks: [3]u32 = undefined; + try mtp.held(&.{ sid3, sid4 }, &.{ b3_toks[0..3], b4_toks[0..3] }); + if (!std.mem.eql(u32, &b3_toks, &held_toks) or !std.mem.eql(u32, &b4_toks, &held_toks)) { + return error.MtpBatchDraftRoundMismatch; + } +} + pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const a = init.arena.allocator(); @@ -147,16 +296,21 @@ pub fn main(init: std.process.Init) !void { var model_dir: ?[]const u8 = null; var json_path: ?[]const u8 = null; var st_path: ?[]const u8 = null; + var mtp_oracle_path: ?[]const u8 = null; var i: usize = 1; while (i < args.len) : (i += 1) { if (i + 1 >= args.len) return error.MissingValue; - if (std.mem.eql(u8, args[i], "--model")) model_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--oracle-json")) json_path = args[i + 1] else if (std.mem.eql(u8, args[i], "--oracle-st")) st_path = args[i + 1] else return error.UnknownOption; + if (std.mem.eql(u8, args[i], "--model")) model_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--oracle-json")) json_path = args[i + 1] else if (std.mem.eql(u8, args[i], "--oracle-st")) st_path = args[i + 1] else if (std.mem.eql(u8, args[i], "--mtp-oracle")) mtp_oracle_path = args[i + 1] else return error.UnknownOption; i += 1; } const dir = model_dir orelse return error.MissingModel; const m = try q.model.Model.load(gpa, io, dir, 128, null); defer m.deinit(); const is_awq = m.weights.head.bits == 4; + if (mtp_oracle_path) |mp| { + try verifyMtpOracle(a, gpa, io, m, dir, mp, is_awq); + if (json_path == null and st_path == null) return; + } const oj_raw = try std.Io.Dir.cwd().readFileAlloc(io, json_path orelse return error.MissingOracleJson, a, .limited(32 << 20)); const oj = try std.json.parseFromSlice(std.json.Value, a, oj_raw, .{}); const st_bytes = try std.Io.Dir.cwd().readFileAlloc(io, st_path orelse return error.MissingOracleSt, a, .limited(64 << 20)); From cedf8f1718b0fb11e52ef1940660cfe2c4008419 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:16:25 +0100 Subject: [PATCH 353/361] docs: SenseNova-Loop MTP environment and recipe receipts --- docs/environment.md | 4 +++- docs/optimization-ledger.md | 4 ++-- docs/recipes/README.md | 2 +- docs/recipes/sensenova-loop-9b.md | 32 ++++++++++++++++++++++++++++++- 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index f0962686dce..d2a625fb9ca 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -34,7 +34,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_Q27_DFLASH_ADAPTIVE_BLOCK` | Qwen3.8-27B on Metal: exactly `0` or `1`; default 0. `1` lets a lone stream's DFlash2 block narrow from 16 to 8 rows after 8 consecutive rounds landing at most 4 tree drafts, and return to 16 after a round landing 6 or more. Only the drafter's proposal changes. | | `TF_Q27_DFLASH_ABSORB_BATCH` | Qwen3.8-27B on Metal: exactly `0` or `1`; default `0`. `1` absorbs a shared round's new DFlash2 taps for up to 128 rows across streams in one pass, each stream's results in its own caches. | | `TF_Q27_KV_GROW` | Qwen3.8-27B on Metal: `0` (the default: every slot holds the whole context) or a row count that is a multiple of 16, at most 4294967280; blank and other text are refused. A slot starts at that many rows, grows to a need rounded up to the step or a quarter more, at most the context, and gives the rows back when its stream ends; drafter tap rings grow the same way. Read when the K/V is not paged; checked at every Metal start | -| `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one; existing depth when unset | +| `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one (`0` is clamped to `1` on SenseNova-Loop MTP); existing depth when unset (`3` on SenseNova-Loop MTP) | | `TF_TIMING` | Exactly `0` or `1`; default off (each call's wall time on stderr while set) | | `TF_NO_TREES` | Exactly `0` or `1`; default off. `1` keeps the CUDA drafter's chains only, and retains precedence over `TF_DRAFT_NODES` | | `TF_DFLASH_QL_SPAN` | Exactly `0` or `1`; default off. `1` drafts a ModelOpt NVFP4 or FP8 head over the DFlash2 vocabulary spans; other head formats stay whole | @@ -115,6 +115,8 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_Q27_MTP_GPU_PICK` | Qwen3.8-27B with `--mtp-drafts` on Metal: exactly `0` or `1`; `1` runs each MTP absorb on one command buffer and picks drafts on the GPU; unset or blank is `0` | | `TF_QWEN27_JOIN` | Qwen3.8-27B on Metal before M5: exactly `0` or `1`; `1` runs a window's rows in pairs over the keys below it in the decode tail attention (same replies); unset or blank is `1` | | `TF_QWEN27_TIED_HEAD` | Dense Qwen on Metal: exactly `0` or `1`; `1` lets a checkpoint with a tied head load on the 27B engine, its head read from the embedding (one Mac, no draft head, qualified shapes only); unset or blank is `0` | +| `TF_MTP_PLAIN_GUARD` | SenseNova-Loop MTP on Metal: exactly `0` or `1`; `1` runs a plain-round fallback alongside MTP when verification rejects the drafted chain; unset or blank is `1` | +| `TF_MTP_BITS` | SenseNova-Loop MTP on Metal: exactly `4` or `16`; quantizes loaded `mtp.safetensors` projections (and a draft-only copy of `lm_head` when the target head is BF16) to AWQ 4-bit `g128` at boot (`4`) or keeps BF16 (`16`) for drafting while target verification always runs in checkpoint weights; unset or blank defaults to `4` | | `TF_QWEN35_METAL_KV_PAGES` | Qwen 3.5 on Metal: exactly `0` or `1`; `1` puts the streams' keys and values in core-pool pages; unset or blank is `0` | | `TF_QWEN35_CHUNK` | Qwen 3.5 on Metal: whole prompt rows a prefill pass, 1 through the served context window; default 128. Checked before the checkpoint loads, naming the setting | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 925a590ba86..961b5cea372 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -237,11 +237,11 @@ ling `ling` (host package only, no engine yet; CUDA plan in [#850]). | 12. Add + norm | done¹ | done M¹ | yes | open M[#3859] | | 13. MoE grouped | done¹ | done¹ | no (dense) | no (dense) | | 14. CUDA graphs | no (Metal) | no (Metal) | no (prompt) | no (Metal) | -| 15. MTP | done¹ | no (DSpark) | no (prompt) | yes | +| 15. MTP | done¹ | no (DSpark) | no (prompt) | open M | | 16. DFlash(2) | yes | yes | no (prompt) | yes | | 17. DSpark | yes | yes | no (prompt) | yes | | 18. Copy drafts | done M¹ | done [#2221] | no (prompt) | done¹ | -| 19. Shared drafts | yes | yes | no (prompt) | no (copies) | +| 19. Shared drafts | yes | yes | no (prompt) | open M | | 20. Solo chunks | yes | yes | no (prompt) | yes | | 21. Read-ahead | no (Metal) | no (Metal) | yes | no (Metal) | | 22. Direct load | yes | yes | yes | yes | diff --git a/docs/recipes/README.md b/docs/recipes/README.md index 4a5ea6171ee..69e6082ca85 100644 --- a/docs/recipes/README.md +++ b/docs/recipes/README.md @@ -38,7 +38,7 @@ For agent-assisted contributions, read the [TensorFold contributor skill](SKILL. | Muse Spark Open | [EXL3 on CUDA, two-rank DGX Spark, plain decode](muse-spark.md) | | Ripple-65B-Preview | [Native CUDA, the publisher's NVFP4 release](ripple-65b-cuda.md), [native Metal, the publisher's NVFP4 and bf16 releases](ripple-65b-metal.md) | | Ling-3.0-tiny | [Native CPU on aarch64 Linux, the Q4_K_M GGUF, exact greedy decode from token IDs](ling-3.0-tiny-cpu.md) | -| SenseNova-Loop-9B | [Native Metal, BF16 and AWQ g128, 512k context, images](sensenova-loop-9b.md) | +| SenseNova-Loop-9B | [Native Metal, BF16 and AWQ g128, 512k context, MTP drafts, images](sensenova-loop-9b.md) | [Persisted serving-state identities](persisted-serving-keys.md) lists the disk owners, their compatibility keys and stale-state host checks. diff --git a/docs/recipes/sensenova-loop-9b.md b/docs/recipes/sensenova-loop-9b.md index 0e529c07ce4..d15d09f343f 100644 --- a/docs/recipes/sensenova-loop-9b.md +++ b/docs/recipes/sensenova-loop-9b.md @@ -12,7 +12,15 @@ Each trunk layer runs a two-stream manifold-constrained hyper-connection (`mHC`) - **AWQ g128 export config:** Converted from `sensenova/SenseNova-Loop-9B` (`rev 3e1ba6e8ac98090f9f7c03a55f26269eb3850fb6`) with `"quantization_config": {"quant_method": "awq", "bits": 4, "group_size": 128, "zero_point": true, "version": "gemm"}`, keeping `mhc_*`, `linear_attn.{in_proj_a,in_proj_b,conv1d,A_log,dt_bias,norm}`, RMSNorms, `embed_tokens`, `model.visual`, and `loop_gate` in BF16 (`modules_to_not_convert`), calibrating AWQ input activation scales across both loop passes of layers `4..27`. - **Context length:** Static YaRN scaling enabled at `factor=2.0` (`262,144` base to `524,288` max context), plus `--rope-yarn` factor selection on SenseNova checkpoints. - **Vision inputs:** Supports the checkpoint's `model.visual.` tower through `--vision`. -- **Prompt chunking and decoding:** Uses `2048`-row linear-attention prompt chunks on Apple M3 Ultra and M5 Ultra (via single-chain prompt planning on `wide_prompt`), Copy-Draft (`--no-drafts` disables drafting), and fused tail greedy argmax. +- **Prompt chunking and decoding:** Uses `2048`-row linear-attention prompt chunks on Apple M3 Ultra and M5 Ultra (via single-chain prompt planning on `wide_prompt`), native Multi-Token Prediction (`MTP`) speculative drafting when `mtp.safetensors` is present beside the checkpoint (falling back to Copy-Draft when absent; `--no-drafts` disables drafting), and fused tail greedy argmax. + +## Multi-token speculative drafting (MTP) + +When `mtp.safetensors` is placed next to the checkpoint (from `sensenova/SenseNova-Loop-9B`, Apache-2.0), the engine attaches the native Metal MTP drafter (`TF_MTP_DRAFTS`, default `3` steps). Intermediate prompt chunks advance the drafter state via `keysOnly` attention absorb (skipping full-chunk query projections, MLP, and norm until the final kept token), and active streams share a single Metal command buffer per round via `draft_round` and `sn_mtp_batch`. + +- **`TF_MTP_DRAFTS`:** Draft depth per round (default `3`; clamped to `1` through the drafter's window less one). +- **`TF_MTP_PLAIN_GUARD`:** `0` or `1` (default `1`); runs a plain-round fallback alongside MTP when verification rejects the drafted chain. +- **`TF_MTP_BITS`:** `4` (default) or `16`; quantizes loaded `mtp.safetensors` projections (and a draft-only copy of `lm_head` when the target head is BF16) to AWQ 4-bit `g128` at boot, or keeps BF16 (`16`). Target verification always runs in full checkpoint precision, producing bit-identical `token_sha` outputs to `--no-drafts` at both `T=0` and seeded `T=1.0`. ## Launch @@ -31,6 +39,10 @@ Measured against `sensenova/SenseNova-Loop-9B` (Apache-2.0, Hugging Face revisio - **BF16 vs Hugging Face PyTorch trace:** `embed_tokens cos=1.0000000`, `exec3_out cos=0.9999639`, `exec27_h_after_collapse cos=0.9998821`, `exec51_h_after_collapse cos=0.9999005`, `exec55_out cos=0.9998916`, `final_norm cos=0.9998723`, `logits_bf16 cos=0.9999594`, top-1 `4/4`, top-16 overlap `16/16`, `6/6` greedy generations exact (`4/4`, `4/4`, `42/42`, `64/64`, `64/64`, `64/64`). - **AWQ W4A16 g128 vs quantized PyTorch trace:** `embed_tokens cos=1.0000000`, `exec3_out cos=0.9999746`, `exec27_h_after_collapse cos=0.9999127`, `exec51_h_after_collapse cos=0.9998882`, `exec55_out cos=0.9999162`, `final_norm cos=0.9998916`, `logits_bf16 cos=0.9999633`, top-1 `4/4`, top-16 overlap `16/16`, `6/6` greedy generations exact (`4/4`, `42/42`, `22/22`, `64/64`, `96/96`, `64/64`). +- **MTP head (`tf-sensenova-oracle --mtp-oracle`, including split `prompt_only` prefill and 2-stream batched `draftRound`):** + - `TF_MTP_BITS=16` on BF16: `absorb_out last cos=0.9999904 max_abs=0.06250`, `chain[0..2]` `cos=0.9999904`, `0.9999332`, `0.9999087`, greedy `20/20`, `22/22`, `22/22`. + - `TF_MTP_BITS=4` on BF16: `absorb_out last cos=0.9844645 max_abs=3.04688`, `chain[0..2]` `cos=0.9844645`, `0.9146141`, `0.8913979`, greedy `20/20`, `22/22`, `22/22`. + - `TF_MTP_BITS=4` on AWQ g128: `absorb_out last cos=0.9831613 max_abs=1.71875`, `chain[0..2]` `cos=0.9831613`, `0.9113104`, `0.8807949`, greedy `20/20`, `22/22`, `22/22`. ### Decode, concurrency, and cold prefill (Apple M5 Ultra) @@ -46,6 +58,24 @@ Measured against `sensenova/SenseNova-Loop-9B` (Apache-2.0, Hugging Face revisio | `tools/bench_cache.py --require-cold` (`8,192` tok) | BF16 / AWQ | Raw token array, median `4` runs | — | `2.345s` (`3,493`) / `2.885s` (`2,840` tok/s) | `qualified: true` | | `tools/bench_cache.py --require-cold` (`32,768` tok) | BF16 / AWQ | Raw token array, median `4` runs | — | `10.227s` (`3,204`) / `12.543s` (`2,613` tok/s) | `qualified: true` | +### MTP vs `--no-drafts` on Apple M5 Ultra (`--parallel 4 --context 36864 --prompt-cache-gib 0`) + +With `mtp.safetensors` (`TF_MTP_BITS=4`, `TF_MTP_DRAFTS=3`, `TF_MTP_PLAIN_GUARD=1`), active memory once loaded is `29.6 GiB` in BF16 (vs `25.5 GiB` with `--no-drafts`) and `18.4 GiB` in AWQ g128 (vs `14.9 GiB` with `--no-drafts`). + +| Check | Format | Prompt / Mode | MTP (`tok/s`) | `--no-drafts` (`tok/s`) | Gain / Exactness | +| --- | --- | --- | --- | --- | --- | +| `tools/bench_openai.py` (`256` tok, `3` reps) | BF16 | `fibonacci-raw` `T=1.0` / `T=0` | `67.61` / `73.80` (`2.639` / `2.753` tok/chunk) | `29.02` / `29.15` | `2.33x` / `2.53x`, identical `token_sha` | +| `tools/bench_openai.py` (`256` tok, `3` reps) | BF16 | `gpu-chat-no-think` `T=1.0` / `T=0` | `49.56` / `58.34` (`1.855` / `2.169` tok/chunk) | `29.05` / `29.10` | `1.71x` / `2.00x`, identical `token_sha` | +| `tools/bench_openai.py` (`256` tok, `3` reps) | AWQ g128 | `fibonacci-raw` `T=1.0` / `T=0` | `114.23` / `117.73` (`2.667` / `2.783` tok/chunk) | `55.45` / `54.28` | `2.06x` / `2.17x`, identical `token_sha` | +| `tools/bench_openai.py` (`256` tok, `3` reps) | AWQ g128 | `gpu-chat-no-think` `T=1.0` / `T=0` | `79.19` / `83.00` (`1.842` / `1.954` tok/chunk) | `55.44` / `54.28` | `1.43x` / `1.53x`, identical `token_sha` | +| `tools/bench_concurrent.py` (`c=4`, `T=1.0` / `T=0`) | BF16 | `code` (`agg`, `per-stream`) | `176.6` (`48.9`) / `205.9` (`52.3`) | `—` / `109.6` (`27.6`) | `1.88x` (`T=0`), `alone 12/12`, `serial 4/4` & `1/1`, `unequal: 0` | +| `tools/bench_concurrent.py` (`c=4`, `T=1.0` / `T=0`) | BF16 | `chat` (`agg`, `per-stream`) | `144.2` (`40.9`) / `171.6` (`44.0`) | `—` / `108.8` (`27.6`) | `1.58x` (`T=0`), `alone 12/12`, `serial 4/4` & `1/1`, `unequal: 0` | +| `tools/bench_concurrent.py` (`c=4`, `T=1.0` / `T=0`) | AWQ g128 | `code` (`agg`, `per-stream`) | `321.5` (`88.2`) / `356.4` (`91.3`) | `—` / `200.6` (`51.0`) | `1.78x` (`T=0`), `alone 12/12`, `serial 4/4` & `1/1`, `unequal: 0` | +| `tools/bench_concurrent.py` (`c=4`, `T=1.0` / `T=0`) | AWQ g128 | `chat` (`agg`, `per-stream`) | `251.7` (`67.0`) / `257.5` (`66.3`) | `—` / `198.8` (`51.0`) | `1.30x` (`T=0`), `alone 12/12`, `serial 4/4` & `1/1`, `unequal: 0` | +| `tools/bench_cache.py --require-cold` (`2,048` tok) | BF16 / AWQ | First `ttft_s` (4-run median) | `0.627s` (`0.609s`) / `0.830s` (`0.769s`) | `0.605s` (`0.597s`) / `0.788s` (`0.755s`) | `qualified: true`, `cached_tokens: 0` | +| `tools/bench_cache.py --require-cold` (`8,192` tok) | BF16 / AWQ | First `ttft_s` (4-run median) | `2.393s` (`2.377s`) / `2.976s` (`2.946s`) | `2.318s` (`2.337s`) / `2.957s` (`2.897s`) | `qualified: true`, `cached_tokens: 0` | +| `tools/bench_cache.py --require-cold` (`32,768` tok) | BF16 / AWQ | First `ttft_s` (4-run median) | `10.615s` (`10.587s`) / `12.959s` (`12.934s`) | `10.246s` (`10.209s`) / `12.561s` (`12.553s`) | `qualified: true`, `cached_tokens: 0` | + ### Metal kernel contracts - **Apple M5 Ultra (`applegpu_g17`, `tensor_units=true`):** From 40d3cbfe56066e0117ae24565c76579d805b371c Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:37:26 +0100 Subject: [PATCH 354/361] qwen27: guard optional mtp host field in residency helpers --- zig/src/families/qwen27/residency.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index b4bc9e5e94f..eee1205d4b4 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -145,7 +145,7 @@ pub fn hold(h: anytype, io: std.Io) !void { try list.append(h.gpa, d.model.pending); try appendDraft(&d.model.backend, h.gpa, &list); } - if (h.mtp) |m| try m.appendBuffers(h.gpa, &list); + if (@hasField(@TypeOf(h.*), "mtp")) if (h.mtp) |m| try m.appendBuffers(h.gpa, &list); if (h.back.vision) |v| { const held = v.buffers(); try list.appendSlice(h.gpa, &held); @@ -156,7 +156,7 @@ pub fn hold(h: anytype, io: std.Io) !void { h.runner.setResident(r.follow()); setBack(h.back, r.follow()); if (h.draft) |d| d.model.backend.setResident(r.follow()); - if (h.mtp) |m| m.setResident(r.follow()); + if (@hasField(@TypeOf(h.*), "mtp")) if (h.mtp) |m| m.setResident(r.follow()); } h.warm = if (h.resident) |*r| r.target() else .{ .queue = h.model.queue }; } @@ -166,7 +166,7 @@ pub fn drop(h: anytype) void { h.runner.setResident(null); setBack(h.back, null); if (h.draft) |d| d.model.backend.setResident(null); - if (h.mtp) |m| m.setResident(null); + if (@hasField(@TypeOf(h.*), "mtp")) if (h.mtp) |m| m.setResident(null); if (h.resident) |*r| r.deinit(); h.resident = null; h.warm = .{ .queue = h.model.queue }; From ad658c79856783e22617ae19f33c72e3ca4dceb9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:56:48 +0000 Subject: [PATCH 355/361] qwen27: SenseNova-Loop's MTP head beside main's Qwen3.8-27B MTP head, each with its own host field and tap slots Main's 4f8b193b7/090c9c4a9 line serves Qwen3.8-27B's MTP head under --mtp-drafts (Host.mtp: qwen27_mtp.zig's Mtp, its taps through qwen27_features.zig's prepare and rows in the lane backend's table). This PR's head for SenseNova-Loop came with a Host.mtp of its own type and the same two table slots, plus prefill_features. - qwen27_served: the PR's head is Host.sn_mtp; it loads only when --mtp-drafts is off (so at most one head drafts), sets the backend's sn_features before its wrapper takes the backend's table, and frees as the PR placed it. - qwen27_lanes: Metal.sn_features picks the table. With it, the PR's slots (sensenova_features.zig's prefill_features, prepare_features and features); without it, main's table unchanged, so a Qwen3.8-27B prompt under --mtp-drafts keeps main's prompt pass (Drafted streams prompts through prefill_features whenever one is set). - residency: the PR's three resident-set lines name sn_mtp, the type whose buffers they add. Main's Qwen3.8-27B MTP, DFlash2 and plain paths keep main's code; SenseNova-Loop's keeps the PR's. --- zig/src/families/qwen27/residency.zig | 6 +++--- zig/src/native/qwen27_lanes.zig | 6 ++++-- zig/src/native/qwen27_served.zig | 1 + 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index eee1205d4b4..1203c50c7d8 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -145,7 +145,7 @@ pub fn hold(h: anytype, io: std.Io) !void { try list.append(h.gpa, d.model.pending); try appendDraft(&d.model.backend, h.gpa, &list); } - if (@hasField(@TypeOf(h.*), "mtp")) if (h.mtp) |m| try m.appendBuffers(h.gpa, &list); + if (@hasField(@TypeOf(h.*), "sn_mtp")) if (h.sn_mtp) |m| try m.appendBuffers(h.gpa, &list); if (h.back.vision) |v| { const held = v.buffers(); try list.appendSlice(h.gpa, &held); @@ -156,7 +156,7 @@ pub fn hold(h: anytype, io: std.Io) !void { h.runner.setResident(r.follow()); setBack(h.back, r.follow()); if (h.draft) |d| d.model.backend.setResident(r.follow()); - if (@hasField(@TypeOf(h.*), "mtp")) if (h.mtp) |m| m.setResident(r.follow()); + if (@hasField(@TypeOf(h.*), "sn_mtp")) if (h.sn_mtp) |m| m.setResident(r.follow()); } h.warm = if (h.resident) |*r| r.target() else .{ .queue = h.model.queue }; } @@ -166,7 +166,7 @@ pub fn drop(h: anytype) void { h.runner.setResident(null); setBack(h.back, null); if (h.draft) |d| d.model.backend.setResident(null); - if (@hasField(@TypeOf(h.*), "mtp")) if (h.mtp) |m| m.setResident(null); + if (@hasField(@TypeOf(h.*), "sn_mtp")) if (h.sn_mtp) |m| m.setResident(null); if (h.resident) |*r| r.deinit(); h.resident = null; h.warm = .{ .queue = h.model.queue }; diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index db495dc6717..71d33b91bd6 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -99,6 +99,7 @@ pub const Metal = struct { draft_block: @import("qwen27_draft_block.zig").Lone = .{}, // TF_Q27_DFLASH_ADAPTIVE_BLOCK: a lone stream's block rows held_taps: ?mtl.Buffer = null, features_state: @import("sensenova_features.zig").State = .{}, + sn_features: bool = false, // SenseNova-Loop's MTP head in front: its tap slots are sensenova_features.zig's pub fn init(gpa: std.mem.Allocator, runner: *q.decode_round.Runner, draft: ?*Draft) !*Metal { if (runner.slots == 0 or runner.slots > max_streams) return error.TargetBinding; @@ -170,8 +171,9 @@ pub const Metal = struct { pub const refill = slots.refill; pub fn backend(b: *Metal) be.Backend { - const feat = @import("sensenova_features.zig"); - return .{ .ptr = b, .defer_lone_draft = b.runner.slots == 1, .first_before_draft = b.tensor_units, .penalties = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = slots.prefillStep, .cancel_prefill = slots.cancelPrefill, .prefill_features = feat.prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draft_fns.draftFn, .prepare_features = features.prepare, .features = features.rows, .draft_capacity = draft_fns.capacityFn, .probabilities = draft_fns.probabilitiesFn, .tree = draft_fns.treeFn, .release = releaseFn, .reports_fill = true } }; + const feat = @import("sensenova_features.zig"); // SenseNova-Loop's head keeps its own taps; else the 27B's + if (b.sn_features) return .{ .ptr = b, .defer_lone_draft = b.runner.slots == 1, .first_before_draft = b.tensor_units, .penalties = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = slots.prefillStep, .cancel_prefill = slots.cancelPrefill, .prefill_features = feat.prefillFeaturesFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draft_fns.draftFn, .prepare_features = feat.prepareFeaturesFn, .features = feat.featuresFn, .draft_capacity = draft_fns.capacityFn, .probabilities = draft_fns.probabilitiesFn, .tree = draft_fns.treeFn, .release = releaseFn, .reports_fill = true } }; + return .{ .ptr = b, .defer_lone_draft = b.runner.slots == 1, .first_before_draft = b.tensor_units, .penalties = true, .vtable = &.{ .prefill = prefillFn, .prefill_step = slots.prefillStep, .cancel_prefill = slots.cancelPrefill, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draft_fns.draftFn, .prepare_features = features.prepare, .features = features.rows, .draft_capacity = draft_fns.capacityFn, .probabilities = draft_fns.probabilitiesFn, .tree = draft_fns.treeFn, .release = releaseFn, .reports_fill = true } }; } /// What the round loop reads at setup: up to TF_Q27_DRAFT_SLOTS streams draft trees; every stream verifies copies. diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index de34f027439..384d03e10e1 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -381,6 +381,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q holdResident(h, io) catch |err| std.log.warn("qwen27: no residency set ({s}); the first request after an idle second re-wires the weights", .{@errorName(err)}); residency.end(); errdefer q.residency.drop(h); // decided before cache sizing and the worker starts + h.back.sn_features = h.sn_mtp != null; // before a wrapper takes the backend's table if ((h.sn_mtp != null or !o.drafts) and copies_value == null) h.back.copies = false; if (h.sn_mtp) |m| { try m.warmup(io); From ce0c40cd3177a88179c90824d038ae947652df56 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:41:40 +0000 Subject: [PATCH 356/361] qwen27: extract served and lane helpers for file limits --- zig/src/native/qwen27_drafts.zig | 5 +++++ zig/src/native/qwen27_lanes.zig | 4 +--- zig/src/native/qwen27_served.zig | 8 +------- zig/src/native/qwen27_served_startup_test.zig | 11 +++++++++++ 4 files changed, 18 insertions(+), 10 deletions(-) create mode 100644 zig/src/native/qwen27_served_startup_test.zig diff --git a/zig/src/native/qwen27_drafts.zig b/zig/src/native/qwen27_drafts.zig index 946bdf8214e..b1d189f509f 100644 --- a/zig/src/native/qwen27_drafts.zig +++ b/zig/src/native/qwen27_drafts.zig @@ -171,3 +171,8 @@ pub fn treeFn(ptr: *anyopaque, s: *lanes.Stream, gpa: std.mem.Allocator) anyerro errdefer gpa.free(tokens); return .{ .count = @intCast(t.tokens.len), .tokens = tokens, .parents = try gpa.dupe(i32, t.parents) }; } + +/// Streams that draft their own trees in shared rounds, while no more are live (TF_Q27_DRAFT_SLOTS; 1: slot 0 alone). +pub fn draftSlots() !u32 { + return std.math.clamp(try @import("sys").environment.read(u32, "TF_Q27_DRAFT_SLOTS", 8), 1, q.attention_plan.max_streams); +} diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index 71d33b91bd6..b9940aa0710 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -602,6 +602,4 @@ pub const Metal = struct { }; /// Streams that draft their own trees in shared rounds, while no more are live (TF_Q27_DRAFT_SLOTS; 1: slot 0 alone). -pub fn draftSlots() !u32 { - return std.math.clamp(try @import("sys").environment.read(u32, "TF_Q27_DRAFT_SLOTS", 8), 1, max_streams); -} +pub const draftSlots = draft_fns.draftSlots; diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 384d03e10e1..abb2adab967 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -542,15 +542,9 @@ pub fn close(ptr: *anyopaque) void { h.gpa.destroy(h); } -test "qwen27 startup: the adaptive block hooks are analyzed" { - _ = &lb.Metal.init; - _ = &lb.Metal.backend; - _ = &lb.Metal.lone; -} - test { + _ = @import("qwen27_served_startup_test.zig"); _ = @import("qwen27_draft_block.zig"); _ = @import("qwen27_share_fit.zig"); - _ = @import("qwen27_startup_line.zig"); _ = @import("qwen27_served_test.zig"); } diff --git a/zig/src/native/qwen27_served_startup_test.zig b/zig/src/native/qwen27_served_startup_test.zig new file mode 100644 index 00000000000..ab01458a80d --- /dev/null +++ b/zig/src/native/qwen27_served_startup_test.zig @@ -0,0 +1,11 @@ +const lb = @import("qwen27_lanes.zig"); + +test "qwen27 startup: the adaptive block hooks are analyzed" { + _ = &lb.Metal.init; + _ = &lb.Metal.backend; + _ = &lb.Metal.lone; +} + +test { + _ = @import("qwen27_startup_line.zig"); +} From c8ff82763ca3953ee0602dbc2873ea6304502dac Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:14:04 +0100 Subject: [PATCH 357/361] environment: scope TF_MTP_DRAFTS to CUDA and Metal so XPU ignores it --- zig/src/platform/environment.zig | 11 ++++++++--- zig/src/platform/environment_flags.zig | 5 +++++ zig/src/platform/environment_kv_test.zig | 16 +++++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index b2e287bdd65..f56ec64ca08 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -10,6 +10,7 @@ pub const alias_retire = "1.4.0"; pub const Rule = struct { name: [:0]const u8, scope: Scope, + also: ?Scope = null, kind: Kind, forms: []const u8, trim: []const u8 = "", @@ -35,6 +36,10 @@ pub const Rule = struct { flag: ?[]const u8 = null, /// The release from which the server refuses this alias, naming `flag`. retire: ?[]const u8 = null, + + pub fn matches(r: Rule, scope: Scope) bool { + return r.scope == scope or r.also == scope; + } }; pub fn isReal(kind: Kind) bool { @@ -68,7 +73,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_CUDA_SEGMENTS", .scope = .cuda, .kind = .segments, .trim = " ", .forms = "a whole number from 1 to 4, or empty for the default" }, .{ .name = "TF_CUDA_CARVEOUT", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_CUDA_CARVEOUT_MIB", .scope = .cuda, .kind = .mib, .forms = "a positive whole MiB count fitting a native byte size, or empty for 1792 MiB" }, - .{ .name = "TF_MTP_DRAFTS", .scope = .common, .kind = .u32, .forms = "a whole number from 0 to 4294967295 (clamped to the drafter's window)" }, + .{ .name = "TF_MTP_DRAFTS", .scope = .cuda, .also = .metal, .kind = .u32, .forms = "a whole number from 0 to 4294967295 (clamped to the drafter's window)" }, .{ .name = "TF_DSPINE_WINDOW", .scope = .cuda, .kind = .size, .min = 16, .max = 8192, .forms = "a whole row count from 16 to 8192, at most the DSpine drafter's own sliding_window" }, .{ .name = "TF_DRAFT_NODES", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size node count (capped by the drafter's window)" }, .{ .name = "TF_QMMF_HALF_BELOW", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size block count (0 disables half tiles)" }, @@ -508,7 +513,7 @@ pub fn list(name: [:0]const u8) Error!?[:0]const u8 { /// One scope's rules in table order, without allocating: the first malformed value is logged and refused. pub fn checkScope(scope: Scope, environment: anytype) Error!void { - for (rules) |r| if (r.scope == scope and !masked(r, environment)) { + for (rules) |r| if (r.matches(scope) and !masked(r, environment)) { _ = try checked(r.name, environment.get(r.name)); }; } @@ -536,7 +541,7 @@ pub const Flags = @import("environment_flags.zig").Flags; /// The environment is injectable so the actual startup validator runs against host fixtures without a GPU. pub fn refusal(a: std.mem.Allocator, environment: anytype, flags: Flags) !?[]const u8 { for (rules) |r| { - if (!flags.includes(r.scope) or masked(r, environment)) continue; + if (!flags.includesRule(r) or masked(r, environment)) continue; if (std.mem.eql(u8, r.name, "TF_CUDA_DEVICE") and flags.device != null) continue; if (std.mem.eql(u8, r.name, "TF_CUDA_SEGMENTS") and flags.segments != null) continue; if (std.mem.eql(u8, r.name, "TENSORFOLD_PARALLEL") and flags.parallel_named) continue; diff --git a/zig/src/platform/environment_flags.zig b/zig/src/platform/environment_flags.zig index 82009b0c3b8..f7d87a74590 100644 --- a/zig/src/platform/environment_flags.zig +++ b/zig/src/platform/environment_flags.zig @@ -1,5 +1,6 @@ //! Which scopes a startup checks: each backend or feature switch the server or a family entry point turns on. const Scope = @import("environment.zig").Scope; +const Rule = @import("environment.zig").Rule; pub const Flags = struct { cuda: bool = false, @@ -41,4 +42,8 @@ pub const Flags = struct { .hub => f.hub, }; } + + pub fn includesRule(f: Flags, r: Rule) bool { + return f.includes(r.scope) or if (r.also) |s| f.includes(s) else false; + } }; diff --git a/zig/src/platform/environment_kv_test.zig b/zig/src/platform/environment_kv_test.zig index 176b3eaeea2..ba6ed5cc6a6 100644 --- a/zig/src/platform/environment_kv_test.zig +++ b/zig/src/platform/environment_kv_test.zig @@ -1,4 +1,4 @@ -//! The Qwen K/V rows: grow-as-used steps on Metal and device prefix snapshots on CUDA, refused by name at startup. +//! Qwen rows split from environment_test.zig: K/V grow and prefix snapshots, and TF_MTP_DRAFTS's two scopes. const std = @import("std"); const e = @import("environment.zig"); const t = std.testing; @@ -35,3 +35,17 @@ test "environment: TF_QWEN_KV_SNAPSHOT_GPU is exact 0 or 1 on CUDA, blank as uns try t.expect(std.mem.indexOf(u8, why, e.rule("TF_QWEN_KV_SNAPSHOT_GPU").forms) != null); try t.expect(try e.refusal(t.allocator, One{ .name = "TF_QWEN_KV_SNAPSHOT_GPU", .raw = "true" }, .{ .metal = true }) == null); } + +test "environment: TF_MTP_DRAFTS is checked on CUDA and Metal and ignored on XPU" { + const env: One = .{ .name = "TF_MTP_DRAFTS", .raw = "bad" }; + for ([_]e.Flags{ .{ .cuda = true }, .{ .metal = true } }) |flags| { + const why = (try e.refusal(t.allocator, env, flags)).?; + defer t.allocator.free(why); + try t.expect(std.mem.indexOf(u8, why, "TF_MTP_DRAFTS") != null); + } + try t.expect((try e.refusal(t.allocator, env, .{ .xpu = true })) == null); + try t.expect((try e.refusal(t.allocator, env, .{})) == null); + try t.expectError(error.InvalidEnvironment, e.checkScope(.cuda, env)); + try t.expectError(error.InvalidEnvironment, e.checkScope(.metal, env)); + try e.checkScope(.xpu, env); +} From 4619b5178f1a74eecc9b92fead3ba4cd60c97532 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:59:15 +0000 Subject: [PATCH 358/361] qwen27: keep qwen27_lanes.zig within 600 lines after the rebase onto main Main's growth beside this series' SenseNova-Loop lane changes put the file at 605 lines. The tail encoder's choice becomes one if/else line and the argmax tail's body one call; no behaviour changes. --- zig/src/native/qwen27_lanes.zig | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index b9940aa0710..c64985509f3 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -297,8 +297,7 @@ pub const Metal = struct { } fn encodeArgmaxTail(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { - const b = self(ptr); - try b.encodeArgmaxRange(e, 0, b.rows); + try self(ptr).encodeArgmaxRange(e, 0, self(ptr).rows); } /// Rows [first, first + rows)'s greedy picks into `picks` at the same rows: one command buffer and one wait. @@ -506,11 +505,7 @@ pub const Metal = struct { for (windows) |w| greedy = greedy or (w.stream.sampling == null and w.masks.len == 0 and !w.stream.penalties.active()); const tail_argmax = r.model.config.looped and !fused and greedy and r.reduce == null; std.debug.assert(r.tail == null); - if (fused) { - r.tail = .{ .ptr = b, .encode = @import("qwen27_keep.zig").encodeTail }; - } else if (tail_argmax) { - r.tail = .{ .ptr = b, .encode = encodeArgmaxTail }; - } + if (fused) r.tail = .{ .ptr = b, .encode = @import("qwen27_keep.zig").encodeTail } else if (tail_argmax) r.tail = .{ .ptr = b, .encode = encodeArgmaxTail }; defer r.tail = null; const before = r.gpu_seconds; if (plain) try r.advance(&b.round.?, .all) else try r.verifyHead(&b.round.?, .all); From 95dcf043ef535cc8e7149b1d2453e6430e876930 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:53:43 +0000 Subject: [PATCH 359/361] tests: re-pin four Qwen27 serving sources after the rebase onto main's solo prompt rows attention.zig, attention_plan.zig, decode_round.zig and qwen27_slots.zig now carry main's solo prompt rows with this stack's SenseNova-Loop changes; their pins are regenerated from the merged files, main's notes kept. --- zig/tests/fixtures/gradient-serving.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index c94898230ca..c81c2754012 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -167,9 +167,9 @@ zig/src/families/flashnext/cuda_round_graph.zig 7fa3a54e93c81de36cf3962d0a68eb72 zig/src/families/flashnext/cuda_rows.zig 735fc8915036e47d09f533f4e5948e5fc4b61556172ebe2c6bfdaad3e0373216 raw main dfd9ac5ef4 (#2585: TF_FLASHNEXT_* read through platform/environment.zig, malformed text refused at startup; valid values keep their meaning) zig/src/families/flashnext/cuda_select_main.zig 5c012c2d59fa6dd573424fce7b6d8b162a06cb9f6103530a0fc0b03dbdb17bd3 raw zig/src/families/flashnext/cuda_snap.zig bbc66ed7e1aed820b4b60c148b1bbe47b2a5c7e7240c7da7f0bd8504080a6b56 raw main 4f6017ced (prompt cache marks kept inside the pass), #1953: the prompt cache ladder's values -zig/src/families/qwen27/attention.zig ef533e2d07f0b38bd035cc79f282a621ae2b8604ef0f2d0436935b85e45fb55b raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention.zig 8847e1519cf981b700996b349f8d3b91732fe45392ca734a9f72286e85071c52 raw #2916 (solo prompt frames; decode and shared limits retained); #3868 (SenseNova-Loop-9B, its wide prompt on the solo plan) zig/src/families/qwen27/attention_memory.zig 49b9a2643b1499d26cd3d41066ab77351eb6a0258fae87eb880503ccd5c5ecec raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/attention_plan.zig 898964a99410620766416c5d5a350ab96061e9d2883354875f7da9e431a9ddc4 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/families/qwen27/decode_round.zig 67ef8d3358e5239943ae80fc67bc431bf40d119206df1cc6ab9fe0505e064cde raw main 1eed88bb09 (public attentionPlan and lane-core Drafter/tail state retained), #2916 (solo prompt frames; decode and shared limits retained) +zig/src/families/qwen27/attention_plan.zig e64049d6bc0e5d252a6503d8023ad9ee32128dcabf38b58d2da2b4527706f097 raw #2916 (solo prompt frames; decode and shared limits retained); #3868 (SenseNova-Loop-9B, its wide prompt on the solo plan) +zig/src/families/qwen27/decode_round.zig ff0338e174cdd681a92cb8f56fbfd0baf260eb816187817eb3c27f73b8cbc81a raw main 1eed88bb09 (public attentionPlan and lane-core Drafter/tail state retained), #2916 (solo prompt frames; decode and shared limits retained); #3868 (SenseNova-Loop-9B, its wide prompt on the solo plan) zig/src/native/qwen27_prompt_rows.zig 5e137f7966c0b725994bc613266be2d83a47800b211dcb7b742455066ed33887 raw #2916 (solo prompt frames; decode and shared limits retained) -zig/src/native/qwen27_slots.zig c98070c752614213466f8e5a5c431b25ba1db7f2b4dfb686569206005342c247 raw #2916 (solo prompt frames; decode and shared limits retained) +zig/src/native/qwen27_slots.zig e19b8a344f4ed9280b11d8e9982019758139d05f21358db036b4ee68c312db06 raw #2916 (solo prompt frames; decode and shared limits retained); #3868 (SenseNova-Loop-9B, its wide prompt on the solo plan) From 94e0f2dc274f1cbd63bde7cc343e47babb87cff3 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:53:28 +0000 Subject: [PATCH 360/361] changelog: #3868 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d9e3b6585d6..7741a70c42a 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 +- Metal: SenseNova-Loop-9B is served natively through the qwen27 lane backend in BF16 and AWQ 4-bit (group size 128), with its looped 56-step schedule, two-stream mHC, 512K YaRN context and vision, and drafts with its published `mtp.safetensors` (#3868, carries #3859, fixes #3781). Thanks @gilby. + - ZONOS3 Mini text to speech on CUDA: named voices, reference codes and cloning from a clip, with frame budgets checked at load; serving checkpoints other than ZONOS3 is unchanged (#3720). - Flash Next on CUDA: on one GPU, a prompt chunk before the last skips its last layer's MLP stream and experts, which nothing reads; tokens unchanged, and tensor-parallel passes run as before (#4885). From ae78e0c70985bceb647c902b56cdef52434ad461 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:07:26 +0800 Subject: [PATCH 361/361] test: bound the startup-tail log check on the deadline, not the clock --- zig/src/server/benchmark_server_log_test.zig | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/zig/src/server/benchmark_server_log_test.zig b/zig/src/server/benchmark_server_log_test.zig index 53ddd2a4ca2..fcee98a231f 100644 --- a/zig/src/server/benchmark_server_log_test.zig +++ b/zig/src/server/benchmark_server_log_test.zig @@ -64,18 +64,16 @@ test "managed log: an exited child's last diagnostic without a newline reaches i defer tmp.cleanup(); var s = try Setup.init(a, &tmp); for ([_][]const u8{ - "sleep 8 & printf 'loading\\nerror: bad model child-log-key'; exit 3", // a descendant keeps the pipe open + "sleep 30 & printf 'loading\\nerror: bad model child-log-key'; exit 3", // a descendant keeps the pipe open "printf 'loading\\nerror: bad model child-log-key'; exit 3", // ordinary end of stream }) |script| { var problem: []const u8 = ""; var tail: []const []const u8 = &.{}; const argv = try a.dupe([]const u8, &.{ "/bin/sh", "-c", script }); - const t0 = std.Io.Clock.awake.now(std.testing.io); try none(try server.Managed.start(a, std.testing.io, &s.env, plan, .{ .startup_timeout_s = 10, .bench_dir = s.bench, .argv = argv, .tail = &tail, .key = "child-log-key" }, &problem)); + // bounded: the descendant outlives the startup deadline, so waiting for it would read timed out try std.testing.expectEqualStrings("Benchmark server exited during startup; check the checkpoint and backend toolchain", problem); try lines(&.{"error: bad model [redacted]"}, tail); - const took = t0.durationTo(std.Io.Clock.awake.now(std.testing.io)).toMilliseconds(); - try std.testing.expect(took < 7000); // bounded: no wait for the descendant } }