diff --git a/CHANGELOG.md b/CHANGELOG.md index d8a4782f7e3..77c6f4a048c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - CUDA: a host guard now fails any programmatic dependent launch of a kernel without its dependency wait, and DeepSeek's generic x3ld kernels wait first (#PR, after #5308). - CI: the environment-names check passes again: the computed trace lookups, two new variables and the names `--confidential` refuses by presence are registered (#5373). Thanks @kotevcode. +- Metal: guard Inkling 2 and LFM2 generated libraries against repeated or conflicting threadgroup-size attributes. - CUDA: Qwen with `--kv-cache fp8` gives the same tokens with the default `TF_QWEN_PDL` on as with it off; the FP8 RoPE kernel no longer starts before its head norms finish (#PR, fixes #5308). Thanks to @jojomondag for the report. diff --git a/zig/build/inkling2_host.zig b/zig/build/inkling2_host.zig index 794a4bdce82..59a57748dea 100644 --- a/zig/build/inkling2_host.zig +++ b/zig/build/inkling2_host.zig @@ -12,7 +12,6 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin core.addImport("living", b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true })); m.addImport("core", core); m.addImport("template", b.createModule(.{ .root_source_file = b.path(dir ++ "template/template.zig"), .target = target, .optimize = optimize, .link_libc = true })); - m.addImport("inkling2_metal", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize })); const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, .optimize = optimize }); if (target.result.os.tag == .macos) { metal.linkFramework("Metal", .{}); @@ -21,6 +20,7 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin } m.addImport("metal", metal); m.addImport("kernel_sources", b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = target, .optimize = optimize })); + m.addImport("inkling2_metal", @import("inkling2_sources.zig").module(b, target, optimize, m.import_table.get("kernel_sources").?)); const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); inkling2_metal_ref.addImport("metal", m.import_table.get("metal").?); m.addImport("inkling2_metal_ref", inkling2_metal_ref); @@ -34,6 +34,16 @@ fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin } pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Build.Step) void { + const sources = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/metal_threadgroup_source_host.zig"), + .target = target, + .optimize = .Debug, + }) })); + b.step("test-metal-threadgroup-source-host", "Complete Inkling and masked-prompt Metal sources have one reservation per declaration").dependOn(&sources.step); + test_step.dependOn(&sources.step); + const owners = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .debug, "zig/inkling2_source_owners_host.zig") })); + b.step("test-inkling2-source-owners-host", "Family and legacy Metal exports share one checked source owner without an SDK").dependOn(&owners.step); + test_step.dependOn(&owners.step); const run = b.addRunArtifact(b.addTest(.{ .root_module = module(b, target, .Debug, "zig/src/families/inkling2/host_test.zig") })); 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); diff --git a/zig/build/inkling2_sources.zig b/zig/build/inkling2_sources.zig new file mode 100644 index 00000000000..804ac1ed430 --- /dev/null +++ b/zig/build/inkling2_sources.zig @@ -0,0 +1,17 @@ +//! One source owner per compilation, shared by the family facade and legacy consumers. +const std = @import("std"); +pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, owner: *std.Build.Module) *std.Build.Module { + return b.createModule(.{ + .root_source_file = b.path("zig/kernels/metal/inkling2_facade.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "kernel_sources", .module = owner }}, + }); +} +pub fn standalone(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + return module(b, target, optimize, b.createModule(.{ + .root_source_file = b.path("zig/kernels/metal/sources.zig"), + .target = target, + .optimize = optimize, + })); +} diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 3d494cdb256..855fa45d137 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -34,7 +34,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { .optimize = .debug, .imports = &.{ .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, - .{ .name = "inkling2_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig") }) }, + .{ .name = "inkling2_metal", .module = @import("inkling2_sources.zig").standalone(b, b.graph.host, .debug) }, .{ .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") }) }, @@ -79,7 +79,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { .optimize = .debug, .imports = &.{ .{ .name = "contract", .module = module(b, b.graph.host, .debug) }, - .{ .name = "inkling2_metal", .module = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig") }) }, + .{ .name = "inkling2_metal", .module = @import("inkling2_sources.zig").standalone(b, b.graph.host, .debug) }, .{ .name = "metal", .module = mapping_stub }, .{ .name = "tensorfold", .module = mapping_tf }, .{ .name = "kernel_sources", .module = mapping_stub }, diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 277ff88b8eb..9947997d4b4 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -442,7 +442,7 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); fabric.addImport("verbs", @import("tp.zig").verbsModule(b, target, optimize)); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); - const inkling2_metal = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/inkling2_sources.zig"), .target = target, .optimize = optimize }); + const inkling2_metal = @import("inkling2_sources.zig").module(b, target, optimize, sources); const inkling2_metal_ref = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/ref.zig"), .target = target, .optimize = optimize }); inkling2_metal_ref.addImport("metal", metal); const inkling2_glue_plan = b.createModule(.{ .root_source_file = b.path("zig/src/families/inkling2/metal/glue_plan.zig"), .target = target, .optimize = optimize }); diff --git a/zig/inkling2_source_owners_host.zig b/zig/inkling2_source_owners_host.zig new file mode 100644 index 00000000000..713b9026398 --- /dev/null +++ b/zig/inkling2_source_owners_host.zig @@ -0,0 +1,33 @@ +//! Independent byte identity receipt against the supplied main's assembled libraries. +const std = @import("std"); +const ink = @import("inkling2_metal"); +const ks = @import("kernel_sources"); +fn equal(source: []const u8, bytes: usize, expected: []const u8) !void { + var hash: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(source, &hash, .{}); + try std.testing.expectEqual(bytes, source.len); + try std.testing.expectEqualStrings(expected, &std.fmt.bytesToHex(hash, .lower)); +} +test "every current generated Inkling and LFM2 library is byte-identical to supplied main" { + try equal(ink.attention, 25176, "446df33916bbd384fb2dec029d0dc2c34acd068047eb6a6b7dca778aaf41345a"); + try equal(ink.prompt_attention, 36507, "2e690463846a822b5c087139eaa3dfbc9a980caa7753e36cb3562afc88a17abd"); + try equal(ink.prompt_attention_pre_m5, 36531, "28b71a25e1aab7174cf121f3ae05f84afb165970443a91f6978c06628630935b"); + try equal(ink.glue, 40891, "d38acec59342de2cf8f69824eb7b73c633b56fad03fdaa6cb1029d99c05ced2e"); + try equal(ink.experts, 36126, "9a59ac2de326eb3fcf0fd832f5e1923272f099505be165a06611a2e32e6e3bf6"); + try equal(ink.experts_mma, 48056, "4448aba61d8e99534d2c2c005fee440aa74f4d5098e57f4b2a1588ed22096b36"); + try equal(ink.dense_mma, 5389, "6d0b015dd66035efbd110ae4d8dd690ca677ed9c500a83837aee7269161b334a"); + try equal(ink.dense_tiled, 4324, "cdddebd86d265d9a79fd93b80894266750ca267e7ffeb76c481e6e73ab03c3ee"); + try equal(ink.loop, 18092, "7c721243e573ffd29ae6c3a594a193f760f8ce0672446e0c9b590842a3ef3793"); + try equal(ink.loop_mma, 23241, "bcb090e30b221ce5978dcc9ec28d8b163d1665b264543cfee848cd4ffb95c095"); + try equal(ink.runtime, 7440, "2ce8a74513b74e4bd9ffb3ab2b4e27268a6297ade723fbaa41813026d8f9cfad"); + try equal(ink.tree, 4183, "03cd2b1384788b46a6de79aacc8edcc854f9a978c81ac3cd2336ae979aab7d69"); + try equal(ink.inkling2_dspark, 34958, "280e181c0ea975da90252417352bd2cbbde2a653951e4e12ecb3dc436b882cb9"); + try equal(ink.inkling2_dspark_pre_m5, 34982, "ed6e11de7d7f14e4821132f3598c7fee0c63f1b211682726911769b2cd042932"); + try equal(ink.vision, 40124, "f3bccee002e5b0d7572dc25316538b384e397a4f5dba3f4ac99839e434d848c6"); + try equal(ink.inkling2_dflash2, 22370, "74a5e9a2324b5875a754e931243203bf19b426758fe6a2a524c62f6809f96dbd"); + try equal(ink.sample, 10443, "747835e5a84d76d7d838958e2677aa5af62e4ebf2e612520bfc759e967d44c81"); + try equal(ks.inkling2_glue, 26246, "0d1f7bb8d2721671eb744a52a39e1e9c26dcb866a026ee1f9c5785ec7b8c1d06"); + try equal(ks.inkling2_sample, 10443, "747835e5a84d76d7d838958e2677aa5af62e4ebf2e612520bfc759e967d44c81"); + try equal(ks.lfm2_prompt_masked.source, 16617, "5b5edd3224410f5bebb192cb2781692e21a17baad26be73b8e842f2bee92b0f0"); + try equal(ks.inkling2_runtime, 7440, "2ce8a74513b74e4bd9ffb3ab2b4e27268a6297ade723fbaa41813026d8f9cfad"); +} diff --git a/zig/kernels/metal/inkling2/attention_sources.zig b/zig/kernels/metal/inkling2/attention_sources.zig index 1aac8a107e1..965b629dca6 100644 --- a/zig/kernels/metal/inkling2/attention_sources.zig +++ b/zig/kernels/metal/inkling2/attention_sources.zig @@ -1,5 +1,6 @@ //! Shader texts; the prompt's fragment helpers are inline so both chip paths use the same resolver. +const guard = @import("../threadgroup_source.zig"); -pub const attention = @embedFile("attention.metal"); -pub const prompt_attention = @embedFile("../nax.h") ++ @embedFile("prompt_attention.metal"); -pub const prompt_attention_pre_m5 = "#define TF_SIMD_FRAGS 1\n" ++ prompt_attention; +pub const attention = guard.normalize(@embedFile("attention.metal")); +pub const prompt_attention = guard.normalize(@embedFile("../nax.h") ++ @embedFile("prompt_attention.metal")); +pub const prompt_attention_pre_m5 = guard.normalize("#define TF_SIMD_FRAGS 1\n" ++ prompt_attention); diff --git a/zig/kernels/metal/inkling2/dense_sources.zig b/zig/kernels/metal/inkling2/dense_sources.zig index faef6cd6c4a..33cade07dd1 100644 --- a/zig/kernels/metal/inkling2/dense_sources.zig +++ b/zig/kernels/metal/inkling2/dense_sources.zig @@ -1,3 +1,4 @@ //! Inkling 2 Mini's multi-row bf16 prompt projections: simdgroup matrices (pre-M5) and register-tiled (M5+). -pub const dense_mma = @embedFile("dense_mma.metal"); -pub const dense_tiled = @embedFile("dense_tiled.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const dense_mma = guard.normalize(@embedFile("dense_mma.metal")); +pub const dense_tiled = guard.normalize(@embedFile("dense_tiled.metal")); diff --git a/zig/kernels/metal/inkling2/dflash2_sources.zig b/zig/kernels/metal/inkling2/dflash2_sources.zig index 2276ea4fff3..8fb8b40ac2b 100644 --- a/zig/kernels/metal/inkling2/dflash2_sources.zig +++ b/zig/kernels/metal/inkling2/dflash2_sources.zig @@ -1,3 +1,4 @@ //! Mini DFlash 2 drafter shader source. +const guard = @import("../threadgroup_source.zig"); -pub const dflash2 = @embedFile("dflash2.metal"); +pub const dflash2 = guard.normalize(@embedFile("dflash2.metal")); diff --git a/zig/kernels/metal/inkling2/dspark_sources.zig b/zig/kernels/metal/inkling2/dspark_sources.zig index cc4f5834469..a0489ab4311 100644 --- a/zig/kernels/metal/inkling2/dspark_sources.zig +++ b/zig/kernels/metal/inkling2/dspark_sources.zig @@ -1,4 +1,5 @@ //! Mini DSpark's arithmetic shader and its twelve Metal library entry points. +const guard = @import("../threadgroup_source.zig"); -pub const dspark = @embedFile("dspark.metal"); -pub const dspark_pre_m5 = "#define TF_SIMD_FRAGS 1\n" ++ dspark; +pub const dspark = guard.normalize(@embedFile("dspark.metal")); +pub const dspark_pre_m5 = guard.normalize("#define TF_SIMD_FRAGS 1\n" ++ dspark); diff --git a/zig/kernels/metal/inkling2/experts_sources.zig b/zig/kernels/metal/inkling2/experts_sources.zig index 14a28fceb2a..006d1b0f0f0 100644 --- a/zig/kernels/metal/inkling2/experts_sources.zig +++ b/zig/kernels/metal/inkling2/experts_sources.zig @@ -1,4 +1,5 @@ //! Inkling 2 Mini's M3 packed-weight expert kernels; activations stay BF16 throughout. -pub const experts = @embedFile("experts.metal") ++ "\n" ++ @embedFile("experts_grouped.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const experts = guard.normalize(@embedFile("experts.metal") ++ "\n" ++ @embedFile("experts_grouped.metal")); /// The same products on simdgroup matrices, for GPUs without tensor units: after the decode helpers above. -pub const experts_mma = experts ++ @embedFile("experts_mma.metal"); +pub const experts_mma = guard.normalize(experts ++ @embedFile("experts_mma.metal")); diff --git a/zig/kernels/metal/inkling2/glue_sources.zig b/zig/kernels/metal/inkling2/glue_sources.zig index 57b8a25b46b..f40694e89f9 100644 --- a/zig/kernels/metal/inkling2/glue_sources.zig +++ b/zig/kernels/metal/inkling2/glue_sources.zig @@ -1,2 +1,3 @@ //! Inkling 2 Mini's glue, paired KV convolution, fused norms, segmented convs, and split router sources. -pub const glue = @embedFile("glue.metal") ++ "\n" ++ @embedFile("glue_kv_conv.metal") ++ "\n" ++ @embedFile("glue_norm.metal") ++ "\n" ++ @embedFile("glue_split.metal") ++ "\n" ++ @embedFile("glue_conv_segs.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const glue = guard.normalize(@embedFile("glue.metal") ++ "\n" ++ @embedFile("glue_kv_conv.metal") ++ "\n" ++ @embedFile("glue_norm.metal") ++ "\n" ++ @embedFile("glue_split.metal") ++ "\n" ++ @embedFile("glue_conv_segs.metal")); diff --git a/zig/kernels/metal/inkling2/loop_sources.zig b/zig/kernels/metal/inkling2/loop_sources.zig index 80238abf137..e1fae0e8d1f 100644 --- a/zig/kernels/metal/inkling2/loop_sources.zig +++ b/zig/kernels/metal/inkling2/loop_sources.zig @@ -1,4 +1,5 @@ //! 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") ++ "\n" ++ @embedFile("loop_roles.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const loop = guard.normalize(@embedFile("loop.metal") ++ "\n" ++ @embedFile("loop_split.metal") ++ "\n" ++ @embedFile("loop_roles.metal")); /// The gates on simdgroup matrices, for GPUs without tensor units: after the loop kernels, whose constants it uses. -pub const loop_mma = loop ++ @embedFile("loop_mma.metal"); +pub const loop_mma = guard.normalize(loop ++ @embedFile("loop_mma.metal")); diff --git a/zig/kernels/metal/inkling2/runtime_sources.zig b/zig/kernels/metal/inkling2/runtime_sources.zig index 5f3a2e70e63..6e4eafbb0c2 100644 --- a/zig/kernels/metal/inkling2/runtime_sources.zig +++ b/zig/kernels/metal/inkling2/runtime_sources.zig @@ -1,2 +1,3 @@ //! Inkling 2 Mini's copy, widening and partial-residual shaders. -pub const runtime = @embedFile("runtime.metal") ++ "\n" ++ @embedFile("runtime_conv.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const runtime = guard.normalize(@embedFile("runtime.metal") ++ "\n" ++ @embedFile("runtime_conv.metal")); diff --git a/zig/kernels/metal/inkling2/sample_sources.zig b/zig/kernels/metal/inkling2/sample_sources.zig index 42d31ab4e0c..c5fb2df9d72 100644 --- a/zig/kernels/metal/inkling2/sample_sources.zig +++ b/zig/kernels/metal/inkling2/sample_sources.zig @@ -1,2 +1,3 @@ //! Inkling 2 Mini f32 top-k rule samplers matching lanes.gpu_rule.sample. -pub const sample = @embedFile("sample.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const sample = guard.normalize(@embedFile("sample.metal")); diff --git a/zig/kernels/metal/inkling2/tree_sources.zig b/zig/kernels/metal/inkling2/tree_sources.zig index 605f0b0c150..277f8cf60eb 100644 --- a/zig/kernels/metal/inkling2/tree_sources.zig +++ b/zig/kernels/metal/inkling2/tree_sources.zig @@ -1,2 +1,3 @@ //! Inkling 2 Mini's tree-verify convolution and surviving-path compaction shaders. -pub const tree = @embedFile("tree.metal"); +const guard = @import("../threadgroup_source.zig"); +pub const tree = guard.normalize(@embedFile("tree.metal")); diff --git a/zig/kernels/metal/inkling2/vision_sources.zig b/zig/kernels/metal/inkling2/vision_sources.zig index 66b3903c5d1..3051fd6852d 100644 --- a/zig/kernels/metal/inkling2/vision_sources.zig +++ b/zig/kernels/metal/inkling2/vision_sources.zig @@ -1,4 +1,5 @@ //! Inkling 2's image tower: the prefill GEMM template, the towers' shared glue, the tower's GEMMs and its glue kernels. +const guard = @import("../threadgroup_source.zig"); -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"); +pub const vision = guard.normalize(@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_facade.zig b/zig/kernels/metal/inkling2_facade.zig new file mode 100644 index 00000000000..5c9cf1935ea --- /dev/null +++ b/zig/kernels/metal/inkling2_facade.zig @@ -0,0 +1,20 @@ +//! Family exports share the checked shader texts owned by kernel_sources. +const owner = @import("kernel_sources").inkling2; + +pub const attention = owner.attention; +pub const prompt_attention = owner.prompt_attention; +pub const prompt_attention_pre_m5 = owner.prompt_attention_pre_m5; +pub const glue = owner.glue; +pub const experts = owner.experts; +pub const experts_mma = owner.experts_mma; +pub const dense_mma = owner.dense_mma; +pub const dense_tiled = owner.dense_tiled; +pub const loop = owner.loop; +pub const loop_mma = owner.loop_mma; +pub const runtime = owner.runtime; +pub const tree = owner.tree; +pub const inkling2_dspark = owner.inkling2_dspark; +pub const inkling2_dspark_pre_m5 = owner.inkling2_dspark_pre_m5; +pub const vision = owner.vision; +pub const inkling2_dflash2 = owner.inkling2_dflash2; +pub const sample = owner.sample; diff --git a/zig/kernels/metal/lfm2/prompt_masked.zig b/zig/kernels/metal/lfm2/prompt_masked.zig index e3cf9bc3900..f2d31cf0bd9 100644 --- a/zig/kernels/metal/lfm2/prompt_masked.zig +++ b/zig/kernels/metal/lfm2/prompt_masked.zig @@ -1,14 +1,21 @@ //! Exceptional twin of the original prompt entry, in its own library. Finite source stays unchanged. const std = @import("std"); +const guard = @import("../threadgroup_source.zig"); pub const original = @embedFile("lfm2_attn_nax.metal"); -pub const source = blk: { - @setEvalBranchQuota(20_000_000); - const begin = std.mem.indexOf(u8, original, "[[kernel]]").?; - var body = edit(original[begin..], "void lfm2_attn_nax(", "void lfm2_attn_masked("); - body = edit(body, "mma_16x32(o[0], o[1], pb[h], v0, v1);", "lfm2_masked_pv(o[0], o[1], pb[h], v0, v1, home, j0 + 16 * h, count0, count1);"); - body = edit(body, "mma_16x32(o[2], o[3], pb[h], v2, v3);", "lfm2_masked_pv(o[2], o[3], pb[h], v2, v3, home, j0 + 16 * h, count0, count1);"); - break :blk original ++ @embedFile("prompt_masked.h") ++ "[[max_total_threads_per_threadgroup(128)]]\n" ++ body ++ @embedFile("../core/prompt_pick.metal") ++ @embedFile("prompt_pick.metal"); -}; +pub const source = build(original); + +pub fn build(comptime input: []const u8) []const u8 { + return comptime blk: { + @setEvalBranchQuota(20_000_000); + const begin = std.mem.indexOf(u8, input, "[[kernel]]").?; + const reservation = "[[max_total_threads_per_threadgroup(128)]]\n"; + _ = guard.normalize(input[0..begin] ++ reservation ++ input[begin..]); + var body = edit(input[begin..], "void lfm2_attn_nax(", "void lfm2_attn_masked("); + body = edit(body, "mma_16x32(o[0], o[1], pb[h], v0, v1);", "lfm2_masked_pv(o[0], o[1], pb[h], v0, v1, home, j0 + 16 * h, count0, count1);"); + body = edit(body, "mma_16x32(o[2], o[3], pb[h], v2, v3);", "lfm2_masked_pv(o[2], o[3], pb[h], v2, v3, home, j0 + 16 * h, count0, count1);"); + break :blk guard.normalize(input ++ @embedFile("prompt_masked.h") ++ reservation ++ body ++ @embedFile("../core/prompt_pick.metal") ++ @embedFile("prompt_pick.metal")); + }; +} fn edit(comptime text: []const u8, comptime from: []const u8, comptime to: []const u8) []const u8 { if (std.mem.count(u8, text, from) != 1) @compileError("LFM2 masked prompt source no longer matches"); const at = std.mem.indexOf(u8, text, from).?; diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index b0b7fd7cb24..070d7acdfbd 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -361,11 +361,14 @@ pub const glm_draft_follow = @embedFile("glm_draft_follow.metal"); /// GLM-5.3-Flash's TFQ3 (2D-AffineCoset/half4) decode and prefill kernels. pub const glm_tfq3 = @import("glm_tfq3/sources.zig"); +/// The shared source owner; family modules expose these texts through a named import. +pub const inkling2 = @import("inkling2_sources.zig"); + /// Inkling 2 Mini's glue and sampling helpers, compiled by its model and kernel contract. -pub const inkling2_glue = @embedFile("inkling2/glue.metal"); -pub const inkling2_sample = @embedFile("inkling2/sample.metal"); +pub const inkling2_glue = @import("threadgroup_source.zig").normalize(@embedFile("inkling2/glue.metal")); +pub const inkling2_sample = inkling2.sample; /// Inkling 2 Mini's runtime helpers, the exact source compiled by its model and kernel contract. -pub const inkling2_runtime = @embedFile("inkling2/runtime.metal") ++ "\n" ++ @embedFile("inkling2/runtime_conv.metal"); +pub const inkling2_runtime = inkling2.runtime; /// Fused DFlash2 decode kernels: K-norm+RoPE+append, QKV prep, and dynamic-conv2+residual+RMSNorm. pub const glm_dflash_opt = @embedFile("glm_dflash_opt.metal"); diff --git a/zig/kernels/metal/threadgroup_source.zig b/zig/kernels/metal/threadgroup_source.zig new file mode 100644 index 00000000000..ba6bbc6e783 --- /dev/null +++ b/zig/kernels/metal/threadgroup_source.zig @@ -0,0 +1,108 @@ +//! Keep one equal threadgroup reservation per declaration and refuse conflicting reservations. +const std = @import("std"); +const name = "max_total_threads_per_threadgroup"; +const Reservation = struct { value: []const u8, start: usize, end: usize, standalone: bool }; + +fn skipQuoted(source: []const u8, start: usize) usize { + var i = start + 1; + while (i < source.len) : (i += 1) { + if (source[i] == '\\') i += @intFromBool(i + 1 < source.len) else if (source[i] == source[start]) return i + 1; + } + return source.len; +} + +fn same(a: []const u8, b: []const u8) bool { + var i: usize = 0; + var j: usize = 0; + while (true) { + while (i < a.len and std.ascii.isWhitespace(a[i])) : (i += 1) {} + while (j < b.len and std.ascii.isWhitespace(b[j])) : (j += 1) {} + if (i == a.len or j == b.len) return i == a.len and j == b.len; + if (a[i] != b[j]) return false; + i += 1; + j += 1; + } +} + +fn append(out: []u8, written: *usize, bytes: []const u8) void { + @memcpy(out[written.*..][0..bytes.len], bytes); + written.* += bytes.len; +} + +/// Only duplicate attribute spans are removed; comments, declarations and kernel bodies retain their bytes. +pub fn write(source: []const u8, out: []u8) !usize { + if (out.len < source.len) return error.NoSpaceLeft; + var cursor: usize = 0; + var copied: usize = 0; + var written: usize = 0; + var previous: ?Reservation = null; + while (cursor < source.len) { + if (std.mem.startsWith(u8, source[cursor..], "//")) { + cursor = if (std.mem.indexOfScalarPos(u8, source, cursor, '\n')) |i| i + 1 else source.len; + continue; + } + if (std.mem.startsWith(u8, source[cursor..], "/" ++ "*")) { + cursor = (std.mem.indexOfPos(u8, source, cursor + 2, "*/") orelse return error.BadMetalSource) + 2; + continue; + } + if (source[cursor] == '"' or source[cursor] == '\'') { + cursor = skipQuoted(source, cursor); + continue; + } + if (std.mem.startsWith(u8, source[cursor..], "[[")) { + const end = (std.mem.indexOfPos(u8, source, cursor + 2, "]]") orelse return error.BadMetalSource) + 2; + const attrs = source[cursor + 2 .. end - 2]; + const at = std.mem.indexOf(u8, attrs, name) orelse { + cursor = end; + continue; + }; + if (std.mem.count(u8, attrs, name) != 1) return error.RepeatedCombinedReservation; + var open = at + name.len; + while (open < attrs.len and std.ascii.isWhitespace(attrs[open])) : (open += 1) {} + if (open == attrs.len or attrs[open] != '(') return error.BadMetalSource; + var close = open + 1; + var depth: usize = 1; + while (close < attrs.len and depth != 0) : (close += 1) { + if (attrs[close] == '(') depth += 1; + if (attrs[close] == ')') depth -= 1; + } + if (depth != 0 or close == open + 2) return error.BadMetalSource; + const value = attrs[open + 1 .. close - 1]; + const standalone = same(attrs, attrs[at..close]); + const stop = end + @intFromBool(end < source.len and source[end] == '\n'); + append(out, &written, source[copied..cursor]); + if (previous) |p| { + if (!same(p.value, value)) return error.ConflictingThreadgroupReservation; + if (standalone) { + copied = stop; + cursor = stop; + continue; + } + if (!p.standalone) return error.RepeatedCombinedReservation; + std.mem.copyForwards(u8, out[p.start..], out[p.end..written]); + written -= p.end - p.start; + } + const start = written; + append(out, &written, source[cursor..stop]); + previous = .{ .value = value, .start = start, .end = written, .standalone = standalone }; + copied = stop; + cursor = stop; + continue; + } + if (std.mem.indexOfScalar(u8, "{};", source[cursor]) != null) previous = null; + cursor += 1; + } + append(out, &written, source[copied..]); + return written; +} + +/// Source assembly fails at build time when reservations disagree, before any runtime Metal compiler is called. +pub fn normalize(comptime source: []const u8) []const u8 { + return comptime blk: { + @setEvalBranchQuota(20_000_000); + var out: [source.len]u8 = undefined; + const len = write(source, &out) catch |err| @compileError("Metal source: " ++ @errorName(err)); + const fixed = out; + break :blk fixed[0..len]; + }; +} diff --git a/zig/kernels/metal/threadgroup_source_test.zig b/zig/kernels/metal/threadgroup_source_test.zig new file mode 100644 index 00000000000..3088c26bf38 --- /dev/null +++ b/zig/kernels/metal/threadgroup_source_test.zig @@ -0,0 +1,75 @@ +//! Host source checks for complete Inkling libraries and declaration reservation edits. +const std = @import("std"); +const guard = @import("threadgroup_source.zig"); +const ink = @import("inkling2_sources.zig"); +const attribute = "[[max_total_threads_per_threadgroup(256)]]\n"; + +fn check(source: []const u8, expected: []const u8) !void { + const out = try std.testing.allocator.alloc(u8, source.len); + defer std.testing.allocator.free(out); + const len = try guard.write(source, out); + try std.testing.expectEqualStrings(expected, out[0..len]); +} + +test "Inkling assembled runtime has one reservation per kernel including convolution entries" { + try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, ink.runtime, attribute ++ attribute)); + try std.testing.expectEqualStrings(ink.runtime, @import("sources.zig").inkling2_runtime); +} + +test "equal reservations collapse without altering kernel bodies or unrelated source bytes" { + const body = "kernel void k() { int x = 2; x += 3; }\n"; + try check(attribute ++ attribute ++ body, attribute ++ body); + try std.testing.expectEqualStrings(attribute ++ body, guard.normalize(attribute ++ attribute ++ body)); + try check(attribute ++ attribute ++ attribute ++ body, attribute ++ body); + const combined = "[[kernel, max_total_threads_per_threadgroup(256)]] void k() {}\n"; + try check(attribute ++ combined, combined); + try check(combined ++ attribute ++ body, combined ++ attribute ++ body); + try check("[[kernel, max_total_threads_per_threadgroup(256)]]\n" ++ attribute ++ "void k() {}", "[[kernel, max_total_threads_per_threadgroup(256)]]\nvoid k() {}"); +} + +test "conflicting and malformed reservations are refused" { + const inputs = [_][]const u8{ + attribute ++ "[[max_total_threads_per_threadgroup(128)]] kernel void k() {}", + "[[kernel, max_total_threads_per_threadgroup(128)]]\n" ++ attribute ++ "void k() {}", + }; + var out: [512]u8 = undefined; + for (inputs) |source| try std.testing.expectError(error.ConflictingThreadgroupReservation, guard.write(source, &out)); + try std.testing.expectError(error.RepeatedCombinedReservation, guard.write("[[kernel, max_total_threads_per_threadgroup(256), max_total_threads_per_threadgroup(256)]] void k() {}", &out)); + try std.testing.expectError(error.BadMetalSource, guard.write("[[max_total_threads_per_threadgroup()]] kernel void k() {}", &out)); +} + +test "comments strings nested expressions and declaration boundaries do not create false reservations" { + const head = "[[max_total_threads_per_threadgroup((8 * 32))]]\n"; + const spaced = "[[max_total_threads_per_threadgroup((8*32))]]\n"; + const body = "kernel void k() { const char* s = \"[[max_total_threads_per_threadgroup(1)]]\"; }\n"; + const comment = "/" ++ "* }; max_total_threads_per_threadgroup(1) */\n"; + try check(head ++ comment ++ spaced ++ body, head ++ comment ++ body); + try check(head ++ body ++ "// max_total_threads_per_threadgroup(1)\n" ++ head ++ body, head ++ body ++ "// max_total_threads_per_threadgroup(1)\n" ++ head ++ body); +} + +test "every complete Inkling library is unchanged by a second reservation check" { + inline for (@typeInfo(ink).@"struct".decl_names) |decl| { + const source = @field(ink, decl); + try check(source, source); + } +} + +test "LFM2 masked builder preserves one existing reservation on either side of the kernel marker" { + const masked = @import("lfm2/prompt_masked.zig"); + const before = "[[max_total_threads_per_threadgroup(128)]]\n" ++ "[[kernel]]"; + const after = "[[kernel]] [[max_total_threads_per_threadgroup(128)]]"; + const with_before = comptime blk: { + @setEvalBranchQuota(20_000_000); + const at = std.mem.indexOf(u8, masked.original, "[[kernel]]").?; + break :blk masked.original[0..at] ++ before ++ masked.original[at + "[[kernel]]".len ..]; + }; + const with_after = comptime blk: { + @setEvalBranchQuota(20_000_000); + const at = std.mem.indexOf(u8, masked.original, "[[kernel]]").?; + break :blk masked.original[0..at] ++ after ++ masked.original[at + "[[kernel]]".len ..]; + }; + const count = "max_total_threads_per_threadgroup(128)"; + try std.testing.expectEqual(@as(usize, 3), std.mem.count(u8, masked.build(with_before), count)); + try std.testing.expectEqual(@as(usize, 3), std.mem.count(u8, masked.build(with_after), count)); + try check(masked.source, masked.source); +} diff --git a/zig/metal_threadgroup_source_host.zig b/zig/metal_threadgroup_source_host.zig new file mode 100644 index 00000000000..dcdb2544744 --- /dev/null +++ b/zig/metal_threadgroup_source_host.zig @@ -0,0 +1,4 @@ +//! Complete Metal source assembly and reservation checks; no device or Apple SDK. +test { + _ = @import("kernels/metal/threadgroup_source_test.zig"); +}