diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index e3ed7723fb2..866be1d46fe 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -170,6 +170,17 @@ for a row whose tile or block reads a non-finite value at a key masked for that `gemma_decode_attention` for a decode row whose 32-key step reads one: P = 0 times Inf inside the P x V mma, where float64 leaves the masked key out. These were seen on the M5, where their cases run. Each kernel has an entry of its own that plants such a value and carries the finding, so its other entries keep a clean gate 1. +Hy4-flash's `tf_hy4_attend_chunks` and `tf_hy4_attend_scored` give NaN for a row and head whose 512-key chunk starts +with a -Inf score, where float64 leaves that key out: the running max is still -Inf there, so the first rescale is +exp(-Inf - -Inf). Its `tf_hy4_attend_nax` gives NaN for a row whose 32-key tile reads a non-finite value at a key it +masks (0 x Inf inside the P x V mma), and 0 for a row whose every score is NaN, where float64 gives NaN: Metal's `max` +drops the NaN, so the running max stays -Inf and the kernel's guard weighs every key 0. Each has an entry of its own. +Hy4-flash's `tf_hy4_route_select_rank` ranks a NaN key 0, since every comparison with it is false, so it races the +row's best expert for the first pick; the core select it stands beside never picks a NaN key. +Hy4-flash's `tf_hy4_group_scores` scores a NaN dot as 0 where float64 keeps the NaN: its relu is `max(dot, 0.0f)`. +Hy4-flash's SwiGLU clip, in `tf_affine_experts_up_4` and `_8` and in affine_mm's `am_swiglu`, gives a finite output for +a NaN gate or up sum where float64 keeps the NaN: `min(gate, 10)` and `clamp(up, -10, 10)` drop it. Its 4-bit tensor +gathers carry affine_mm's +128 code offset finding above. HIP’s MLX stream tile keeps its finite dot2 sums unchanged. A non-finite result with an actual non-finite operand is recomputed by full quantization groups using the factored float64 formula. The plain tile is diff --git a/zig/src/core/contract/hy4_attend_records.zig b/zig/src/core/contract/hy4_attend_records.zig new file mode 100644 index 00000000000..5e9f3436c30 --- /dev/null +++ b/zig/src/core/contract/hy4_attend_records.zig @@ -0,0 +1,19 @@ +//! Hy4-flash's attend launches on Metal (tests/contract/metal_hy4_attend.zig), M1 and M2 limits from --offline. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +/// Attention.attend's 128-thread groups; scored stages 16 keys in threadgroup memory; controls compile their edits. +pub const records = [_]M{ + .{ .name = "hy4 mla_attention tf_hy4_attend_chunks", .threads = 128, .tg_memory = 0, .m1 = 640, .m2 = 640 }, + .{ .name = "hy4 mla_attention tf_hy4_attend_merge", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_attention tf_hy4_attend_scores", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_attention tf_hy4_attend_scored", .threads = 128, .tg_memory = 16384, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_attention control drop-last tf_hy4_attend_chunks", .threads = 128, .tg_memory = 0, .m1 = 640, .m2 = 640 }, + .{ .name = "hy4 mla_attention control no-sink tf_hy4_attend_merge", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_attention control half-sums tf_hy4_attend_chunks", .threads = 128, .tg_memory = 0, .m1 = 768, .m2 = 768 }, + .{ .name = "hy4 mla_attention control skip-nan tf_hy4_attend_merge", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_attention control shuffle tf_hy4_attend_scored", .threads = 128, .tg_memory = 16384, .m1 = 1024, .m2 = 1024 }, +}; + +test "Hy4-flash's attend 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/hy4_experts_records.zig b/zig/src/core/contract/hy4_experts_records.zig new file mode 100644 index 00000000000..5f8e2ef0172 --- /dev/null +++ b/zig/src/core/contract/hy4_experts_records.zig @@ -0,0 +1,44 @@ +//! Hy4-flash's experts launches on Metal (tests/contract/metal_hy4_experts*.zig), M1 and M2 limits from --offline. +const M = @import("limits.zig").MetalLaunch; + +/// affine_experts_metal.Kernels.run: four simdgroups a group, one output each, no threadgroup memory. +fn portable(comptime name: []const u8, m1: u32, m2: u32) M { + return .{ .name = "hy4 affine_experts " ++ name, .threads = 128, .tg_memory = 0, .m1 = m1, .m2 = m2 }; +} + +/// metal_tensor_experts' affine_mm (tensor units only): row sums 24 groups wide, every product 128 threads. +fn units(comptime bits: []const u8) [8]M { + const head = "hy4 units affine_mm " ++ bits ++ " "; + var out: [8]M = undefined; + out[0] = .{ .name = head ++ "tf_affine_row_sums", .threads = 24, .tg_memory = 0, .offline = false }; + // every pipeline the loader builds; Hy4's rows a job launch only the 32-row GLU and scatter gathers + inline for (.{ "tf_affine_mm", "tf_affine_gather_32", "tf_affine_gather_64", "tf_affine_gather_scatter_32", "tf_affine_gather_scatter_64", "tf_affine_gather_glu_32", "tf_affine_gather_glu_64" }, 1..) |f, i| { + out[i] = .{ .name = head ++ f, .threads = 128, .tg_memory = 9728, .offline = false }; + } + return out; +} + +/// tensor_dispatch.metal (tensor units only): the row split's 128 threads, the job tables' one group of 256 or 1,024. +fn dispatch(comptime name: []const u8, threads: u32, tg: u32) M { + return .{ .name = "hy4 units tensor_dispatch " ++ name, .threads = threads, .tg_memory = tg, .reserved = if (threads > 256) threads else 0, .offline = false }; +} + +pub const records = [_]M{ + portable("tf_affine_experts_up_4", 928, 928), + portable("tf_affine_experts_down_4", 1024, 1024), + portable("tf_affine_experts_up_8", 928, 928), + portable("tf_affine_experts_down_8", 1024, 1024), + portable("silu-unrounded tf_affine_experts_up_4", 928, 928), + portable("weight-unrounded tf_affine_experts_down_8", 1024, 1024), + portable("half-sums tf_affine_experts_down_4", 1024, 1024), +} ++ units("q4") ++ units("q8") ++ [_]M{ + .{ .name = "hy4 units affine_mm q4 map-ignored-glu tf_affine_gather_glu_32", .threads = 128, .tg_memory = 9728, .offline = false }, + .{ .name = "hy4 units affine_mm q8 mlx-sigmoid tf_affine_gather_glu_32", .threads = 128, .tg_memory = 9728, .offline = false }, + .{ .name = "hy4 units affine_mm q8 map-ignored-scatter tf_affine_gather_scatter_32", .threads = 128, .tg_memory = 9728, .offline = false }, + dispatch("tf_hy4_qkv_split", 128, 0), + dispatch("tf_hy4_active_experts", 256, 32), + dispatch("tf_hy4_group_pairs", 1024, 20608), + dispatch("kv-short tf_hy4_qkv_split", 128, 0), + dispatch("pair0-dropped tf_hy4_active_experts", 256, 32), + dispatch("own-row tf_hy4_group_pairs", 1024, 20608), +}; diff --git a/zig/src/core/contract/hy4_ihc_records.zig b/zig/src/core/contract/hy4_ihc_records.zig new file mode 100644 index 00000000000..8d4ea77a110 --- /dev/null +++ b/zig/src/core/contract/hy4_ihc_records.zig @@ -0,0 +1,34 @@ +//! Hy4-flash's ihc and DFly2 glue launches on Metal (tests/contract/metal_hy4_ihc.zig), M1/M2 limits from --offline. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "hy4 ihc tf_hy4_ihc_collapse_g4", .threads = 256, .tg_memory = 304, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_ihc_collapse_g8", .threads = 256, .tg_memory = 304, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_ihc_partials_g4", .threads = 32, .tg_memory = 0, .m1 = 928, .m2 = 928 }, + .{ .name = "hy4 ihc tf_hy4_ihc_partials_g8", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_ihc_finish_g4", .threads = 256, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_ihc_finish_g8", .threads = 256, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_tail_g4", .threads = 256, .tg_memory = 640, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_tail_g8", .threads = 256, .tg_memory = 640, .m1 = 832, .m2 = 832 }, + .{ .name = "hy4 ihc tf_hy4_head_g4", .threads = 256, .tg_memory = 64, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_head_g8", .threads = 256, .tg_memory = 64, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_seam_g4", .threads = 256, .tg_memory = 704, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_seam_g8", .threads = 256, .tg_memory = 704, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_ihc_add", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_draft_fuse", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc tf_hy4_draft_residual", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + // the planted controls' pipelines, each compiled from its own edit of ihc.metal + .{ .name = "hy4 ihc control flush tf_hy4_ihc_collapse_g8", .threads = 256, .tg_memory = 304, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control seven tf_hy4_ihc_collapse_g8", .threads = 256, .tg_memory = 304, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control half tf_hy4_ihc_collapse_g8", .threads = 256, .tg_memory = 304, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control slot0 tf_hy4_ihc_finish_g8", .threads = 256, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control unweighted tf_hy4_tail_g8", .threads = 256, .tg_memory = 640, .m1 = 832, .m2 = 832 }, + .{ .name = "hy4 ihc control once tf_hy4_seam_g8", .threads = 256, .tg_memory = 704, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control onegate tf_hy4_ihc_add", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control gain0 tf_hy4_draft_fuse", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 ihc control subtract tf_hy4_draft_residual", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, +}; + +test "Hy4-flash's ihc 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/hy4_index_records.zig b/zig/src/core/contract/hy4_index_records.zig new file mode 100644 index 00000000000..69a007a5bdd --- /dev/null +++ b/zig/src/core/contract/hy4_index_records.zig @@ -0,0 +1,18 @@ +//! Hy4-flash's index launches on Metal with --offline's M1/M2 limits; a word before the function names a control. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "hy4 index_build tf_hy4_index_keys", .threads = 128, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 index_build unrounded tf_hy4_index_keys", .threads = 128, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 index_build tf_hy4_index_groups", .threads = 128, .tg_memory = 2064, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 index_build slot0-bias tf_hy4_index_groups", .threads = 128, .tg_memory = 2064, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 index_recall tf_hy4_group_scores", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 index_recall head15 tf_hy4_group_scores", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 index_recall tf_hy4_recall_groups", .threads = 256, .tg_memory = 3152, .m1 = 928, .m2 = 928 }, + .{ .name = "hy4 index_recall signed-zero tf_hy4_recall_groups", .threads = 256, .tg_memory = 3152, .m1 = 928, .m2 = 928 }, + .{ .name = "hy4 index_recall own-token tf_hy4_recall_groups", .threads = 256, .tg_memory = 3152, .m1 = 928, .m2 = 928 }, +}; + +test "Hy4-flash's index 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/hy4_lane_records.zig b/zig/src/core/contract/hy4_lane_records.zig new file mode 100644 index 00000000000..4b3c97b792a --- /dev/null +++ b/zig/src/core/contract/hy4_lane_records.zig @@ -0,0 +1,30 @@ +//! Hy4-flash's tensor-unit lane projections at each served width: reg kernel, inline-sums twin and sums pass. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +/// [n, k, K splits]: the dense projections, then the q/kv inputs and the queries at 64 and 32 heads. +pub const shapes = [_][3]u32{ + .{ 3072, 16384, 8 }, .{ 3072, 8192, 8 }, .{ 1536, 3072, 4 }, .{ 3072, 1536, 2 }, + .{ 13824, 3072, 4 }, .{ 3072, 13824, 8 }, .{ 120832, 3072, 4 }, .{ 17984, 3072, 4 }, + .{ 9792, 3072, 4 }, .{ 16384, 1024, 2 }, .{ 8192, 1024, 2 }, +}; + +/// Reg threadgroup bytes: later splits' 16 x 32 fp32 partials, plus inline sums' K splits x groups a split x 16 rows. +fn regBytes(k: u32, sk: u32, sums: bool) u32 { + const groups = k / 64; + return (sk - 1) * 2048 + if (sums) sk * ((groups + sk - 1) / sk) * 16 * 4 else 0; +} + +pub const records = blk: { + @setEvalBranchQuota(20000); + var out: [shapes.len * 2 * 3]M = undefined; + var at = 0; + for ([_]u32{ 4, 8 }) |bits| for (shapes) |s| { + const head = std.fmt.comptimePrint("hy4 units lane q{d} n{d} k{d} sk{d}", .{ bits, s[0], s[1], s[2] }); + out[at] = .{ .name = head ++ " tf_lane_reg", .threads = 32 * s[2], .tg_memory = regBytes(s[1], s[2], false), .offline = false }; + out[at + 1] = .{ .name = head ++ " inline tf_lane_reg", .threads = 32 * s[2], .tg_memory = regBytes(s[1], s[2], true), .offline = false }; + out[at + 2] = .{ .name = head ++ " tf_lane_sums", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }; + at += 3; + }; + break :blk out; +}; diff --git a/zig/src/core/contract/hy4_nax_records.zig b/zig/src/core/contract/hy4_nax_records.zig new file mode 100644 index 00000000000..f96e4d635c0 --- /dev/null +++ b/zig/src/core/contract/hy4_nax_records.zig @@ -0,0 +1,16 @@ +//! Hy4-flash's nax launches on Metal (tests/contract/metal_hy4_nax*.zig), as mla_metal.zig's Nax encodes them. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +// nax.h's tensor ops keep every pipeline but the combine from an M1/M2 build ahead of time: 128 threads each. +pub const records = [_]M{ + .{ .name = "hy4 units mla_nax tf_hy4_absorb_nax", .threads = 128, .tg_memory = 0, .offline = false }, + .{ .name = "hy4 units mla_nax tf_hy4_expand_gated_nax", .threads = 128, .tg_memory = 0, .offline = false }, + // part[4][16][32] floats: each simdgroup's slice of a tile's scores + .{ .name = "hy4 units mla_nax tf_hy4_attend_nax", .threads = 128, .tg_memory = 4 * 16 * 32 * 4, .offline = false }, + .{ .name = "hy4 units mla_nax tf_hy4_attend_nax_split", .threads = 128, .tg_memory = 4 * 16 * 32 * 4, .offline = false }, + .{ .name = "hy4 units mla_nax tf_hy4_attend_combine", .threads = 128, .tg_memory = 0, .m1 = 928, .m2 = 928 }, +}; + +test "Hy4-flash's nax 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/hy4_project_records.zig b/zig/src/core/contract/hy4_project_records.zig new file mode 100644 index 00000000000..ffa0102362b --- /dev/null +++ b/zig/src/core/contract/hy4_project_records.zig @@ -0,0 +1,20 @@ +//! Hy4-flash's project launches on Metal (tests/contract/metal_hy4_project.zig), M1/M2 limits from --offline. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + .{ .name = "hy4 mla_project tf_hy4_rotary_table", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project tf_hy4_rotate", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project tf_hy4_cache_keys", .threads = 128, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project tf_hy4_gate_values", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project tf_hy4_absorb_q", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project tf_hy4_expand_v", .threads = 32, .tg_memory = 0, .m1 = 928, .m2 = 928 }, + .{ .name = "hy4 mla_project tf_hy4_expand_v_gated", .threads = 32, .tg_memory = 0, .m1 = 928, .m2 = 928 }, + // the planted controls' own pipelines (metal_hy4_project.zig's controls) + .{ .name = "hy4 mla_project time-axis tf_hy4_rotary_table", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project turned-back tf_hy4_rotate", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project norm-unrounded tf_hy4_cache_keys", .threads = 128, .tg_memory = 16, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project gate-unrounded tf_hy4_gate_values", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project short-sum tf_hy4_absorb_q", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project half-sum tf_hy4_absorb_q", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project short-sum tf_hy4_expand_v", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 mla_project gate-unrounded tf_hy4_expand_v_gated", .threads = 32, .tg_memory = 0, .m1 = 928, .m2 = 928 }, +}; diff --git a/zig/src/core/contract/hy4_records.zig b/zig/src/core/contract/hy4_records.zig new file mode 100644 index 00000000000..e093f0d40a4 --- /dev/null +++ b/zig/src/core/contract/hy4_records.zig @@ -0,0 +1,10 @@ +//! Hy4-flash's launches: a records file for each group of tests/contract/metal_hy4_*.zig. +pub const metal = @import("hy4_index_records.zig").records ++ + @import("hy4_project_records.zig").records ++ + @import("hy4_attend_records.zig").records ++ + @import("hy4_nax_records.zig").records ++ + @import("hy4_ihc_records.zig").records ++ + @import("hy4_route_records.zig").records ++ + @import("hy4_experts_records.zig").records ++ + @import("hy4_rows_records.zig").records ++ + @import("hy4_lane_records.zig").records; diff --git a/zig/src/core/contract/hy4_route_records.zig b/zig/src/core/contract/hy4_route_records.zig new file mode 100644 index 00000000000..ef20601c196 --- /dev/null +++ b/zig/src/core/contract/hy4_route_records.zig @@ -0,0 +1,20 @@ +//! Hy4-flash's route launches on Metal (tests/contract/metal_hy4_route*.zig), M1 and M2 limits from --offline. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +// The last four are the planted controls' texts; tf_add_bf16 at Nemotron's groups of 256 (Hy4 never dispatches it). +pub const records = [_]M{ + .{ .name = "hy4 moe_route tf_route_logits", .threads = 256, .tg_memory = 512, .m1 = 896, .m2 = 896 }, + .{ .name = "hy4 moe_route tf_route_select", .threads = 512, .tg_memory = 9408, .m1 = 576, .m2 = 576 }, + .{ .name = "hy4 route_rows tf_hy4_route_select_rows", .threads = 32, .tg_memory = 0, .m1 = 640, .m2 = 640 }, + .{ .name = "hy4 route_rows tf_hy4_route_select_rank", .threads = 512, .tg_memory = 2112, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 affine_experts tf_hy4_routed_sum", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 elementwise tf_add_bf16", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 moe_route half-sums tf_route_logits", .threads = 256, .tg_memory = 512, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 route_rows nan-picked tf_hy4_route_select_rows", .threads = 32, .tg_memory = 0, .m1 = 640, .m2 = 640 }, + .{ .name = "hy4 route_rows ties-high tf_hy4_route_select_rank", .threads = 512, .tg_memory = 2112, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 affine_experts half-sums tf_hy4_routed_sum", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, +}; + +test "Hy4-flash's route 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/hy4_rows_records.zig b/zig/src/core/contract/hy4_rows_records.zig new file mode 100644 index 00000000000..bff14649706 --- /dev/null +++ b/zig/src/core/contract/hy4_rows_records.zig @@ -0,0 +1,22 @@ +//! Hy4-flash's rows launches on Metal (tests/contract/metal_hy4_rows.zig) with the M1 and M2 limits --offline recorded. +const M = @import("limits.zig").MetalLaunch; +pub const records = [_]M{ + // rows.metal on the wide core row source (metal_linears.zig's Rows.load), the same text on every chip + .{ .name = "hy4 rows tf_hy4_rows_r2_q4", .threads = 128, .tg_memory = 0, .m1 = 384, .m2 = 384 }, + .{ .name = "hy4 rows tf_hy4_rows_r2_q8", .threads = 128, .tg_memory = 0, .m1 = 384, .m2 = 384 }, + .{ .name = "hy4 rows bad-tail tf_hy4_rows_r2_q4", .threads = 128, .tg_memory = 0, .m1 = 384, .m2 = 384 }, + .{ .name = "hy4 rows tf_hy4_argmax", .threads = 1024, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 rows bad-tie tf_hy4_argmax", .threads = 1024, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 rows bad-nan tf_hy4_argmax", .threads = 1024, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, + // engram.metal (metal_engram.zig's Kernels.load) + .{ .name = "hy4 engram tf_hy4_engram_lookup", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 engram bad-scale tf_hy4_engram_lookup", .threads = 32, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 engram tf_hy4_engram_apply", .threads = 128, .tg_memory = 80, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 engram bad-gain tf_hy4_engram_apply", .threads = 128, .tg_memory = 80, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 engram tf_hy4_engram_gather", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 engram bad-group tf_hy4_engram_gather", .threads = 256, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + // core embed_norm.metal's lookups at Hy4's hidden width (metal_model.zig's Head.upload) + .{ .name = "hy4 embed_norm tf_embed_b4_g64", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 embed_norm tf_embed_b8_g64", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, + .{ .name = "hy4 embed_norm bad-round tf_embed_b4_g64", .threads = 128, .tg_memory = 0, .m1 = 1024, .m2 = 1024 }, +}; diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index f8db15e1d8a..b9f7f805528 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -89,6 +89,7 @@ pub const all_metal = @import("lane_q8_records.zig").records ++ @import("qwen27_prompt_records.zig").records ++ @import("affine_gather_records.zig").records ++ @import("flint_records.zig").records ++ + @import("hy4_records.zig").metal ++ @import("uocr_records.zig").records ++ @import("bolt_records.zig").records; pub const landed_cuda = registry.cuda ++ @import("muse_cuda_records.zig").cuda ++ diff --git a/zig/src/families/hy4_flash/contract_exports.zig b/zig/src/families/hy4_flash/contract_exports.zig new file mode 100644 index 00000000000..cc9b3509414 --- /dev/null +++ b/zig/src/families/hy4_flash/contract_exports.zig @@ -0,0 +1,45 @@ +//! Hy4-flash's modules the kernel contract's tests read: the loaders, their argument layouts and the CPU references. +pub const affine_experts_metal = @import("affine_experts_metal.zig"); +pub const attention_slots = @import("attention_slots.zig"); +pub const config = @import("config.zig"); +pub const cuda_dense = @import("cuda_dense.zig"); +pub const cuda_projection = @import("cuda_projection.zig"); +pub const dfly2_inputs = @import("dfly2_inputs.zig"); +pub const engram = @import("engram.zig"); +pub const engram_rows = @import("engram_rows.zig"); +pub const forward = @import("forward.zig"); +pub const host_tests = @import("host_tests.zig"); +pub const ihc = @import("ihc.zig"); +pub const ihc_cuda = @import("ihc_cuda.zig"); +pub const ihc_metal = @import("ihc_metal.zig"); +pub const index_groups = @import("index_groups.zig"); +pub const index_recall = @import("index_recall.zig"); +pub const index_recall_cuda = @import("index_recall_cuda.zig"); +pub const index_recall_metal = @import("index_recall_metal.zig"); +pub const indexpool_cuda = @import("indexpool_cuda.zig"); +pub const indexpool_metal = @import("indexpool_metal.zig"); +pub const loader = @import("loader.zig"); +pub const metal_dense = @import("metal_dense.zig"); +pub const metal_draft = @import("metal_draft.zig"); +pub const metal_engram = @import("metal_engram.zig"); +pub const metal_index = @import("metal_index.zig"); +pub const metal_linears = @import("metal_linears.zig"); +pub const metal_model = @import("metal_model.zig"); +pub const metal_routed = @import("metal_routed.zig"); +pub const metal_scratch = @import("metal_scratch.zig"); +pub const metal_tensor_experts = @import("metal_tensor_experts.zig"); +pub const metal_tensor_qkv = @import("metal_tensor_qkv.zig"); +pub const mla_attention = @import("mla_attention.zig"); +pub const mla_cuda = @import("mla_cuda.zig"); +pub const mla_metal = @import("mla_metal.zig"); +pub const mla_weights = @import("mla_weights.zig"); +pub const model_weights = @import("model_weights.zig"); +pub const moe_cuda = @import("moe_cuda.zig"); +pub const rank_weights = @import("rank_weights.zig"); +pub const rope = @import("rope.zig"); +pub const serve_draft = @import("serve_draft.zig"); +pub const serve_metal = @import("serve_metal.zig"); +pub const serve_resident = @import("serve_resident.zig"); +pub const weights = @import("weights.zig"); +/// The served checkpoint's config.json (its text model is the one the engine loads). +pub const config_json = @embedFile("config_fixture.json"); diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index a74d99301a2..848b04bce42 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -77,6 +77,7 @@ pub const step5 = @import("families/step5/step5.zig"); pub const spark25_metal = @import("families/spark25/metal.zig"); pub const minimax_m3 = @import("families/minimax_m3/minimax_m3.zig"); pub const hy4_flash = @import("families/hy4_flash/serve_metal.zig"); +pub const hy4_contract = @import("families/hy4_flash/contract_exports.zig"); pub const qwen3_metal = @import("families/qwen3/metal/metal.zig"); pub const llama = @import("families/llama/llama.zig"); pub const flint = @import("families/flint/flint.zig"); diff --git a/zig/tests/contract/metal_affine.zig b/zig/tests/contract/metal_affine.zig index b2dbe966ef3..8359fa44fa9 100644 --- a/zig/tests/contract/metal_affine.zig +++ b/zig/tests/contract/metal_affine.zig @@ -17,7 +17,7 @@ const lane = tf.lane_projection; pub const Kind = enum { row, affine_mm, simd, simd_half, simd_sums, simd_bits, lane, lane_reg }; /// One variant: kernel, code width and group, output, lane K slices; control: simd_half's or simd_sums' planted fault. -pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, control: bool = false, served: ?[]const c.Shape = null }; +pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, control: bool = false, served: ?[]const c.Shape = null, inline_sums: bool = false }; pub const Reg = struct { v: Variant, name: []const u8 }; /// The half-operand tiles, the chunk pairs on the prepass's sums, and their planted controls, beside simd_qmm's entry. pub const half = [_]Reg{ @@ -53,6 +53,13 @@ const offset_inf = c.Known{ .gate = .nonfinite, .finding = "an infinite input gi /// Ornith-1.5-122B's 8-bit router: 256 experts and the shared gate's row padded to 320, a prompt chunk's rows. const router_rows = [_]c.Shape{ .{ .rows = 1024, .n = 320, .k = 3072 }, .{ .rows = 65, .n = 320, .k = 3072 } }; +/// What a reg lane variant must equal bit for bit: inline sums its reg twin, 4-bit reg the cooperative kernel. +fn laneBase(v: Variant) ?[]const u8 { + if (v.kind != .lane_reg) return null; + if (v.inline_sums) return "the reg kernel with its sums pass"; + return if (v.bits == 4) "the cooperative lane kernel" else null; +} + pub fn spec(v: Variant, name: []const u8) c.Spec { const out: c.Elem = if (v.f32_out) .f32 else .bf16; const step: usize = @max(16, v.group); @@ -64,7 +71,7 @@ pub fn spec(v: Variant, name: []const u8) c.Spec { .simd_half => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .replaces = "simd_qmm's fp32 tiles", .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 32, .n = 6240, .k = 512 }, .{ .rows = 9, .n = 12288, .k = 256 } } }, // the 27B's down and o (16 chunks, four column tiles), as a prompt chunk and an odd tail take them .simd_sums => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .replaces = "simd_qmm's fp32 tiles", .tiles = .{ .{ .size = 16, .min = 9 }, .{ .size = 128, .step = 32, .min = 96 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 64, .n = 5120, .k = 1024 }, .{ .rows = 9, .n = 512, .k = 512 } } }, - .lane, .lane_reg => .{ .name = name, .accum = .f32, .depth = laneDepth, .out = out, .replaces = if (v.kind == .lane_reg) "the cooperative lane kernel" else null, .tiles = .{ .{ .size = 16 }, .{ .size = 32, .step = 16, .min = 32 }, .{ .size = 4 * v.group, .step = v.group, .min = v.group } }, .served = v.served orelse &.{ .{ .rows = 16, .n = 2048, .k = 2048 }, .{ .rows = 5, .n = 512, .k = 896 } } }, + .lane, .lane_reg => .{ .name = name, .accum = .f32, .depth = laneDepth, .out = out, .replaces = laneBase(v), .tiles = .{ .{ .size = 16 }, .{ .size = 32, .step = 16, .min = 32 }, .{ .size = 4 * v.group, .step = v.group, .min = v.group } }, .served = v.served orelse &.{ .{ .rows = 16, .n = 2048, .k = 2048 }, .{ .rows = 5, .n = 512, .k = 896 } } }, }; } @@ -114,7 +121,9 @@ pub const Proj = struct { p.mm_p = pipes; }, .lane => {}, - .lane_reg => p.order = try lane.RegOrder.init(device), + .lane_reg => if (v.bits == 4) { + p.order = try lane.RegOrder.init(device); + }, } return p; } @@ -145,9 +154,11 @@ pub const Proj = struct { const vt = g.hooks(Proj); - fn layout(p: *const Proj, shape: c.Shape, coop: bool) lane.Layout { - const reg = p.v.kind == .lane_reg and !coop; - return .{ .n = shape.n, .k = shape.k, .format = .{ .bits = p.v.bits, .group = p.v.group }, .sk = p.v.sk, .output = if (p.v.f32_out) .f32 else .bf16, .precompute_sums = p.v.kind == .lane_reg or p.v.coop, .cooperative = coop or (p.v.coop and !reg), .reg = reg }; + /// The kernel's layout, or with `base` the layout of the kernel it replaces. + fn layout(p: *const Proj, shape: c.Shape, base: bool) lane.Layout { + const reg = p.v.kind == .lane_reg and (!base or p.v.inline_sums); + const coop = base and !reg; + return .{ .n = shape.n, .k = shape.k, .format = .{ .bits = p.v.bits, .group = p.v.group }, .sk = p.v.sk, .output = if (p.v.f32_out) .f32 else .bf16, .precompute_sums = p.v.kind == .lane_reg or p.v.coop, .cooperative = coop or (p.v.coop and !reg), .reg = reg, .inline_sums = reg and p.v.inline_sums and !base }; } /// Whether the kernel takes this shape, as the engine's own validation says. @@ -200,9 +211,14 @@ pub const Proj = struct { p.s = try p.rig.input(std.mem.sliceAsBytes(psb)); if (p.v.kind == .lane_reg) { p.tiled = try p.rig.input(std.mem.sliceAsBytes(pw)); - try p.order.?.run(&.{.{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .n = shape.n, .k = shape.k }}); - p.coop_p = try lane.Projection.init(p.a, p.rig.device, p.layout(shape, true)); - p.base = try p.rig.scratch(out_bytes); + if (p.order) |o| try o.run(&.{.{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .n = shape.n, .k = shape.k }}) else { + const reg_words = p.rig.bytes(p.w, pw.len * 4); + try lane.regOrder8(@alignCast(std.mem.bytesAsSlice(u32, reg_words)), shape.n, shape.k); + } + if (laneBase(p.v) != null) { + p.coop_p = try lane.Projection.init(p.a, p.rig.device, p.layout(shape, true)); + p.base = try p.rig.scratch(out_bytes); + } } }, } @@ -269,14 +285,14 @@ pub const Proj = struct { /// The replaced kernel's bytes on the same inputs: the cooperative lane kernel's, or simd_qmm's fp32 tiles'. pub fn replaced(p: *Proj) ![]const u8 { - if (p.v.kind != .lane_reg and p.v.kind != .simd_half and p.v.kind != .simd_sums) return error.NotAReplacement; + if ((p.v.kind != .lane_reg or laneBase(p.v) == null) and p.v.kind != .simd_half and p.v.kind != .simd_sums) return error.NotAReplacement; const f = p.f.?; const len = f.outputs() * c.size(spec(p.v, p.name).out); @memset(p.rig.bytes(p.base, len), 0xff); const pass = p.rig.begin(); if (p.v.kind == .simd_half or p.v.kind == .simd_sums) { sq.encode(pass.e, try sq.call(&p.sq_p.?, f.shape.n, f.shape.k, f.shape.rows, false, false, 0), p.matrix(f.shape), p.x.buf, p.x.off, p.base.buf, p.base.off); - } else try p.coop_p.?.encode(pass.e, ref(p.x), ref(p.tiled), ref(p.s), ref(p.base), @intCast(f.shape.rows)); + } else try p.coop_p.?.encode(pass.e, ref(p.x), ref(if (p.v.inline_sums) p.w else p.tiled), ref(p.s), ref(p.base), @intCast(f.shape.rows)); try p.rig.finish(pass); return p.rig.bytes(p.base, len); } diff --git a/zig/tests/contract/metal_hy4.zig b/zig/tests/contract/metal_hy4.zig new file mode 100644 index 00000000000..4333e9a3efa --- /dev/null +++ b/zig/tests/contract/metal_hy4.zig @@ -0,0 +1,75 @@ +//! Hy4-flash's Metal kernels under the contract, a file a group; flint's helpers (ranges, edits, lists) are shared. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +pub const fl = @import("metal_flint.zig"); +pub const hy = @import("tensorfold").hy4_contract; +const g = contract.gates; + +/// Hy4-flash's served widths: `text()` parses the checkpoint's config.json (hy.config_json); hidden 3,072. +pub const hidden = 3072; +pub fn text(a: std.mem.Allocator) !std.json.Parsed(hy.config.Model) { + return hy.config.parse(a, hy.config_json); +} +/// Rows a call serves: one decode row, DFly2's window (the pending row and five drafts), a prompt chunk. +pub const decode_rows = 1; +pub const window_rows = 6; +pub const prompt_rows = 512; + +const groups = .{ @import("metal_hy4_index.zig"), @import("metal_hy4_project.zig"), @import("metal_hy4_attend.zig"), @import("metal_hy4_nax.zig"), @import("metal_hy4_ihc.zig"), @import("metal_hy4_route.zig"), @import("metal_hy4_experts.zig"), @import("metal_hy4_rows.zig") }; +const fields = .{ "index", "project", "attend", "nax", "ihc", "route", "experts", "rows" }; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + index: groups[0].Suite = undefined, + project: groups[1].Suite = undefined, + attend: groups[2].Suite = undefined, + nax: groups[3].Suite = undefined, + ihc: groups[4].Suite = undefined, + route: groups[5].Suite = undefined, + experts: groups[6].Suite = undefined, + rows: groups[7].Suite = undefined, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + inline for (fields) |f| { + @field(s, f) = .{ .a = s.a, .device = s.device, .queue = s.queue, .kernels = s.kernels }; + try @field(s, f).collect(only); + } + } + pub fn deinit(s: *Suite) void { + inline for (fields) |f| @field(s, f).deinit(); + } +}; + +/// Gate 5's texts for an `hy4 ` registration: the group whose launches it names compiles it as its loader does. +pub fn limitsText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !fl.Texts { + if (std.mem.startsWith(u8, name, "hy4 units lane ")) return laneText(a, device, name); + inline for (groups) |grp| if (try grp.limitsText(a, device, name)) |t| return t; + return error.UnknownLaunch; +} + +/// A "hy4 units lane qB nN kK skS [inline] fn" record's text: the layout metal_tensor_qkv.zig builds at that width. +fn laneText(a: std.mem.Allocator, device: mtl.Device, name: []const u8) !fl.Texts { + const lane = @import("tensorfold").lane_projection; + var words = std.mem.tokenizeScalar(u8, name["hy4 units lane ".len..], ' '); + var v: [4]usize = undefined; + for (&v, "qnks") |*x, letter| { + const w = words.next() orelse return error.UnknownLaunch; + if (w.len < 2 or w[0] != letter) return error.UnknownLaunch; + x.* = try std.fmt.parseInt(usize, w[if (letter == 's') 2 else 1..], 10); + } + const sums = std.mem.indexOf(u8, name, " inline ") != null; + const l: lane.Layout = .{ .n = v[1], .k = v[2], .sk = v[3], .format = .{ .bits = @intCast(v[0]), .group = 64 }, .reg = true, .precompute_sums = true, .rows = prompt_rows, .inline_sums = sums }; + try l.validate(); + const body = try lane.source(a, l); + const here = try lane.frags.source(device, a, body); + return .{ .here = here, .pre_m5 = body }; +} + +/// Launches named `hy4 units ` load only on tensor units (their loaders' `device.tensorUnits()` branches). +pub fn tensorOnly(name: []const u8) bool { + return std.mem.startsWith(u8, name, "hy4 units "); +} diff --git a/zig/tests/contract/metal_hy4_attend.zig b/zig/tests/contract/metal_hy4_attend.zig new file mode 100644 index 00000000000..2bf37fda9bd --- /dev/null +++ b/zig/tests/contract/metal_hy4_attend.zig @@ -0,0 +1,334 @@ +//! Hy4-flash's MLA attention kernels (mla_attention.metal) under the contract, launched by mla_metal.zig's encoder. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const h = @import("metal_hy4.zig"); +const rig_ = @import("rig.zig"); +const inputs = @import("metal_hy4_attend_inputs.zig"); +const g = contract.gates; +const c = contract.spec; +const ar = contract.attention_range; +const fl = h.fl; +const mla = h.hy.mla_metal; +const Lists = inputs.Lists; +const lat = inputs.lat; + +const stem = "hy4 mla_attention "; +const sliding_heads = 64; +const sparse_heads = 32; +/// A row deep in a long stream: past the sliding window and the 2,048 keys a sparse layer attends unrecalled. +const deep = 9000; + +/// The one-step pass (chunks) or the two-step one (scores, then each chunk's softmax over them). +pub const Path = enum { chunks, scored }; + +const one_step = "metal hy4 mla_attention tf_hy4_attend_chunks + tf_hy4_attend_merge"; +const two_step = "metal hy4 mla_attention tf_hy4_attend_scores + tf_hy4_attend_scored + tf_hy4_attend_merge"; + +/// A planted control: one kernel's edit, the gate that must catch it, what it breaks, and its launch's word. +pub const Fault = enum { drop_last, no_sink, half_sums, skip_nan, shuffle }; +const Control = struct { edit: fl.Edit, gate: c.Gate, what: []const u8, word: []const u8 }; + +fn control(f: Fault) Control { + return switch (f) { + .drop_last => .{ .edit = .{ .kernel = "tf_hy4_attend_chunks", .from = "counts[row]);", .to = "counts[row] - 1);" }, .gate = .shapes, .what = "each row's last key dropped", .word = "drop-last" }, + .no_sink => .{ .edit = .{ .kernel = "tf_hy4_attend_merge", .from = "float denom = precise::exp(sinks[head] - top)", .to = "float denom = 0.0f" }, .gate = .shapes, .what = "the sink dropped from the merge's denominator", .word = "no-sink" }, + .half_sums => .{ .edit = .{ .kernel = "tf_hy4_attend_chunks", .from = "accum[i] = fma(p, kv[i], accum[i] * old);", .to = "accum[i] = float(half(fma(p, kv[i], accum[i] * old)));" }, .gate = .sums, .what = "each chunk's values summed in half", .word = "half-sums" }, + .skip_nan => .{ .edit = .{ .kernel = "tf_hy4_attend_merge", .from = "const float p = precise::exp(part[lat] - top);", .to = "if (isnan(part[lat + 1])) continue;\n const float p = precise::exp(part[lat] - top);" }, .gate = .nonfinite, .what = "the merge skipping a chunk whose mass is NaN", .word = "skip-nan" }, + .shuffle => .{ .edit = .{ .kernel = "tf_hy4_attend_scored", .from = "simd_shuffle(p, ushort(h + t))", .to = "simd_shuffle(p, ushort(t))" }, .gate = .shapes, .what = "each 32-key step's last 16 keys weighed as its first 16", .word = "shuffle" }, + }; +} + +/// Gate 1's finding: carried by an entry of its own that plants it, so the other entries keep a clean gate 1. +const first_inf_finding = "a key whose score is -Inf at the start of a 512-key chunk gives its row's head NaN where " ++ + "float64 leaves the key out: the running max is still -Inf there, so the first rescale is exp(-Inf - -Inf)"; + +/// What one registration runs: its pass, its lists, and a control's fault or the known finding's plant. +pub const Case = struct { path: Path, lists: Lists, fault: ?Fault = null, first_inf: bool = false }; + +const cases = [_]Case{ + .{ .path = .chunks, .lists = .window }, + .{ .path = .scored, .lists = .sparse }, + .{ .path = .scored, .lists = .draft }, + .{ .path = .chunks, .lists = .window, .first_inf = true }, + .{ .path = .scored, .lists = .sparse, .first_inf = true }, + .{ .path = .chunks, .lists = .window, .fault = .drop_last }, + .{ .path = .chunks, .lists = .window, .fault = .no_sink }, + .{ .path = .chunks, .lists = .window, .fault = .half_sums }, + .{ .path = .chunks, .lists = .window, .fault = .skip_nan }, + .{ .path = .scored, .lists = .sparse, .fault = .shuffle }, +}; + +/// Rows of n heads, the last at position k - 1: sliding layers (64 heads) a 512-key window, sparse ones (32) every key. +const window_served = [_]c.Shape{ + .{ .rows = h.window_rows, .n = sliding_heads, .k = deep }, // DFly2's window, 512 keys a row + .{ .rows = h.decode_rows, .n = sliding_heads, .k = deep }, + .{ .rows = h.prompt_rows, .n = sliding_heads, .k = h.prompt_rows }, // a prompt's first chunk: 1 to 512 keys + .{ .rows = h.prompt_rows, .n = sliding_heads, .k = 2 * h.prompt_rows }, // its next: 512 keys a row + .{ .rows = h.decode_rows, .n = sparse_heads, .k = 1 }, // a sparse layer's first key + .{ .rows = h.window_rows, .n = sparse_heads, .k = 300 }, + .{ .rows = h.prompt_rows, .n = sparse_heads, .k = h.prompt_rows }, +}; +/// Past 2,048 keys each row attends its 2,048 recalled slots (a few dropped), in the recall's order. +const sparse_served = [_]c.Shape{ + .{ .rows = h.window_rows, .n = sparse_heads, .k = 1100 }, // a stride of 1,536 + .{ .rows = h.decode_rows, .n = sparse_heads, .k = 1024 }, + .{ .rows = h.prompt_rows, .n = sparse_heads, .k = 2 * h.prompt_rows }, + .{ .rows = h.prompt_rows, .n = sparse_heads, .k = 4 * h.prompt_rows }, + .{ .rows = h.decode_rows, .n = sparse_heads, .k = deep }, + .{ .rows = h.window_rows, .n = sparse_heads, .k = deep }, + .{ .rows = h.prompt_rows, .n = sparse_heads, .k = deep }, +}; +/// DFly2's draft rows at a stride of 2,560: past 2,048 the anchor's recall then the window's own rows, else every key. +const draft_served = [_]c.Shape{ + .{ .rows = h.window_rows, .n = sparse_heads, .k = deep }, + .{ .rows = h.decode_rows, .n = sparse_heads, .k = deep }, + .{ .rows = h.window_rows, .n = sparse_heads, .k = 2052 }, + .{ .rows = h.window_rows, .n = sparse_heads, .k = 700 }, +}; + +/// A score's chain and a chunk's rescales and sums, then the merge's chunks (bounds() derives the real allowance). +fn depth(s: c.Shape) usize { + return 23 + 2 * inputs.chunk + inputs.strideOf(.sparse, s.k) / inputs.chunk + 2; +} + +pub fn spec(v: Case, name: []const u8) c.Spec { + const served: []const c.Shape = switch (v.lists) { + .window => &window_served, + .sparse => &sparse_served, + .draft => &draft_served, + }; + // heads come four a threadgroup; each row's keys in 512-key chunks (the draft's stride stays 2,560) + var s: c.Spec = .{ + .name = name, + .accum = .f32, + .depth = depth, + .ops = 1, // gate 4's exact sums meet the merge's fp32 division before the bf16 rounding + .out = .bf16, + .tiles = .{ .{}, .{ .size = 4, .step = 1, .min = 1 }, if (v.lists == .draft) .{} else .{ .size = inputs.chunk, .step = 1, .min = 1 } }, + .served = served, + .replaces = if (v.path == .scored) one_step else null, + }; + if (v.first_inf) { + s.served = served[0..1]; + s.tiles = .{ .{}, .{}, .{} }; + s.known = .{ .gate = .nonfinite, .finding = first_inf_finding }; + } + return s; +} + +fn baseName(v: Case, buf: []u8) []const u8 { + const path = if (v.path == .chunks) one_step else two_step; + const extra = if (v.first_inf) ", -Inf score at a chunk's first key" else ""; + return std.fmt.bufPrint(buf, "{s} {t}{s}", .{ path, v.lists, extra }) catch path; +} + +/// The control's own pipeline: mla_attention.metal with its edit, compiled as Attention.load compiles the source. +fn ownPipeline(a: std.mem.Allocator, device: mtl.Device, f: Fault) !mtl.Pipeline { + const e = control(f).edit; + const text = try fl.edited(a, sources.hy4_flash_mla_attention, e); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, e.kernel, false); +} + +fn ref(r: rig_.Ref) mla.Ref { + return .{ .buffer = r.buf, .offset = r.off }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + plain: *const mla.Attention, + own: ?mtl.Pipeline = null, + v: Case, + base: [192]u8 = undefined, + label: [320]u8 = undefined, + name: []const u8 = "", + in: inputs.Inputs, + ins: [5]rig_.Ref = undefined, + parts: rig_.Ref = undefined, + scores: ?rig_.Ref = null, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, plain: *const mla.Attention, v: Case) !Probe { + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .plain = plain, .v = v, .in = .{ .a = a }, .own = if (v.fault) |f| try ownPipeline(a, device, f) else null }; + } + + fn drop(t: *Probe) void { + t.rig.reset(); + t.in.deinit(); + } + + pub fn deinit(t: *Probe) void { + t.drop(); + t.rig.deinit(); + if (t.own) |o| o.deinit(); + } + + /// The harness's release frees the host inputs and ranges too, so only one entry's are held at a time. + const vt: g.VTable = blk: { + var x = g.hooks(Probe); + x.release = release; + break :blk x; + }; + fn release(ctx: *anyopaque) void { + const t: *Probe = @ptrCast(@alignCast(ctx)); + t.drop(); + } + + pub fn kernel(t: *Probe) g.Kernel { + const b = baseName(t.v, &t.base); + const what = if (t.v.fault) |f| control(f).what else null; + t.name = fl.named(b, what, &t.label); + return .{ .spec = spec(t.v, t.name), .ctx = t, .vt = &vt, .control = if (t.v.fault) |f| control(f).gate else null }; + } + + /// The loader's pipelines, with a control's edited one in its kernel's place. + fn pipes(t: *const Probe) mla.Attention { + var p = t.plain.*; + const o = t.own orelse return p; + const name = control(t.v.fault.?).edit.kernel; + inline for (.{ "chunks", "merge", "scores", "scored" }) |f| { + if (std.mem.eql(u8, name, "tf_hy4_attend_" ++ f)) @field(p, f) = o; + } + return p; + } + + fn shape(t: *const Probe) !h.hy.mla_attention.Shape { + return h.hy.mla_attention.Shape.init(@intCast(t.in.rows), @intCast(t.in.heads), @intCast(t.in.stride)); + } + + pub fn prepare(t: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + t.drop(); + t.in = (try inputs.build(t.a, t.v.lists, s, fill, seed, t.v.first_inf)) orelse return false; + const in = &t.in; + const bytes = [_][]const u8{ std.mem.sliceAsBytes(in.q), std.mem.sliceAsBytes(in.cache), std.mem.sliceAsBytes(in.lists), std.mem.sliceAsBytes(in.counts), std.mem.sliceAsBytes(in.sinks) }; + for (bytes, &t.ins) |b, *r| r.* = try t.rig.input(b); + t.parts = try t.rig.scratch((try t.shape()).scratchBytes()); + t.scores = if (t.v.path == .scored) try t.rig.scratch(in.rows * in.heads * in.stride * 4) else null; + t.out = try t.rig.output(t.count() * 2); + return true; + } + + /// One pass through mla_metal.zig's Attention.attend: the two-step path with key scores bound, else chunks. + fn launch(t: *Probe, p: mla.Attention, two_step_path: bool) !void { + const b: mla.Attention.Buffers = .{ + .query = ref(t.ins[0]), + .cache = ref(t.ins[1]), + .slots = ref(t.ins[2]), + .counts = ref(t.ins[3]), + .sinks = ref(t.ins[4]), + .scratch = ref(t.parts), + .output = ref(t.out), + .key_scores = if (two_step_path) ref(t.scores.?) else null, + }; + const sh = try t.shape(); + const pass = t.rig.begin(); + const encoded = p.attend(pass.e, b, sh); + try t.rig.finish(pass); + return encoded; + } + + pub fn run(t: *Probe) !void { + return t.launch(t.pipes(), t.v.path == .scored); + } + + /// The one-step pass on the same inputs: the bytes the two-step pass must give. + pub fn replaced(t: *Probe) ![]const u8 { + try t.launch(t.plain.*, false); + return t.rig.bytes(t.out, t.count() * 2); + } + + pub fn count(t: *Probe) usize { + return t.in.outputs(); + } + + pub fn reference(t: *Probe, want: []f64, mag: []f64) !void { + try t.in.ranges(); + @memcpy(want, t.in.point); + for (mag, want) |*m, w| m.* = if (std.math.isFinite(w)) @abs(w) else 0; + } + + /// The range's allowance (attention_range.allowBf16); gate 4's exact sums keep the exact bound. + pub fn bounds(t: *Probe, want: []const f64, _: []const f64, allow: []f64) !void { + try t.in.ranges(); + const s = spec(t.v, t.name); + for (allow, want, t.in.point, t.in.half) |*l, w, p, hf| l.* = if (t.in.fill == .stress) c.boundExact(s, w) else ar.allowBf16(p, hf, 0, 0); + } + + /// Each bf16 output within its range's rounded ends (attention_range.intervalBf16); gate 4's are open. + pub fn intervals(t: *Probe, low: []f64, high: []f64) !void { + try t.in.ranges(); + for (low, high, t.in.point, t.in.half) |*l, *hi, p, hf| { + const e = if (t.in.fill == .stress) [2]f64{ -std.math.floatMax(f64), std.math.floatMax(f64) } else ar.intervalBf16(p, hf, 0, 0); + l.* = e[0]; + hi.* = e[1]; + } + } + + pub fn simulate(t: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + return t.in.simulate(acc, order, out); + } +}; + +/// The engine's widths, so these shapes move with its config: 64 sliding heads, 32 sparse, a 576-word slot. +fn checkConfig(a: std.mem.Allocator) !void { + const parsed = try h.text(a); + defer parsed.deinit(); + const t = parsed.value.text_config; + if (t.swa_num_attention_heads != sliding_heads or t.num_attention_heads != sparse_heads or t.sliding_window != inputs.window or + t.kv_lora_rank != lat or lat + t.qk_rope_head_dim != inputs.key or lat + t.swa_qk_rope_head_dim != inputs.key) + return error.Hy4AttentionGeometryMoved; +} + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + /// The loader's own four pipelines (Attention.load), shared by every entry. + plain: ?*mla.Attention = null, + tests: fl.List(Probe) = .{}, + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (cases) |v| { + var base: [192]u8 = undefined; + var label: [320]u8 = undefined; + const name = fl.named(baseName(v, &base), if (v.fault) |f| control(f).what else null, &label); + if (!fl.wanted(only, name)) continue; + if (s.plain == null) { + try checkConfig(s.a); + const p = try s.a.create(mla.Attention); + errdefer s.a.destroy(p); + p.* = try mla.Attention.load(s.device); + s.plain = p; + } + try s.tests.add(s.a, s.kernels, try Probe.init(s.a, s.device, s.queue, s.plain.?, v)); + } + } + + pub fn deinit(s: *Suite) void { + s.tests.deinit(s.a); + if (s.plain) |p| { + p.deinit(); + s.a.destroy(p); + } + } +}; + +/// Gate 5's text for an `hy4 mla_attention ` launch: the source as Attention.load compiles it, or a control's edit. +pub fn limitsText(a: std.mem.Allocator, _: mtl.Device, name: []const u8) !?fl.Texts { + if (!std.mem.startsWith(u8, name, stem)) return null; + for (std.enums.values(Fault)) |f| { + const ctl = control(f); + const want = try std.fmt.allocPrint(a, stem ++ "control {s} {s}", .{ ctl.word, ctl.edit.kernel }); + defer a.free(want); + if (!std.mem.eql(u8, name, want)) continue; + const text = try fl.edited(a, sources.hy4_flash_mla_attention, ctl.edit); + return .{ .here = text, .pre_m5 = text }; + } + return .{ .here = sources.hy4_flash_mla_attention, .pre_m5 = sources.hy4_flash_mla_attention }; +} diff --git a/zig/tests/contract/metal_hy4_attend_inputs.zig b/zig/tests/contract/metal_hy4_attend_inputs.zig new file mode 100644 index 00000000000..aab4ef321a2 --- /dev/null +++ b/zig/tests/contract/metal_hy4_attend_inputs.zig @@ -0,0 +1,297 @@ +//! Hy4-flash's MLA attention inputs: slot lists over a shuffled page table, the gates' fills and float64's ranges. +const std = @import("std"); +const contract = @import("contract"); +const h = @import("metal_hy4.zig"); +const fl = h.fl; +const c = contract.spec; +const g = contract.gates; +const ar = contract.attention_range; +const Cache = h.hy.attention_slots.Cache; + +/// A slot's 576 words: the 512-word latent (both key and value) and the 64 rope words (key only). +pub const lat = h.hy.mla_weights.latent; +pub const key = h.hy.mla_weights.absorbed_stride; +pub const chunk = h.hy.mla_attention.chunk_keys; +pub const window = h.hy.serve_metal.window; +pub const recalled = h.hy.metal_index.keys_a_row; +pub const draft_stride = h.hy.serve_metal.draft_stride; +pub const draft_rows = h.hy.serve_metal.max_window; +const scale: f64 = h.hy.mla_attention.score_scale; +/// A key's columns and one more: the sink is a key of value 0 whose score is q's extra 1 against sink / scale. +const E = key + 1; +const page_tokens = 64; +const nan16: u16 = 0x7fc0; + +/// Whose slot lists: a sliding layer's window, a sparse layer's (every key to 2,048, then recalled), DFly2's rows. +pub const Lists = enum { window, sparse, draft }; + +/// The key stride a pass binds: the window, a sparse pass's keys to a whole window or its recall, the draft's. +pub fn strideOf(l: Lists, end: usize) usize { + return switch (l) { + .window => window, + .sparse => if (end > recalled) recalled else (end + window - 1) / window * window, + .draft => draft_stride, + }; +} + +/// fp32 steps: 23 a score, precise::exp a weight, a rescale a key and the merge's; o 2 a key, l 1, then the merge. +fn form(keys: usize, chunks: usize) ar.Form { + const k: f64 = @floatFromInt(keys); + const n: f64 = @floatFromInt(chunks); + return .{ .score = 23, .fast_exp = false, .chunk_exp = false, .p_rel = 0, .num = 2 * k + n + 2, .den = k + n + 2, .exp_ulps = .{ 4 * (k + 2), 2 } }; +} + +/// Gate 4's values by residue: 127 and 16,256 in turn, the second half negated, four nudged; a window sums to 4. +fn stressValue(rho: usize) f32 { + const at = rho % 256; + const big: f32 = if (at % 2 == 0) 127 else 16256; + const one: f32 = if (at < 8 and at % 2 == 0) 1 else 0; + return if (rho < 256) big + one else -big; +} + +pub const Inputs = struct { + a: std.mem.Allocator, + rows: usize = 0, + heads: usize = 0, + stride: usize = 0, + fill: g.Fill = .random, + /// [rows][heads][576] absorbed queries, [slots + 1][576] the cache (the last slot all NaN), [rows][stride] lists. + q: []u16 = &.{}, + cache: []u16 = &.{}, + lists: []u32 = &.{}, + counts: []u32 = &.{}, + sinks: []f32 = &.{}, + /// Float64's outputs and how far the kernel's fp32 steps may move each, made when a gate first asks. + point: []f64 = &.{}, + half: []f64 = &.{}, + + pub fn deinit(in: *Inputs) void { + inline for (.{ "q", "cache", "lists", "counts", "sinks", "point", "half" }) |f| in.a.free(@field(in, f)); + in.* = .{ .a = in.a }; + } + + pub fn outputs(in: *const Inputs) usize { + return in.rows * in.heads * lat; + } + + fn list(in: *const Inputs, r: usize) []u32 { + return in.lists[r * in.stride ..][0..in.stride]; + } + + /// Whether slot `s` is a 512-key chunk's first key in any row's list. + fn leads(in: *const Inputs, s: u32) bool { + for (0..in.rows) |r| { + var i: usize = 0; + while (i < in.counts[r]) : (i += chunk) if (in.list(r)[i] == s) return true; + } + return false; + } + + /// A slot of row `r`'s list `back` keys before its last that leads no chunk in any list (null: none). + fn safe(in: *const Inputs, r: usize, back: usize) ?u32 { + var i = in.counts[r] -| (1 + back); + while (true) : (i -= 1) { + if (!in.leads(in.list(r)[i])) return in.list(r)[i]; + if (i == 0) return null; + } + } + + /// 2,048 distinct positions below `end`, a few dropped (-1) as DFly2's reuse does; gate 4's the last, in order. + fn recall(in: *const Inputs, pick: []i32, all: []i32, end: usize, rng: std.Random) void { + if (in.fill == .stress) { + for (pick, 0..) |*x, i| x.* = @intCast(end - recalled + i); + return; + } + for (all[0..end], 0..) |*x, i| x.* = @intCast(i); + for (pick, 0..) |*x, i| { + const j = i + rng.uintLessThan(usize, end - i); + std.mem.swap(i32, &all[i], &all[j]); + x.* = if (rng.uintLessThan(u32, 64) == 0) -1 else all[i]; + } + } + + /// Each row's list through the page table, as attention_slots.zig gives the engine's. + fn place(in: *Inputs, l: Lists, t: Cache, first: usize, recall_all: bool, rng: std.Random) !void { + const all = try in.a.alloc(i32, first + in.rows + recalled); + defer in.a.free(all); + const pick = all[first + in.rows ..][0..recalled]; + const draft_recall = l == .draft and first >= recalled; + if (draft_recall) in.recall(pick, all, first, rng); + const own = try in.a.alloc(i32, recalled + draft_rows); + defer in.a.free(own); + for (0..in.rows) |r| { + const end: u32 = @intCast(first + r + 1); + const out = in.list(r); + in.counts[r] = switch (l) { + .window => try t.sliding(end, window, out), + .sparse => if (recall_all) blk: { + in.recall(pick, all, end, rng); + break :blk try t.retained(end, pick, out); + } else try t.sliding(end, end, out), + // past 2,048 the anchor's recall below the window, then the window's own rows to this one + .draft => if (draft_recall) blk: { + @memcpy(own[0..recalled], pick); + for (own[recalled..][0 .. r + 1], 0..) |*x, i| x.* = @intCast(first + i); + break :blk try t.retained(end, own[0 .. recalled + r + 1], out); + } else try t.sliding(end, end, out), + }; + } + } + + /// NaN, +Inf and -Inf in a query, keys rows 1 to 3 see and two sinks; `first_inf` adds -Inf at row 4's first key. + fn plant(in: *Inputs, first_inf: bool) void { + const inf = fl.inf32; + if (in.heads > 1) in.q[(0 * in.heads + 1) * key + 3] = c.toBf16(fl.nan32); + const at = [_]struct { row: usize, back: usize, col: usize, v: f32 }{ + .{ .row = 1, .back = 1, .col = 5, .v = inf }, + .{ .row = 2, .back = 5, .col = lat + 8, .v = -inf }, + .{ .row = 3, .back = 9, .col = 7, .v = inf }, + .{ .row = 3, .back = 13, .col = 9, .v = -inf }, + }; + for (at) |p| if (p.row < in.rows) { + const s = in.safe(p.row, p.back) orelse continue; + in.cache[s * key + p.col] = c.toBf16(p.v); + // other rows meet it at a score of -Inf, so there it drops out but for its own latent column's 0 x Inf + for (0..in.rows) |r| if (r != p.row) for (0..in.heads) |hd| { + const w = &in.q[(r * in.heads + hd) * key + p.col]; + w.* = if (p.v > 0) w.* | 0x8000 else w.* & 0x7fff; + }; + }; + if (in.heads > 3) { + in.sinks[2] = fl.nan32; + in.sinks[3] = -inf; + } + if (!first_inf or in.rows < 5) return; + in.cache[in.list(4)[0] * key + lat + 8] = c.toBf16(-inf); + for (0..in.rows * in.heads) |rh| in.q[rh * key + lat + 8] = c.toBf16(1); + } + + /// Float64's outputs and half widths (attention_range.head per row and head), rows split over threads. + pub fn ranges(in: *Inputs) !void { + if (in.point.len != 0) return; + in.point = try in.a.alloc(f64, in.outputs()); + in.half = try in.a.alloc(f64, in.outputs()); + const threads = contract.reference_threads; + var jobs: [threads.maximum]Job = undefined; + const k = threads.count(threads.maximum, in.rows); + for (jobs[0..k], 0..) |*j, i| j.* = .{ .in = in, .first = i, .step = k }; + threads.run(Job, jobs[0..k], .normal); + for (jobs[0..k]) |j| if (j.err) |e| return e; + } + + const Job = struct { + in: *Inputs, + first: usize, + step: usize, + err: ?anyerror = null, + + pub fn run(j: *Job) void { + j.work() catch |e| { + j.err = e; + }; + } + + fn work(j: *Job) !void { + const in = j.in; + var most: usize = 0; + for (in.counts) |n| most = @max(most, n); + most += 1; + const buf = try in.a.alloc(f64, 2 * most * E + 2 * most + 3 * E); + defer in.a.free(buf); + const kv = 2 * most * E; + var r = j.first; + while (r < in.rows) : (r += j.step) in.row(r, buf[0 .. most * E], buf[most * E .. kv], buf[kv..][0..most], buf[kv + most ..][0..most], buf[kv + 2 * most ..][0 .. 3 * E]); + } + }; + + /// One row's keys gathered once, then each head through attention_range.head with its sink as one more key. + fn row(in: *Inputs, r: usize, kf: []f64, vf: []f64, w: []f64, tau: []f64, rest: []f64) void { + const qf = rest[0..E]; + const pt = rest[E .. 2 * E]; + const hf = rest[2 * E ..]; + const n = in.counts[r]; + for (in.list(r)[0..n], 0..) |s, j| { + const k = kf[j * E ..][0..E]; + const v = vf[j * E ..][0..E]; + for (k[0..key], in.cache[s * key ..][0..key]) |*x, word| x.* = c.fromBf16(word); + k[key] = 0; + @memcpy(v[0..lat], k[0..lat]); + @memset(v[lat..], 0); + } + const f = form(@min(n, chunk), (in.stride - 1) / chunk + 1); + for (0..in.heads) |hd| { + const sink: f64 = in.sinks[hd]; + const m = if (std.math.isNegativeInf(sink)) n else n + 1; + @memset(kf[n * E ..][0..E], 0); + @memset(vf[n * E ..][0..E], 0); + kf[n * E + key] = sink / scale; + for (qf[0..key], in.q[(r * in.heads + hd) * key ..][0..key]) |*x, word| x.* = c.fromBf16(word); + qf[key] = 1; + ar.head(qf, kf[0 .. m * E], vf[0 .. m * E], m, E, scale, f, w[0..m], tau[0..m], pt, hf); + const at = (r * in.heads + hd) * lat; + @memcpy(in.point[at..][0..lat], pt[0..lat]); + @memcpy(in.half[at..][0..lat], hf[0..lat]); + } + } + + /// Gate 4's sums: every score 0 and the sinks -Inf, so each output is its row's listed values' mean, rounded. + pub fn simulate(in: *const Inputs, acc: c.Accum, order: g.Order, out: []f64) !void { + if (in.fill != .stress) return error.StressRequiresEqualScores; + const terms = try in.a.alloc(f64, in.stride); + defer in.a.free(terms); + for (0..in.rows) |r| { + const n = in.counts[r]; + for (0..lat) |e| { + for (terms[0..n], in.list(r)[0..n]) |*t, s| t.* = c.fromBf16(in.cache[s * key + e]); + const o = fl.bf(contract.rows.sumIn(acc, order, terms[0..n]) / @as(f64, @floatFromInt(n))); + for (0..in.heads) |hd| out[(r * in.heads + hd) * lat + e] = o; + } + } + } +}; + +/// `shape.rows` rows of `shape.n` heads, the last at position `shape.k` - 1; null where the lists cannot serve it. +pub fn build(a: std.mem.Allocator, l: Lists, shape: c.Shape, fill: g.Fill, seed: u64, first_inf: bool) !?Inputs { + const rows = shape.rows; + const end = shape.k; + if (rows == 0 or shape.n == 0 or shape.n > 64 or end < rows) return null; + const first = end - rows; + const recall_all = l == .sparse and end > recalled; + if (recall_all and first + 1 < recalled) return null; + if (l == .draft and rows > draft_rows) return null; + var in: Inputs = .{ .a = a, .rows = rows, .heads = shape.n, .stride = strideOf(l, end), .fill = fill }; + errdefer in.deinit(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const pages = (end + page_tokens - 1) / page_tokens; + const bases = try a.alloc(u32, pages); + defer a.free(bases); + for (bases, 0..) |*b, i| b.* = @intCast(i * page_tokens); + rng.shuffle(u32, bases); + const table: Cache = .{ .page_bases = bases, .page_tokens = page_tokens, .capacity = @intCast(pages * page_tokens) }; + // every list entry past a row's count names the last slot, and every slot no list names stays NaN + const poison = pages * page_tokens; + in.cache = try a.alloc(u16, (poison + 1) * key); + @memset(in.cache, nan16); + in.lists = try a.alloc(u32, rows * in.stride); + @memset(in.lists, @intCast(poison)); + in.counts = try a.alloc(u32, rows); + in.q = try a.alloc(u16, rows * shape.n * key); + in.sinks = try a.alloc(f32, shape.n); + try in.place(l, table, first, recall_all, rng); + const seen = try a.alloc(bool, poison); + defer a.free(seen); + @memset(seen, false); + for (0..rows) |r| for (in.list(r)[0..in.counts[r]]) |s| { + seen[s] = true; + }; + for (0..end) |x| { + const s = try table.slot(@intCast(x)); + if (!seen[s]) continue; + for (in.cache[s * key ..][0..key], 0..) |*w, e| w.* = c.toBf16(if (fill != .stress) rng.float(f32) * 2 - 1 else if (e < lat) stressValue((x + e) % window) else 0); + } + for (in.q) |*x| x.* = if (fill == .stress) 0 else c.toBf16(rng.float(f32) * 4 - 2); + for (in.sinks) |*x| x.* = if (fill == .stress) -fl.inf32 else rng.float(f32) * 4 - 2; + if (fill == .nonfinite) in.plant(first_inf); + return in; +} diff --git a/zig/tests/contract/metal_hy4_experts.zig b/zig/tests/contract/metal_hy4_experts.zig new file mode 100644 index 00000000000..1123afc2380 --- /dev/null +++ b/zig/tests/contract/metal_hy4_experts.zig @@ -0,0 +1,131 @@ +//! Hy4-flash's experts group: the portable routed rows, the units' affine_mm gathers, tensor_dispatch's tables. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const h = @import("metal_hy4.zig"); +const mmx = @import("metal_hy4_experts_mm.zig"); +const ix = @import("metal_hy4_experts_index.zig"); +const g = contract.gates; + +// --- the planted faults; each is also a gate-5 launch named "hy4 [units ] [qN ]