diff --git a/CHANGELOG.md b/CHANGELOG.md index 4692a3cf5a2..cc966d6f462 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Hy4-flash (`hy_v4_flash`) on Metal: `tensorfold-native serve` takes Tencent's 4- and 8-bit MLX checkpoints with DFly2 drafts, contexts to 256K tokens (128K by default; the compressed indexer recalls 2,048 keys a sparse layer past 2,048 tokens), and a following prompt that starts with the last one's tokens prefills only the rest; Hy4's chat template needs `str.format()` from #3816 (Refs #3797). - CLI: `tensorfold log` reads the request journal read-only while a server runs: `list` with tokens, time to first token and decode rate, `show ID` with the reply decoded, `follow` across rotations and `--json`; journal `finish` records carry the queue wait, time to first token, decode rate and token counts (#4160, part of #3666). - Engine: under SRPT scheduling, a prompt that finishes on its last fill step no longer writes its lent time to freed scheduler memory (#4159, fixes #3709). diff --git a/build.zig b/build.zig index 8eedd401e6d..3f34ae85875 100644 --- a/build.zig +++ b/build.zig @@ -187,6 +187,7 @@ pub fn build(b: *std.Build) void { else => {}, } @import("zig/build/gemma4_backward.zig").tests(b, test_step); + @import("zig/build/hy4_flash.zig").tests(b, test_step); const gemma4_host_sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = b.graph.host }); gemma4_host_sources.addAnonymousImport("nemotron_packed_metallib", .{ .root_source_file = b.addWriteFiles().add("gemma4-host-empty.metallib", "") }); const gemma4_contract_host = @import("zig/build/gemma4_host.zig").tests(b, gemma4_host_sources); diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index 6dc95046a32..d6aa84acf4a 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -148,6 +148,13 @@ pub const kernels = [_]Kernel{ .{ .name = "glm_glue", .flags = &.{"-O3"} }, // ours: the Python family's Triton glue by hand, its PTX op for op .{ .name = "glm_ops", .flags = &.{"-O3"} }, // ours: GLM's integer work the Python family did in torch (the DSA token lists) .{ .name = "glm_index", .flags = &.{"-O3"} }, // a prompt chunk's DSA scores and top-512 pools + .{ .name = "hy4_indexpool", .src = "hy4_flash/indexpool", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "affine_experts", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "hy4_index_recall", .src = "hy4_flash/index_recall", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "hy4_attention_sink", .src = "hy4_flash/attention_sink", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "hy4_mla_project", .src = "hy4_flash/mla_project", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "hy4_mla_attention", .src = "hy4_flash/mla_attention", .flags = &.{ "-O3", "--fmad=false" } }, + .{ .name = "hy4_ihc", .src = "hy4_flash/ihc", .flags = &.{ "-O3", "--fmad=false" } }, .{ .name = "minimax_m3", .flags = glue }, // ours: MiniMax-M3.1-Flash's glue (norms, RoPE prep, routing, DSpark, tower RoPE) .{ .name = "minimax_m3_attn", .flags = glue }, // ours: MiniMax-M3.1-Flash's indexer and block-sparse attention .{ .name = "idol", .flags = glue }, // ours: Idol's denoiser glue and its fp16 head-64 attention diff --git a/zig/build/hy4_flash.zig b/zig/build/hy4_flash.zig new file mode 100644 index 00000000000..89f7be189be --- /dev/null +++ b/zig/build/hy4_flash.zig @@ -0,0 +1,23 @@ +//! Host checks for native Hy4-flash tensor layouts, retained keys and draft inputs. +const std = @import("std"); + +pub fn tests(b: *std.Build, test_step: *std.Build.Step) void { + const core = b.createModule(.{ + .root_source_file = b.path("zig/src/core/root.zig"), + .target = b.graph.host, + .link_libc = true, + }); + const hash = b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig") }); + const module = b.createModule(.{ + .root_source_file = b.path("zig/src/families/hy4_flash/host_tests.zig"), + .target = b.graph.host, + .link_libc = true, + .imports = &.{ + .{ .name = "core", .module = core }, + .{ .name = "engram_hash_core", .module = hash }, + }, + }); + const run = b.addRunArtifact(b.addTest(.{ .root_module = module })); + test_step.dependOn(&run.step); + b.step("test-hy4-flash-host", "Hy4-flash checkpoint layout, slot selection, Engram gathers and DFly2 inputs").dependOn(&run.step); +} diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index b00995dcff3..bc32613dff3 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -554,6 +554,7 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living } }, }); + engine.addImport("engram_hash_core", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize })); return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; } diff --git a/zig/gemma4_shared_affine_test.zig b/zig/gemma4_shared_affine_test.zig index 4ab73b90968..6c2b89115f0 100644 --- a/zig/gemma4_shared_affine_test.zig +++ b/zig/gemma4_shared_affine_test.zig @@ -103,14 +103,14 @@ test "landed Metal source bytes are pinned without shader compilation" { { var hash: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(ks.core_affine_mm, &hash, .{}); - // dda89ef49's bytes: 47afc1620..dda89ef49 reworded comments only, after cf10a6b7d's pinned edit - try std.testing.expectEqualStrings("c959eb1f5ac8a57049c09b3aad5d20f26b64f2e47d8b082c47ebbfae90d97a8b", &std.fmt.bytesToHex(hash, .lower)); + // Hy4-flash's mapped experts and rounded SiLU, both behind defines that are off for every other caller + try std.testing.expectEqualStrings("2cf4deb55455fda30efb4fce3043ef5d90052d71f48ce7660960e8b588478aca", &std.fmt.bytesToHex(hash, .lower)); } { var hash: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(ks.core_lane_projection, &hash, .{}); - // Packed affine lanes with producer sums and independent prompt row blocks. - try std.testing.expectEqualStrings("7befe2028dae5036541f311f230a02d5652e634450ef16dc66dce6e15e935277", &std.fmt.bytesToHex(hash, .lower)); + // Packed affine lanes with producer sums, prompt row blocks, inline sums and the 8-bit reg layout. + try std.testing.expectEqualStrings("d921d9a938d3c4f1fe5a1c89ddfd135d96845055bee1721080ba82fef7a9f8e3", &std.fmt.bytesToHex(hash, .lower)); } } test "released lane parameters and conservative scratch size" { diff --git a/zig/kernels/cuda/affine_experts.cu b/zig/kernels/cuda/affine_experts.cu new file mode 100644 index 00000000000..e3296e44de0 --- /dev/null +++ b/zig/kernels/cuda/affine_experts.cu @@ -0,0 +1,82 @@ +// CUDA grouped FFN rows over the checkpoint's 4- or 8-bit MLX affine experts (group size 64). +#include +#include +#include "common/reduce.cuh" + +struct AffineExpertShape { + uint32_t width, inner, first, experts, pairs, rows; + float swiglu_limit; +}; + +template +__device__ float dot(const __nv_bfloat16 *input, const uint32_t *words, const __nv_bfloat16 *scale, + const __nv_bfloat16 *bias, uint32_t width, uint32_t lane) { + constexpr uint32_t mask = (1 << Bits) - 1; + float acc = 0.0f; + for (uint32_t group = 0; group < width / 64; ++group) { + const float s = __bfloat162float(scale[group]), b = __bfloat162float(bias[group]); + for (uint32_t i = lane; i < 64; i += 32) { + const uint32_t index = group * 64 + i; + const uint32_t bit = index * Bits; + const float code = float((words[bit / 32] >> (bit % 32)) & mask); + const float w = __bfloat162float(__float2bfloat16_rn(__fmaf_rn(code, s, b))); + acc = __fmaf_rn(__bfloat162float(input[index]), w, acc); + } + } + return tf_common::warp_sum(acc); +} + +template +__device__ void expert_rows(const __nv_bfloat16 *x, const int32_t *ids, const int32_t *source, + const uint32_t *words, const __nv_bfloat16 *scale, const __nv_bfloat16 *bias, + void *output, AffineExpertShape a) { + const uint32_t pair = blockIdx.y, lane = threadIdx.x % 32; + const uint32_t n = 4 * blockIdx.x + threadIdx.x / 32; + const uint32_t width = Up ? a.width : a.inner, size = Up ? a.inner : a.width; + if (n >= size) return; + const uint64_t out = uint64_t(pair) * size + n; + const int32_t id = ids[pair]; + const int32_t row = Up ? source[pair] : pair; + if (id < 0 || uint32_t(id) < a.first || uint32_t(id) - a.first >= a.experts || + row < 0 || (Up && uint32_t(row) >= a.rows)) { + if (lane == 0) { + if constexpr (Up) reinterpret_cast<__nv_bfloat16 *>(output)[out] = __float2bfloat16_rn(0.0f); + else reinterpret_cast(output)[out] = 0.0f; + } + return; + } + + const __nv_bfloat16 *input = x + uint64_t(row) * width; + const uint64_t expert_row = uint64_t(uint32_t(id) - a.first) * (Up ? 2 * size : size) + n; + const uint32_t packed_width = width * Bits / 32, groups = width / 64; + const uint64_t wc = expert_row * packed_width, gc = expert_row * groups; + const float first = dot(input, words + wc, scale + gc, bias + gc, width, lane); + if constexpr (Up) { + const uint64_t wu = wc + uint64_t(size) * packed_width, gu = gc + uint64_t(size) * groups; + const float second = dot(input, words + wu, scale + gu, bias + gu, width, lane); + if (lane == 0) { + float gate = __bfloat162float(__float2bfloat16_rn(first)); + float up = __bfloat162float(__float2bfloat16_rn(second)); + if (a.swiglu_limit > 0) { + gate = fminf(gate, a.swiglu_limit); + up = fminf(a.swiglu_limit, fmaxf(-a.swiglu_limit, up)); + } + const float activated = __bfloat162float(__float2bfloat16_rn(gate / (1.0f + expf(-gate)))); + reinterpret_cast<__nv_bfloat16 *>(output)[out] = __float2bfloat16_rn(activated * up); + } + } else if (lane == 0) { + reinterpret_cast(output)[out] = first; + } +} + +#define TF_AFFINE_EXPERTS(bits, suffix, up) \ +extern "C" __global__ void __launch_bounds__(128) tf_affine_experts_##suffix##_##bits( \ + const __nv_bfloat16 *x, const int32_t *ids, const int32_t *rows, const uint32_t *words, \ + const __nv_bfloat16 *scale, const __nv_bfloat16 *bias, void *out, AffineExpertShape shape) { \ + expert_rows(x, ids, rows, words, scale, bias, out, shape); \ +} + +TF_AFFINE_EXPERTS(4, up, true) +TF_AFFINE_EXPERTS(4, down, false) +TF_AFFINE_EXPERTS(8, up, true) +TF_AFFINE_EXPERTS(8, down, false) diff --git a/zig/kernels/cuda/hy4_flash/attention_sink.cu b/zig/kernels/cuda/hy4_flash/attention_sink.cu new file mode 100644 index 00000000000..2b8d1d106b1 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/attention_sink.cu @@ -0,0 +1,21 @@ +// Finish a head's online softmax with its learned, zero-value sink. +extern "C" __global__ void tf_hy4_finish_attention( + const float *maxima, + const float *mass, + const float *numerator, + const float *sinks, + float *output, + unsigned int rows, + unsigned int heads, + unsigned int width) { + const unsigned int row_head = blockIdx.x; + const unsigned int column = blockIdx.y * blockDim.x + threadIdx.x; + if (column >= width || row_head >= static_cast(rows) * heads) return; + + const float sink = sinks[row_head % heads]; + const float top = fmaxf(maxima[row_head], sink); + const float prior = expf(maxima[row_head] - top); + const float denominator = mass[row_head] * prior + expf(sink - top); + const unsigned long long offset = static_cast(row_head) * width + column; + output[offset] = numerator[offset] * prior / denominator; +} diff --git a/zig/kernels/cuda/hy4_flash/ihc.cu b/zig/kernels/cuda/hy4_flash/ihc.cu new file mode 100644 index 00000000000..4d67223b373 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/ihc.cu @@ -0,0 +1,59 @@ +// Hy4-flash reads independent stream gates in FP32 and stores BF16 hidden rows. +#include +#include +#include "../common/reduce.cuh" + +struct Hy4IhcShape { + uint32_t rows, width, gates; + float eps, gate_eps, post_magnitude; +}; + +extern "C" __global__ void __launch_bounds__(256) tf_hy4_ihc_collapse( + const __nv_bfloat16 *hidden, const float *project, const float *bias, const float *scale, + __nv_bfloat16 *collapsed, float *post, Hy4IhcShape a) { + __shared__ float partial[9][8], pre[4]; + const uint32_t t = threadIdx.x, wide = 4 * a.width, row = blockIdx.x; + const uint32_t lane = t % 32, warp = t / 32; + const __nv_bfloat16 *x = hidden + uint64_t(row) * wide; + float sq = 0.0f, logits[8] = {}; + for (uint32_t i = t; i < wide; i += 256) { + const float v = __bfloat162float(x[i]); + sq = __fmaf_rn(v, v, sq); + for (uint32_t j = 0; j < a.gates; ++j) logits[j] = __fmaf_rn(v, project[j * wide + i], logits[j]); + } + sq = tf_common::warp_sum(sq); + if (lane == 0) partial[8][warp] = sq; + for (uint32_t j = 0; j < a.gates; ++j) { + const float score = tf_common::warp_sum(logits[j]); + if (lane == 0) partial[j][warp] = score; + } + __syncthreads(); + if (t < a.gates) { + float sum = 0.0f, dot = 0.0f; + for (uint32_t i = 0; i < 8; ++i) { + sum += partial[8][i]; + dot += partial[t][i]; + } + const float mix = dot * rsqrtf(sum / float(wide) + a.eps); + const float gate = 1.0f / (1.0f + expf(-(mix * scale[t / 4] + bias[t]))); + if (t < 4) pre[t] = gate + a.gate_eps; + else post[uint64_t(row) * 4 + t - 4] = a.post_magnitude * gate + a.gate_eps; + } + __syncthreads(); + for (uint32_t i = t; i < a.width; i += 256) { + float v = 0.0f; + for (uint32_t j = 0; j < 4; ++j) v += pre[j] * __bfloat162float(x[j * a.width + i]); + collapsed[uint64_t(row) * a.width + i] = __float2bfloat16_rn(v); + } +} + +extern "C" __global__ void __launch_bounds__(256) tf_hy4_ihc_add( + const __nv_bfloat16 *residual, const __nv_bfloat16 *branch, const float *post, + __nv_bfloat16 *output, Hy4IhcShape a) { + const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y; + if (i >= 4 * a.width) return; + const uint64_t full = uint64_t(row) * 4 * a.width + i; + const uint64_t local = uint64_t(row) * a.width + i % a.width; + output[full] = __float2bfloat16_rn(__bfloat162float(residual[full]) + + post[uint64_t(row) * 4 + i / a.width] * __bfloat162float(branch[local])); +} diff --git a/zig/kernels/cuda/hy4_flash/index_recall.cu b/zig/kernels/cuda/hy4_flash/index_recall.cu new file mode 100644 index 00000000000..cd821e709fa --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/index_recall.cu @@ -0,0 +1,58 @@ +// Score only earlier completed groups. When they all fit, selection reads no scores. +#include +#include +#include "../common/reduce.cuh" +#include "../glm_index_pools.cuh" + +struct Hy4RecallShape { uint32_t rows, score_groups, group_budget; }; +struct Hy4RecallRow { uint32_t group_base, token; }; + +extern "C" __global__ void __launch_bounds__(128) tf_hy4_group_scores( + const __nv_bfloat16 *query, const __nv_bfloat16 *keys, const __nv_bfloat16 *head_weights, + const Hy4RecallRow *rows, float *scores, Hy4RecallShape a, float head_scale) { + const uint32_t r = blockIdx.y, lane = threadIdx.x % 32; + const uint32_t group = blockIdx.x * 4 + threadIdx.x / 32; + const Hy4RecallRow row = rows[r]; + const uint32_t closed = row.token / 4; + if (closed < a.group_budget || closed > a.score_groups || group >= closed) return; + const __nv_bfloat16 *key = keys + (uint64_t(row.group_base) + group) * 128; + float cached[4]; + for (uint32_t d = 0; d < 4; ++d) cached[d] = __bfloat162float(key[lane + d * 32]); + float score = 0.0f; + for (uint32_t head = 0; head < 16; ++head) { + const __nv_bfloat16 *q = query + (uint64_t(r) * 16 + head) * 128; + float dot = 0.0f; + for (uint32_t d = 0; d < 4; ++d) dot = __fmaf_rn(__bfloat162float(q[lane + d * 32]), cached[d], dot); + dot = tf_common::warp_sum(dot); + const float weight = __bfloat162float(head_weights[uint64_t(r) * 16 + head]) * head_scale; + score = __fmaf_rn(weight, fmaxf(dot, 0.0f), score); + } + if (lane == 0) scores[uint64_t(r) * a.score_groups + group] = score; +} + +extern "C" __global__ void __launch_bounds__(256) tf_hy4_recall_groups( + const float *scores, const Hy4RecallRow *rows, int32_t *tokens, int32_t *counts, Hy4RecallShape a) { + __shared__ glm_index::Smem scratch; + __shared__ int64_t selected[511]; + const uint32_t r = blockIdx.x, position = rows[r].token, closed = position / 4; + if (closed > a.score_groups) { + if (threadIdx.x == 0) counts[r] = 0; + return; + } + const uint32_t keep = min(closed, a.group_budget - 1); + if (closed > keep) { + int phase = 0; + const glm_index::Row candidates { scores + uint64_t(r) * a.score_groups, int(closed) }; + glm_index::select(scratch, candidates, int(keep), selected, phase); + } else { + for (uint32_t i = threadIdx.x; i < keep; i += 256) selected[i] = i; + } + __syncthreads(); + int32_t *out = tokens + uint64_t(r) * a.group_budget * 4; + const uint32_t count = keep * 4 + position % 4 + 1; + for (uint32_t i = threadIdx.x; i < count; i += 256) { + const uint32_t id = i / 4 < keep ? uint32_t(selected[i / 4]) : closed; + out[i] = int32_t(id * 4 + i % 4); + } + if (threadIdx.x == 0) counts[r] = int32_t(count); +} diff --git a/zig/kernels/cuda/hy4_flash/indexpool.cu b/zig/kernels/cuda/hy4_flash/indexpool.cu new file mode 100644 index 00000000000..0e90a872779 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/indexpool.cu @@ -0,0 +1,32 @@ +// Hy4-flash's four-slot sparse index pooling before key normalization and RoPE. +extern "C" __global__ void tf_hy4_pool_groups( + const float *values, + const float *gates, + const float *position_bias, + float *output, + unsigned int groups, + unsigned int width) { + const unsigned int group = blockIdx.x; + const unsigned int column = blockIdx.y * blockDim.x + threadIdx.x; + if (column >= width || group >= groups) return; + + const unsigned long long base = static_cast(group) * 4 * width + column; + float logits[4]; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) { + const unsigned int offset = slot * width; + logits[slot] = gates[base + offset] + position_bias[offset + column]; + } + const float maximum = fmaxf(fmaxf(logits[0], logits[1]), fmaxf(logits[2], logits[3])); + float weights[4]; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) weights[slot] = expf(logits[slot] - maximum); + const float normalizer = ((weights[0] + weights[1]) + weights[2]) + weights[3]; + float projected[4]; + #pragma unroll + for (unsigned int slot = 0; slot < 4; ++slot) { + projected[slot] = values[base + slot * width] * (weights[slot] / normalizer); + } + output[static_cast(group) * width + column] = + ((projected[0] + projected[1]) + projected[2]) + projected[3]; +} diff --git a/zig/kernels/cuda/hy4_flash/mla_attention.cu b/zig/kernels/cuda/hy4_flash/mla_attention.cu new file mode 100644 index 00000000000..281d67dc6f6 --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_attention.cu @@ -0,0 +1,37 @@ +// Score absorbed queries against retained BF16 cache rows. The retained slots already include any causal limit. +#include +#include +#include "../common/mla.cuh" + +extern "C" __global__ void __launch_bounds__(256) tf_hy4_attend_chunks( + const __nv_bfloat16 *qa, const __nv_bfloat16 *cache, const int *slots, const int *counts, + float *numerator, float *maxima, float *mass, int64_t rows, int64_t heads, int64_t key_stride, + float scale) { + glm_attn::chunks_wide<16, false, 64>( + qa, cache, nullptr, slots, counts, numerator, maxima, mass, rows, heads, key_stride, scale, + 1, nullptr, 0); +} + +// Merge tiled maxima and mass, counting each head's learned zero-value sink exactly once. +extern "C" __global__ void __launch_bounds__(128) tf_hy4_attend_merge( + const float *numerator, const float *maxima, const float *mass, const float *sinks, + __nv_bfloat16 *output, int64_t rows, int64_t heads, int32_t chunks) { + constexpr int latent = glm_attn::LW; + const int64_t head = blockIdx.y; + const int64_t row_head = blockIdx.x * heads + head; + const int64_t plane = rows * heads; + const int column = threadIdx.x * 4; + float top = sinks[head]; + for (int i = 0; i < chunks; ++i) top = fmaxf(top, maxima[i * plane + row_head]); + float denom = expf(sinks[head] - top); + float acc[4] = {}; + for (int i = 0; i < chunks; ++i) { + const int64_t base = i * plane + row_head; + const float p = expf(maxima[base] - top); + denom = __fmaf_rn(mass[base], p, denom); + #pragma unroll + for (int j = 0; j < 4; ++j) acc[j] = __fmaf_rn(numerator[base * latent + column + j], p, acc[j]); + } + #pragma unroll + for (int j = 0; j < 4; ++j) output[row_head * latent + column + j] = __float2bfloat16_rn(acc[j] / denom); +} diff --git a/zig/kernels/cuda/hy4_flash/mla_project.cu b/zig/kernels/cuda/hy4_flash/mla_project.cu new file mode 100644 index 00000000000..02d916e671a --- /dev/null +++ b/zig/kernels/cuda/hy4_flash/mla_project.cu @@ -0,0 +1,85 @@ +// Hy4-flash's 192-wide query and 256-wide value projections on the shared MLA tiles. +#include +#include +#include "../common/mla.cuh" +#include "../common/reduce.cuh" + +struct Hy4RopeParameters { float frequencies[32]; uint32_t axes[32]; }; +struct Hy4RopeView { uint32_t rows, heads, input_stride, output_stride; }; +struct Hy4CacheWrite { uint32_t rows, capacity; float epsilon; }; + +// A request's write slots address distinct live rows in the retained latent arena. +extern "C" __global__ void __launch_bounds__(128) tf_hy4_cache_keys( + const __nv_bfloat16 *input, const __nv_bfloat16 *gain, const __nv_bfloat16 *table, const int32_t *slots, + __nv_bfloat16 *cache, Hy4CacheWrite a) { + const uint32_t row = blockIdx.x, t = threadIdx.x; + const int slot = slots[row]; + if (slot < 0 || uint32_t(slot) >= a.capacity) return; + const __nv_bfloat16 *x = input + uint64_t(row) * 576; + __nv_bfloat16 *y = cache + uint64_t(slot) * 576; + float v[4], sq = 0.0f; + #pragma unroll + for (int i = 0; i < 4; ++i) { + v[i] = __bfloat162float(x[t + i * 128]); + sq = __fmaf_rn(v[i], v[i], sq); + } + __shared__ float partial[4]; + const float inverse = rsqrtf(tf_common::block_sum_tree(sq, partial, 4) / 512.0f + a.epsilon); + for (int i = 0; i < 4; ++i) { + const uint32_t col = t + i * 128; + const float normalized = __bfloat162float(__float2bfloat16_rn(v[i] * inverse)); + y[col] = __float2bfloat16_rn(normalized * __bfloat162float(gain[col])); + } + if (t < 32) { + const uint32_t col = 2 * t; + const float u = __bfloat162float(x[512 + col]), v1 = __bfloat162float(x[513 + col]); + const float c = __bfloat162float(table[uint64_t(row) * 64 + col]); + const float s = __bfloat162float(table[uint64_t(row) * 64 + col + 1]); + y[512 + col] = __float2bfloat16_rn(u * c - v1 * s); + y[513 + col] = __float2bfloat16_rn(v1 * c + u * s); + } +} + +// Per-value gate on the expanded heads. Sigmoid rounds to BF16 before the product. +extern "C" __global__ void __launch_bounds__(128) tf_hy4_gate_values( + __nv_bfloat16 *values, const __nv_bfloat16 *logits, uint32_t columns) { + const uint32_t col = blockIdx.x * blockDim.x + threadIdx.x; + if (col >= columns) return; + const uint64_t i = uint64_t(blockIdx.y) * columns + col; + const float gate = 1.0f / (1.0f + expf(-__bfloat162float(logits[i]))); + values[i] = __float2bfloat16_rn(__bfloat162float(values[i]) * __bfloat162float(__float2bfloat16_rn(gate))); +} + +extern "C" __global__ void __launch_bounds__(32) tf_hy4_rotary_table( + const int32_t *positions, __nv_bfloat16 *table, Hy4RopeParameters p) { + const uint32_t pair = threadIdx.x, row = blockIdx.x; + const float phase = float(positions[uint64_t(row) * 3 + p.axes[pair]]) * p.frequencies[pair]; + float s, c; + sincosf(phase, &s, &c); + table[uint64_t(row) * 64 + 2 * pair] = __float2bfloat16_rn(c); + table[uint64_t(row) * 64 + 2 * pair + 1] = __float2bfloat16_rn(s); +} + +extern "C" __global__ void __launch_bounds__(32) tf_hy4_rotate( + const __nv_bfloat16 *input, const __nv_bfloat16 *table, __nv_bfloat16 *output, Hy4RopeView v) { + const uint32_t row = blockIdx.x, head = blockIdx.y, col = 2 * threadIdx.x; + const uint64_t row_head = uint64_t(row) * v.heads + head; + const uint64_t i = row_head * v.input_stride + col, o = row_head * v.output_stride + col; + const uint64_t base = uint64_t(row) * 64 + col; + const float a = __bfloat162float(input[i]), b = __bfloat162float(input[i + 1]); + const float c = __bfloat162float(table[base]), s = __bfloat162float(table[base + 1]); + output[o] = __float2bfloat16_rn(a * c - b * s); + output[o + 1] = __float2bfloat16_rn(b * c + a * s); +} + +extern "C" __global__ void __launch_bounds__(128) +tf_hy4_absorb_q(const __nv_bfloat16 *q, const __nv_bfloat16 *wk, __nv_bfloat16 *out, + int64_t rows, int64_t heads, int64_t rows_per_block) { + tf_mla::absorb_q<192>(q, wk, out, rows, heads, rows_per_block, 256, 576); +} + +extern "C" __global__ void __launch_bounds__(128) +tf_hy4_expand_v(const __nv_bfloat16 *o, const __nv_bfloat16 *wv, __nv_bfloat16 *out, + int64_t rows, int64_t heads, int64_t rows_per_block) { + tf_mla::expand_v<256>(o, wv, out, rows, heads, rows_per_block); +} diff --git a/zig/kernels/metal/core/affine_mm.metal b/zig/kernels/metal/core/affine_mm.metal index 833756dc2c4..c5b94d93d98 100644 --- a/zig/kernels/metal/core/affine_mm.metal +++ b/zig/kernels/metal/core/affine_mm.metal @@ -442,12 +442,20 @@ TF_GATHER(32) TF_GATHER(64) // The gathers with each sorted row's output put back at row DST[row] (e.g. the (row, slot) pairs' own order). +#ifdef TF_AM_MAPPED_EXPERTS +#define TF_AM_MAP_ARG const device int32_t* EA [[buffer(13)]], +#define TF_AM_EXPERT(e) EA[e] +#else +#define TF_AM_MAP_ARG +#define TF_AM_EXPERT(e) (e) +#endif + #define TF_GATHER_SCATTER(BM) \ [[kernel]] void tf_affine_gather_scatter_##BM( \ const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], \ const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], \ const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device TF_OUT_T* Y [[buffer(6)]], \ - const device int32_t* OFFS [[buffer(7)]], const device int32_t* DST [[buffer(8)]], \ + const device int32_t* OFFS [[buffer(7)]], const device int32_t* DST [[buffer(8)]], TF_AM_MAP_ARG \ uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ uint3 tg [[threadgroup_position_in_grid]]) { \ threadgroup bfloat tile[64 * PAD]; \ @@ -455,7 +463,7 @@ TF_GATHER(64) int expert, row, rows; \ if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ const int col = int(tg.x) * 64; \ - am_block(X, a.k, XS, a.k / TF_GROUP, row, rows, a.k, a.n, col, long(expert) * a.n + col, W, S, B, Y, \ + am_block(X, a.k, XS, a.k / TF_GROUP, row, rows, a.k, a.n, col, long(TF_AM_EXPERT(expert)) * a.n + col, W, S, B, Y, \ tile, sb, sg, lane, DST); \ } TF_GATHER_SCATTER(32) @@ -481,7 +489,11 @@ inline bfloat am_swiglu(float g, float u, float limit) { const float lim = float(bfloat(limit)); const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim)); const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim)); +#ifdef TF_GLU_ROUND_SILU + const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); +#else const bfloat sl = gt * am_sigmoid(gt); +#endif return sl * up; } #endif @@ -508,7 +520,7 @@ inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \ const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \ const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \ - const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], \ + const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], TF_AM_MAP_ARG \ uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ uint3 tg [[threadgroup_position_in_grid]]) { \ constexpr int SM = BM / 2; \ @@ -519,7 +531,7 @@ inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ const int c0 = int(tg.x) * 32, t = int(sg) * 32 + int(lane), tr = t / 2; \ const bool up = ((tr >> 4) & 1) != 0; \ - const long wrow = long(expert) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ + const long wrow = long(TF_AM_EXPERT(expert)) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \ const short2 home = frag_home(ushort(lane)); \ const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \ diff --git a/zig/kernels/metal/core/lane_projection.metal b/zig/kernels/metal/core/lane_projection.metal index 7e65ddb08b6..f8d2d071a83 100644 --- a/zig/kernels/metal/core/lane_projection.metal +++ b/zig/kernels/metal/core/lane_projection.metal @@ -15,6 +15,14 @@ using namespace mpp::tensor_ops; #ifndef TF_ROW_BLOCKS #define TF_ROW_BLOCKS 0 #endif +// TF_INLINE_SUMS: each split adds its rows' group sums with the sums pass's own loop (no sums dispatch, same words). +#ifndef TF_INLINE_SUMS +#define TF_INLINE_SUMS 0 +#endif +#if TF_INLINE_SUMS +// A split's groups at most; its (group, row) sums sit in threadgroup memory as XS does with stride 16. +constant constexpr int TF_GPS = (TF_GN + TF_SK - 1) / TF_SK; +#endif #ifndef TF_YS #define TF_YS TF_N #endif @@ -224,6 +232,17 @@ inline void tf_stage_codes(threadgroup uint* stage, thread const tf_raw& raw, in const device uint4* sbv = (const device uint4*)SBt; float C[NF * 8]; for (int i = 0; i < NF * 8; i++) C[i] = 0.0f; +#if TF_INLINE_SUMS && !TF_PRECOMPUTE_SUMS + // the split's group sums up front, a (group, row) chain a lane at a time over the pass's rows: the same words + threadgroup float xs_all[TF_SK * TF_GPS * 16]; + threadgroup float* XT = xs_all + sg * TF_GPS * 16; + for (int p = lane; p < (g_end - g_begin) * 16; p += 32) XT[p] = 0.0f; + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int p = lane; p < (g_end - g_begin) * M; p += 32) XT[(p / M) * 16 + p % M] = tf_lane_xsum(X, p % M, g_begin + p / M, M); + simdgroup_barrier(mem_flags::mem_threadgroup); +#undef TF_SUM_VALUE +#define TF_SUM_VALUE(row, g) XT[((g) - g_begin) * 16 + (row)] +#endif tf_raw r0 = tf_lane_fetch(W, sbv, tile, g_begin, g_end, n0, lane, fn); #if TF_PF == 2 tf_raw r1 = tf_lane_fetch(W, sbv, tile, g_begin + 1, g_end, n0, lane, fn); @@ -303,12 +322,27 @@ uint group_id [[simdgroup_index_in_threadgroup]],uint lane [[thread_index_in_sim } #endif -#if TF_BITS == 4 && defined(TF_REG) -struct tf_reg_load { uint4 w0, w1, q0, q1; float x0, x1; }; // a lane's codes, its two metadata quads and its two row sums for one group +#if (TF_BITS == 4 || TF_BITS == 8) && defined(TF_REG) +// A lane's codes for one group (4-bit: two quads; 8-bit: the same codes a byte each), metadata quads and row sums. +#if TF_BITS == 8 +struct tf_reg_load { uint4 w[4]; uint4 q0, q1; float x0, x1; }; +constant constexpr int TF_REG_QUADS = 4; +#define TF_REG_CODES(wl, g) {wl[(size_t)(g) * 128], wl[(size_t)(g) * 128 + 32], wl[(size_t)(g) * 128 + 64], wl[(size_t)(g) * 128 + 96]} +#else +struct tf_reg_load { uint4 w0, w1, q0, q1; float x0, x1; }; +constant constexpr int TF_REG_QUADS = 2; +#define TF_REG_CODES(wl, g) wl[(size_t)(g) * 64], wl[(size_t)(g) * 64 + 32] +#endif inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, const device float* XS, int g, int n, int m, int stride) { - return {wl[(size_t)g * 64], wl[(size_t)g * 64 + 32], sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XS[g * stride + m], XS[g * stride + m + 8]}; + return {TF_REG_CODES(wl, g), sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XS[g * stride + m], XS[g * stride + m + 8]}; +} + +#if TF_INLINE_SUMS +inline tf_reg_load tf_reg_fetch_tg(const device uint4* wl, const device uint4* sbv, const threadgroup float* XT, int g, int first, int n, int m) { + return {TF_REG_CODES(wl, g), sbv[((size_t)g * TF_N + n) / 4], sbv[((size_t)g * TF_N + n + 16) / 4], XT[(g - first) * 16 + m], XT[(g - first) * 16 + m + 8]}; } +#endif // tf_lane's arithmetic with codes unpacked straight into tensor-op registers: every word equals tf_lane_pair's. [[kernel]] void tf_lane_reg(const device bfloat* X [[buffer(0)]], const device uint4* W [[buffer(1)]], const device bfloat* SB [[buffer(2)]], @@ -329,25 +363,46 @@ inline tf_reg_load tf_reg_fetch(const device uint4* wl, const device uint4* sbv, auto cb = op.template get_right_input_cooperative_tensor(); auto P = op.template get_destination_cooperative_tensor, metal::remove_addrspace_t, float>(); thread half2* b2 = (thread half2*)&cb[0]; - const device uint4* wl = W + (size_t)tile * KG * 64 + lane; + const device uint4* wl = W + (size_t)tile * KG * 32 * TF_REG_QUADS + lane; const device uint4* sbv = (const device uint4*)SB; const half2 bias = half2(1024.0h); float C[16]; for (int i = 0; i < 16; i++) C[i] = 0.0f; tf_reg_load next = {}; - if (first < last) next = tf_reg_fetch(wl, sbv, XS, first, n0 + nb, mb, stride); +#if TF_INLINE_SUMS + threadgroup float xs_all[TF_SK * TF_GPS * 16]; + threadgroup float* XT = xs_all + ks * TF_GPS * 16; + // one (group, row) sum a lane at a time over the pass's rows only; rows past it read zero + for (int p = lane; p < (last - first) * 16; p += 32) XT[p] = 0.0f; + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int p = lane; p < (last - first) * M; p += 32) XT[(p / M) * 16 + p % M] = tf_lane_xsum(X, p % M, first + p / M, M); + simdgroup_barrier(mem_flags::mem_threadgroup); +#define TF_REG_FETCH(g) tf_reg_fetch_tg(wl, sbv, XT, g, first, n0 + nb, mb) +#else +#define TF_REG_FETCH(g) tf_reg_fetch(wl, sbv, XS, g, n0 + nb, mb, stride) +#endif + if (first < last) next = TF_REG_FETCH(first); for (int g = first; g < last; g++) { const tf_reg_load cur = next; for (int w = 0; w < 8; w++) { + const int e = 16 * (w & 1) + 2 * (w >> 1); +#if TF_BITS == 8 + // the 4-bit order a byte a code: word 2w holds that word's first four codes, 2w + 1 the four 16 deeper + const uint a = cur.w[w >> 1][2 * (w & 1)], c = cur.w[w >> 1][2 * (w & 1) + 1]; + b2[e] = as_type((a & 0xFFu) | ((a << 8) & 0x00FF0000u) | 0x64006400u) - bias; + b2[e + 1] = as_type(((a >> 16) & 0xFFu) | ((a >> 8) & 0x00FF0000u) | 0x64006400u) - bias; + b2[e + 8] = as_type((c & 0xFFu) | ((c << 8) & 0x00FF0000u) | 0x64006400u) - bias; + b2[e + 9] = as_type(((c >> 16) & 0xFFu) | ((c >> 8) & 0x00FF0000u) | 0x64006400u) - bias; +#else // 1024 + code as fp16 bits, codes (0,4) (1,5) (2,6) (3,7) of a word; subtracting 1024 is exact const uint word = w < 4 ? cur.w0[w] : cur.w1[w - 4], lo = word & 0x0F0F0F0Fu, hi = (word >> 4) & 0x0F0F0F0Fu; - const int e = 16 * (w & 1) + 2 * (w >> 1); b2[e] = as_type((lo & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 1] = as_type((hi & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 8] = as_type(((lo >> 8) & 0x00FF00FFu) | 0x64006400u) - bias; b2[e + 9] = as_type(((hi >> 8) & 0x00FF00FFu) | 0x64006400u) - bias; +#endif } - if (g + 1 < last) next = tf_reg_fetch(wl, sbv, XS, g + 1, n0 + nb, mb, stride); + if (g + 1 < last) next = TF_REG_FETCH(g + 1); auto x = a.slice(g * GS, 0); op.run(x, cb, P); for (int j = 0; j < 4; j++) { diff --git a/zig/kernels/metal/hy4_flash/affine_experts.metal b/zig/kernels/metal/hy4_flash/affine_experts.metal new file mode 100644 index 00000000000..ff5b6008c15 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/affine_experts.metal @@ -0,0 +1,97 @@ +// Routed rows over group-64 affine experts, with checkpoint SwiGLU rounding. +#include +using namespace metal; +#pragma clang fp contract(off) + +struct Hy4ExpertShape { + uint width, inner, first, experts, pairs, rows; + float swiglu_limit; +}; + +template +inline float affine_expert_dot( + const device bfloat *input, const device uint *words, const device bfloat *scale, + const device bfloat *bias, uint width, uint lane) { + constexpr uint mask = (1u << Bits) - 1; + float acc = 0.0f; + for (uint group = 0; group < width / 64; ++group) { + const float s = float(scale[group]), b = float(bias[group]); + for (uint i = lane; i < 64; i += 32) { + const uint index = group * 64 + i, bit = index * Bits; + const float code = float((words[bit / 32] >> (bit % 32)) & mask); + const float w = float(bfloat(fma(code, s, b))); + acc = fma(float(input[index]), w, acc); + } + } + for (ushort d = 16; d > 0; d >>= 1) acc += simd_shuffle_xor(acc, d); + return acc; +} + +template +inline void affine_expert_rows( + const device bfloat *x, const device int *ids, const device int *row_ids, + const device uint *words, const device bfloat *scale, const device bfloat *bias, + device Output *result, constant Hy4ExpertShape &s, uint2 group, uint simd, uint lane) { + const uint pair = group.y, n = group.x * 4 + simd; + const uint width = Up ? s.width : s.inner, size = Up ? s.inner : s.width; + if (n >= size) return; + const ulong out = ulong(pair) * size + n; + const int id = ids[pair], row = Up ? row_ids[pair] : int(pair); + if (id < 0 || uint(id) < s.first || uint(id) - s.first >= s.experts || + row < 0 || (Up && uint(row) >= s.rows)) { + if (lane == 0) result[out] = Output(0); + return; + } + const device bfloat *input = x + ulong(row) * width; + const ulong expert_row = ulong(uint(id) - s.first) * (Up ? 2 * size : size) + n; + const uint packed_width = width * Bits / 32, groups = width / 64; + const ulong wc = expert_row * packed_width, gc = expert_row * groups; + const float first = affine_expert_dot(input, words + wc, scale + gc, bias + gc, width, lane); + if (Up) { + const ulong wu = wc + ulong(size) * packed_width, gu = gc + ulong(size) * groups; + const float second = affine_expert_dot(input, words + wu, scale + gu, bias + gu, width, lane); + if (lane == 0) { + float gate = float(bfloat(first)), value = float(bfloat(second)); + if (s.swiglu_limit > 0) { + gate = min(gate, s.swiglu_limit); + value = clamp(value, -s.swiglu_limit, s.swiglu_limit); + } + const float a = float(bfloat(precise::divide(gate, 1.0f + precise::exp(-gate)))); + result[out] = Output(a * value); + } + } else if (lane == 0) { + result[out] = Output(first); + } +} + +#define TF_HY4_EXPERTS(bits, direction, up, out_type) \ +kernel void tf_affine_experts_##direction##_##bits( \ + const device bfloat *x [[buffer(0)]], const device int *ids [[buffer(1)]], \ + const device int *rows [[buffer(2)]], const device uint *words [[buffer(3)]], \ + const device bfloat *scale [[buffer(4)]], const device bfloat *bias [[buffer(5)]], \ + device out_type *output [[buffer(6)]], constant Hy4ExpertShape &shape [[buffer(7)]], \ + uint2 group [[threadgroup_position_in_grid]], uint simd [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]]) { \ + affine_expert_rows(x, ids, rows, words, scale, bias, output, shape, group, simd, lane); \ +} + +TF_HY4_EXPERTS(4, up, true, bfloat) +TF_HY4_EXPERTS(4, down, false, float) +TF_HY4_EXPERTS(8, up, true, bfloat) +TF_HY4_EXPERTS(8, down, false, float) + +// All expert contributions remain FP32 until the weighted latent sum is ready for the next projection. +kernel void tf_hy4_routed_sum( + const device float *parts [[buffer(0)]], + const device float *weights [[buffer(1)]], + device bfloat *out [[buffer(2)]], + constant uint2 &shape [[buffer(3)]], + uint2 at [[thread_position_in_grid]]) { + const uint width = shape.x, picks = shape.y; + const ulong row = ulong(at.y) * picks; + float sum = 0.0f; + for (uint slot = 0; slot < picks; ++slot) { + sum = fma(weights[row + slot], parts[(row + slot) * width + at.x], sum); + } + out[ulong(at.y) * width + at.x] = bfloat(sum); +} diff --git a/zig/kernels/metal/hy4_flash/attention_sink.metal b/zig/kernels/metal/hy4_flash/attention_sink.metal new file mode 100644 index 00000000000..1d58a18412a --- /dev/null +++ b/zig/kernels/metal/hy4_flash/attention_sink.metal @@ -0,0 +1,30 @@ +// Finish a head's online softmax with its learned, zero-value sink. +#include +using namespace metal; +#pragma clang fp contract(off) + +struct Hy4SinkArgs { + uint rows; + uint heads; + uint width; +}; + +kernel void tf_hy4_finish_attention( + const device float *maxima [[buffer(0)]], + const device float *mass [[buffer(1)]], + const device float *numerator [[buffer(2)]], + const device float *sinks [[buffer(3)]], + device float *output [[buffer(4)]], + constant Hy4SinkArgs &args [[buffer(5)]], + uint2 tid [[thread_position_in_grid]]) { + const uint column = tid.x; + const uint row_head = tid.y; + if (column >= args.width || row_head >= ulong(args.rows) * args.heads) return; + + const float sink = sinks[row_head % args.heads]; + const float top = max(maxima[row_head], sink); + const float prior = precise::exp(maxima[row_head] - top); + const float denominator = mass[row_head] * prior + precise::exp(sink - top); + const ulong offset = ulong(row_head) * args.width + column; + output[offset] = numerator[offset] * prior / denominator; +} diff --git a/zig/kernels/metal/hy4_flash/engram.metal b/zig/kernels/metal/hy4_flash/engram.metal new file mode 100644 index 00000000000..f0bbad8d76e --- /dev/null +++ b/zig/kernels/metal/hy4_flash/engram.metal @@ -0,0 +1,145 @@ +// Hy4-flash's file-backed rows enter this pass as BF16. Only the trained Engram branch simulates FP8. +#include +using namespace metal; +#pragma clang fp contract(off) + +constant constexpr uint heads = 16, head_width = 96, streams = 4, threads = 128; +constant constexpr float rms_epsilon = 0x1.0p-23f; + +inline float bf(float x) { return float(bfloat(x)); } + +// E4M3FN rounds ties to even, includes subnormals and saturates at 448. +inline float hy4_e4m3(float x) { + const float a = fabs(x); + if (a == 0.0f) return x; + const float step = exp2(max(floor(log2(a)), -6.0f) - 3.0f); + return copysign(min(448.0f, rint(a / step) * step), x); +} + +kernel void tf_hy4_engram_lookup( + const device bfloat *raw [[buffer(0)]], + const device bfloat *gamma [[buffer(1)]], + device bfloat *out [[buffer(2)]], + constant uint &fp8 [[buffer(3)]], + uint2 group [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint head = group.x; + const ulong start = (ulong(group.y) * heads + head) * head_width; + float x[3], maximum = 0.0f; + for (uint i = 0; i < 3; ++i) { + x[i] = float(raw[start + lane + i * 32]); + maximum = max(maximum, fabs(x[i])); + } + if (fp8 != 0) { + const float scale = bf(precise::divide(max(simd_max(maximum), bf(1e-12f)), 448.0f)); + for (uint i = 0; i < 3; ++i) { + const float code = hy4_e4m3(clamp(bf(precise::divide(x[i], scale)), -448.0f, 448.0f)); + const float quantized = bf(code * scale); + x[i] = bf(x[i] + bf(quantized - x[i])); + } + } + const float sum = simd_sum(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]); + const float inv = precise::rsqrt(sum / float(head_width) + rms_epsilon); + for (uint i = 0; i < 3; ++i) { + const uint col = lane + 32 * i; + out[start + col] = bfloat((x[i] * inv) * float(gamma[head * head_width + col])); + } +} + +struct Hy4EngramArgs { uint rows, hidden; }; + +kernel void tf_hy4_engram_apply( + const device bfloat *state [[buffer(0)]], + const device bfloat *keys [[buffer(1)]], + const device bfloat *key_bias [[buffer(2)]], + const device bfloat *key_gain [[buffer(3)]], + const device bfloat *query_gain [[buffer(4)]], + const device bfloat *delta_gain [[buffer(5)]], + const device bfloat *value [[buffer(6)]], + const device bfloat *value_bias [[buffer(7)]], + const device bfloat *value_gain [[buffer(8)]], + const device uint *media_mask [[buffer(9)]], + device bfloat *out [[buffer(10)]], + constant Hy4EngramArgs &a [[buffer(11)]], + uint2 group [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint stream = group.x, row = group.y, h = a.hidden; + const ulong base = (ulong(row) * streams + stream) * h; + if (media_mask[row] != 0) { + for (uint j = t; j < h; j += threads) out[base + j] = state[base + j]; + return; + } + const ulong kbase = (ulong(stream) * a.rows + row) * h, vbase = ulong(row) * h; + const uint gain = stream * h; + float sq_key = 0.0f, sq_query = 0.0f, sq_value = 0.0f; + for (uint j = t; j < h; j += threads) { + const float k = bf(float(keys[kbase + j]) + float(key_bias[gain + j])); + const float q = float(state[base + j]); + const float v = bf(float(value[vbase + j]) + float(value_bias[j])); + sq_key = fma(k, k, sq_key); + sq_query = fma(q, q, sq_query); + sq_value = fma(v, v, sq_value); + } + const float key_sum = simd_sum(sq_key), query_sum = simd_sum(sq_query), value_sum = simd_sum(sq_value); + threadgroup float partial[3][4]; + if (lane == 0) { partial[0][sg] = key_sum; partial[1][sg] = query_sum; partial[2][sg] = value_sum; } + threadgroup_barrier(mem_flags::mem_threadgroup); + float norm[3]; + for (uint i = 0; i < 3; ++i) { + const float sum = (partial[i][0] + partial[i][2]) + (partial[i][1] + partial[i][3]); + norm[i] = precise::rsqrt(sum / float(h) + rms_epsilon); + } + float dot = 0.0f; + for (uint j = t; j < h; j += threads) { + const float k = bf(float(keys[kbase + j]) + float(key_bias[gain + j])); + const float q = float(state[base + j]); + const float key = bf((k * norm[0]) * float(key_gain[gain + j])); + const float query = bf((q * norm[1]) * float(query_gain[gain + j])); + dot += bf(key * query); + } + const float sum = simd_sum(dot); + threadgroup float parts[4], gate; + if (lane == 0) parts[sg] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + const float scaled = bf(bf((parts[0] + parts[2]) + (parts[1] + parts[3])) * precise::rsqrt(float(h))); + const float x = scaled == 0.0f ? 0.0f : copysign(bf(precise::sqrt(max(fabs(scaled), bf(1e-6f)))), scaled); + gate = bf(precise::divide(1.0f, 1.0f + precise::exp(-x))); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint j = t; j < h; j += threads) { + const float v = bf(float(value[vbase + j]) + float(value_bias[j])); + const float signal = bf(bf(v * norm[2]) * float(value_gain[j])); + const float delta = bf(bf(gate * signal) + bf(float(delta_gain[gain + j]) * signal)); + out[base + j] = bfloat(float(state[base + j]) + delta); + } +} + +// Engram tables resident in GPU memory: each cell's affine code times its group's scale +inline ushort hy4_engram_round(float v) { + const uint u = as_type(v); + if ((u & 0x7fffffffu) > 0x7f800000u) return ushort((u >> 16) | 0x40u); + return ushort((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +kernel void tf_hy4_engram_gather( + const device uint *words [[buffer(0)]], + const device ushort *scales [[buffer(1)]], + const device ushort *biases [[buffer(2)]], + const device uint *rows [[buffer(3)]], + device ushort *out [[buffer(4)]], + constant uint2 &a [[buffer(5)]], + uint gid [[thread_position_in_grid]]) { + if (gid >= a.y) return; + const uint cell = gid / head_width, i = gid % head_width, bits = a.x; + const ulong row = rows[cell]; + const uint bit = i * bits; + const uint word = words[row * (head_width * bits / 32) + bit / 32]; + const float code = float((word >> (bit % 32)) & ((1u << bits) - 1u)); + const ulong g = row * (head_width / 32) + i / 32; + const float s = as_type(uint(scales[g]) << 16), b = as_type(uint(biases[g]) << 16); + const float prod = code * s; + out[gid] = hy4_engram_round(prod + b); +} diff --git a/zig/kernels/metal/hy4_flash/ihc.metal b/zig/kernels/metal/hy4_flash/ihc.metal new file mode 100644 index 00000000000..6b982f31cfa --- /dev/null +++ b/zig/kernels/metal/hy4_flash/ihc.metal @@ -0,0 +1,531 @@ +// Hy4-flash reads independent stream gates in FP32 and stores BF16 hidden rows. +#include +using namespace metal; +#pragma clang fp contract(off) + +struct Hy4IhcShape { + uint rows, width, gates; + float eps, gate_eps, post_magnitude; +}; + +inline float ihc_simd_sum(float score) { + for (ushort s = 16; s > 0; s >>= 1) score += simd_shuffle_xor(score, s); + return score; +} + +kernel void tf_hy4_ihc_collapse( + const device bfloat *hidden [[buffer(0)]], + const device float *project [[buffer(1)]], + const device float *bias [[buffer(2)]], + const device float *scale [[buffer(3)]], + device bfloat *collapsed [[buffer(4)]], + device float *post [[buffer(5)]], + constant Hy4IhcShape &a [[buffer(6)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint simd [[simdgroup_index_in_threadgroup]]) { + threadgroup float partial[9][8], pre[4]; + const uint wide = 4 * a.width; + const device bfloat *x = hidden + ulong(row) * wide; + float sq = 0.0f, logits[8] = {}; + for (uint i = t; i < wide; i += 256) { + const float v = float(x[i]); + sq = fma(v, v, sq); + for (uint j = 0; j < a.gates; ++j) logits[j] = fma(v, project[j * wide + i], logits[j]); + } + sq = ihc_simd_sum(sq); + if (lane == 0) partial[8][simd] = sq; + for (uint j = 0; j < a.gates; ++j) { + const float score = ihc_simd_sum(logits[j]); + if (lane == 0) partial[j][simd] = score; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < a.gates) { + float sum = 0.0f, dot = 0.0f; + for (uint i = 0; i < 8; ++i) { + sum += partial[8][i]; + dot += partial[t][i]; + } + const float mix = dot * precise::rsqrt(sum / float(wide) + a.eps); + const float gate = 1.0f / (1.0f + precise::exp(-(mix * scale[t / 4] + bias[t]))); + if (t < 4) pre[t] = gate + a.gate_eps; + else post[ulong(row) * 4 + t - 4] = a.post_magnitude * gate + a.gate_eps; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < a.width; i += 256) { + float v = 0.0f; + for (uint stream = 0; stream < 4; ++stream) v += pre[stream] * float(x[stream * a.width + i]); + collapsed[ulong(row) * a.width + i] = bfloat(v); + } +} + +// tf_hy4_ihc_collapse with the gate count fixed at compile time +template +inline void ihc_collapse_fixed( + const device bfloat *hidden, const device float *project, const device float *bias, const device float *scale, + device bfloat *collapsed, device float *post, constant Hy4IhcShape &a, + uint row, uint t, uint lane, uint simd, threadgroup float (&partial)[9][8], threadgroup float (&pre)[4]) { + const uint wide = 4 * a.width; + const device bfloat *x = hidden + ulong(row) * wide; + float sq = 0.0f, logits[G]; +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = 0.0f; + for (uint i = t; i < wide; i += 256) { + const float v = float(x[i]); + sq = fma(v, v, sq); +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = fma(v, project[j * wide + i], logits[j]); + } + sq = ihc_simd_sum(sq); + if (lane == 0) partial[8][simd] = sq; +#pragma unroll + for (uint j = 0; j < G; ++j) { + const float score = ihc_simd_sum(logits[j]); + if (lane == 0) partial[j][simd] = score; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < G) { + float sum = 0.0f, dot = 0.0f; + for (uint i = 0; i < 8; ++i) { + sum += partial[8][i]; + dot += partial[t][i]; + } + const float mix = dot * precise::rsqrt(sum / float(wide) + a.eps); + const float gate = 1.0f / (1.0f + precise::exp(-(mix * scale[t / 4] + bias[t]))); + if (t < 4) pre[t] = gate + a.gate_eps; + else post[ulong(row) * 4 + t - 4] = a.post_magnitude * gate + a.gate_eps; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < a.width; i += 256) { + float v = 0.0f; + for (uint stream = 0; stream < 4; ++stream) v += pre[stream] * float(x[stream * a.width + i]); + collapsed[ulong(row) * a.width + i] = bfloat(v); + } +} + +#define HY4_IHC_FIXED(G) \ + kernel void tf_hy4_ihc_collapse_g##G( \ + const device bfloat *hidden [[buffer(0)]], const device float *project [[buffer(1)]], \ + const device float *bias [[buffer(2)]], const device float *scale [[buffer(3)]], \ + device bfloat *collapsed [[buffer(4)]], device float *post [[buffer(5)]], constant Hy4IhcShape &a [[buffer(6)]], \ + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint simd [[simdgroup_index_in_threadgroup]]) { \ + threadgroup float partial[9][8], pre[4]; \ + ihc_collapse_fixed(hidden, project, bias, scale, collapsed, post, a, row, t, lane, simd, partial, pre); \ + } +HY4_IHC_FIXED(4) +HY4_IHC_FIXED(8) + +// The same collapse in two launches. +template +inline void ihc_partials_fixed(const device bfloat *hidden, const device float *project, device float *part, + constant Hy4IhcShape &a, uint row, uint simd, uint lane) { + const uint wide = 4 * a.width, t = 32 * simd + lane; + const device bfloat *x = hidden + ulong(row) * wide; + float sq = 0.0f, logits[G]; +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = 0.0f; +#pragma unroll 4 + for (uint i = t; i < wide; i += 256) { + const float v = float(x[i]); + sq = fma(v, v, sq); +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = fma(v, project[j * wide + i], logits[j]); + } + device float *p = part + ulong(row) * 72; + sq = ihc_simd_sum(sq); + if (lane == 0) p[64 + simd] = sq; +#pragma unroll + for (uint j = 0; j < G; ++j) { + const float score = ihc_simd_sum(logits[j]); + if (lane == 0) p[8 * j + simd] = score; + } +} + +// Threadgroup `slice` of a row writes columns [256 slice, 256 slice + 256) +template +inline void ihc_finish_fixed(const device bfloat *hidden, const device float *part, const device float *bias, + const device float *scale, device bfloat *collapsed, device float *post, + constant Hy4IhcShape &a, uint row, uint t, uint slice, threadgroup float (&pre)[4]) { + const uint wide = 4 * a.width; + const device bfloat *x = hidden + ulong(row) * wide; + const device float *p = part + ulong(row) * 72; + if (t < G && (t < 4 || slice == 0)) { + float sum = 0.0f, dot = 0.0f; + for (uint i = 0; i < 8; ++i) { + sum += p[64 + i]; + dot += p[8 * t + i]; + } + const float mix = dot * precise::rsqrt(sum / float(wide) + a.eps); + const float gate = 1.0f / (1.0f + precise::exp(-(mix * scale[t / 4] + bias[t]))); + if (t < 4) pre[t] = gate + a.gate_eps; + else post[ulong(row) * 4 + t - 4] = a.post_magnitude * gate + a.gate_eps; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint i = 256 * slice + t; + if (i < a.width) { + float v = 0.0f; + for (uint stream = 0; stream < 4; ++stream) v += pre[stream] * float(x[stream * a.width + i]); + collapsed[ulong(row) * a.width + i] = bfloat(v); + } +} + +#define HY4_IHC_SPLIT(G) \ + kernel void tf_hy4_ihc_partials_g##G( \ + const device bfloat *hidden [[buffer(0)]], const device float *project [[buffer(1)]], \ + device float *part [[buffer(2)]], constant Hy4IhcShape &a [[buffer(3)]], \ + uint2 group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]]) { \ + ihc_partials_fixed(hidden, project, part, a, group.y, group.x, lane); \ + } \ + kernel void tf_hy4_ihc_finish_g##G( \ + const device bfloat *hidden [[buffer(0)]], const device float *part [[buffer(1)]], \ + const device float *bias [[buffer(2)]], const device float *scale [[buffer(3)]], \ + device bfloat *collapsed [[buffer(4)]], device float *post [[buffer(5)]], constant Hy4IhcShape &a [[buffer(6)]], \ + uint2 group [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { \ + threadgroup float pre[4]; \ + ihc_finish_fixed(hidden, part, bias, scale, collapsed, post, a, group.y, t, group.x, pre); \ + } +HY4_IHC_SPLIT(4) +HY4_IHC_SPLIT(8) + +kernel void tf_hy4_ihc_add( + const device bfloat *residual [[buffer(0)]], + const device bfloat *branch [[buffer(1)]], + const device float *post [[buffer(2)]], + device bfloat *output [[buffer(3)]], + constant Hy4IhcShape &a [[buffer(4)]], + uint2 tid [[thread_position_in_grid]]) { + const ulong full = ulong(tid.y) * 4 * a.width + tid.x; + const ulong local = ulong(tid.y) * a.width + tid.x % a.width; + output[full] = bfloat(float(residual[full]) + post[ulong(tid.y) * 4 + tid.x / a.width] * float(branch[local])); +} + +// The fusion is attached only to slot zero of every DFly2 block. +kernel void tf_hy4_draft_fuse( + device bfloat *embedded [[buffer(0)]], + const device bfloat *delta [[buffer(1)]], + const device bfloat *gain [[buffer(2)]], + constant uint2 &shape [[buffer(3)]], + uint2 tid [[thread_position_in_grid]]) { + const ulong anchor = ulong(tid.y) * shape.x * shape.y + tid.x; + const bfloat update = bfloat(float(delta[ulong(tid.y) * shape.x + tid.x]) * float(gain[tid.x])); + embedded[anchor] = bfloat(float(embedded[anchor]) + float(update)); +} + +kernel void tf_hy4_draft_residual( + const device bfloat *base [[buffer(0)]], + const device bfloat *branch [[buffer(1)]], + device bfloat *out [[buffer(2)]], + constant uint2 &shape [[buffer(3)]], + uint2 tid [[thread_position_in_grid]]) { + const ulong o = ulong(tid.y) * shape.x + tid.x; + const ulong i = ulong(tid.y) * shape.y + tid.x; + out[o] = bfloat(float(base[i]) + float(branch[o])); +} + +// ---- Sub-block seams in two launches instead of five (decode and prompt alike) ---- tail +constant constexpr uint seam_tgs = 12; +struct Hy4TailShape { uint rows, width, two, partials; float eps; uint mode; }; + +inline float seam_tg_sum(float v, uint lane, uint sg, threadgroup float *scratch) { + v = ihc_simd_sum(v); + if (lane == 0) scratch[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (uint i = 0; i < 8; ++i) total += scratch[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return total; +} + +// The 10 stream products sum_i m[s][i] m[u][i] (s <= u) a row +constant constexpr uint seam_gram = 10; +constant constexpr uint seam_slots = 16; + +template +inline void ihc_tail(const device bfloat *branch, const device bfloat *branch2, const device bfloat *gain, + const device bfloat *residual, const device float *post, device bfloat *out, + const device float *project, device float *part, constant Hy4TailShape &a, uint row, uint tg, + uint t, uint lane, uint sg, threadgroup float *scratch, threadgroup float (&sums)[9 + seam_gram][8]) { + const uint W = a.width, wide = 4 * W; + const device bfloat *b0 = branch + ulong(row) * W; + const device bfloat *b1 = branch2 + ulong(row) * W; + float inv = 0.0f; + if (a.mode != 0) { + float sq = 0.0f; + for (uint i = t; i < W; i += 256) { + const float v = a.two ? float(bfloat(b0[i] + b1[i])) : float(b0[i]); + sq = fma(v, v, sq); + } + inv = precise::rsqrt(seam_tg_sum(sq, lane, sg, scratch) / float(W) + a.eps); + } + float msq = 0.0f, logits[G], gram[seam_gram]; +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = 0.0f; +#pragma unroll + for (uint k = 0; k < seam_gram; ++k) gram[k] = 0.0f; + // a column's four streams together (for the 3072 width, thread t of threadgroup tg owns one column; + for (uint col = tg * 256 + t; col < W; col += seam_tgs * 256) { + float m[4]; + float v = 0.0f, normed = 0.0f; + if (a.mode != 0) { + v = a.two ? float(bfloat(b0[col] + b1[col])) : float(b0[col]); + normed = float(bfloat(float(bfloat(v * inv)) * float(gain[col]))); + } +#pragma unroll + for (uint stream = 0; stream < 4; ++stream) { + const ulong i = ulong(row) * wide + stream * W + col; + if (a.mode != 0) { + m[stream] = float(bfloat(float(residual[i]) + post[ulong(row) * 4 + stream] * normed)); + out[i] = bfloat(m[stream]); + } else { + m[stream] = float(residual[i]); + } + } + if (a.partials) { +#pragma unroll + for (uint stream = 0; stream < 4; ++stream) { + msq = fma(m[stream], m[stream], msq); +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = fma(m[stream], project[j * wide + stream * W + col], logits[j]); + } + uint k = 0; +#pragma unroll + for (uint s = 0; s < 4; ++s) +#pragma unroll + for (uint u = s; u < 4; ++u, ++k) gram[k] = fma(m[s], m[u], gram[k]); + } + } + if (!a.partials) return; + // every sum's simdgroup totals in one threadgroup step, then each added over the 8 simdgroups in order +#pragma unroll + for (uint j = 0; j < G; ++j) { + const float v = ihc_simd_sum(logits[j]); + if (lane == 0) sums[j][sg] = v; + } + { + const float v = ihc_simd_sum(msq); + if (lane == 0) sums[8][sg] = v; + } +#pragma unroll + for (uint k = 0; k < seam_gram; ++k) { + const float v = ihc_simd_sum(gram[k]); + if (lane == 0) sums[9 + k][sg] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device float *p = part + ulong(row) * (9 + seam_gram) * seam_slots; + if (t < G || t == 8 || (t >= 9 && t < 9 + seam_gram)) { + float total = 0.0f; + for (uint i = 0; i < 8; ++i) total += sums[t][i]; + p[t * seam_slots + tg] = total; + } +} + +// head: the collapse's gates from the tail's partials (added over the 12 threadgroups in order) +template +inline void ihc_head(const device bfloat *hidden, const device float *part, const device float *bias, + const device float *scale, const device bfloat *gain, device bfloat *collapsed, + device bfloat *normalized, device float *post, constant Hy4IhcShape &a, float norm_eps, uint row, + uint slice, uint t, threadgroup float (&pre)[4], threadgroup float (&gram)[seam_gram]) { + const uint W = a.width, wide = 4 * W; + const device bfloat *x = hidden + ulong(row) * wide; + const device float *p = part + ulong(row) * (9 + seam_gram) * seam_slots; + if (t < G && (t < 4 || slice == 0)) { + float sum = 0.0f, dot = 0.0f; + for (uint i = 0; i < seam_tgs; ++i) { + sum += p[8 * seam_slots + i]; + dot += p[t * seam_slots + i]; + } + const float mix = dot * precise::rsqrt(sum / float(wide) + a.eps); + const float gate = 1.0f / (1.0f + precise::exp(-(mix * scale[t / 4] + bias[t]))); + if (t < 4) pre[t] = gate + a.gate_eps; + else post[ulong(row) * 4 + t - 4] = a.post_magnitude * gate + a.gate_eps; + } else if (t >= 32 && t < 32 + seam_gram) { + float g = 0.0f; + for (uint i = 0; i < seam_tgs; ++i) g += p[(9 + t - 32) * seam_slots + i]; + gram[t - 32] = g; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float sq = 0.0f; + uint k = 0; + for (uint s = 0; s < 4; ++s) + for (uint u = s; u < 4; ++u, ++k) sq = fma((s == u ? 1.0f : 2.0f) * pre[s] * pre[u], gram[k], sq); + const float inv = precise::rsqrt(sq / float(W) + norm_eps); + for (uint i = slice * 256 + t; i < W; i += seam_tgs * 256) { + float v = 0.0f; + for (uint stream = 0; stream < 4; ++stream) v += pre[stream] * float(x[stream * W + i]); + const float c = float(bfloat(v)); + collapsed[ulong(row) * W + i] = bfloat(v); + normalized[ulong(row) * W + i] = bfloat(float(bfloat(c * inv)) * float(gain[i])); + } +} + +// ---- tail and the next head in one launch (decode passes) +struct Hy4SeamBarrier { atomic_uint count; atomic_uint gen; }; + +inline void seam_barrier(device Hy4SeamBarrier* b, uint t) { + // every thread's stores published, then one thread a threadgroup arrives and waits for the row's other 11 + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); + threadgroup_barrier(mem_flags::mem_device); + if (t == 0) { + const uint gen = atomic_load_explicit(&b->gen, memory_order_relaxed); + // the generation read stays ahead of the arrival (else the last arrival's bump could come first) + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); + const uint seen = atomic_fetch_add_explicit(&b->count, 1u, memory_order_relaxed); + if (seen + 1 == seam_tgs) { + atomic_store_explicit(&b->count, 0u, memory_order_relaxed); + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); + atomic_fetch_add_explicit(&b->gen, 1u, memory_order_relaxed); + } else { + while (atomic_load_explicit(&b->gen, memory_order_relaxed) == gen) { + } + } + } + threadgroup_barrier(mem_flags::mem_device); + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); +} + +template +inline void ihc_seam(const device bfloat *branch, const device bfloat *branch2, const device bfloat *gain, + const device bfloat *residual, device float *post, device bfloat *out, + const device float *project, device atomic_float *part, constant Hy4TailShape &a, + const device float *bias, const device float *scale, const device bfloat *next_gain, + device bfloat *collapsed, device bfloat *normalized, constant Hy4IhcShape &n, float norm_eps, + device Hy4SeamBarrier *bars, uint row, uint tg, uint t, uint lane, uint sg, + threadgroup float *scratch, threadgroup float (&sums)[9 + seam_gram][8], + threadgroup float (&pre)[4], threadgroup float (&gram)[seam_gram]) { + const uint W = a.width, wide = 4 * W; + const device bfloat *b0 = branch + ulong(row) * W; + const device bfloat *b1 = branch2 + ulong(row) * W; + float sq = 0.0f; + for (uint i = t; i < W; i += 256) { + const float v = a.two ? float(bfloat(b0[i] + b1[i])) : float(b0[i]); + sq = fma(v, v, sq); + } + const float inv = precise::rsqrt(seam_tg_sum(sq, lane, sg, scratch) / float(W) + a.eps); + const uint col = tg * 256 + t; + float m[4]; + const float v = a.two ? float(bfloat(b0[col] + b1[col])) : float(b0[col]); + const float normed = float(bfloat(float(bfloat(v * inv)) * float(gain[col]))); +#pragma unroll + for (uint stream = 0; stream < 4; ++stream) { + const ulong i = ulong(row) * wide + stream * W + col; + m[stream] = float(bfloat(float(residual[i]) + post[ulong(row) * 4 + stream] * normed)); + out[i] = bfloat(m[stream]); + } + float msq = 0.0f, logits[G], gr[seam_gram]; +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = 0.0f; +#pragma unroll + for (uint k = 0; k < seam_gram; ++k) gr[k] = 0.0f; +#pragma unroll + for (uint stream = 0; stream < 4; ++stream) { + msq = fma(m[stream], m[stream], msq); +#pragma unroll + for (uint j = 0; j < G; ++j) logits[j] = fma(m[stream], project[j * wide + stream * W + col], logits[j]); + } + { + uint k = 0; +#pragma unroll + for (uint s0 = 0; s0 < 4; ++s0) +#pragma unroll + for (uint u = s0; u < 4; ++u, ++k) gr[k] = fma(m[s0], m[u], gr[k]); + } +#pragma unroll + for (uint j = 0; j < G; ++j) { + const float x = ihc_simd_sum(logits[j]); + if (lane == 0) sums[j][sg] = x; + } + { + const float x = ihc_simd_sum(msq); + if (lane == 0) sums[8][sg] = x; + } +#pragma unroll + for (uint k = 0; k < seam_gram; ++k) { + const float x = ihc_simd_sum(gr[k]); + if (lane == 0) sums[9 + k][sg] = x; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device atomic_float *p = part + ulong(row) * (9 + seam_gram) * seam_slots; + if (t < G || t == 8 || (t >= 9 && t < 9 + seam_gram)) { + float total = 0.0f; + for (uint i = 0; i < 8; ++i) total += sums[t][i]; + atomic_store_explicit(p + t * seam_slots + tg, total, memory_order_relaxed); + } + // every threadgroup has read this sub-block's post gates above; the head may now overwrite them + seam_barrier(bars + row, t); + if (t < G && (t < 4 || tg == 0)) { + float sum = 0.0f, dot = 0.0f; + for (uint i = 0; i < seam_tgs; ++i) { + sum += atomic_load_explicit(p + 8 * seam_slots + i, memory_order_relaxed); + dot += atomic_load_explicit(p + t * seam_slots + i, memory_order_relaxed); + } + const float mix = dot * precise::rsqrt(sum / float(wide) + n.eps); + const float gate = 1.0f / (1.0f + precise::exp(-(mix * scale[t / 4] + bias[t]))); + if (t < 4) pre[t] = gate + n.gate_eps; + else post[ulong(row) * 4 + t - 4] = n.post_magnitude * gate + n.gate_eps; + } else if (t >= 32 && t < 32 + seam_gram) { + float g = 0.0f; + for (uint i = 0; i < seam_tgs; ++i) g += atomic_load_explicit(p + (9 + t - 32) * seam_slots + i, memory_order_relaxed); + gram[t - 32] = g; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float hsq = 0.0f; + uint k = 0; + for (uint s0 = 0; s0 < 4; ++s0) + for (uint u = s0; u < 4; ++u, ++k) hsq = fma((s0 == u ? 1.0f : 2.0f) * pre[s0] * pre[u], gram[k], hsq); + const float hinv = precise::rsqrt(hsq / float(W) + norm_eps); + float c = 0.0f; + for (uint stream = 0; stream < 4; ++stream) c += pre[stream] * m[stream]; + const float cb = float(bfloat(c)); + collapsed[ulong(row) * W + col] = bfloat(c); + normalized[ulong(row) * W + col] = bfloat(float(bfloat(cb * hinv)) * float(next_gain[col])); +} + +#define HY4_IHC_SEAM_FUSED(G) \ + kernel void tf_hy4_seam_g##G( \ + const device bfloat *branch [[buffer(0)]], const device bfloat *branch2 [[buffer(1)]], \ + const device bfloat *gain [[buffer(2)]], const device bfloat *residual [[buffer(3)]], \ + device float *post [[buffer(4)]], device bfloat *out [[buffer(5)]], \ + const device float *project [[buffer(6)]], device atomic_float *part [[buffer(7)]], \ + constant Hy4TailShape &a [[buffer(8)]], const device float *bias [[buffer(9)]], \ + const device float *scale [[buffer(10)]], const device bfloat *next_gain [[buffer(11)]], \ + device bfloat *collapsed [[buffer(12)]], device bfloat *normalized [[buffer(13)]], \ + constant Hy4IhcShape &n [[buffer(14)]], constant float &norm_eps [[buffer(15)]], \ + device Hy4SeamBarrier *bars [[buffer(16)]], uint2 group [[threadgroup_position_in_grid]], \ + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ + uint sg [[simdgroup_index_in_threadgroup]]) { \ + threadgroup float scratch[8], sums[9 + seam_gram][8], pre[4], gram[seam_gram]; \ + ihc_seam(branch, branch2, gain, residual, post, out, project, part, a, bias, scale, next_gain, \ + collapsed, normalized, n, norm_eps, bars, group.y, group.x, t, lane, sg, scratch, sums, pre, \ + gram); \ + } +HY4_IHC_SEAM_FUSED(4) +HY4_IHC_SEAM_FUSED(8) + +#define HY4_IHC_SEAMS(G) \ + kernel void tf_hy4_tail_g##G( \ + const device bfloat *branch [[buffer(0)]], const device bfloat *branch2 [[buffer(1)]], \ + const device bfloat *gain [[buffer(2)]], const device bfloat *residual [[buffer(3)]], \ + const device float *post [[buffer(4)]], device bfloat *out [[buffer(5)]], \ + const device float *project [[buffer(6)]], device float *part [[buffer(7)]], \ + constant Hy4TailShape &a [[buffer(8)]], uint2 group [[threadgroup_position_in_grid]], \ + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ + uint sg [[simdgroup_index_in_threadgroup]]) { \ + threadgroup float scratch[8], sums[9 + seam_gram][8]; \ + ihc_tail(branch, branch2, gain, residual, post, out, project, part, a, group.y, group.x, t, lane, sg, \ + scratch, sums); \ + } \ + kernel void tf_hy4_head_g##G( \ + const device bfloat *hidden [[buffer(0)]], const device float *part [[buffer(1)]], \ + const device float *bias [[buffer(2)]], const device float *scale [[buffer(3)]], \ + const device bfloat *gain [[buffer(4)]], device bfloat *collapsed [[buffer(5)]], \ + device bfloat *normalized [[buffer(6)]], device float *post [[buffer(7)]], \ + constant Hy4IhcShape &a [[buffer(8)]], constant float &norm_eps [[buffer(9)]], \ + uint2 group [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { \ + threadgroup float pre[4], gram[seam_gram]; \ + ihc_head(hidden, part, bias, scale, gain, collapsed, normalized, post, a, norm_eps, group.y, group.x, \ + t, pre, gram); \ + } +HY4_IHC_SEAMS(4) +HY4_IHC_SEAMS(8) diff --git a/zig/kernels/metal/hy4_flash/index_build.metal b/zig/kernels/metal/hy4_flash/index_build.metal new file mode 100644 index 00000000000..a54efbaa659 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/index_build.metal @@ -0,0 +1,84 @@ +// Hy4-flash's compressed indexer, the parts before scoring +#include +using namespace metal; +#pragma clang fp contract(off) + +struct Hy4IndexKeys { uint rows, capacity; float epsilon; }; +struct Hy4IndexGroups { uint first, count, capacity_groups; float epsilon; }; + +inline float hy4_ix_value(ushort word) { return as_type(uint(word) << 16); } + +inline ushort hy4_ix_round(float value) { + const uint bits = as_type(value); + if ((bits & 0x7fffffffu) > 0x7f800000u) return ushort((bits >> 16) | 0x0040u); + return ushort((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); +} + +// One threadgroup of 128 a row: RMS over the 128 key columns in fp32, the normalized value rounded to BF16 +kernel void tf_hy4_index_keys( + const device ushort *keys [[buffer(0)]], + const device ushort *gain [[buffer(1)]], + const device int *slots [[buffer(2)]], + device ushort *cache [[buffer(3)]], + constant Hy4IndexKeys &a [[buffer(4)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint simd [[simdgroup_index_in_threadgroup]]) { + threadgroup float partial[4]; + const int slot = slots[row]; + const float x = hy4_ix_value(keys[ulong(row) * 128 + t]); + float sq = simd_sum(x * x); + if (lane == 0) partial[simd] = sq; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float total = ((partial[0] + partial[1]) + partial[2]) + partial[3]; + if (slot < 0 || uint(slot) >= a.capacity) return; + const float inv = precise::rsqrt(total / 128.0f + a.epsilon); + const float normed = hy4_ix_value(hy4_ix_round(x * inv)); + cache[ulong(slot) * 128 + t] = hy4_ix_round(hy4_ix_value(gain[t]) * normed); +} + +// One threadgroup of 128 a group (thread = output column) +kernel void tf_hy4_index_groups( + const device ushort *token_keys [[buffer(0)]], + const device float *value_w [[buffer(1)]], + const device float *gate_w [[buffer(2)]], + const device float *bias [[buffer(3)]], + const device float *norm_w [[buffer(4)]], + device ushort *group_keys [[buffer(5)]], + constant Hy4IndexGroups &a [[buffer(6)]], + uint tg [[threadgroup_position_in_grid]], + uint c [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint simd [[simdgroup_index_in_threadgroup]]) { + threadgroup float x[4][128]; + threadgroup float partial[4]; + const uint g = a.first + tg; + if (g >= a.capacity_groups) return; + for (uint s = 0; s < 4; ++s) x[s][c] = hy4_ix_value(token_keys[(ulong(g) * 4 + s) * 128 + c]); + threadgroup_barrier(mem_flags::mem_threadgroup); + const device float *wv = value_w + ulong(c) * 128; + const device float *wg = gate_w + ulong(c) * 128; + float v[4], z[4]; + for (uint s = 0; s < 4; ++s) { + float sv = 0.0f, sg = 0.0f; + for (uint k = 0; k < 128; ++k) { + sv = fma(wv[k], x[s][k], sv); + sg = fma(wg[k], x[s][k], sg); + } + v[s] = sv; + z[s] = sg + bias[s * 128 + c]; + } + const float top = max(max(z[0], z[1]), max(z[2], z[3])); + float w[4]; + for (uint s = 0; s < 4; ++s) w[s] = precise::exp(z[s] - top); + const float denom = ((w[0] + w[1]) + w[2]) + w[3]; + float pooled = 0.0f; + for (uint s = 0; s < 4; ++s) pooled += v[s] * (w[s] / denom); + const float sq = simd_sum(pooled * pooled); + if (lane == 0) partial[simd] = sq; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float total = ((partial[0] + partial[1]) + partial[2]) + partial[3]; + const float inv = precise::rsqrt(total / 128.0f + a.epsilon); + group_keys[ulong(g) * 128 + c] = hy4_ix_round(norm_w[c] * (pooled * inv)); +} diff --git a/zig/kernels/metal/hy4_flash/index_recall.metal b/zig/kernels/metal/hy4_flash/index_recall.metal new file mode 100644 index 00000000000..093c865b909 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/index_recall.metal @@ -0,0 +1,117 @@ +// Recall complete index groups in logical token order, including the causal part of the current group. +#include +using namespace metal; + +struct Hy4RecallShape { uint rows, score_groups, group_budget; }; +struct Hy4RecallRow { uint group_base, token; }; + +kernel void tf_hy4_group_scores( + const device bfloat *query [[buffer(0)]], + const device bfloat *keys [[buffer(1)]], + const device bfloat *head_weights [[buffer(2)]], + const device Hy4RecallRow *rows [[buffer(3)]], + device float *scores [[buffer(4)]], + constant Hy4RecallShape &a [[buffer(5)]], + constant float &head_scale [[buffer(6)]], + uint2 tg [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]], + uint simd [[simdgroup_index_in_threadgroup]]) { + const uint r = tg.y, group = tg.x * 4 + simd; + const Hy4RecallRow row = rows[r]; + const uint closed = row.token / 4; + if (closed < a.group_budget || closed > a.score_groups || group >= closed) return; + const device bfloat *key = keys + (ulong(row.group_base) + group) * 128; + float cached[4]; + for (uint d = 0; d < 4; ++d) cached[d] = float(key[lane + d * 32]); + float score = 0.0f; + for (uint head = 0; head < 16; ++head) { + const device bfloat *q = query + (ulong(r) * 16 + head) * 128; + float dot = 0.0f; + for (uint d = 0; d < 4; ++d) dot = fma(float(q[lane + d * 32]), cached[d], dot); + for (ushort d = 16; d > 0; d >>= 1) dot += simd_shuffle_xor(dot, d); + const float w = float(head_weights[ulong(r) * 16 + head]) * head_scale; + score = fma(w, max(dot, 0.0f), score); + } + if (lane == 0) scores[ulong(r) * a.score_groups + group] = score; +} + +inline uint hy4_order(float x) { + const uint bits = as_type(x + 0.0f); + return (bits & 0x80000000u) ? ~bits : bits | 0x80000000u; +} + +kernel void tf_hy4_recall_groups( + const device float *scores [[buffer(0)]], + const device Hy4RecallRow *rows [[buffer(1)]], + device int *tokens [[buffer(2)]], + device int *counts [[buffer(3)]], + constant Hy4RecallShape &a [[buffer(4)]], + uint r [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint simd [[simdgroup_index_in_threadgroup]]) { + threadgroup atomic_uint hist[256]; + threadgroup uint picked[511], digit, next_need, included[8], equal[8], run_gt, run_eq; + const uint position = rows[r].token, closed = position / 4, keep = min(closed, a.group_budget - 1); + if (closed > a.score_groups) { + if (t == 0) counts[r] = 0; + return; + } + if (closed > keep) { + const device float *row_scores = scores + ulong(r) * a.score_groups; + uint prefix = 0, mask = 0, need = keep; + for (int shift = 24; shift >= 0; shift -= 8) { + atomic_store_explicit(&hist[t], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < closed; i += 256) { + const uint k = hy4_order(row_scores[i]); + if ((k & mask) == prefix) atomic_fetch_add_explicit(&hist[(k >> shift) & 255u], 1u, memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + uint above = 0, b = 255; + for (;;) { + const uint n = atomic_load_explicit(&hist[b], memory_order_relaxed); + if (above + n >= need || b == 0) break; + above += n; + --b; + } + digit = b; + next_need = need - above; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + prefix |= digit << shift; + mask |= 255u << shift; + need = next_need; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (t == 0) run_gt = run_eq = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint base = 0; base < closed; base += 256) { + const uint i = base + t, k = i < closed ? hy4_order(row_scores[i]) : 0u; + const uint gt = i < closed && k > prefix ? 1u : 0u; + const uint eq = i < closed && k == prefix ? 1u : 0u; + const uint ix_gt = simd_prefix_exclusive_sum(gt), ix_eq = simd_prefix_exclusive_sum(eq); + if (lane == 31) { included[simd] = ix_gt + gt; equal[simd] = ix_eq + eq; } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint prior_gt = run_gt + ix_gt, prior_eq = run_eq + ix_eq; + for (uint j = 0; j < simd; ++j) { prior_gt += included[j]; prior_eq += equal[j]; } + if (gt != 0 || (eq != 0 && prior_eq < need)) picked[prior_gt + min(prior_eq, need)] = i; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + for (uint j = 0; j < 8; ++j) { run_gt += included[j]; run_eq += equal[j]; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } else { + for (uint i = t; i < keep; i += 256) picked[i] = i; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device int *out = tokens + ulong(r) * a.group_budget * 4; + const uint count = keep * 4 + position % 4 + 1; + for (uint i = t; i < count; i += 256) { + const uint group = i / 4 < keep ? picked[i / 4] : closed; + out[i] = int(group * 4 + i % 4); + } + if (t == 0) counts[r] = int(count); +} diff --git a/zig/kernels/metal/hy4_flash/indexpool.metal b/zig/kernels/metal/hy4_flash/indexpool.metal new file mode 100644 index 00000000000..3070c5fab9b --- /dev/null +++ b/zig/kernels/metal/hy4_flash/indexpool.metal @@ -0,0 +1,37 @@ +// Hy4-flash's four-slot sparse index pooling before key normalization and RoPE. +#include +using namespace metal; +#pragma clang fp contract(off) + +struct Hy4PoolArgs { + uint groups; + uint width; +}; + +kernel void tf_hy4_pool_groups( + const device float *values [[buffer(0)]], + const device float *gates [[buffer(1)]], + const device float *position_bias [[buffer(2)]], + device float *output [[buffer(3)]], + constant Hy4PoolArgs &args [[buffer(4)]], + uint2 tid [[thread_position_in_grid]]) { + const uint column = tid.x; + const uint group = tid.y; + if (column >= args.width || group >= args.groups) return; + + const ulong base = ulong(group) * 4 * args.width + column; + float logits[4]; + for (uint slot = 0; slot < 4; ++slot) { + const uint offset = slot * args.width; + logits[slot] = gates[base + offset] + position_bias[offset + column]; + } + const float maximum = max(max(logits[0], logits[1]), max(logits[2], logits[3])); + float weights[4]; + for (uint slot = 0; slot < 4; ++slot) weights[slot] = precise::exp(logits[slot] - maximum); + const float normalizer = ((weights[0] + weights[1]) + weights[2]) + weights[3]; + float projected[4]; + for (uint slot = 0; slot < 4; ++slot) { + projected[slot] = values[base + slot * args.width] * (weights[slot] / normalizer); + } + output[ulong(group) * args.width + column] = ((projected[0] + projected[1]) + projected[2]) + projected[3]; +} diff --git a/zig/kernels/metal/hy4_flash/mla_attention.metal b/zig/kernels/metal/hy4_flash/mla_attention.metal new file mode 100644 index 00000000000..fef8fc07a54 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/mla_attention.metal @@ -0,0 +1,184 @@ +// Absorbed MLA using physical BF16 KV slots and rank-local attention sinks. +#include +using namespace metal; + +constant constexpr uint lat = 512, key = 576, chunk_keys = 512, heads_per_group = 4; + +struct Hy4AttendShape { + uint rows, heads, key_stride, chunks; +}; + +inline float hy4_float(ushort word) { return as_type(uint(word) << 16); } + +inline ushort hy4_bf16(float x) { + const uint word = as_type(x); + if (isnan(x)) return ushort((word >> 16) | 0x40u); + return ushort((word + 0x7fffu + ((word >> 16) & 1u)) >> 16); +} + +kernel void tf_hy4_attend_chunks( + const device ushort *query [[buffer(0)]], + const device ushort *cache [[buffer(1)]], + const device uint *slots [[buffer(2)]], + const device uint *counts [[buffer(3)]], + device float *scratch [[buffer(4)]], + constant Hy4AttendShape &shape [[buffer(5)]], + constant float &scale [[buffer(6)]], + uint3 group [[threadgroup_position_in_grid]], + uint simd [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row = group.z, head = group.x * heads_per_group + simd, chunk = group.y; + if (head >= shape.heads) return; + const ulong row_head = ulong(row) * shape.heads + head; + const device ushort *q = query + row_head * key; + const ulong plane = ulong(shape.rows) * shape.heads; + device float *out = scratch + (ulong(chunk) * plane + row_head) * (lat + 2); + const uint start = chunk * chunk_keys, end = min(start + chunk_keys, counts[row]); + const uint latent_col = 16 * lane, rope_col = lat + 2 * lane; + float ql[16], accum[16] = {}, top = -INFINITY, denom = 0.0f; + for (uint i = 0; i < 16; ++i) ql[i] = hy4_float(q[latent_col + i]); + const float q0 = hy4_float(q[rope_col]), q1 = hy4_float(q[rope_col + 1]); + const device uint *list = slots + ulong(row) * shape.key_stride; + for (uint j = start; j < end; ++j) { + const device ushort *k = cache + ulong(list[j]) * key; + float kv[16], dot = 0.0f; + for (uint i = 0; i < 16; ++i) { + kv[i] = hy4_float(k[latent_col + i]); + dot = fma(ql[i], kv[i], dot); + } + dot = fma(q0, hy4_float(k[rope_col]), dot); + dot = fma(q1, hy4_float(k[rope_col + 1]), dot); + for (ushort d = 16; d > 0; d >>= 1) dot += simd_shuffle_xor(dot, d); + const float score = dot * scale, next = max(top, score); + const float old = precise::exp(top - next), p = precise::exp(score - next); + denom = fma(denom, old, p); + for (uint i = 0; i < 16; ++i) accum[i] = fma(p, kv[i], accum[i] * old); + top = next; + } + if (lane == 0) { + out[lat] = top; + out[lat + 1] = denom; + } + for (uint i = 0; i < 16; ++i) out[latent_col + i] = accum[i]; +} + +kernel void tf_hy4_attend_merge( + const device float *scratch [[buffer(0)]], + const device float *sinks [[buffer(1)]], + device ushort *output [[buffer(2)]], + constant Hy4AttendShape &shape [[buffer(3)]], + uint2 group [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]]) { + const ulong head = group.x, row_head = ulong(group.y) * shape.heads + head; + const ulong step = ulong(shape.rows) * shape.heads * (lat + 2); + const device float *base = scratch + row_head * (lat + 2); + const uint column = lane * 4; + float top = sinks[head]; + for (uint i = 0; i < shape.chunks; ++i) top = max(top, base[i * step + lat]); + float denom = precise::exp(sinks[head] - top), acc[4] = {}; + for (uint i = 0; i < shape.chunks; ++i) { + const device float *part = base + i * step; + const float p = precise::exp(part[lat] - top); + denom = fma(part[lat + 1], p, denom); + for (uint j = 0; j < 4; ++j) acc[j] = fma(part[column + j], p, acc[j]); + } + for (uint j = 0; j < 4; ++j) output[row_head * lat + column + j] = hy4_bf16(precise::divide(acc[j], denom)); +} + +// Chunked attention in two steps. +kernel void tf_hy4_attend_scores( + const device ushort *query [[buffer(0)]], + const device ushort *cache [[buffer(1)]], + const device uint *slots [[buffer(2)]], + const device uint *counts [[buffer(3)]], + device float *scores [[buffer(4)]], + constant Hy4AttendShape &shape [[buffer(5)]], + constant float &scale [[buffer(6)]], + uint3 group [[threadgroup_position_in_grid]], + uint simd [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const uint row = group.z, head = group.x * heads_per_group + simd; + if (head >= shape.heads) return; + const ulong row_head = ulong(row) * shape.heads + head; + const device ushort *q = query + row_head * key; + const uint start = group.y * 64, end = min(start + 64, counts[row]); + if (start >= end) return; + const uint latent_col = 16 * lane, rope_col = lat + 2 * lane; + float ql[16]; + for (uint i = 0; i < 16; ++i) ql[i] = hy4_float(q[latent_col + i]); + const float q0 = hy4_float(q[rope_col]), q1 = hy4_float(q[rope_col + 1]); + const device uint *list = slots + ulong(row) * shape.key_stride; + device float *out = scores + row_head * shape.key_stride; + for (uint j = start; j < end; ++j) { + const device ushort *k = cache + ulong(list[j]) * key; + float dot = 0.0f; + for (uint i = 0; i < 16; ++i) dot = fma(ql[i], hy4_float(k[latent_col + i]), dot); + dot = fma(q0, hy4_float(k[rope_col]), dot); + dot = fma(q1, hy4_float(k[rope_col + 1]), dot); + for (ushort d = 16; d > 0; d >>= 1) dot += simd_shuffle_xor(dot, d); + if (lane == 0) out[j] = dot * scale; + } +} + +kernel void tf_hy4_attend_scored( + const device float *scores [[buffer(0)]], + const device ushort *cache [[buffer(1)]], + const device uint *slots [[buffer(2)]], + const device uint *counts [[buffer(3)]], + device float *scratch [[buffer(4)]], + constant Hy4AttendShape &shape [[buffer(5)]], + uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]], + uint simd [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + // The threadgroup's four heads share one row's keys + threadgroup uint4 tile[16][64]; + const uint row = group.z, head = group.x * heads_per_group + simd, chunk = group.y; + const bool live = head < shape.heads; + const ulong row_head = ulong(row) * shape.heads + head; + const ulong plane = ulong(shape.rows) * shape.heads; + const uint start = chunk * chunk_keys, end = min(start + chunk_keys, counts[row]); + const uint latent_col = 16 * lane; + float accum[16] = {}, top = -INFINITY, denom = 0.0f; + const device uint *list = slots + ulong(row) * shape.key_stride; + const device float *score_row = scores + (live ? row_head : 0) * shape.key_stride; + // 32 keys of scores a step (lane t: key j + t) + for (uint j = start; j < end; j += 32) { + const uint n = min(32u, end - j); + const float score = lane < n ? score_row[j + lane] : -INFINITY; + float m = score; + for (ushort d = 1; d < 32; d <<= 1) { + const float o = simd_shuffle_up(m, d); + if (lane >= d) m = max(m, o); + } + const float next = max(top, m); + float before = simd_shuffle_up(next, 1); + if (lane == 0) before = top; + const float old = precise::exp(before - next), p = precise::exp(score - next); + for (uint h = 0; h < n; h += 16) { + const uint tn = min(16u, n - h); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = tid; e < tn * 64; e += 128) { + const uint t = e / 64, part = e % 64; + tile[t][part] = *((const device uint4 *)(cache + ulong(list[j + h + t]) * key) + part); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (live) { + for (uint t = 0; t < tn; ++t) { + const threadgroup ushort *kv_row = (const threadgroup ushort *)&tile[t][0]; + const float pt = simd_shuffle(p, ushort(h + t)), ot = simd_shuffle(old, ushort(h + t)); + denom = fma(denom, ot, pt); + for (uint i = 0; i < 16; ++i) accum[i] = fma(pt, hy4_float(kv_row[latent_col + i]), accum[i] * ot); + } + } + } + top = simd_shuffle(next, ushort(n - 1)); + } + if (!live) return; + device float *out = scratch + (ulong(chunk) * plane + row_head) * (lat + 2); + if (lane == 0) { + out[lat] = top; + out[lat + 1] = denom; + } + for (uint i = 0; i < 16; ++i) out[latent_col + i] = accum[i]; +} diff --git a/zig/kernels/metal/hy4_flash/mla_nax.metal b/zig/kernels/metal/hy4_flash/mla_nax.metal new file mode 100644 index 00000000000..c075d70af0c --- /dev/null +++ b/zig/kernels/metal/hy4_flash/mla_nax.metal @@ -0,0 +1,273 @@ +// Hy4-flash's absorbed-MLA BF16 products on the tensor units (nax.h's 16x32x16 op) +#include "../nax.h" +using namespace tfp; + +struct Hy4MlaProjectArgs { uint rows; uint heads; }; + +inline float hy4n_value(bfloat w) { return float(w); } +inline bfloat hy4n_round(float value) { + const uint bits = as_type(value); + if ((bits & 0x7fffffffu) > 0x7f800000u) return as_type(ushort((bits >> 16) | 0x0040u)); + return as_type(ushort((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16)); +} + +// absorbed[r][h][0, 512) = q[r][h][0, 192) W_UK[h], W_UK[h] row-major [192][512]; rows 576 apart a head. +[[kernel]] void tf_hy4_absorb_nax(const device bfloat* query [[buffer(0)]], const device bfloat* wk [[buffer(1)]], + device bfloat* absorbed [[buffer(2)]], constant Hy4MlaProjectArgs& args [[buffer(3)]], + uint3 group [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]]) { + const short2 home = frag_home(ushort(lane)); + const int heads = int(args.heads), h = int(group.y), r0 = int(group.z) * 16, n0 = int(group.x) * 128 + int(sg) * 32; + const int live = int(args.rows) - r0; + const device bfloat* a_rows = query + long(r0) * heads * 256 + h * 256; + const device bfloat* b = wk + long(h) * 192 * 512; + frag lo = 0.0f, hi = 0.0f; + for (int k = 0; k < 192; k += 16) { + frag a, b0, b1; + frag_get_in(a, a_rows, heads * 256, 0, k, home, live, 192); + frag_get(b0, b, 512, k, n0, home); + frag_get(b1, b, 512, k, n0 + 16, home); + mma_16x32(lo, hi, a, b0, b1); + } + device bfloat* c = absorbed + long(r0) * heads * 576 + h * 576; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int rr = home.y + (e >> 2) * 8, cc = home.x + TF_COL(e); + if (rr < live) { + c[long(rr) * heads * 576 + n0 + cc] = hy4n_round(lo[e]); + c[long(rr) * heads * 576 + n0 + 16 + cc] = hy4n_round(hi[e]); + } + } +} + +// values[r][h][0, 256) = gate(latent[r][h][0, 512) W_UV[h]^T), W_UV[h] stored [256][512]; +[[kernel]] void tf_hy4_expand_gated_nax(const device bfloat* latent [[buffer(0)]], const device bfloat* wv [[buffer(1)]], + device bfloat* values [[buffer(2)]], constant Hy4MlaProjectArgs& args [[buffer(3)]], + const device bfloat* logits [[buffer(4)]], uint3 group [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + const short2 home = frag_home(ushort(lane)); + const int heads = int(args.heads), h = int(group.y), r0 = int(group.z) * 16, n0 = int(group.x) * 128 + int(sg) * 32; + const int live = int(args.rows) - r0; + const device bfloat* a_rows = latent + long(r0) * heads * 512 + h * 512; + const device bfloat* bt = wv + long(h) * 256 * 512; + frag lo = 0.0f, hi = 0.0f; + for (int k = 0; k < 512; k += 16) { + frag a, b0, b1; + frag_get_in(a, a_rows, heads * 512, 0, k, home, live, 512); + frag_get_t(b0, bt, 512, n0, k, home); + frag_get_t(b1, bt, 512, n0 + 16, k, home); + mma_16x32(lo, hi, a, b0, b1); + } + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int rr = home.y + (e >> 2) * 8, cc = home.x + TF_COL(e); + if (rr < live) { + for (int side = 0; side < 2; ++side) { + const long at = long(r0 + rr) * heads * 256 + h * 256 + n0 + 16 * side + cc; + const bfloat v = hy4n_round(side ? hi[e] : lo[e]); + const float gate = 1.0f / (1.0f + precise::exp(-float(logits[at]))); + values[at] = hy4n_round(float(v) * float(hy4n_round(gate))); + } + } + } +} + +// Absorbed MLA attention on the tensor units, flash style +constant constexpr int hy4_tk = 32, hy4_kw = 576, hy4_lw = 512; +struct Hy4FlashShape { uint rows, heads; float scale; uint pad; }; + +// SPLIT (decode passes, one row block): threadgroup z of `a.pad` takes the z-th run of the tiles and stores its +template +inline void hy4_attend_nax(const device bfloat* query, const device bfloat* cache, const device uint2* ranges, + const device uint* tiles, const device float* sinks, device bfloat* out, + constant Hy4FlashShape& a, uint3 group, uint sg, uint lane, device float* o_part, + device float* ml_part, threadgroup float (&part)[4][16][hy4_tk]) { + const short2 home = frag_home(ushort(lane)); + const int heads = int(a.heads), h = int(group.x), r0 = int(group.y) * 16; + const int live = min(16, int(a.rows) - r0); + uint lo[2] = {0u, 0u}, hi[2] = {0u, 0u}; + for (int i = 0; i < 2; ++i) { + const int rr = home.y + 8 * i; + if (rr < live) { const uint2 g = ranges[r0 + rr]; lo[i] = g.x; hi[i] = g.y; } + } + uint blo = 0xffffffffu, bhi = 0u; + for (int r = 0; r < live; ++r) { const uint2 g = ranges[r0 + r]; blo = min(blo, g.x); bhi = max(bhi, g.y); } + const device bfloat* q = query + (long(r0) * heads + h) * hy4_kw; + const int ldq = heads * hy4_kw; + frag o[4][2]; + TF_UNROLL + for (int j = 0; j < 4; ++j) { o[j][0] = 0.0f; o[j][1] = 0.0f; } + float m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f}; + int t0 = int(blo / hy4_tk), t1 = int((bhi + hy4_tk - 1) / hy4_tk); + if (SPLIT) { + const int per = (t1 - t0 + int(a.pad) - 1) / int(a.pad); + t0 = min(t1, t0 + int(group.z) * per); + t1 = min(t1, t0 + per); + } + for (int t = t0; t < t1; ++t) { + const device bfloat* k = cache + long(tiles[t]) * hy4_kw; + frag slo = 0.0f, shi = 0.0f; + for (int d = int(sg) * 144; d < int(sg) * 144 + 144; d += 16) { + frag qa, k0, k1; + frag_get_in(qa, q, ldq, 0, d, home, live, hy4_kw); + frag_get_t(k0, k, hy4_kw, 0, d, home); + frag_get_t(k1, k, hy4_kw, 16, d, home); + mma_16x32(slo, shi, qa, k0, k1); + } + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int rr = home.y + (e >> 2) * 8, cc = home.x + TF_COL(e); + part[sg][rr][cc] = slo[e]; + part[sg][rr][16 + cc] = shi[e]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float p[2][8]; + float tmax[2] = {-INFINITY, -INFINITY}; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int i = e >> 2, rr = home.y + i * 8, cc = home.x + TF_COL(e); + for (int side = 0; side < 2; ++side) { + const int col = side * 16 + cc; + float s = part[0][rr][col]; + s += part[1][rr][col]; + s += part[2][rr][col]; + s += part[3][rr][col]; + const uint key = uint(t * hy4_tk + col); + s = (key >= lo[i] && key < hi[i]) ? s * a.scale : -INFINITY; + p[side][e] = s; + tmax[i] = max(tmax[i], s); + } + } + float alpha[2]; + for (int i = 0; i < 2; ++i) { + tmax[i] = max(tmax[i], simd_shuffle_xor(tmax[i], ushort(1))); + tmax[i] = max(tmax[i], simd_shuffle_xor(tmax[i], ushort(8))); + const float next = max(m[i], tmax[i]); + alpha[i] = next == -INFINITY ? 1.0f : precise::exp(m[i] - next); + m[i] = next; + } + float sum[2] = {0.0f, 0.0f}; + frag plo, phi; + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int i = e >> 2; + for (int side = 0; side < 2; ++side) { + const float v = m[i] == -INFINITY ? 0.0f : precise::exp(p[side][e] - m[i]); + p[side][e] = v; + sum[i] += v; + } + plo[e] = bfloat(p[0][e]); + phi[e] = bfloat(p[1][e]); + } + for (int i = 0; i < 2; ++i) { + sum[i] += simd_shuffle_xor(sum[i], ushort(1)); + sum[i] += simd_shuffle_xor(sum[i], ushort(8)); + l[i] = l[i] * alpha[i] + sum[i]; + } + TF_UNROLL + for (int j = 0; j < 4; ++j) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + o[j][0][e] *= alpha[e >> 2]; + o[j][1][e] *= alpha[e >> 2]; + } + const int n = int(sg) * 128 + j * 32; + frag v0, v1; + frag_get(v0, k, hy4_kw, 0, n, home); + frag_get(v1, k, hy4_kw, 0, n + 16, home); + mma_16x32(o[j][0], o[j][1], plo, v0, v1); + frag_get(v0, k, hy4_kw, 16, n, home); + frag_get(v1, k, hy4_kw, 16, n + 16, home); + mma_16x32(o[j][0], o[j][1], phi, v0, v1); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if (SPLIT) { + const long z = long(group.z), rows = long(a.rows); + for (int i = 0; i < 2; ++i) { + const int rr = home.y + 8 * i; + if (rr < live && sg == 0) { + device float* ml = ml_part + ((z * rows + r0 + rr) * heads + h) * 2; + ml[0] = m[i]; + ml[1] = l[i]; + } + } + TF_UNROLL + for (int j = 0; j < 4; ++j) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int i = e >> 2, rr = home.y + i * 8, cc = home.x + TF_COL(e); + if (rr < live) { + device float* row = o_part + ((z * rows + r0 + rr) * heads + h) * hy4_lw + int(sg) * 128 + j * 32 + cc; + row[0] = o[j][0][e]; + row[16] = o[j][1][e]; + } + } + } + return; + } + const float sink = sinks[h]; + float keep[2], denom[2]; + for (int i = 0; i < 2; ++i) { + const float top = max(m[i], sink); + keep[i] = m[i] == -INFINITY ? 0.0f : precise::exp(m[i] - top); + denom[i] = l[i] * keep[i] + precise::exp(sink - top); + } + TF_UNROLL + for (int j = 0; j < 4; ++j) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int i = e >> 2, rr = home.y + i * 8, cc = home.x + TF_COL(e); + if (rr < live) { + device bfloat* row = out + (long(r0 + rr) * heads + h) * hy4_lw + int(sg) * 128 + j * 32 + cc; + row[0] = bfloat(precise::divide(o[j][0][e] * keep[i], denom[i])); + row[16] = bfloat(precise::divide(o[j][1][e] * keep[i], denom[i])); + } + } + } +} + +[[kernel]] void tf_hy4_attend_nax(const device bfloat* query [[buffer(0)]], const device bfloat* cache [[buffer(1)]], + const device uint2* ranges [[buffer(2)]], const device uint* tiles [[buffer(3)]], + const device float* sinks [[buffer(4)]], device bfloat* out [[buffer(5)]], + constant Hy4FlashShape& a [[buffer(6)]], uint3 group [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4][16][hy4_tk]; + hy4_attend_nax(query, cache, ranges, tiles, sinks, out, a, group, sg, lane, nullptr, nullptr, part); +} + +[[kernel]] void tf_hy4_attend_nax_split(const device bfloat* query [[buffer(0)]], const device bfloat* cache [[buffer(1)]], + const device uint2* ranges [[buffer(2)]], const device uint* tiles [[buffer(3)]], + const device float* sinks [[buffer(4)]], device bfloat* out [[buffer(5)]], + constant Hy4FlashShape& a [[buffer(6)]], device float* o_part [[buffer(7)]], + device float* ml_part [[buffer(8)]], uint3 group [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4][16][hy4_tk]; + hy4_attend_nax(query, cache, ranges, tiles, sinks, out, a, group, sg, lane, o_part, ml_part, part); +} + +// The split runs of tf_hy4_attend_nax_split joined with the learned sink +[[kernel]] void tf_hy4_attend_combine(const device float* o_part [[buffer(0)]], const device float* ml_part [[buffer(1)]], + const device float* sinks [[buffer(2)]], device bfloat* out [[buffer(3)]], + constant Hy4FlashShape& a [[buffer(4)]], uint2 group [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + const int h = int(group.x), r = int(group.y), heads = int(a.heads), splits = min(int(a.pad), 8); + const long rows = long(a.rows); + const float sink = sinks[h]; + float top = sink; + for (int z = 0; z < splits; ++z) top = max(top, ml_part[((z * rows + r) * heads + h) * 2]); + float w[8]; + float denom = precise::exp(sink - top); + for (int z = 0; z < 8; ++z) { + w[z] = 0.0f; + if (z >= splits) continue; + const device float* ml = ml_part + ((z * rows + r) * heads + h) * 2; + w[z] = ml[0] == -INFINITY ? 0.0f : precise::exp(ml[0] - top); + denom += ml[1] * w[z]; + } + for (int c = int(t) * 4; c < int(t) * 4 + 4; ++c) { + float v = 0.0f; + for (int z = 0; z < splits; ++z) v += o_part[((z * rows + r) * heads + h) * hy4_lw + c] * w[z]; + out[(long(r) * heads + h) * hy4_lw + c] = bfloat(precise::divide(v, denom)); + } +} diff --git a/zig/kernels/metal/hy4_flash/mla_project.metal b/zig/kernels/metal/hy4_flash/mla_project.metal new file mode 100644 index 00000000000..f44055f5262 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/mla_project.metal @@ -0,0 +1,158 @@ +// Hy4-flash projections around absorbed MLA. The rotary lanes are filled separately. +#include +using namespace metal; +#pragma clang fp contract(off) + +struct Hy4MlaProjectArgs { uint rows; uint heads; }; +struct Hy4RopeParameters { float frequencies[32]; uint axes[32]; }; +struct Hy4RopeView { uint rows, heads, input_stride, output_stride; }; +struct Hy4CacheWrite { uint rows, capacity; float epsilon; }; + +inline float hy4_mla_value(ushort word) { return as_type(uint(word) << 16); } + +inline ushort hy4_mla_round(float value) { + const uint bits = as_type(value); + if ((bits & 0x7fffffffu) > 0x7f800000u) return ushort((bits >> 16) | 0x0040u); + return ushort((bits + 0x7fffu + ((bits >> 16) & 1u)) >> 16); +} + +// Match the checkpoint's BF16 trigonometric coefficients before the FP32 pair rotation. +kernel void tf_hy4_rotary_table( + const device int *positions [[buffer(0)]], + device ushort *table [[buffer(1)]], + constant Hy4RopeParameters &p [[buffer(2)]], + uint2 tid [[thread_position_in_grid]]) { + const uint pair = tid.x, row = tid.y; + const float phase = float(positions[ulong(row) * 3 + p.axes[pair]]) * p.frequencies[pair]; + table[ulong(row) * 64 + 2 * pair] = hy4_mla_round(precise::cos(phase)); + table[ulong(row) * 64 + 2 * pair + 1] = hy4_mla_round(precise::sin(phase)); +} + +kernel void tf_hy4_rotate( + const device ushort *input [[buffer(0)]], + const device ushort *table [[buffer(1)]], + device ushort *output [[buffer(2)]], + constant Hy4RopeView &v [[buffer(3)]], + uint3 tid [[thread_position_in_grid]]) { + const ulong row_head = ulong(tid.z) * v.heads + tid.y; + const uint col = 2 * tid.x; + const ulong i = row_head * v.input_stride + col, o = row_head * v.output_stride + col; + const ulong base = ulong(tid.z) * 64 + col; + const float a = hy4_mla_value(input[i]), b = hy4_mla_value(input[i + 1]); + const float c = hy4_mla_value(table[base]), s = hy4_mla_value(table[base + 1]); + output[o] = hy4_mla_round(a * c - b * s); + output[o + 1] = hy4_mla_round(b * c + a * s); +} + +kernel void tf_hy4_cache_keys( + const device ushort *input [[buffer(0)]], + const device ushort *gain [[buffer(1)]], + const device ushort *table [[buffer(2)]], + const device int *slots [[buffer(3)]], + device ushort *cache [[buffer(4)]], + constant Hy4CacheWrite &a [[buffer(5)]], + uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], + uint simd [[simdgroup_index_in_threadgroup]]) { + const int slot = slots[row]; + if (slot < 0 || uint(slot) >= a.capacity) return; + const device ushort *x = input + ulong(row) * 576; + device ushort *y = cache + ulong(slot) * 576; + float v[4], sq = 0.0f; + for (uint i = 0; i < 4; ++i) { + v[i] = hy4_mla_value(x[t + i * 128]); + sq = fma(v[i], v[i], sq); + } + for (ushort d = 16; d > 0; d >>= 1) sq += simd_shuffle_xor(sq, d); + threadgroup float part[4]; + if (lane == 0) part[simd] = sq; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float sum = (part[0] + part[2]) + (part[1] + part[3]); + const float inverse = precise::rsqrt(sum / 512.0f + a.epsilon); + for (uint i = 0; i < 4; ++i) { + const uint col = t + i * 128; + const float normalized = hy4_mla_value(hy4_mla_round(v[i] * inverse)); + y[col] = hy4_mla_round(normalized * hy4_mla_value(gain[col])); + } + if (t < 32) { + const uint col = 2 * t; + const float u = hy4_mla_value(x[512 + col]), v1 = hy4_mla_value(x[513 + col]); + const float c = hy4_mla_value(table[ulong(row) * 64 + col]); + const float s = hy4_mla_value(table[ulong(row) * 64 + col + 1]); + y[512 + col] = hy4_mla_round(u * c - v1 * s); + y[513 + col] = hy4_mla_round(v1 * c + u * s); + } +} + +kernel void tf_hy4_gate_values( + device ushort *values [[buffer(0)]], + const device ushort *logits [[buffer(1)]], + constant uint &columns [[buffer(2)]], + uint2 tid [[thread_position_in_grid]]) { + const ulong i = ulong(tid.y) * columns + tid.x; + const float gate = 1.0f / (1.0f + precise::exp(-hy4_mla_value(logits[i]))); + values[i] = hy4_mla_round(hy4_mla_value(values[i]) * hy4_mla_value(hy4_mla_round(gate))); +} + +kernel void tf_hy4_absorb_q( + const device ushort *query [[buffer(0)]], + const device ushort *key_projection [[buffer(1)]], + device ushort *absorbed [[buffer(2)]], + constant Hy4MlaProjectArgs &args [[buffer(3)]], + uint2 tid [[thread_position_in_grid]]) { + const uint column = tid.x; + const uint row_head = tid.y; + if (column >= 512 || row_head >= ulong(args.rows) * args.heads) return; + + const ulong q = ulong(row_head) * 256; + const ulong wk = ulong(row_head % args.heads) * 192 * 512 + column; + float sum = 0.0f; + for (uint i = 0; i < 192; ++i) { + sum = fma(hy4_mla_value(query[q + i]), hy4_mla_value(key_projection[wk + i * 512]), sum); + } + absorbed[ulong(row_head) * 576 + column] = hy4_mla_round(sum); +} + +kernel void tf_hy4_expand_v( + const device ushort *latent [[buffer(0)]], + const device ushort *value_projection [[buffer(1)]], + device ushort *expanded [[buffer(2)]], + constant Hy4MlaProjectArgs &args [[buffer(3)]], + uint2 tid [[thread_position_in_grid]]) { + const uint column = tid.x; + const uint row_head = tid.y; + if (column >= 256 || row_head >= ulong(args.rows) * args.heads) return; + + const ulong from = ulong(row_head) * 512; + const ulong wv = (ulong(row_head % args.heads) * 256 + column) * 512; + float sum = 0.0f; + for (uint i = 0; i < 512; ++i) { + sum = fma(hy4_mla_value(latent[from + i]), hy4_mla_value(value_projection[wv + i]), sum); + } + expanded[ulong(row_head) * 256 + column] = hy4_mla_round(sum); +} + +// tf_hy4_expand_v then tf_hy4_gate_values in one launch +kernel void tf_hy4_expand_v_gated( + const device ushort *latent [[buffer(0)]], + const device ushort *value_projection [[buffer(1)]], + device ushort *expanded [[buffer(2)]], + constant Hy4MlaProjectArgs &args [[buffer(3)]], + const device ushort *logits [[buffer(4)]], + uint2 tid [[thread_position_in_grid]]) { + const uint column = tid.x; + const uint row_head = tid.y; + if (column >= 256 || row_head >= ulong(args.rows) * args.heads) return; + + const ulong from = ulong(row_head) * 512; + const ulong wv = (ulong(row_head % args.heads) * 256 + column) * 512; + float sum = 0.0f; + for (uint i = 0; i < 512; ++i) { + sum = fma(hy4_mla_value(latent[from + i]), hy4_mla_value(value_projection[wv + i]), sum); + } + const ulong at = ulong(row_head) * 256 + column; + const ushort value = hy4_mla_round(sum); + const float gate = 1.0f / (1.0f + precise::exp(-hy4_mla_value(logits[at]))); + expanded[at] = hy4_mla_round(hy4_mla_value(value) * hy4_mla_value(hy4_mla_round(gate))); +} diff --git a/zig/kernels/metal/hy4_flash/route_rows.metal b/zig/kernels/metal/hy4_flash/route_rows.metal new file mode 100644 index 00000000000..0dffb2a0954 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/route_rows.metal @@ -0,0 +1,77 @@ + +// Appended to the core router source (its TF_E, TF_TOPK, PER, RouteArgs and tf_sigmoid_precise). +[[kernel]] void tf_hy4_route_select_rows(const device float* LOGITS [[buffer(0)]], const device float* BIAS [[buffer(1)]], + constant RouteArgs& a [[buffer(2)]], device int* PICK [[buffer(3)]], + device float* WTS [[buffer(4)]], uint r_ [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const int r = int(r_); + if (r >= a.rows) return; + float c[PER], sc[PER]; + for (int j = 0; j < PER; j++) { + const int id = j * 32 + int(lane); + if (id < TF_E) { + sc[j] = tf_sigmoid_precise(LOGITS[r * TF_E + id]); + c[j] = sc[j] + BIAS[id]; + } else { + sc[j] = 0.0f; c[j] = -INFINITY; + } + } + float w[TF_TOPK]; + for (int k = 0; k < TF_TOPK; k++) { + float best = -INFINITY, bsc = 0.0f; + int bid = TF_E; + for (int j = 0; j < PER; j++) { + const int id = j * 32 + int(lane); + if (id < TF_E && (c[j] > best || (c[j] == best && id < bid))) { best = c[j]; bid = id; bsc = sc[j]; } + } + for (int off = 16; off > 0; off /= 2) { + const float ob = simd_shuffle_xor(best, off); + const int oi = simd_shuffle_xor(bid, off); + const float os = simd_shuffle_xor(bsc, off); + if (ob > best || (ob == best && oi < bid)) { best = ob; bid = oi; bsc = os; } + } + w[k] = bsc; + if (int(lane) == bid % 32) c[bid / 32] = -INFINITY; + if (lane == 0) PICK[r * TF_TOPK + k] = bid; + } + if (lane == 0) { + float total = w[0]; + for (int k = 1; k < TF_TOPK; k++) total = total + w[k]; + for (int k = 0; k < TF_TOPK; k++) WTS[r * TF_TOPK + k] = (w[k] / total) * a.scale; + } +} + +// tf_hy4_route_select_rows as ranks: one thread an expert (TF_E <= 512, threadgroup 512) +[[kernel]] void tf_hy4_route_select_rank(const device float* LOGITS [[buffer(0)]], const device float* BIAS [[buffer(1)]], + constant RouteArgs& a [[buffer(2)]], device int* PICK [[buffer(3)]], + device float* WTS [[buffer(4)]], uint r_ [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + threadgroup float cs[512]; + threadgroup float w[TF_TOPK]; + const int r = int(r_), id = int(t); + if (r >= a.rows) return; + float sc = 0.0f, c = -INFINITY; + if (id < TF_E) { + sc = tf_sigmoid_precise(LOGITS[r * TF_E + id]); + c = sc + BIAS[id]; + } + cs[t] = c; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (id < TF_E) { + int rank = 0; + for (int j = 0; j < TF_E; ++j) { + const float o = cs[j]; + rank += (o > c || (o == c && j < id)) ? 1 : 0; + } + if (rank < TF_TOPK) { + PICK[r * TF_TOPK + rank] = id; + w[rank] = sc; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t == 0) { + float total = w[0]; + for (int k = 1; k < TF_TOPK; k++) total = total + w[k]; + for (int k = 0; k < TF_TOPK; k++) WTS[r * TF_TOPK + k] = (w[k] / total) * a.scale; + } +} diff --git a/zig/kernels/metal/hy4_flash/rows.metal b/zig/kernels/metal/hy4_flash/rows.metal new file mode 100644 index 00000000000..74bc8e330a3 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/rows.metal @@ -0,0 +1,86 @@ + +// Hy4-flash lane windows (compiled after the chip's core row projection source, whose helpers it calls). +template +inline void tf_hy4_rows_block(const device uint8_t* wr, const device bfloat* sr, const device bfloat* br, + const device bfloat* X, int K, int N, int GS, int m, int row0, uint lane, + device bfloat* OUT) { + float acc[MB][RPS]; + tf_rp_rows= 3)>(wr, sr, br, X + size_t(m) * K, K, GS, lane, acc); + if (lane == 0) + for (int b = 0; b < MB; b++) + for (int j = 0; j < RPS; j++) OUT[size_t(m + b) * N + row0 + j] = tf_rp_out(acc[b][j]); +} + +// dims: K, N, GS, rows (as tf_row_projection). X [rows, K]; W [N, K*BITS/32] words; S, B [N, K/GS]. +template +[[kernel]] void tf_hy4_rows(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], + constant int* dims [[buffer(4)]], device bfloat* OUT [[buffer(5)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const int K = dims[0], N = dims[1], GS = dims[2], rows = dims[3]; + const int row0 = (int(tg.x) * SG + int(sg)) * RPS; + if (row0 >= N) return; + const size_t at = size_t(row0); + const device uint8_t* wr = (const device uint8_t*)W + at * (K * BITS / 8); + const device bfloat* sr = S + at * (K / GS); + const device bfloat* br = B + at * (K / GS); + int m = 0; + #pragma clang loop unroll(disable) + for (; m + 8 <= rows; m += 8) tf_hy4_rows_block(wr, sr, br, X, K, N, GS, m, row0, lane, OUT); + if (m + 6 <= rows) { + tf_hy4_rows_block(wr, sr, br, X, K, N, GS, m, row0, lane, OUT); + m += 6; + } else if (m + 4 <= rows) { + tf_hy4_rows_block(wr, sr, br, X, K, N, GS, m, row0, lane, OUT); + m += 4; + } + if (m + 2 <= rows) { + tf_hy4_rows_block(wr, sr, br, X, K, N, GS, m, row0, lane, OUT); + m += 2; + } + if (m < rows) tf_hy4_rows_block(wr, sr, br, X, K, N, GS, m, row0, lane, OUT); +} + +template [[host_name("tf_hy4_rows_r2_q4")]] [[kernel]] decltype(tf_hy4_rows<2, 4, 4>) tf_hy4_rows<2, 4, 4>; +template [[host_name("tf_hy4_rows_r2_q8")]] [[kernel]] decltype(tf_hy4_rows<2, 4, 8>) tf_hy4_rows<2, 4, 8>; +template [[host_name("tf_hy4_rows_r4_q4")]] [[kernel]] decltype(tf_hy4_rows<4, 4, 4>) tf_hy4_rows<4, 4, 4>; +template [[host_name("tf_hy4_rows_r4_q8")]] [[kernel]] decltype(tf_hy4_rows<4, 4, 8>) tf_hy4_rows<4, 4, 8>; +template [[host_name("tf_hy4_rows_r2s_q4")]] [[kernel]] decltype(tf_hy4_rows<2, 4, 4, true>) tf_hy4_rows<2, 4, 4, true>; +template [[host_name("tf_hy4_rows_r2s_q8")]] [[kernel]] decltype(tf_hy4_rows<2, 4, 8, true>) tf_hy4_rows<2, 4, 8, true>; +template [[host_name("tf_hy4_rows_r1s_q4")]] [[kernel]] decltype(tf_hy4_rows<1, 8, 4, true>) tf_hy4_rows<1, 8, 4, true>; +template [[host_name("tf_hy4_rows_r1s_q8")]] [[kernel]] decltype(tf_hy4_rows<1, 8, 8, true>) tf_hy4_rows<1, 8, 8, true>; +template [[host_name("tf_hy4_rows_r1_q4")]] [[kernel]] decltype(tf_hy4_rows<1, 8, 4>) tf_hy4_rows<1, 8, 4>; +template [[host_name("tf_hy4_rows_r1_q8")]] [[kernel]] decltype(tf_hy4_rows<1, 8, 8>) tf_hy4_rows<1, 8, 8>; + +// Greedy pick on the GPU: the first index of a row's largest BF16 logit (NaN never wins), as the host's scan. +[[kernel]] void tf_hy4_argmax(const device ushort* logits [[buffer(0)]], device uint* out [[buffer(1)]], + constant uint2& a [[buffer(2)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + const device ushort* x = logits + size_t(row) * a.x; + float best = -INFINITY; + uint id = 0xffffffffu; + for (uint i = t; i < a.x; i += 1024) { + const float v = as_type(uint(x[i]) << 16); + if (v > best) { best = v; id = i; } + } + for (ushort o = 16; o > 0; o >>= 1) { + const float ov = simd_shuffle_xor(best, o); + const uint oi = simd_shuffle_xor(id, o); + if (ov > best || (ov == best && oi < id)) { best = ov; id = oi; } + } + threadgroup float bv[32]; + threadgroup uint bi[32]; + if (lane == 0) { bv[sg] = best; bi[sg] = id; } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + best = bv[lane]; id = bi[lane]; + for (ushort o = 16; o > 0; o >>= 1) { + const float ov = simd_shuffle_xor(best, o); + const uint oi = simd_shuffle_xor(id, o); + if (ov > best || (ov == best && oi < id)) { best = ov; id = oi; } + } + if (lane == 0) out[a.y + row] = id; + } +} diff --git a/zig/kernels/metal/hy4_flash/tensor_dispatch.metal b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal new file mode 100644 index 00000000000..8836b29ea61 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal @@ -0,0 +1,84 @@ +// Bit-preserving row and route layouts for the TensorOps dispatches. +#include +using namespace metal; + +kernel void tf_hy4_qkv_split( + const device ushort* input [[buffer(0)]], device ushort* q [[buffer(1)]], + device ushort* kv [[buffer(2)]], device ushort* gate [[buffer(3)]], + constant uint3& dims [[buffer(4)]], uint2 tid [[thread_position_in_grid]]) { + const uint col = tid.x, row = tid.y; + const uint qn = dims.x, kn = dims.y, gn = dims.z; + const ushort v = input[ulong(row) * (qn + kn + gn) + col]; + if (col < qn) q[ulong(row) * qn + col] = v; + else if (col < qn + kn) kv[ulong(row) * kn + col - qn] = v; + else gate[ulong(row) * gn + col - qn - kn] = v; +} + +// The router has already grouped picks by active expert. Write only their compact offsets and pair IDs. +kernel void tf_hy4_active_experts( + const device int* members [[buffer(0)]], const device int* active [[buffer(1)]], + device int* offsets [[buffer(2)]], device int* order [[buffer(3)]], + constant uint2& shape [[buffer(4)]], uint t [[thread_index_in_threadgroup]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + threadgroup uint counts[8]; + uint n = 0; + if (int(t) < active[0]) { + for (uint i = 0; i < shape.y && members[t * shape.y + i] >= 0; ++i) ++n; + } + const uint local = simd_prefix_exclusive_sum(n); + if (lane == 31) counts[sg] = local + n; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t >= shape.x) return; + uint base = local; + for (uint i = 0; i < sg; ++i) base += counts[i]; + offsets[t] = int(base); + for (uint i = 0; i < n; ++i) order[base + i] = members[t * shape.y + i]; +} + +// A prompt chunk's (row, pick) pairs grouped by expert for the gathers +kernel void tf_hy4_group_pairs( + const device int* pick [[buffer(0)]], device int* offsets [[buffer(1)]], device int* order [[buffer(2)]], + device int* ids [[buffer(3)]], constant uint3& a [[buffer(4)]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup atomic_uint counts[8][512]; // each block's count of an expert, then where its pairs start + threadgroup uint bits[64][16]; + threadgroup uint carry[32]; + const uint pairs = a.x, experts = a.y, topk = a.z, rows = pairs / topk, blocks = (rows + 63) / 64; + for (uint i = t; i < 8 * 512; i += 1024) atomic_store_explicit(&counts[i / 512][i % 512], 0u, memory_order_relaxed); + for (uint e = t; e < experts; e += 1024) ids[e] = int(e); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint p = t; p < pairs; p += 1024) atomic_fetch_add_explicit(&counts[(p / topk) / 64][pick[p]], 1u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + uint total = 0; + if (t < experts) for (uint b = 0; b < blocks; ++b) total += atomic_load_explicit(&counts[b][t], memory_order_relaxed); + const uint local = simd_prefix_exclusive_sum(total); + if (lane == 31) carry[sg] = local + total; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < experts) { + uint base = local; + for (uint i = 0; i < sg; ++i) base += carry[i]; + offsets[t] = int(base); + for (uint b = 0; b < blocks; ++b) { + const uint n = atomic_load_explicit(&counts[b][t], memory_order_relaxed); + atomic_store_explicit(&counts[b][t], base, memory_order_relaxed); + base += n; + } + } + for (uint b = 0; b < blocks; ++b) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < 64 * 16; i += 1024) bits[i / 16][i % 16] = 0u; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint first = b * 64, last = min(rows, first + 64); + for (uint p = first * topk + t; p < last * topk; p += 1024) { + const uint e = uint(pick[p]); + atomic_fetch_or_explicit((threadgroup atomic_uint *)&bits[p / topk - first][e / 32], 1u << (e % 32), memory_order_relaxed); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint p = first * topk + t; p < last * topk; p += 1024) { + const uint e = uint(pick[p]), r = p / topk - first; + uint rank = 0; + for (uint q = 0; q < r; ++q) rank += (bits[q][e / 32] >> (e % 32)) & 1u; + order[atomic_load_explicit(&counts[b][e], memory_order_relaxed) + rank] = int(p); + } + } +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 5f80a87466f..ef8cd4cab78 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -3,6 +3,20 @@ /// DeepSeek-V4.1's sources live beside their kernels: users say sources.dsv41.NAME. pub const dsv41 = @import("deepseek_v41/sources.zig"); +pub const hy4_flash_indexpool = @embedFile("hy4_flash/indexpool.metal"); +pub const hy4_flash_index_recall = @embedFile("hy4_flash/index_recall.metal"); +pub const hy4_flash_index_build = @embedFile("hy4_flash/index_build.metal"); +pub const hy4_flash_attention_sink = @embedFile("hy4_flash/attention_sink.metal"); +pub const hy4_flash_mla_project = @embedFile("hy4_flash/mla_project.metal"); +pub const hy4_flash_mla_attention = @embedFile("hy4_flash/mla_attention.metal"); +pub const hy4_flash_ihc = @embedFile("hy4_flash/ihc.metal"); +pub const hy4_flash_rows = @embedFile("hy4_flash/rows.metal"); +pub const hy4_flash_mla_nax = @embedFile("hy4_flash/mla_nax.metal"); +pub const hy4_flash_route_rows = @embedFile("hy4_flash/route_rows.metal"); +pub const hy4_flash_engram = @embedFile("hy4_flash/engram.metal"); +pub const hy4_flash_affine_experts = @embedFile("hy4_flash/affine_experts.metal"); +pub const hy4_flash_tensor_dispatch = @embedFile("hy4_flash/tensor_dispatch.metal"); + /// Nemotron's generated kernels (tools/zig/gen_nemotron_kernels.py). pub const nemotron = @import("nemotron/kernels.zig"); /// Nemotron's KV in pages of the core pool: twins of its seven K/V kernels, each library beside its original. @@ -108,6 +122,8 @@ pub const flashnext_rotary_prepare = @embedFile("prefill/fn_rotary_prepare.metal /// A source file of MLX-exact kernels: compiled as one library, its kernels found by name. pub const File = struct { name: []const u8, text: []const u8 }; +pub const elementwise = @embedFile("ops/elementwise.metal"); +pub const embed_norm = @embedFile("ops/embed_norm.metal"); /// Prompt-chunk kernels (tools/zig/prefill_*.py), bit-identical to MLX 0.32.3's prefill kernels. pub const prefill = [_]File{ @@ -119,8 +135,8 @@ pub const prefill = [_]File{ .{ .name = "qmm_nax", .text = @embedFile("prefill/qmm_nax.metal") }, .{ .name = "scan", .text = @embedFile("prefill/scan.metal") }, .{ .name = "sort", .text = @embedFile("prefill/sort.metal") }, - .{ .name = "embed_norm", .text = @embedFile("ops/embed_norm.metal") }, - .{ .name = "elementwise", .text = @embedFile("ops/elementwise.metal") }, + .{ .name = "embed_norm", .text = embed_norm }, + .{ .name = "elementwise", .text = elementwise }, .{ .name = "route", .text = @embedFile("ops/route.metal") }, .{ .name = "qmv", .text = @embedFile("ops/qmv.metal") }, }; diff --git a/zig/src/core/affine_mm.zig b/zig/src/core/affine_mm.zig index b633469e5a1..3630543d02b 100644 --- a/zig/src/core/affine_mm.zig +++ b/zig/src/core/affine_mm.zig @@ -5,11 +5,18 @@ const ks = @import("kernel_sources"); const frags = @import("frags.zig"); const bf16_round = @import("bf16_round"); -/// The gather GLU's SwiGLU: GLM's clipped bf16 form, or mlx-lm's compiled silu(g) * u on bf16 rows (LFM2). -pub const Glu = enum { clipped, plain }; +/// SwiGLU variants for clipped BF16 intermediates, directly rounded SiLU, and compiled MLX SiLU. +pub const Glu = enum { clipped, clipped_silu, plain }; /// The weights' bits (2-6 or 8) and group (32, 64 or 128), the output's type and the GLU epilogue. -pub const Format = struct { bits: u8 = 4, group: u16 = 64, out_f32: bool = false, glu: Glu = .clipped }; +pub const Format = struct { + bits: u8 = 4, + group: u16 = 64, + out_f32: bool = false, + glu: Glu = .clipped, + /// Scatter and GLU gathers read this batch's active-to-global expert map. + mapped_experts: bool = false, +}; /// The kernel source for `f` (nax.h inlined for this GPU). pub fn source(device: mtl.Device, a: std.mem.Allocator, f: Format) ![]u8 { @@ -17,10 +24,15 @@ pub fn source(device: mtl.Device, a: std.mem.Allocator, f: Format) ![]u8 { if (f.bits < 2 or f.bits > 8 or f.bits == 7 or !group_ok) return error.UnsupportedFormat; const body = try frags.source(device, a, ks.core_affine_mm); defer a.free(body); - const glu = if (f.glu == .plain) "#define TF_GLU_PLAIN 1\n" else ""; + const glu = switch (f.glu) { + .plain => "#define TF_GLU_PLAIN 1\n", + .clipped_silu => "#define TF_GLU_ROUND_SILU 1\n", + .clipped => "", + }; + const map = if (f.mapped_experts) "#define TF_AM_MAPPED_EXPERTS 1\n" else ""; const out = if (f.out_f32) "float" else "bfloat"; - const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}"; - return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, body }); + const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}{s}"; + return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, map, body }); } /// Entry points: row sums, dense matmul, tiled and scattering gathers, ordered expert gate/up into SwiGLU. @@ -97,6 +109,12 @@ pub fn gatherTo(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: a e.dispatchGroups(mtl.Size.of(q.n / 64, tiles, 1), mtl.Size.of(32, 2, 2)); } +/// Scatter gather with compact offsets and an explicit map to the checkpoint's resident expert rows. +pub fn gatherToMapped(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, offsets: anytype, y: anytype, dst: anytype, ids: anytype, rows: u32, experts: u32) void { + bind(e, 13, ids); + gatherTo(e, p, x, sums, q, offsets, y, dst, rows, experts); +} + /// act: SwiGLU(x W_gate^T, x W_up^T) clipped at `limit`, expert-sorted pairs (`offsets`); pair i: x row order[i]/topk. pub fn gatherGlu(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, gate: anytype, up: anytype, offsets: anytype, order: anytype, act: anytype, rows: u32, experts: u32, topk: u32, limit: f32) void { std.debug.assert(gate.n % 32 == 0 and gate.k % 64 == 0 and gate.n == up.n and gate.k == up.k); @@ -119,6 +137,12 @@ pub fn gatherGlu(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, gat e.dispatchGroups(mtl.Size.of(gate.n / 32, tiles, 1), mtl.Size.of(32, 2, 2)); } +/// The GLU gather over a compact active expert list, with no copy of expert weights. +pub fn gatherGluMapped(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, gate: anytype, up: anytype, offsets: anytype, order: anytype, act: anytype, ids: anytype, rows: u32, experts: u32, topk: u32, limit: f32) void { + bind(e, 13, ids); + gatherGlu(e, p, x, sums, gate, up, offsets, order, act, rows, experts, topk, limit); +} + /// The code at bit `at` of a little-endian bit stream (MLX's packing at every width). fn code(bytes: []const u8, at: usize, bits: usize) u32 { var v: u32 = 0; diff --git a/zig/src/core/lane_projection.zig b/zig/src/core/lane_projection.zig index 14e6029d370..b43bf48e4a5 100644 --- a/zig/src/core/lane_projection.zig +++ b/zig/src/core/lane_projection.zig @@ -2,7 +2,8 @@ const std = @import("std"); const mtl = @import("metal"); const ks = @import("kernel_sources"); -const frags = @import("frags.zig"); +/// nax.h inlined for this GPU, for family prompt kernels on the same fragments. +pub const frags = @import("frags.zig"); /// The tensor units' affine products by expert, beside the lane layouts (one module for their shared fragments). pub const affine_mm = @import("affine_mm.zig"); @@ -42,11 +43,13 @@ pub const Layout = struct { row_blocks: bool = false, /// Elements between output rows (default N): a member of a fused stack writes its columns of the fused rows. y_stride: ?usize = null, + /// Reg layouts: the kernel adds its rows' group sums with the sums pass's loop (no sums dispatch, same words). + inline_sums: bool = false, pub fn validate(l: Layout) !void { try l.format.validate(); if (l.cooperative and l.format.bits != 4) return error.UnsupportedCooperativeFormat; - if (l.reg and (l.cooperative or l.format.bits != 4 or l.format.group != 64 or !l.precompute_sums)) return error.UnsupportedRegFormat; + if (l.reg and (l.cooperative or (l.format.bits != 4 and l.format.bits != 8) or l.format.group != 64 or !l.precompute_sums)) return error.UnsupportedRegFormat; if ((l.cooperative or l.reg) and l.n % 32 != 0) return error.InvalidShape; if (l.y_stride) |s| if (s < l.n or s > std.math.maxInt(i32) / 16) return error.InvalidOutputStride; if (l.n == 0 or l.n % 16 != 0 or l.k == 0 or l.k % l.format.group != 0 or @@ -124,6 +127,7 @@ pub fn source(a: std.mem.Allocator, l: Layout) ![]u8 { try text.print(a, "#define TF_PRECOMPUTE_SUMS {d}\n", .{@intFromBool(l.precompute_sums)}); try text.print(a, "#define TF_ROW_BLOCKS {d}\n", .{@intFromBool(l.row_blocks and !l.reg and !l.cooperative and l.rows > 16)}); if (l.reg) try text.appendSlice(a, "#define TF_REG 1\n"); + if (l.inline_sums) try text.appendSlice(a, "#define TF_INLINE_SUMS 1\n"); if (l.y_stride) |s| try text.print(a, "#define TF_YS {d}\n", .{s}); try text.appendSlice(a, ks.core_lane_projection); return text.toOwnedSlice(a); @@ -173,6 +177,25 @@ pub fn regBlock(tiled: *const [256]u32, out: *[256]u32) void { pub const Order = struct { w: Ref, n: usize, k: usize }; +/// Rewrites host-visible tile-order 8-bit g64 words in place into the 8-bit reg layout (the 4-bit reg order, bytes). +pub fn regOrder8(words: []u32, n: usize, k: usize) !void { + if (n == 0 or n % 32 != 0 or k == 0 or k % 64 != 0 or words.len != n * k / 4) return error.InvalidShape; + var block: [512]u32 = undefined; + var at: usize = 0; + while (at < words.len) : (at += 512) { + const tiled = words[at..][0..512]; // [32 columns][16 words], word i: codes 4i..4i+3 + for (0..32) |lane| for (0..8) |w| { + const col = ((lane >> 1) & 3) + 4 * ((lane >> 4) & 1) + 8 * (w >> 1); + const first = 2 * (((lane >> 3) & 1) + 4 * (w & 1)) + (lane & 1); + const q = w >> 1; + const j = 2 * (w & 1); + block[(q * 32 + lane) * 4 + j] = tiled[col * 16 + first]; + block[(q * 32 + lane) * 4 + j + 1] = tiled[col * 16 + first + 4]; + }; + @memcpy(tiled, &block); + } +} + /// The reg_layout rewrite on the GPU: one library and queue for any number of runs. pub const RegOrder = struct { pipe: mtl.Pipeline, @@ -244,6 +267,8 @@ pub const Projection = struct { threads_per_slice: usize = 32, reg: bool = false, cooperative: bool = false, + /// The kernel adds its own group sums: encode runs no sums pass, and the sums buffer is only bound. + inline_sums: bool = false, /// Capacity is the reg or opted-in row count on tensor units, otherwise 16. max_rows: u32 = reg_rows, @@ -270,7 +295,7 @@ pub const Projection = struct { errdefer sums_pipe.?.deinit(); sums_buffer = try device.buffer(capacity * (l.k / l.format.group) * 4, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); } - return .{ .pipe = p, .external_sums = l.precompute_sums and l.format.bits == 8 and l.format.group == 64 and !l.cooperative, .n = l.n, .k = l.k, .group_count = l.k / l.format.group, .weight_bytes = l.weightWords() * 4, .metadata_bytes = l.metadataElements() * 2, .output_bytes = if (l.output == .f32) 4 else 2, .y_stride = l.y_stride orelse l.n, .tile_count = l.tiles(), .sk = l.sk, .sums_pipe = sums_pipe, .sums_buffer = sums_buffer, .threads_per_slice = if (l.cooperative) 64 else 32, .reg = l.reg, .cooperative = l.cooperative, .max_rows = @intCast(capacity) }; + return .{ .pipe = p, .external_sums = l.precompute_sums and l.format.bits == 8 and l.format.group == 64 and !l.cooperative, .n = l.n, .k = l.k, .group_count = l.k / l.format.group, .weight_bytes = l.weightWords() * 4, .metadata_bytes = l.metadataElements() * 2, .output_bytes = if (l.output == .f32) 4 else 2, .y_stride = l.y_stride orelse l.n, .tile_count = l.tiles(), .sk = l.sk, .sums_pipe = sums_pipe, .sums_buffer = sums_buffer, .threads_per_slice = if (l.cooperative) 64 else 32, .reg = l.reg, .cooperative = l.cooperative, .inline_sums = l.reg and l.inline_sums, .max_rows = @intCast(capacity) }; } pub fn deinit(p: Projection) void { @@ -300,7 +325,7 @@ pub const Projection = struct { try checkRef(w, p.weight_bytes, if (p.reg) 16 else 8); try checkRef(sb, p.metadata_bytes, 16); try checkRef(y, ((rows - 1) * p.y_stride + p.n) * p.output_bytes, p.output_bytes); - if (given == null) if (p.sums_pipe) |pipe| { + if (given == null and !p.inline_sums) if (p.sums_pipe) |pipe| { e.setPipeline(pipe); e.setBuffer(x.buf, x.off, 0); e.setValue(@as(i32, @intCast(rows)), 1); @@ -317,7 +342,7 @@ pub const Projection = struct { e.setBuffer(y.buf, y.off, 4); if (given) |g| e.setBuffer(g.ref.buf, g.ref.off, 5) else if (p.sums_buffer) |buffer| e.setBuffer(buffer, 0, 5); e.dispatchGroups(mtl.Size.of(p.tile_count, if (p.cooperative) 1 else blocks, 1), mtl.Size.of(p.threads_per_slice * p.sk, 1, 1)); - if (given == null and p.sums_buffer != null) e.barrier(); + if (given == null and p.sums_buffer != null and !p.inline_sums) e.barrier(); } }; diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 5d5755be77f..83ceaa32e28 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -21,6 +21,7 @@ pub const exl3_load = @import("exl3_load.zig"); pub const direct_io = @import("direct_io.zig"); pub const direct_gather = @import("direct_gather.zig"); pub const Checkpoint = checkpoint.Checkpoint; +pub const checkpoint_host = checkpoint; // the name the engine module (tensorfold.zig) also gives it pub const draft_depth = @import("draft_depth.zig"); pub const prompt_tail = @import("prompt_tail.zig"); pub const CopyIndex = @import("copy_index.zig").CopyIndex; diff --git a/zig/src/cuda/affine_experts.zig b/zig/src/cuda/affine_experts.zig new file mode 100644 index 00000000000..5bed7b2f121 --- /dev/null +++ b/zig/src/cuda/affine_experts.zig @@ -0,0 +1,76 @@ +//! Routed BF16 rows over rank-local 4- or 8-bit MLX affine tensors in their checkpoint layout. +const std = @import("std"); +const kernels = @import("kernels.zig"); +const Driver = @import("driver.zig").Driver; +const launch = @import("launch.zig"); +const Module = @import("module.zig").Module; +const Function = @import("module.zig").Function; +const Stream = @import("stream.zig").Stream; + +pub const Shape = extern struct { + width: u32, + inner: u32, + first: u32, + experts: u32, + pairs: u32, + rows: u32, + swiglu_limit: f32, + + pub fn check(self: Shape) !void { + if (self.width == 0 or self.width % 64 != 0 or self.width > 65536 or + self.inner == 0 or self.inner % 64 != 0 or self.inner > 65536 or + self.experts == 0 or @as(u64, self.first) + self.experts > std.math.maxInt(i32) or + self.pairs == 0 or self.pairs > std.math.maxInt(u16) or self.rows == 0 or + !std.math.isFinite(self.swiglu_limit) or self.swiglu_limit < 0) return error.BadAffineExpertShape; + } +}; + +pub const Weights = struct { words: u64, scales: u64, biases: u64 }; + +pub const Direction = enum { up, down }; +pub const Precision = enum { q4, q8 }; + +pub const Arguments = struct { + input: u64, + ids: u64, + src_rows: u64 = 0, + weights: Weights, + output: u64, +}; + +pub const Kernels = struct { + image: Module, + ops: [2][2]Function, + + pub fn load(driver: *const Driver) !Kernels { + if (!kernels.available) return error.BuiltWithoutKernels; + var image = try Module.load(driver, kernels.affine_experts); + errdefer image.unload(); + var ops: [2][2]Function = undefined; + inline for ([_]u8{ 4, 8 }, 0..) |bits, i| { + inline for ([_]Direction{ .up, .down }, 0..) |direction, j| { + const name = std.fmt.comptimePrint("tf_affine_experts_{s}_{d}", .{ @tagName(direction), bits }); + ops[i][j] = try image.function(name); + } + } + return .{ .image = image, .ops = ops }; + } + + pub fn deinit(self: *Kernels) void { + self.image.unload(); + self.* = undefined; + } + + /// Up returns pair rows in BF16. Down reads pair rows and returns FP32 expert contributions. + pub fn run(self: Kernels, s: Stream, precision: Precision, direction: Direction, b: Arguments, a: Shape) !void { + try a.check(); + if (direction == .up and b.src_rows == 0) return error.AffineExpertMissingRows; + const size = if (direction == .up) a.inner else a.width; + var args: launch.Args = .{}; + inline for (.{ b.input, b.ids, b.src_rows, b.weights.words, b.weights.scales, b.weights.biases, b.output, a }) |x| args.add(x); + try launch.launch(self.ops[@backingInt(precision)][@backingInt(direction)], .{ + .grid = .{ .x = (size + 3) / 4, .y = a.pairs }, + .block = .{ .x = 128 }, + }, s, &args); + } +}; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index c1f96bf4533..81571c73bb2 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -98,6 +98,13 @@ pub const modelopt_pack: []const u8 = if (available) &Blob("fatbin_modelopt_pack pub const glm_glue: []const u8 = if (available) &Blob("fatbin_glm_glue").bytes else &.{}; pub const glm_ops: []const u8 = if (available) &Blob("fatbin_glm_ops").bytes else &.{}; pub const glm_index: []const u8 = if (available) &Blob("fatbin_glm_index").bytes else &.{}; +pub const hy4_indexpool: []const u8 = if (available) &Blob("fatbin_hy4_indexpool").bytes else &.{}; +pub const affine_experts: []const u8 = if (available) &Blob("fatbin_affine_experts").bytes else &.{}; +pub const hy4_index_recall: []const u8 = if (available) &Blob("fatbin_hy4_index_recall").bytes else &.{}; +pub const hy4_attention_sink: []const u8 = if (available) &Blob("fatbin_hy4_attention_sink").bytes else &.{}; +pub const hy4_mla_project: []const u8 = if (available) &Blob("fatbin_hy4_mla_project").bytes else &.{}; +pub const hy4_mla_attention: []const u8 = if (available) &Blob("fatbin_hy4_mla_attention").bytes else &.{}; +pub const hy4_ihc: []const u8 = if (available) &Blob("fatbin_hy4_ihc").bytes else &.{}; pub const minimax_m3: []const u8 = if (available) &Blob("fatbin_minimax_m3").bytes else &.{}; pub const minimax_m3_attn: []const u8 = if (available) &Blob("fatbin_minimax_m3_attn").bytes else &.{}; pub const idol: []const u8 = if (available) &Blob("fatbin_idol").bytes else &.{}; diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index b6476817f2b..263fce038dd 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -55,6 +55,7 @@ pub const kda = @import("kda.zig"); pub const gdn_prep = @import("gdn_prep.zig"); pub const qk_rows = @import("qk_rows.zig"); pub const experts = @import("experts.zig"); +pub const affine_experts = @import("affine_experts.zig"); pub const experts32 = @import("experts32.zig"); pub const experts_waves = @import("experts_waves.zig"); pub const sample = @import("sample.zig"); diff --git a/zig/src/families/hy4_flash/affine_experts_metal.zig b/zig/src/families/hy4_flash/affine_experts_metal.zig new file mode 100644 index 00000000000..6c2ad772f8f --- /dev/null +++ b/zig/src/families/hy4_flash/affine_experts_metal.zig @@ -0,0 +1,72 @@ +//! Metal routed rows over the unmodified 4- or 8-bit affine checkpoint tensors. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); + +pub const Shape = extern struct { + width: u32, + inner: u32, + first: u32, + experts: u32, + pairs: u32, + rows: u32, + swiglu_limit: f32, + + pub fn check(self: Shape) !void { + if (self.width == 0 or self.width % 64 != 0 or self.width > 65536 or + self.inner == 0 or self.inner % 64 != 0 or self.inner > 65536 or + self.experts == 0 or @as(u64, self.first) + self.experts > std.math.maxInt(i32) or + self.pairs == 0 or self.pairs > std.math.maxInt(u16) or self.rows == 0 or + !std.math.isFinite(self.swiglu_limit) or self.swiglu_limit < 0) return error.BadAffineExpertShape; + } +}; + +pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; +pub const Weights = struct { words: Ref, scales: Ref, biases: Ref }; +pub const Direction = enum { up, down }; +pub const Precision = enum { q4, q8 }; + +pub const Arguments = struct { + input: Ref, + ids: Ref, + src_rows: ?Ref = null, + weights: Weights, + output: Ref, +}; + +pub const Kernels = struct { + ops: [4]mtl.Pipeline, + + pub fn load(device: mtl.Device) !Kernels { + const lib = try mtl.Library.fromSource(device, sources.hy4_flash_affine_experts, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var self: Kernels = undefined; + var loaded: usize = 0; + errdefer for (self.ops[0..loaded]) |pipe| pipe.deinit(); + const names = [_][]const u8{ + "tf_affine_experts_up_4", "tf_affine_experts_down_4", "tf_affine_experts_up_8", "tf_affine_experts_down_8", + }; + for (&self.ops, names) |*pipe, name| { + pipe.* = try mtl.Pipeline.init(device, lib, name, false); + loaded += 1; + } + return self; + } + + pub fn deinit(self: *Kernels) void { + for (self.ops) |pipe| pipe.deinit(); + self.* = undefined; + } + + /// Up returns BF16 activated pair rows. Down writes FP32 contributions for weighted combination. + pub fn run(self: Kernels, e: mtl.ComputeEncoder, precision: Precision, direction: Direction, b: Arguments, a: Shape) !void { + try a.check(); + if (direction == .up and b.src_rows == null) return error.AffineExpertMissingRows; + const size = if (direction == .up) a.inner else a.width; + e.setPipeline(self.ops[2 * @as(usize, @backingInt(precision)) + @backingInt(direction)]); + const args = [_]Ref{ b.input, b.ids, b.src_rows orelse b.ids, b.weights.words, b.weights.scales, b.weights.biases, b.output }; + for (args, 0..) |ref, i| e.setBuffer(ref.buffer, ref.offset, i); + e.setValue(a, args.len); + e.dispatchGroups(mtl.Size.of((size + 3) / 4, a.pairs, 1), mtl.Size.of(128, 1, 1)); + } +}; diff --git a/zig/src/families/hy4_flash/attention_slots.zig b/zig/src/families/hy4_flash/attention_slots.zig new file mode 100644 index 00000000000..9ac41aaad23 --- /dev/null +++ b/zig/src/families/hy4_flash/attention_slots.zig @@ -0,0 +1,66 @@ +//! Translate lane-local token positions to physical latent KV slots for Metal and CUDA. +const std = @import("std"); + +pub const Cache = struct { + /// Offset of each logical page's first row in the layer's contiguous latent arena. + page_bases: []const u32, + page_tokens: u32, + capacity: u32, + + pub fn slot(self: Cache, position: u32) !u32 { + if (self.page_tokens == 0) return error.BadHy4CachePage; + const page = position / self.page_tokens; + if (page >= self.page_bases.len) return error.BadHy4CachePage; + const row = @as(u64, self.page_bases[page]) + position % self.page_tokens; + if (row >= self.capacity or row > std.math.maxInt(i32)) return error.BadHy4CacheSlot; + return @intCast(row); + } + + /// Includes the query row itself. Length is the final per-row attention count. + pub fn sliding(self: Cache, visible_end: u32, width: u32, output: []u32) !u32 { + const count = @min(visible_end, width); + if (count > output.len) return error.ShortHy4KeyList; + const first = visible_end - count; + for (output[0..count], 0..) |*dst, i| dst.* = try self.slot(first + @as(u32, @intCast(i))); + return count; + } + + /// Compact the sparse selector's positions (also used for DFly2 reuse) in their original order. + pub fn retained(self: Cache, visible_end: u32, positions: []const i32, output: []u32) !u32 { + var count: u32 = 0; + for (positions) |position| { + if (position == -1) continue; + if (position < 0 or position >= visible_end) return error.NonCausalHy4Key; + if (count == output.len) return error.ShortHy4KeyList; + output[count] = try self.slot(@intCast(position)); + count += 1; + } + return count; + } +}; + +test "a 512-token window crosses a physically reordered cache page" { + const cache: Cache = .{ .page_bases = &.{ 512, 0 }, .page_tokens = 512, .capacity = 1024 }; + var keys: [513]u32 = @splat(0xffffffff); + for ([_]u32{ 511, 512, 513 }) |end| { + const count = try cache.sliding(end, 512, &keys); + try std.testing.expectEqual(@min(end, 512), count); + try std.testing.expectEqual(@as(u32, if (end > 512) 513 else 512), keys[0]); + try std.testing.expectEqual(@as(u32, if (end > 512) 0 else 512 + end - 1), keys[count - 1]); + try std.testing.expectEqual(@as(u32, 0xffffffff), keys[count]); + } +} + +test "draft attention compacts masked target keys and future draft rows" { + const dfly2 = @import("dfly2_inputs.zig"); + const cache: Cache = .{ .page_bases = &.{ 8, 12, 0, 4, 16 }, .page_tokens = 4, .capacity = 20 }; + const frame: dfly2.Frame = .{ .source_row = 2, .anchor = 13, .query_rows = 6 }; + var positions: [16]i32 = undefined; + try dfly2.reuseIndices(frame, &.{ 0, 8, 10, 12, 13, -1 }, 3, 2, &positions); + var keys: [16]u32 = @splat(0xffffffff); + const count = try cache.retained(frame.anchor + 3, &positions, &keys); + try std.testing.expectEqualSlices(u32, &.{ 8, 0, 2, 3, 4, 5, 6, 7 }, keys[0..count]); + try std.testing.expectEqual(@as(u32, 0xffffffff), keys[count]); + try std.testing.expectError(error.NonCausalHy4Key, cache.retained(frame.anchor + 2, &positions, &keys)); + try std.testing.expectError(error.BadHy4CachePage, cache.slot(20)); +} diff --git a/zig/src/families/hy4_flash/config.zig b/zig/src/families/hy4_flash/config.zig new file mode 100644 index 00000000000..8f026c79f15 --- /dev/null +++ b/zig/src/families/hy4_flash/config.zig @@ -0,0 +1,220 @@ +const std = @import("std"); +const rope = @import("rope.zig"); + +pub const Attention = enum { sliding_attention, deepseek_sparse_attention }; +pub const FeedForward = enum { dense, sparse }; + +pub const HeadShape = struct { + heads: u32, + non_rotary: u32, + rotary: u32, + value: u32, + + pub fn queryRows(self: HeadShape) u32 { + return self.heads * (self.non_rotary + self.rotary); + } + + pub fn kvRows(self: HeadShape) u32 { + return self.heads * (self.non_rotary + self.value); + } +}; + +pub const Text = struct { + hidden_size: u32, + intermediate_size: u32, + moe_intermediate_size: u32, + routed_expert_hidden_size: u32, + num_hidden_layers: u32, + vocab_size: u32, + max_position_embeddings: u32, + q_lora_rank: u32, + kv_lora_rank: u32, + num_attention_heads: u32, + qk_nope_head_dim: u32, + qk_rope_head_dim: u32, + v_head_dim: u32, + swa_num_attention_heads: u32, + swa_qk_nope_head_dim: u32, + swa_qk_rope_head_dim: u32, + swa_v_head_dim: u32, + sliding_window: u32, + compressed_indexer_compress_ratio: u32, + compressed_indexer_num_attention_heads: u32, + compressed_indexer_head_dim: u32, + compressed_indexer_group_topk: u32, + compressed_indexer_candidate_topk: u32, + n_routed_experts: u32, + num_experts_per_tok: u32, + n_shared_experts: u32, + n_group: u32, + topk_group: u32, + norm_topk_prob: bool, + swiglu_limit: f32, + routed_scaling_factor: f32, + enable_ihc: bool, + hc_mult: u32, + hc_eps: f32, + hc_magnitude: f32, + rms_norm_eps: f32, + rope_parameters: struct { + sliding_attention: rope.Config, + deepseek_sparse_attention: rope.Config, + }, + layer_types: []const Attention, + mlp_layer_types: []const FeedForward, + engram_layer_ids: []const u32, + engram_max_ngram_size: u32, + engram_n_head_per_ngram: u32, + engram_n_embed_per_ngram: u32, + engram_pad_id: u32, + engram_seed: u64, + engram_fp8_embedding: bool, + engram_lookup_table_size: u32 = 120818, + engram_layer_head_vocab_sizes: std.json.ArrayHashMap([]const []const u32), + + pub fn rotary(self: Text, attention: Attention) !rope.Parameters { + return switch (attention) { + .sliding_attention => self.rope_parameters.sliding_attention.parameters(self.swa_qk_rope_head_dim), + .deepseek_sparse_attention => self.rope_parameters.deepseek_sparse_attention.parameters(self.qk_rope_head_dim), + }; + } + + pub fn headShape(self: Text, layer: u32) HeadShape { + return switch (self.layer_types[layer]) { + .sliding_attention => .{ + .heads = self.swa_num_attention_heads, + .non_rotary = self.swa_qk_nope_head_dim, + .rotary = self.swa_qk_rope_head_dim, + .value = self.swa_v_head_dim, + }, + .deepseek_sparse_attention => .{ + .heads = self.num_attention_heads, + .non_rotary = self.qk_nope_head_dim, + .rotary = self.qk_rope_head_dim, + .value = self.v_head_dim, + }, + }; + } + + pub fn engramRows(self: Text, layer: u32) !usize { + var layer_name: [10]u8 = undefined; + const key = try std.fmt.bufPrint(&layer_name, "{d}", .{layer}); + const orders = self.engram_layer_head_vocab_sizes.map.get(key) orelse return error.BadEngramGeometry; + if (self.engram_max_ngram_size < 2 or orders.len != self.engram_max_ngram_size - 1) + return error.BadEngramGeometry; + var rows: usize = 0; + for (orders) |heads| { + if (heads.len != self.engram_n_head_per_ngram) return error.BadEngramGeometry; + for (heads) |prime| { + if (prime < 2) return error.BadEngramGeometry; + rows = try std.math.add(usize, rows, prime); + } + } + return rows; + } +}; + +pub const Model = struct { + model_type: []const u8, + quantization: ?struct { + bits: u8, + group_size: u16, + mode: []const u8 = "affine", + } = null, + text_config: Text, + vision_config: struct { + hidden_size: u32, + num_hidden_layers: u32, + num_attention_heads: u32, + out_hidden_size: u32, + patch_size: u32, + spatial_merge_size: u32, + }, + speculative_config: struct { + method: []const u8, + num_speculative_tokens: u32, + }, + dfly_num_hidden_layers: u32, + dfly_intermediate_size: ?u32 = null, + dfly_target_index_topk: u32, + dfly_target_index_layer: []const u32, + dfly_target_kv_layers: []const u32, + dfly_enable_hidden_correction: bool, + dfly_mask_token_id: u32, + dfly_mtp_fusion: []const u8, + + pub fn validate(self: Model) !void { + if (!std.mem.eql(u8, self.model_type, "hy_v4_flash")) return error.WrongFamily; + const t = self.text_config; + _ = try t.rotary(.sliding_attention); + _ = try t.rotary(.deepseek_sparse_attention); + if (t.layer_types.len == 0 or t.layer_types.len != t.num_hidden_layers or + t.mlp_layer_types.len != t.num_hidden_layers or t.hidden_size == 0 or + t.q_lora_rank == 0 or t.kv_lora_rank == 0 or t.sliding_window == 0 or + !t.enable_ihc or t.hc_mult == 0 or self.vision_config.out_hidden_size != t.hidden_size) + return error.BadArchitecture; + if (t.num_experts_per_tok == 0 or t.num_experts_per_tok > t.n_routed_experts or + t.routed_expert_hidden_size == 0 or t.moe_intermediate_size == 0 or t.n_group != 1 or t.topk_group != 1 or + !t.norm_topk_prob or !std.math.isFinite(t.swiglu_limit) or t.swiglu_limit <= 0 or + !std.math.isFinite(t.routed_scaling_factor) or t.routed_scaling_factor <= 0) + return error.BadExpertGeometry; + if (t.compressed_indexer_compress_ratio == 0 or t.compressed_indexer_group_topk == 0 or + @as(u64, t.compressed_indexer_compress_ratio) * t.compressed_indexer_group_topk != t.compressed_indexer_candidate_topk) + return error.BadSparseGeometry; + if (t.engram_max_ngram_size < 2 or t.engram_n_head_per_ngram == 0 or t.engram_n_embed_per_ngram == 0 or + t.engram_n_embed_per_ngram % t.engram_n_head_per_ngram != 0 or t.engram_pad_id >= t.vocab_size) + return error.BadEngramGeometry; + // Engram layer numbers are one-based, whereas DFly2 target layers are zero-based. + var previous: u32 = 0; + for (t.engram_layer_ids) |n| { + if (n <= previous or n > t.num_hidden_layers) return error.BadEngramGeometry; + _ = try t.engramRows(n); + previous = n; + } + if (!std.mem.eql(u8, self.speculative_config.method, "dfly") or + !std.mem.eql(u8, self.dfly_mtp_fusion, "slot0") or !self.dfly_enable_hidden_correction or + self.dfly_num_hidden_layers == 0 or self.speculative_config.num_speculative_tokens == 0 or + self.dfly_target_kv_layers.len != self.dfly_num_hidden_layers or + self.dfly_target_index_layer.len != self.dfly_num_hidden_layers or + self.dfly_target_index_topk != t.compressed_indexer_candidate_topk or self.dfly_mask_token_id >= t.vocab_size) + return error.BadDraftGeometry; + for (self.dfly_target_index_layer, self.dfly_target_kv_layers) |index, kv| { + if (index >= t.num_hidden_layers or kv >= t.num_hidden_layers or + t.layer_types[index] != .deepseek_sparse_attention) return error.BadDraftGeometry; + } + } +}; + +pub fn parse(allocator: std.mem.Allocator, bytes: []const u8) !std.json.Parsed(Model) { + const parsed = try std.json.parseFromSlice(Model, allocator, bytes, .{ + .ignore_unknown_fields = true, + .allocate = .alloc_always, + }); + errdefer parsed.deinit(); + try parsed.value.validate(); + return parsed; +} + +test "released Hy4-flash geometry" { + const parsed = try parse(std.testing.allocator, @embedFile("config_fixture.json")); + defer parsed.deinit(); + const m = parsed.value; + const t = m.text_config; + try std.testing.expectEqual(@as(u32, 8192), t.headShape(0).queryRows()); + try std.testing.expectEqual(@as(u32, 16384), t.headShape(2).queryRows()); + try std.testing.expectEqual(@as(u32, 14336), t.headShape(0).kvRows()); + try std.testing.expectEqual(@as(u32, 28672), t.headShape(2).kvRows()); + try std.testing.expectEqualSlices(u32, &.{ 2, 12, 22, 32 }, t.engram_layer_ids); + try std.testing.expectEqual(@as(usize, 165008942), try t.engramRows(32)); + try std.testing.expectEqualSlices(u32, &.{ 25, 29, 33, 37, 41 }, m.dfly_target_kv_layers); + try std.testing.expectEqual(@as(u32, 5), m.speculative_config.num_speculative_tokens); + try std.testing.expectEqual(@as(u32, 512), t.n_routed_experts); +} + +test "DFly2 fails closed on a sliding index source" { + const parsed = try parse(std.testing.allocator, @embedFile("config_fixture.json")); + defer parsed.deinit(); + var broken = parsed.value; + broken.dfly_target_index_layer = &.{ 2, 29, 33, 37, 41 }; + try std.testing.expectError(error.BadDraftGeometry, broken.validate()); +} diff --git a/zig/src/families/hy4_flash/config_fixture.json b/zig/src/families/hy4_flash/config_fixture.json new file mode 100644 index 00000000000..53b66f45537 --- /dev/null +++ b/zig/src/families/hy4_flash/config_fixture.json @@ -0,0 +1,494 @@ +{ + "architectures": [ + "HYV4FlashForConditionalGeneration" + ], + "dtype": "bfloat16", + "image_end_token_id": 120119, + "image_newline_token_id": 120121, + "image_start_token_id": 120118, + "image_token_id": 120120, + "model_type": "hy_v4_flash", + "processor_class": "HYV4FlashProcessor", + "spatial_merge_size": 2, + "text_config": { + "architectures": [ + "HYV4FlashForCausalLM" + ], + "attention_bias": false, + "attention_dropout": 0.0, + "bitwise_backward_align": true, + "bos_token_id": 120000, + "compressed_indexer_candidate_topk": 2048, + "compressed_indexer_compress_ratio": 4, + "compressed_indexer_group_topk": 512, + "compressed_indexer_head_dim": 128, + "compressed_indexer_key_pooling": "gated", + "compressed_indexer_num_attention_heads": 16, + "compressed_indexer_reuse_fine_indexer": false, + "compressed_indexer_skip_fine_select": true, + "compressed_indexer_stage2_query_block_size": 8192, + "compressed_indexer_teacher_pooling_type": "max", + "compressed_indexer_triton_pooling_min_groups": 1, + "compressed_indexer_use_triton_pooling": true, + "dsa_skip_attn_post_norm": false, + "enable_ihc": true, + "enable_lm_head_fp32": true, + "engram_embed_random_seed": 1234, + "engram_fp8_embedding": true, + "engram_isolate_fffd_namespace": false, + "engram_layer_head_vocab_sizes": { + "12": [ + [ + 10312277, + 10312283, + 10312301, + 10312343, + 10312373, + 10312397, + 10312409, + 10312453 + ], + [ + 10312457, + 10312483, + 10312507, + 10312513, + 10312531, + 10312543, + 10312567, + 10312571 + ] + ], + "2": [ + [ + 10312007, + 10312021, + 10312039, + 10312069, + 10312091, + 10312121, + 10312123, + 10312147 + ], + [ + 10312177, + 10312187, + 10312207, + 10312213, + 10312229, + 10312241, + 10312249, + 10312259 + ] + ], + "22": [ + [ + 10312613, + 10312619, + 10312633, + 10312657, + 10312681, + 10312699, + 10312723, + 10312747 + ], + [ + 10312759, + 10312789, + 10312811, + 10312823, + 10312867, + 10312873, + 10312889, + 10312903 + ] + ], + "32": [ + [ + 10312909, + 10312919, + 10312927, + 10312957, + 10312979, + 10313011, + 10313021, + 10313057 + ], + [ + 10313063, + 10313117, + 10313123, + 10313129, + 10313161, + 10313179, + 10313189, + 10313201 + ] + ] + }, + "engram_layer_ids": [ + 2, + 12, + 22, + 32 + ], + "engram_max_ngram_size": 3, + "engram_n_embed_per_ngram": 768, + "engram_n_head_per_ngram": 8, + "engram_pad_id": 120002, + "engram_seed": 0, + "engram_tokenizer_name_or_path": null, + "engram_vocab_map_path": null, + "engram_vocab_size": [ + 10312000, + 10312000 + ], + "eos_token_id": 120025, + "fast_op_fp32_linear_gemm": true, + "first_k_dense_replace": 1, + "full_nope": false, + "gate_groups": 1, + "gate_lora_op": "none", + "gate_lora_rank": null, + "gated_mla": true, + "gating_type": "elementwise", + "hc_eps": 1e-06, + "hc_magnitude": 2.0, + "hc_mult": 4, + "head_dim": 64, + "hidden_act": "silu", + "hidden_size": 3072, + "ihc_kernel_backend": "naive", + "index_head_dim": 128, + "index_n_heads": 16, + "index_topk": 2048, + "indexer_types": [ + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full", + "full" + ], + "initializer_range": 0.006, + "intermediate_size": 13824, + "kv_lora_rank": 512, + "layer_types": [ + "deepseek_sparse_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention", + "sliding_attention", + "sliding_attention", + "sliding_attention", + "deepseek_sparse_attention" + ], + "learnable_sink": true, + "learnable_sink_init": 0.0, + "max_position_embeddings": 1048576, + "mlp_layer_types": [ + "dense", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse", + "sparse" + ], + "model_type": "hy_v4_flash", + "moe_aux_loss_coeff": 0.0, + "moe_intermediate_size": 1536, + "moe_router_enable_expert_bias": true, + "moe_router_use_sigmoid": true, + "n_group": 1, + "n_routed_experts": 512, + "n_shared_experts": 1, + "norm_topk_prob": true, + "num_attention_heads": 32, + "num_experts_per_tok": 16, + "num_hidden_layers": 42, + "num_key_value_heads": 32, + "num_nextn_predict_layers": 0, + "o_groups": 1, + "o_lora_op": "none", + "o_lora_rank": null, + "output_router_logits": false, + "pad_token_id": 120002, + "q_lora_rank": 1024, + "qk_head_dim": 256, + "qk_nope_head_dim": 192, + "qk_norm": true, + "qk_rope_head_dim": 64, + "return_bos_score": true, + "return_max_logit": true, + "rms_norm_eps": 1e-05, + "rope_parameters": { + "sliding_attention": { + "mrope_interleaved": true, + "mrope_section": [ + 12, + 10, + 10 + ], + "rope_theta": 10000, + "rope_type": "default" + }, + "deepseek_sparse_attention": { + "mrope_interleaved": true, + "mrope_section": [ + 12, + 10, + 10 + ], + "rope_theta": 10000000, + "rope_type": "default" + } + }, + "routed_expert_hidden_size": 1536, + "routed_scaling_factor": 3.998, + "sandwich_norm": true, + "sliding_window": 512, + "swa_num_attention_heads": 64, + "swa_pattern": [ + 0, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 0 + ], + "swa_qk_head_dim": 256, + "swa_qk_nope_head_dim": 192, + "swa_qk_rope_head_dim": 64, + "swa_v_head_dim": 256, + "swiglu_limit": 10.0, + "tie_word_embeddings": false, + "topk_group": 1, + "use_cache": true, + "use_compressed_indexer": true, + "use_dsa": true, + "use_grouped_mm": false, + "use_mla": true, + "v_head_dim": 256, + "vocab_size": 120832, + "window_size": [ + 511, + 0 + ] + }, + "transformers_version": "5.23.0", + "video_end_token_id": 120123, + "video_start_token_id": 120122, + "video_token_id": 120124, + "vision_config": { + "add_patchemb_bias": true, + "anyres_vit_max_image_size": 2048, + "attention_backend": "hf_align_sdpa", + "attention_dropout": 0.0, + "bias_activation_fusion": true, + "cat_extra_token": 0, + "hidden_act": "gelu", + "hidden_dropout": 0.0, + "hidden_size": 1152, + "img_max_token_num": 4096, + "intermediate_size": 4304, + "interpolate_mode": "bilinear", + "learnable_mlp_pooling_size": 0, + "max_image_size": 2048, + "max_vit_seq_len": 16384, + "min_image_size": 512, + "model_type": "hy_v4_flash", + "num_attention_heads": 16, + "num_channels": 3, + "num_hidden_layers": 27, + "num_key_value_heads": 16, + "out_hidden_size": 3072, + "packed_seq_alignment": 128, + "patch_size": 16, + "perceive_post_norm": false, + "perceive_pre_norm": true, + "projector_type": "rmsnorm_mlp_adapter", + "remove_prenorm": true, + "resize_resolution": 2048, + "rms_norm_eps": 1e-05, + "rope_2d_percent": 1.0, + "rope_2d_theta": 10000.0, + "spatial_merge_size": 2, + "spatial_patch_size": 1, + "temporal_patch_size": 1, + "text_hidden_size": 3072, + "video_max_image_size": 768, + "video_min_image_size": 256, + "video_spatial_compression": false, + "video_temporal_compression": false, + "vision_full_attention": false + }, + "vision_start_token_id": 120118, + "speculative_config": { + "method": "dfly", + "model": "dfly", + "num_speculative_tokens": 5, + "draft_sample_method": "probabilistic" + }, + "dfly_mtp_fusion": "slot0", + "dfly_target_index_topk": 2048, + "dfly_context_local_window": null, + "dfly_enable_hidden_correction": true, + "dfly_num_hidden_layers": 5, + "dfly_mask_token_id": 120009, + "dfly_target_index_layer": [ + 25, + 29, + 33, + 37, + 41 + ], + "dfly_target_kv_layers": [ + 25, + 29, + 33, + 37, + 41 + ] +} diff --git a/zig/src/families/hy4_flash/cuda_dense.zig b/zig/src/families/hy4_flash/cuda_dense.zig new file mode 100644 index 00000000000..5e3c2c07761 --- /dev/null +++ b/zig/src/families/hy4_flash/cuda_dense.zig @@ -0,0 +1,266 @@ +//! The native CUDA attention and dense feed-forward passes for Hy4-flash. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const proj = @import("cuda_projection.zig"); +const ihc = @import("ihc.zig"); +const hc_gpu = @import("ihc_cuda.zig"); +const mla = @import("mla_cuda.zig"); +const shape_ = @import("mla_attention.zig"); +const dims = @import("mla_weights.zig"); +const model = @import("model_weights.zig"); +const rope = @import("rope.zig"); + +pub const Hyper = struct { + w: u64, + b: u64, + scale: u64, + shape: ihc.Shape, + + fn upload(a: *proj.Owned, w: ihc.Weights) !Hyper { + return .{ + .w = try a.upload(w.project.bytes), + .b = try a.upload(w.bias.bytes), + .scale = try a.upload(w.scale.bytes), + .shape = w.shape, + }; + } +}; + +pub const Attention = struct { + heads: u32, + position: rope.Parameters, + q_a: proj.Weight, + q_norm: u64, + q_b: proj.Weight, + kv_a: proj.Weight, + kv_norm: u64, + gate: proj.Weight, + output: proj.Weight, + output_norm: u64, + key: u64, + value: u64, + sinks: u64, + norm: u64, + merge: Hyper, + needs_reduction: bool, + + pub fn upload(k: *const Kernels, a: *proj.Owned, s: cuda.Stream, w: *const model.TargetLayer) !Attention { + const heads = w.attention.heads.count; + return .{ + .heads = heads, + .position = w.position, + .q_a = try k.project.pack(a, s, w.project_query), + .q_norm = try a.upload(w.norm_query.bytes), + .q_b = try k.project.pack(a, s, w.attention.query), + .kv_a = try k.project.pack(a, s, w.project_kv), + .kv_norm = try a.upload(w.norm_kv.bytes), + .gate = try k.project.pack(a, s, w.attention.gate), + .output = try k.project.pack(a, s, w.attention.output), + .output_norm = try a.upload(w.attention_output_norm.bytes), + .key = try a.upload(std.mem.sliceAsBytes(w.absorbed.key)), + .value = try a.upload(std.mem.sliceAsBytes(w.absorbed.value)), + .sinks = try a.upload(std.mem.sliceAsBytes(w.sinks[0..heads])), + .norm = try a.upload(w.attention_norm.bytes), + .merge = try Hyper.upload(a, w.attention_hc), + .needs_reduction = w.attention.owns_output, + }; + } +}; + +pub const Feed = struct { + gate: proj.Weight, + up: proj.Weight, + down: proj.Weight, + output_norm: u64, + input_norm: u64, + merge: Hyper, + + pub fn upload(k: *const Kernels, a: *proj.Owned, s: cuda.Stream, w: *const model.TargetLayer) !Feed { + if (w.feed != .dense) return error.Hy4DenseFeedRequired; + const f = w.feed.dense; + return .{ + .gate = try k.project.pack(a, s, f.projections.gate), + .up = try k.project.pack(a, s, f.projections.up), + .down = try k.project.pack(a, s, f.projections.down), + .output_norm = try a.upload(f.norm.bytes), + .input_norm = try a.upload(w.mlp_norm.bytes), + .merge = try Hyper.upload(a, w.mlp_hc), + }; + } +}; + +pub const Scratch = struct { + cap: shape_.Shape, + shape: shape_.Shape, + inner: u32, + collapsed: u64, + post: u64, + norm_input: u64, + normalized: u64, + q_low: u64, + q_norm: u64, + q: u64, + q_absorbed: u64, + kv: u64, + gate: u64, + values: u64, + latent: u64, + rotary: u64, + part: u64, + sums: u64, + branch: u64, + ffn_gate: u64, + ffn_up: u64, + act: u64, + + pub fn init(a: *proj.Owned, shape: shape_.Shape, hidden: u32, q_rank: u32, inner: u32) !Scratch { + try shape.check(); + const rows = shape.rows; + const heads = shape.heads; + if (rows > proj.max_rows or hidden == 0 or q_rank == 0 or inner == 0) return error.ShortHy4CudaScratch; + const max_width = @max(hidden, q_rank, inner, heads * dims.value_width); + return .{ + .cap = shape, + .shape = shape, + .inner = inner, + .collapsed = try bf16(a, rows, hidden), + .post = try a.alloc(@as(usize, rows) * ihc.streams * 4), + .norm_input = try bf16(a, rows, @max(hidden, q_rank)), + .normalized = try bf16(a, rows, hidden), + .q_low = try bf16(a, rows, q_rank), + .q_norm = try bf16(a, rows, q_rank), + .q = try bf16(a, rows, heads * dims.query_stride), + .q_absorbed = try bf16(a, rows, heads * dims.absorbed_stride), + .kv = try bf16(a, rows, dims.absorbed_stride), + .gate = try bf16(a, rows, heads * dims.value_width), + .values = try bf16(a, rows, heads * dims.value_width), + .latent = try bf16(a, rows, heads * dims.latent), + .rotary = try bf16(a, rows, dims.rope), + .part = try a.alloc(shape.scratchBytes()), + .sums = try a.alloc(@as(usize, rows) * max_width / 64 * 4), + .branch = try bf16(a, rows, hidden), + .ffn_gate = try bf16(a, rows, inner), + .ffn_up = try bf16(a, rows, inner), + .act = try bf16(a, rows, inner), + }; + } + + pub fn bind(self: *Scratch, rows: u32, heads: u32, keys: u32) !void { + if (rows > self.cap.rows or heads > self.cap.heads or keys > self.cap.key_stride) return error.ShortHy4CudaScratch; + self.shape = try shape_.Shape.init(rows, heads, keys); + } +}; + +fn bf16(a: *proj.Owned, rows: u32, width: u32) !u64 { + return a.alloc(@as(usize, rows) * width * @sizeOf(u16)); +} + +pub const Cache = struct { + positions: u64, + slots: u64, + retained: u64, + counts: u64, + data: u64, + capacity: u32, +}; + +pub const Reduce = struct { + ctx: *anyopaque, + /// Reduce this rank's output projection before applying the checkpoint's output norm. + call: *const fn (*anyopaque, cuda.Stream, u64, usize) anyerror!void, +}; + +pub const Kernels = struct { + project: proj.Kernels, + norm: cuda.norms.Norms, + merge: hc_gpu.Kernels, + mla_project: mla.Projections, + mla_attend: mla.Attention, + + pub fn load(ctx: *const cuda.Context) !Kernels { + var project = try proj.Kernels.load(ctx); + errdefer project.deinit(); + var norm = try cuda.norms.Norms.load(ctx.d); + errdefer norm.unload(); + var merge = try hc_gpu.Kernels.load(ctx.d); + errdefer merge.deinit(); + var m = try mla.Projections.load(ctx.d); + errdefer m.deinit(); + return .{ + .project = project, + .norm = norm, + .merge = merge, + .mla_project = m, + .mla_attend = try mla.Attention.load(ctx.d), + }; + } + + pub fn deinit(self: *Kernels) void { + self.mla_attend.deinit(); + self.mla_project.deinit(); + self.merge.deinit(); + self.norm.unload(); + self.project.deinit(); + } + + fn normal(self: *const Kernels, s: cuda.Stream, x: u64, w: u64, y: u64, f: *const Scratch, width: usize, eps: f32) !void { + try self.norm.addRmsTail(s, x, null, w, f.norm_input, y, null, f.shape.rows, width, eps, .{ .round = true }); + } + + fn collapse(self: *const Kernels, s: cuda.Stream, w: Hyper, norm: u64, f: *const Scratch, x: u64) !ihc.Shape { + var shape = w.shape; + shape.rows = f.shape.rows; + try self.merge.collapse(s, .{ .hidden = x, .projection = w.w, .bias = w.b, .scale = w.scale, .output = f.collapsed, .post = f.post }, shape); + try self.normal(s, f.collapsed, norm, f.normalized, f, shape.width, shape.eps); + return shape; + } + + pub fn attend(self: *const Kernels, s: cuda.Stream, w: *const Attention, f: *const Scratch, cache: Cache, reduction: ?Reduce, x: u64, out: u64) !void { + if (f.shape.heads != w.heads or w.needs_reduction != (reduction != null)) return error.BadHy4Rank; + const shape = try self.collapse(s, w.merge, w.norm, f, x); + const r = shape.rows; + try self.project.run(s, w.q_a, f.normalized, f.sums, f.q_low, r); + try self.project.run(s, w.kv_a, f.normalized, f.sums, f.kv, r); + try self.project.run(s, w.gate, f.normalized, f.sums, f.gate, r); + try self.normal(s, f.q_low, w.q_norm, f.q_norm, f, w.q_b.inputs(), shape.eps); + try self.project.run(s, w.q_b, f.q_norm, f.sums, f.q, r); + try mla.forward(self.mla_project, self.mla_attend, s, .{ + .query = f.q, + .key_weights = w.key, + .value_weights = w.value, + .value_logits = f.gate, + .positions = cache.positions, + .rotary_table = f.rotary, + .values = f.values, + .kv = .{ .projection = f.kv, .gain = w.kv_norm, .write_slots = cache.slots, .capacity = cache.capacity, .epsilon = shape.eps }, + .attention = .{ + .query = f.q_absorbed, + .cache = cache.data, + .slots = cache.retained, + .counts = cache.counts, + .sinks = w.sinks, + .scratch = f.part, + .scratch_bytes = f.cap.scratchBytes(), + .output = f.latent, + }, + }, f.shape, w.position); + try self.project.run(s, w.output, f.values, f.sums, f.branch, r); + if (reduction) |op| try op.call(op.ctx, s, f.branch, @as(usize, r) * shape.width); + try self.normal(s, f.branch, w.output_norm, f.normalized, f, shape.width, shape.eps); + try self.merge.add(s, .{ .residual = x, .branch = f.normalized, .post = f.post, .output = out }, shape); + } + + pub fn feed(self: *const Kernels, s: cuda.Stream, w: *const Feed, f: *const Scratch, x: u64, out: u64) !void { + const inner = w.down.inputs(); + if (inner > f.inner) return error.ShortHy4CudaScratch; + const shape = try self.collapse(s, w.merge, w.input_norm, f, x); + const r = shape.rows; + try self.project.run(s, w.gate, f.normalized, f.sums, f.ffn_gate, r); + try self.project.run(s, w.up, f.normalized, f.sums, f.ffn_up, r); + try self.project.act.swigluRound(s, f.ffn_gate, inner, f.ffn_up, inner, f.act, null, r, inner); + try self.project.run(s, w.down, f.act, f.sums, f.branch, r); + try self.normal(s, f.branch, w.output_norm, f.normalized, f, shape.width, shape.eps); + try self.merge.add(s, .{ .residual = x, .branch = f.normalized, .post = f.post, .output = out }, shape); + } +}; diff --git a/zig/src/families/hy4_flash/cuda_projection.zig b/zig/src/families/hy4_flash/cuda_projection.zig new file mode 100644 index 00000000000..b7cdd940ff7 --- /dev/null +++ b/zig/src/families/hy4_flash/cuda_projection.zig @@ -0,0 +1,130 @@ +//! Lossless device packing and row-stable CUDA projections for the two published affine widths. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); + +pub const max_rows = 16; + +pub const Owned = struct { + a: std.mem.Allocator, + driver: *const cuda.Driver, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + pub fn alloc(self: *Owned, bytes: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(self.driver, bytes); + errdefer b.free(); + try self.buffers.append(self.a, b); + return b.ptr; + } + + pub fn upload(self: *Owned, bytes: []const u8) !u64 { + var b = try cuda.DeviceBuffer.alloc(self.driver, bytes.len); + errdefer b.free(); + try b.upload(0, bytes); + try self.buffers.append(self.a, b); + return b.ptr; + } + + fn rollback(self: *Owned, start: usize) void { + for (self.buffers.items[start..]) |*b| b.free(); + self.buffers.shrinkRetainingCapacity(start); + } + + pub fn deinit(self: *Owned) void { + self.rollback(0); + self.buffers.deinit(self.a); + } +}; + +pub const Weight = union(enum) { + q4: cuda.qlinear.Affine4, + q8: cuda.qlinear.AffineN, + + pub fn inputs(self: Weight) usize { + return switch (self) { + inline else => |w| w.k, + }; + } +}; + +pub const Kernels = struct { + modules: [6]cuda.Module, + q4: cuda.qlinear.Affine4Kernels, + q8: cuda.qlinear.AffineNKernels, + act: cuda.act_rows.ActRows, + + pub fn load(ctx: *const cuda.Context) !Kernels { + const k = cuda.kernels; + if (!k.available) return error.BuiltWithoutKernels; + var out: Kernels = undefined; + var count: usize = 0; + errdefer for (out.modules[0..count]) |*m| m.unload(); + for (&out.modules, [_][]const u8{ k.qmm_group, k.qmm_prefill, k.lane_gemv, k.affine4_pack, k.affine8, k.affine_prefill }) |*slot, image| { + slot.* = try cuda.Module.load(ctx.d, image); + count += 1; + } + const sms = @as(usize, @intCast(try ctx.attribute(.multiprocessor_count))); + const gb10 = try ctx.capability() == 121; + const m = out.modules; + out.q4 = try cuda.qlinear.Affine4Kernels.resolve(ctx.d, m[0], m[1], m[2], m[3], sms, gb10); + errdefer out.q4.deinit(); + out.q8 = try cuda.qlinear.AffineNKernels.resolve(ctx.d, m[4], m[5], m[3], sms, gb10); + errdefer out.q8.deinit(); + out.act = try cuda.act_rows.ActRows.load(ctx.d); + return out; + } + + pub fn deinit(self: *Kernels) void { + self.act.unload(); + self.q8.deinit(); + self.q4.deinit(); + for (&self.modules) |*m| m.unload(); + } + + /// Adapt the storage layout without requantizing the checkpoint. + pub fn pack(self: *const Kernels, owner: *Owned, s: cuda.Stream, host: core.quant.mlx.Host) !Weight { + if (host.group != 64 or (host.bits != 4 and host.bits != 8)) return error.BadHy4ProjectionWidth; + const dims = try core.quant.mlx.geometry.shape(host.words, host.scales, host.biases, host.bits, host.group, false); + const n = host.words.shape[0]; + const k = host.scales.shape[1] * host.group; + if (dims.elements == 0 or n == 0 or k == 0) return error.BadHy4ProjectionWidth; + const start = owner.buffers.items.len; + errdefer owner.rollback(start); + var raw: Owned = .{ .a = owner.a, .driver = owner.driver }; + defer raw.deinit(); + const codes = try raw.upload(host.words.bytes); + const scales = try raw.upload(host.scales.bytes); + const zeros = try raw.upload(host.biases.bytes); + const size = cuda.qlinear.AffineN.layout(n, k, host.bits); + const w = try owner.alloc(size.words); + const scale = try owner.alloc(size.scales); + const bias = try owner.alloc(size.scales); + errdefer s.synchronize() catch {}; + const packed_: Weight = switch (host.bits) { + 4 => blk: { + const q: cuda.qlinear.Affine4 = .{ .w = w, .s = scale, .b = bias, .n = n, .k = k, .npad = size.npad }; + try self.q4.pack(s, codes, scales, zeros, q); + break :blk .{ .q4 = q }; + }, + 8 => blk: { + try self.q8.packWords(s, codes, 8, n, k, w); + try self.q8.packTable(s, scales, n, k, size.npad, scale); + try self.q8.packTable(s, zeros, n, k, size.npad, bias); + break :blk .{ .q8 = .{ .w = w, .s = scale, .b = bias, .n = n, .k = k, .npad = size.npad, .bits = 8 } }; + }, + else => unreachable, + }; + try s.synchronize(); + return packed_; + } + + pub fn run(self: *const Kernels, s: cuda.Stream, w: Weight, input: u64, sums: u64, output: u64, rows: usize) !void { + if (rows == 0 or rows > max_rows or sums == 0) return error.BadHy4ProjectionRows; + const width = w.inputs(); + try self.act.groupSums(s, input, width, sums, rows, width); + switch (w) { + .q4 => |q| try self.q4.decode(s, input, sums, q, output, rows), + .q8 => |q| try self.q8.decode(s, input, sums, q, output, rows), + } + } +}; diff --git a/zig/src/families/hy4_flash/dfly2_inputs.zig b/zig/src/families/hy4_flash/dfly2_inputs.zig new file mode 100644 index 00000000000..35fb148386a --- /dev/null +++ b/zig/src/families/hy4_flash/dfly2_inputs.zig @@ -0,0 +1,56 @@ +const std = @import("std"); + +pub const Frame = struct { + source_row: usize, + anchor: u32, + query_rows: u32, +}; + +/// The target row survives rejection; the first draft query uses the target's bonus token. +pub fn prepare(positions: []const u32, rejected: usize, bonus: ?u32, context: u32, mask_token: u32, block_tokens: []u32, block_positions: []u32) !?Frame { + if (block_tokens.len != block_positions.len or block_tokens.len < 2) return error.BadDraftBlock; + const token = bonus orelse return null; + if (rejected >= positions.len) return error.BadRejectionCount; + const source_row = positions.len - rejected - 1; + const anchor = std.math.add(u32, positions[source_row], 1) catch return error.BadDraftBlock; + const rows = std.math.cast(u32, block_tokens.len) orelse return error.BadDraftBlock; + if (anchor > context or rows > context - anchor) return null; + @memset(block_tokens, mask_token); + block_tokens[0] = token; + for (block_positions, 0..) |*position, i| position.* = anchor + @as(u32, @intCast(i)); + return .{ .source_row = source_row, .anchor = anchor, .query_rows = rows }; +} + +/// Use target sparse indices, then an optional local prefix and each query's causal draft prefix. +pub fn reuseIndices(frame: Frame, target: []const i32, local_window: u32, query: u32, out: []i32) !void { + const total = std.math.add(usize, target.len, local_window) catch return error.BadDraftBlock; + const size = std.math.add(usize, total, frame.query_rows) catch return error.BadDraftBlock; + if (query >= frame.query_rows or out.len < size or + @as(u64, frame.anchor) + query > std.math.maxInt(i32)) return error.BadDraftBlock; + const window_start = @as(i64, frame.anchor) - local_window; + @memset(out, -1); + for (out[0..target.len], target) |*entry, position| { + if (position >= 0 and position < window_start) entry.* = position; + } + for (out[target.len..total], 0..) |*entry, i| { + entry.* = @intCast(@max(-1, window_start + @as(i64, @intCast(i)))); + } + for (out[total .. total + query + 1], 0..) |*entry, i| entry.* = @intCast(frame.anchor + i); +} + +test "rejected target rows do not advance the DFly2 anchor" { + var tokens: [6]u32 = undefined; + var positions: [6]u32 = undefined; + const frame = (try prepare(&.{ 10, 11, 12, 13 }, 1, 42, 20, 120009, &tokens, &positions)).?; + try std.testing.expectEqual(@as(usize, 2), frame.source_row); + try std.testing.expectEqualSlices(u32, &.{ 42, 120009, 120009, 120009, 120009, 120009 }, &tokens); + try std.testing.expectEqualSlices(u32, &.{ 13, 14, 15, 16, 17, 18 }, &positions); + try std.testing.expectEqual(@as(?Frame, null), try prepare(&.{ 10, 11, 12, 13 }, 1, 42, 18, 120009, &tokens, &positions)); +} + +test "the DFly2 draft row uses neither duplicate local keys nor future query keys" { + const frame: Frame = .{ .source_row = 2, .anchor = 13, .query_rows = 6 }; + var out: [16]i32 = undefined; + try reuseIndices(frame, &.{ 0, 8, 10, 12, 13, -1 }, 3, 2, &out); + try std.testing.expectEqualSlices(i32, &.{ 0, 8, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1 }, &out); +} diff --git a/zig/src/families/hy4_flash/engram.zig b/zig/src/families/hy4_flash/engram.zig new file mode 100644 index 00000000000..25580878839 --- /dev/null +++ b/zig/src/families/hy4_flash/engram.zig @@ -0,0 +1,82 @@ +//! Engram row selection for Tencent's released Hy4-flash vocabulary map. +const std = @import("std"); +const config = @import("config.zig"); +const hashValues = @import("engram_hash_core").hashValues; + +pub const order = 3; +pub const heads = 8; +pub const columns = (order - 1) * heads; +const lookup_sha = "87c7b2e1c2fc227ba7fdec4dd7a867533072eb2b73a85cc54189174ccfaf5f3f"; + +pub const TokenMap = struct { + bytes: []const u8, + pad: u32, + + pub fn open(bytes: []const u8, text: config.Text) !TokenMap { + if (bytes.len != @as(usize, text.engram_lookup_table_size) * 4 or + text.engram_pad_id >= text.engram_lookup_table_size) return error.BadEngramMap; + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{}); + const hex = std.fmt.bytesToHex(digest, .lower); + if (!std.mem.eql(u8, &hex, lookup_sha)) return error.UnknownEngramVocabulary; + return .{ .bytes = bytes, .pad = text.engram_pad_id }; + } + + pub fn normalize(self: TokenMap, id: u32) u32 { + const slot = if (id < self.bytes.len / 4) id else self.pad; + return std.mem.readInt(u32, self.bytes[@as(usize, slot) * 4 ..][0..4], .little); + } +}; + +pub const Layer = struct { + multipliers: [order]u64, + primes: [columns]u32, + offsets: [columns]u32, + + pub fn open(text: config.Text, number: u32) !Layer { + if (text.engram_seed != 0 or text.engram_max_ngram_size != order or text.engram_n_head_per_ngram != heads) + return error.UnsupportedEngramHash; + // The reference PCG64 draws use the checked vocabulary's maximum ID plus one, which is 92620. + const multipliers: [order]u64 = switch (number) { + 2 => .{ 81853575799317, 39690085502883, 24229915018165 }, + 12 => .{ 19457948045719, 44729556510419, 84779352922315 }, + 22 => .{ 72974230057307, 21530602121221, 55998057243097 }, + 32 => .{ 29128509562787, 16745155128523, 22474588302733 }, + else => return error.UnknownEngramLayer, + }; + _ = try text.engramRows(number); + var key_storage: [10]u8 = undefined; + const key = try std.fmt.bufPrint(&key_storage, "{d}", .{number}); + const groups = text.engram_layer_head_vocab_sizes.map.get(key) orelse return error.UnknownEngramLayer; + var result: Layer = .{ .multipliers = multipliers, .primes = undefined, .offsets = undefined }; + var row: u32 = 0; + for (groups, 0..) |group, n| for (group, 0..) |prime, head| { + const col = n * heads + head; + result.primes[col] = prime; + result.offsets[col] = row; + row = try std.math.add(u32, row, prime); + }; + return result; + } + + pub fn hash(self: Layer, map: TokenMap, tokens: [order]u32) [columns]u32 { + var normalized: [order]u32 = undefined; + for (tokens, &normalized) |token, *value| value.* = map.normalize(token); + return self.hashNormalized(normalized); + } + + pub fn hashNormalized(self: Layer, normalized: [order]u32) [columns]u32 { + var rows: [columns]u32 = undefined; + hashValues(&normalized, &self.multipliers, &self.primes, &self.offsets, heads, &rows); + return rows; + } +}; + +test "the native Engram hash returns the upstream rows for a released token window" { + const parsed = try config.parse(std.testing.allocator, @embedFile("config_fixture.json")); + defer parsed.deinit(); + const layer = try Layer.open(parsed.value.text_config, 2); + const rows = layer.hashNormalized(.{ 1, 0, 91804 }); + const expected = [_]u32{ 9395452, 11699939, 23502176, 32861672, 43851032, 53212976, 68274127, 73702352, 91770608, 93761842, 110295210, 116456011, 133373173, 137621161, 154112274, 155288835 }; + try std.testing.expectEqualSlices(u32, &expected, &rows); +} diff --git a/zig/src/families/hy4_flash/engram_rows.zig b/zig/src/families/hy4_flash/engram_rows.zig new file mode 100644 index 00000000000..1aa9bf0f31e --- /dev/null +++ b/zig/src/families/hy4_flash/engram_rows.zig @@ -0,0 +1,93 @@ +//! Gather Hy4-flash's selected affine Engram rows from the mapped checkpoint. +const std = @import("std"); +const core = @import("core"); +const engram = @import("engram.zig"); +const loader = @import("loader.zig"); + +const group = 32; + +/// Borrows the loader's checkpoint mapping. The large embedding table can stay in file-backed memory. +fn willNeed(t: core.checkpoint_host.Tensor, spans: []const core.quant.Span) void { + const os = @import("builtin").os.tag; + if (os != .macos and os != .linux) return; + if (t.shape[0] == 0 or t.bytes.len == 0) return; + const row = t.bytes.len / t.shape[0]; + const page = std.heap.pageSize(); + for (spans) |span| { + const lo = std.mem.alignBackward(usize, @intFromPtr(t.bytes.ptr) + span.from * row, page); + const hi = std.mem.alignForward(usize, @intFromPtr(t.bytes.ptr) + span.to * row, page); + _ = std.c.madvise(@ptrFromInt(lo), hi - lo, std.c.MADV.WILLNEED); + } +} + +pub const Table = struct { + map: engram.TokenMap, + hash: engram.Layer, + affine: core.quant.mlx.Host, + width: usize, + + pub fn open(model: *loader.Loaded, layer_number: u32) !Table { + const text = model.config.value.text_config; + if (std.mem.indexOfScalar(u32, text.engram_layer_ids, layer_number) == null) return error.UnknownEngramLayer; + const hash = try engram.Layer.open(text, layer_number); + const rows = try text.engramRows(layer_number); + const width = text.engram_n_embed_per_ngram / engram.heads; + if (width == 0 or width % group != 0) return error.BadEngramGeometry; + + var buffer: [160]u8 = undefined; + var name = try std.fmt.bufPrint(&buffer, "model.layers.{d}.engram_layer.lookup_table", .{layer_number - 1}); + const map = try engram.TokenMap.open((try model.checkpoint.expect(name, .i32, &.{text.engram_lookup_table_size})).bytes, text); + const prefix = "model.layers.{d}.engram_layer.multi_head_embedding.embedding"; + name = try std.fmt.bufPrint(&buffer, prefix ++ ".weight", .{layer_number - 1}); + const words = try model.checkpoint.expect(name, .u32, &.{ rows, @as(usize, width) * model.bits / 32 }); + try model.checkpoint.adviseRandom(name); + name = try std.fmt.bufPrint(&buffer, prefix ++ ".scales", .{layer_number - 1}); + const scales = try model.checkpoint.expect(name, .bf16, &.{ rows, width / group }); + try model.checkpoint.adviseRandom(name); + name = try std.fmt.bufPrint(&buffer, prefix ++ ".biases", .{layer_number - 1}); + const biases = try model.checkpoint.expect(name, .bf16, &.{ rows, width / group }); + try model.checkpoint.adviseRandom(name); + return .{ + .map = map, + .hash = hash, + .affine = .{ .words = words, .scales = scales, .biases = biases, .bits = model.bits, .group = group }, + .width = width, + }; + } + + /// The table rows a token window reads, one a column (the gather's spans). + pub fn windowRows(self: Table, window: [engram.order]u32) [engram.columns]u32 { + return self.hash.hash(self.map, window); + } + + pub fn elementsPerToken(self: Table) usize { + return engram.columns * self.width; + } + + /// Each window is current token first, then older tokens, padded by the caller for a new stream. + pub fn gather(self: Table, a: std.mem.Allocator, windows: []const [engram.order]u32, output: []u16) !void { + const cells = try std.math.mul(usize, windows.len, self.elementsPerToken()); + if (output.len != cells) return error.BadEngramOutput; + if (windows.len == 0) return; + const spans = try a.alloc(core.quant.Span, windows.len * engram.columns); + defer a.free(spans); + for (windows, 0..) |window, token| { + for (self.hash.hash(self.map, window), 0..) |row, head| { + const index: usize = row; + spans[token * engram.columns + head] = .{ .from = index, .to = index + 1 }; + } + } + + // Ask for every row's pages at once (asynchronous read-ahead) + for ([_]core.checkpoint_host.Tensor{ self.affine.words, self.affine.scales, self.affine.biases }) |t| willNeed(t, spans); + const words = try core.quant.slice.takeRows(a, self.affine.words, spans); + defer a.free(words.bytes); + const scales = try core.quant.slice.takeRows(a, self.affine.scales, spans); + defer a.free(scales.bytes); + const biases = try core.quant.slice.takeRows(a, self.affine.biases, spans); + defer a.free(biases.bytes); + const values = try core.quant.mlx.dequant(a, words, scales, biases, group); + defer a.free(values); + for (output, values) |*word, v| word.* = core.quant.convert.bf16(v); + } +}; diff --git a/zig/src/families/hy4_flash/forward.zig b/zig/src/families/hy4_flash/forward.zig new file mode 100644 index 00000000000..6163ad360dd --- /dev/null +++ b/zig/src/families/hy4_flash/forward.zig @@ -0,0 +1,136 @@ +//! Pack lane requests into the buffers used by the native target and DFly2 graph. +const std = @import("std"); +const slots = @import("attention_slots.zig"); +const groups = @import("index_groups.zig"); + +pub const Query = struct { + token: u32, + coordinates: [3]i32, + media: bool = false, +}; + +pub const Lane = struct { + /// Reused or freshly prefetched prefix. Speculative rows are supplied separately. + prefix: []const u32, + queries: []const Query, + cache: slots.Cache, +}; + +pub const Rows = struct { + ids: []u32, + coordinates: [][3]i32, + windows: [][3]u32, + media: []u32, + writes: []u32, + + /// Metadata is identical for a lane in a solo batch or one that shares the forward. + pub fn stage(self: Rows, lanes: []const Lane, pad: u32) !usize { + var row: usize = 0; + for (lanes) |lane| { + for (lane.queries, 0..) |q, i| { + if (row >= self.ids.len or row >= self.coordinates.len or row >= self.windows.len or + row >= self.media.len or row >= self.writes.len) return error.ShortHy4ForwardRows; + const position = try std.math.add(usize, lane.prefix.len, i); + const pos = std.math.cast(u32, position) orelse return error.Hy4PositionTooLarge; + self.ids[row] = q.token; + self.coordinates[row] = q.coordinates; + self.windows[row][0] = q.token; + for (1..3) |lag| { + self.windows[row][lag] = if (lag <= i) + lane.queries[i - lag].token + else if (lag <= position) + lane.prefix[position - lag] + else + pad; + } + self.media[row] = @intFromBool(q.media); + self.writes[row] = try lane.cache.slot(pos); + row += 1; + } + } + return row; + } +}; + +pub const Attention = union(enum) { + sliding: u32, + sparse: struct { + group_budget: u32, + /// Selected logical token indices for rows beyond the all-keys frontier. + retained: []const []const i32 = &.{}, + }, +}; + +pub const Keys = struct { + slots: []u32, + counts: []u32, + stride: u32, + + pub fn stage(self: Keys, lanes: []const Lane, mode: Attention) !usize { + if (self.stride == 0) return error.ShortHy4KeyList; + var row: usize = 0; + for (lanes) |lane| { + for (0..lane.queries.len) |i| { + if (row >= self.counts.len or row >= self.slots.len / self.stride) return error.ShortHy4KeyList; + const buffer = self.slots[row * self.stride ..][0..self.stride]; + const pos = try std.math.add(usize, lane.prefix.len, i); + const end = std.math.cast(u32, try std.math.add(usize, pos, 1)) orelse return error.Hy4PositionTooLarge; + self.counts[row] = switch (mode) { + .sliding => |window| try lane.cache.sliding(end, window, buffer), + .sparse => |s| blk: { + const f = try groups.frontier(pos, s.group_budget); + if (f.groups_to_recall == f.indexed_groups) break :blk try lane.cache.sliding(end, end, buffer); + if (row >= s.retained.len) return error.Hy4IndexRowsRequired; + const n = try lane.cache.retained(end, s.retained[row], buffer); + const expected = f.groups_to_recall * groups.slots + f.visible_end - f.current_group_start; + if (n != expected) return error.BadHy4RetainedCount; + break :blk n; + }, + }; + row += 1; + } + } + return row; + } +}; + +test "sharing a target pass preserves tokenizer history and physical cache isolation" { + const t = std.testing; + const one: Lane = .{ + .prefix = &.{ 7, 8, 9 }, + .queries = &.{ + .{ .token = 20, .coordinates = .{ 3, 7, 10 }, .media = true }, + .{ .token = 21, .coordinates = .{ 4, 4, 4 } }, + }, + .cache = .{ .page_bases = &.{ 16, 32 }, .page_tokens = 4, .capacity = 64 }, + }; + const two: Lane = .{ + .prefix = &.{11}, + .queries = &.{.{ .token = 22, .coordinates = .{ 1, 1, 1 } }}, + .cache = .{ .page_bases = &.{48}, .page_tokens = 4, .capacity = 64 }, + }; + var ids: [3]u32 = undefined; + var coords: [3][3]i32 = undefined; + var windows: [3][3]u32 = undefined; + var media: [3]u32 = undefined; + var writes: [3]u32 = undefined; + const rows: Rows = .{ .ids = &ids, .coordinates = &coords, .windows = &windows, .media = &media, .writes = &writes }; + try t.expectEqual(@as(usize, 3), try rows.stage(&.{ two, one }, 2)); + try t.expectEqualSlices(u32, &.{ 22, 20, 21 }, &ids); + try t.expectEqualSlices(u32, &.{ 49, 19, 32 }, &writes); + try t.expectEqualSlices(u32, &.{ 21, 20, 9 }, &windows[2]); + try t.expectEqualSlices(u32, &.{ 0, 1, 0 }, &media); + try t.expectEqualSlices(i32, &.{ 3, 7, 10 }, &coords[1]); + + var keys: [3 * 4]u32 = undefined; + var counts: [3]u32 = undefined; + const k: Keys = .{ .slots = &keys, .counts = &counts, .stride = 4 }; + try t.expectEqual(@as(usize, 3), try k.stage(&.{ two, one }, .{ .sliding = 4 })); + try t.expectEqualSlices(u32, &.{ 17, 18, 19, 32 }, keys[8..]); + try t.expectEqualSlices(u32, &.{ 2, 4, 4 }, &counts); + + try t.expectEqual(@as(usize, 2), try rows.stage(&.{one}, 2)); + try t.expectEqualSlices(u32, &.{ 21, 20, 9 }, &windows[1]); + try t.expectEqualSlices(u32, &.{ 19, 32 }, writes[0..2]); + try t.expectError(error.Hy4IndexRowsRequired, k.stage(&.{one}, .{ .sparse = .{ .group_budget = 1 } })); +} diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig new file mode 100644 index 00000000000..c5e1b265d1f --- /dev/null +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -0,0 +1,56 @@ +const std = @import("std"); +const core = @import("core"); +const engram = @import("engram.zig"); +const engram_rows = @import("engram_rows.zig"); + +test { + _ = @import("config.zig"); + _ = @import("attention_slots.zig"); + _ = @import("mla_attention.zig"); + _ = @import("index_groups.zig"); + _ = @import("rope.zig"); + _ = @import("rank_weights.zig"); + _ = @import("index_recall.zig"); + _ = @import("forward.zig"); +} + +fn tensor(dtype: core.checkpoint_host.DType, rows: usize, width: usize, bytes: []const u8) core.checkpoint_host.Tensor { + var result: core.checkpoint_host.Tensor = .{ .dtype = dtype, .rank = 2, .shape = @splat(0), .bytes = bytes }; + result.shape[0..2].* = .{ rows, width }; + return result; +} + +test "Engram gathers the selected affine rows in token and head order" { + const n = engram.columns * 2; + var words: [n][4]u32 = undefined; + var offsets: [engram.columns]u32 = undefined; + for (&words, 0..) |*row, i| row.* = @splat(if (i % 2 == 0) 0x11111111 else 0xeeeeeeee); + for (&offsets, 0..) |*offset, i| offset.* = @intCast(i * 2); + const scales: [n]u16 = @splat(0x3f80); // BF16 1.0 + const biases: [n]u16 = @splat(0xbf80); // BF16 -1.0 + const lookup = [2]u32{ 0, 1 }; + const table: engram_rows.Table = .{ + .map = .{ .bytes = std.mem.asBytes(&lookup), .pad = 0 }, + .hash = .{ .multipliers = .{ 3, 5, 7 }, .primes = @splat(2), .offsets = offsets }, + .affine = .{ + .words = tensor(.u32, n, 4, std.mem.asBytes(&words)), + .scales = tensor(.bf16, n, 1, std.mem.asBytes(&scales)), + .biases = tensor(.bf16, n, 1, std.mem.asBytes(&biases)), + .bits = 4, + .group = 32, + }, + .width = 32, + }; + const a = std.testing.allocator; + const window0 = [3]u32{ 1, 0, 1 }; + const window1 = [3]u32{ 0xffffffff, 0, 1 }; + var out: [2 * engram.columns * 32]u16 = undefined; + try table.gather(a, &.{ window0, window1 }, &out); + for (out, 0..) |word, i| { + const head = (i / 32) % engram.columns; + const from_first = i / 32 < engram.columns; + const on = from_first == (head < engram.heads); + try std.testing.expectEqual(@as(u16, if (on) 0x4150 else 0), word); // BF16 13.0 or 0.0 + } + try std.testing.expectError(error.BadEngramOutput, table.gather(a, &.{window0}, out[1..])); +} diff --git a/zig/src/families/hy4_flash/ihc.zig b/zig/src/families/hy4_flash/ihc.zig new file mode 100644 index 00000000000..70e66a8dc2b --- /dev/null +++ b/zig/src/families/hy4_flash/ihc.zig @@ -0,0 +1,63 @@ +//! FP32 weights and parameters for Hy4-flash's independent hyper-connections. +const std = @import("std"); +const core = @import("core"); +const loader = @import("loader.zig"); + +pub const streams = 4; +pub const Which = union(enum) { attention: u32, feed_forward: u32, head }; + +pub const Shape = extern struct { + rows: u32, + width: u32, + gates: u32, + eps: f32, + gate_eps: f32, + post_magnitude: f32, + + pub fn check(self: Shape) !void { + if (self.rows == 0 or self.rows > std.math.maxInt(u16) or self.width == 0 or self.width > 8192 or + (self.gates != streams and self.gates != 2 * streams) or !std.math.isFinite(self.eps) or self.eps <= 0 or + !std.math.isFinite(self.gate_eps) or self.gate_eps < 0 or + !std.math.isFinite(self.post_magnitude) or self.post_magnitude < 0) return error.BadHy4IhcShape; + } +}; + +pub const Weights = struct { + project: core.checkpoint_host.Tensor, + bias: core.checkpoint_host.Tensor, + scale: core.checkpoint_host.Tensor, + shape: Shape, + + pub fn read(model: *loader.Loaded, which: Which, rows: u32) !Weights { + const config = model.config.value.text_config; + if (config.hc_mult != streams) return error.BadHy4IhcShape; + var prefix: [120]u8 = undefined; + const base = switch (which) { + .attention => |layer| try blockPrefix(model, &prefix, layer, "hc_attn_layer"), + .feed_forward => |layer| try blockPrefix(model, &prefix, layer, "hc_mlp_layer"), + .head => "model.hc_head.hc_head_", + }; + const gates: u32 = if (which == .head) streams else 2 * streams; + const shape: Shape = .{ + .rows = rows, + .width = config.hidden_size, + .gates = gates, + .eps = config.rms_norm_eps, + .gate_eps = config.hc_eps, + .post_magnitude = config.hc_magnitude, + }; + try shape.check(); + var name: [128]u8 = undefined; + return .{ + .project = try model.checkpoint.expect(try std.fmt.bufPrint(&name, "{s}fn", .{base}), .f32, &.{ gates, streams * shape.width }), + .bias = try model.checkpoint.expect(try std.fmt.bufPrint(&name, "{s}base", .{base}), .f32, &.{gates}), + .scale = try model.checkpoint.expect(try std.fmt.bufPrint(&name, "{s}scale", .{base}), .f32, &.{gates / streams}), + .shape = shape, + }; + } +}; + +fn blockPrefix(model: *const loader.Loaded, buffer: []u8, layer: u32, name: []const u8) ![]const u8 { + if (layer >= model.config.value.text_config.num_hidden_layers) return error.BadHy4IhcLayer; + return std.fmt.bufPrint(buffer, "model.layers.{d}.{s}.hc_pre.hc_", .{ layer, name }); +} diff --git a/zig/src/families/hy4_flash/ihc_cuda.zig b/zig/src/families/hy4_flash/ihc_cuda.zig new file mode 100644 index 00000000000..67d65428a0a --- /dev/null +++ b/zig/src/families/hy4_flash/ihc_cuda.zig @@ -0,0 +1,43 @@ +//! Native CUDA launches for Hy4-flash's independent hyper-connections. +const cuda = @import("cuda"); +const ihc = @import("ihc.zig"); + +pub const Collapse = struct { hidden: u64, projection: u64, bias: u64, scale: u64, output: u64, post: u64 = 0 }; +pub const Add = struct { residual: u64, branch: u64, post: u64, output: u64 }; +pub const Kernels = struct { + image: cuda.Module, + pre: cuda.Function, + mix: cuda.Function, + + pub fn load(driver: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var image = try cuda.Module.load(driver, cuda.kernels.hy4_ihc); + errdefer image.unload(); + return .{ .image = image, .pre = try image.function("tf_hy4_ihc_collapse"), .mix = try image.function("tf_hy4_ihc_add") }; + } + + pub fn deinit(self: *Kernels) void { + self.image.unload(); + self.* = undefined; + } + + pub fn collapse(self: Kernels, s: cuda.Stream, b: Collapse, shape: ihc.Shape) !void { + try shape.check(); + if (shape.gates != ihc.streams and b.post == 0) return error.MissingHy4PostGates; + var args: cuda.Args = .{}; + inline for (.{ b.hidden, b.projection, b.bias, b.scale, b.output, b.post, shape }) |x| args.add(x); + try cuda.launch.launch(self.pre, .{ .grid = .{ .x = shape.rows }, .block = .{ .x = 256 } }, s, &args); + } + + pub fn add(self: Kernels, s: cuda.Stream, b: Add, shape: ihc.Shape) !void { + try shape.check(); + if (shape.gates != 2 * ihc.streams or b.post == 0) return error.MissingHy4PostGates; + var args: cuda.Args = .{}; + inline for (.{ b.residual, b.branch, b.post, b.output, shape }) |x| args.add(x); + const cols = (ihc.streams * shape.width + 255) / 256; + try cuda.launch.launch(self.mix, .{ + .grid = .{ .x = cols, .y = shape.rows }, + .block = .{ .x = 256 }, + }, s, &args); + } +}; diff --git a/zig/src/families/hy4_flash/ihc_metal.zig b/zig/src/families/hy4_flash/ihc_metal.zig new file mode 100644 index 00000000000..f9c6a2e3fd7 --- /dev/null +++ b/zig/src/families/hy4_flash/ihc_metal.zig @@ -0,0 +1,156 @@ +//! Native Metal launches for Hy4-flash's independent hyper-connections. +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const ihc = @import("ihc.zig"); + +pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; +/// `partials` (72 floats a row) selects the two-launch collapse that spreads a row over eight threadgroups. +pub const Collapse = struct { hidden: Ref, projection: Ref, bias: Ref, scale: Ref, output: Ref, post: ?Ref = null, partials: ?Ref = null }; +/// The seam partials a row: 19 sums (8 gate logits, the sum of squares, 10 stream products) x 16 slots. +pub const partial_floats = 19 * 16; +pub const Add = struct { residual: Ref, branch: Ref, post: Ref, output: Ref }; +pub const Kernels = struct { + /// Gate counts fixed at compile time (head: 4, blocks: 8); bit-equal to the generic tf_hy4_ihc_collapse. + pre4: mtl.Pipeline, + pre8: mtl.Pipeline, + /// The same collapse split in two: eight one-simdgroup threadgroups a row, then the gates and the row. + part: [2]mtl.Pipeline, + finish: [2]mtl.Pipeline, + /// Sub-block seams: tail (output norm, residual mix, next collapse's partials), head (gates, row, input norm). + tail: [2]mtl.Pipeline, + head: [2]mtl.Pipeline, + /// tail and the next head in one launch with an in-kernel barrier across a row's 12 threadgroups (decode). + seam: [2]mtl.Pipeline, + mix: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Kernels { + const library = try mtl.Library.fromSource(device, sources.hy4_flash_ihc, mtl.CompileOptions.mlx()); + defer library.deinit(); + var pre4 = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_collapse_g4", false); + errdefer pre4.deinit(); + var pre8 = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_collapse_g8", false); + errdefer pre8.deinit(); + var sets: [5][2]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (0..made) |m| sets[m / 2][m % 2].deinit(); + inline for (.{ "tf_hy4_ihc_partials_g", "tf_hy4_ihc_finish_g", "tf_hy4_tail_g", "tf_hy4_head_g", "tf_hy4_seam_g" }, 0..) |name, si| { + inline for (.{ "4", "8" }, 0..) |g, i| { + sets[si][i] = try mtl.Pipeline.init(device, library, name ++ g, false); + made += 1; + } + } + return .{ .pre4 = pre4, .pre8 = pre8, .part = sets[0], .finish = sets[1], .tail = sets[2], .head = sets[3], .seam = sets[4], .mix = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_add", false) }; + } + + pub fn deinit(self: *Kernels) void { + self.pre4.deinit(); + self.pre8.deinit(); + for (self.part) |p| p.deinit(); + for (self.finish) |p| p.deinit(); + for (self.tail) |p| p.deinit(); + for (self.head) |p| p.deinit(); + for (self.seam) |p| p.deinit(); + self.mix.deinit(); + self.* = undefined; + } + + pub fn collapse(self: Kernels, e: mtl.ComputeEncoder, b: Collapse, shape: ihc.Shape) !void { + try shape.check(); + if (shape.gates != ihc.streams and b.post == null) return error.MissingHy4PostGates; + const which: usize = @intFromBool(shape.gates != ihc.streams); + if (b.partials) |part| { + e.setPipeline(self.part[which]); + for ([_]Ref{ b.hidden, b.projection, part }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, 3); + e.dispatchGroups(mtl.Size.of(8, shape.rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); + e.setPipeline(self.finish[which]); + const args = [_]Ref{ b.hidden, part, b.bias, b.scale, b.output, b.post orelse b.hidden }; + for (args, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, args.len); + e.dispatchGroups(mtl.Size.of((shape.width + 255) / 256, shape.rows, 1), mtl.Size.of(256, 1, 1)); + return; + } + e.setPipeline(if (shape.gates == ihc.streams) self.pre4 else self.pre8); + const args = [_]Ref{ b.hidden, b.projection, b.bias, b.scale, b.output, b.post orelse b.hidden }; + for (args, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, args.len); + e.dispatchGroups(mtl.Size.of(shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + /// The collapse's partial sums only (the first of its two launches). + pub fn partials(self: Kernels, e: mtl.ComputeEncoder, hidden: Ref, projection: Ref, part: Ref, shape: ihc.Shape) !void { + try shape.check(); + e.setPipeline(self.part[@intFromBool(shape.gates != ihc.streams)]); + for ([_]Ref{ hidden, projection, part }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, 3); + e.dispatchGroups(mtl.Size.of(8, shape.rows, 1), mtl.Size.of(32, 1, 1)); + } + + pub const Head = struct { hidden: Ref, partials: Ref, bias: Ref, scale: Ref, gain: Ref, collapsed: Ref, normalized: Ref, post: Ref }; + + /// The collapse's gates and row from its partials, then the input RMS norm: one threadgroup a row. + pub fn headPass(self: Kernels, e: mtl.ComputeEncoder, b: Head, shape: ihc.Shape, norm_eps: f32) !void { + try shape.check(); + e.setPipeline(self.head[@intFromBool(shape.gates != ihc.streams)]); + for ([_]Ref{ b.hidden, b.partials, b.bias, b.scale, b.gain, b.collapsed, b.normalized, b.post }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, 8); + e.setValue(norm_eps, 9); + if (shape.width > 12 * 256) return error.BadHy4SeamWidth; + e.dispatchGroups(mtl.Size.of(12, shape.rows, 1), mtl.Size.of(256, 1, 1)); + } + + pub const TailShape = extern struct { rows: u32, width: u32, two: u32, partials: u32, eps: f32, mode: u32 }; + pub const Tail = struct { branch: Ref, branch2: ?Ref = null, gain: Ref, residual: Ref, post: Ref, output: Ref, next: ?Ref = null, partials: Ref }; + + /// A sub-block's branch (or two, added) through its output norm, mixed into the streams; + pub fn tailPass(self: Kernels, e: mtl.ComputeEncoder, b: Tail, rows: u32, width: u32, eps: f32, gates: u32) void { + e.setPipeline(self.tail[@intFromBool(gates != ihc.streams)]); + const args = [_]Ref{ b.branch, b.branch2 orelse b.branch, b.gain, b.residual, b.post, b.output, b.next orelse b.branch, b.partials }; + for (args, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(TailShape{ .rows = rows, .width = width, .two = @intFromBool(b.branch2 != null), .partials = @intFromBool(b.next != null), .eps = eps, .mode = 1 }, 8); + e.dispatchGroups(mtl.Size.of(12, rows, 1), mtl.Size.of(256, 1, 1)); + } + + pub const Next = struct { bias: Ref, scale: Ref, gain: Ref, collapsed: Ref, normalized: Ref, shape: ihc.Shape, barriers: Ref }; + + /// Rows a fused seam launch may hold (all its threadgroups resident for the in-kernel barrier). + pub const seam_rows = 16; + + /// tailPass then the next collapse's headPass in one launch (rows <= seam_rows, width 3072). + pub fn seamPass(self: Kernels, e: mtl.ComputeEncoder, b: Tail, n: Next, rows: u32, width: u32, eps: f32) !void { + if (rows > seam_rows or width != 12 * 256 or b.next == null) return error.BadHy4FusedSeam; + var next = n.shape; + next.rows = rows; + try next.check(); + e.setPipeline(self.seam[@intFromBool(next.gates != ihc.streams)]); + const args = [_]Ref{ b.branch, b.branch2 orelse b.branch, b.gain, b.residual, b.post, b.output, b.next.?, b.partials }; + for (args, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(TailShape{ .rows = rows, .width = width, .two = @intFromBool(b.branch2 != null), .partials = 1, .eps = eps, .mode = 1 }, 8); + for ([_]Ref{ n.bias, n.scale, n.gain, n.collapsed, n.normalized }, 9..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(next, 14); + e.setValue(next.eps, 15); + e.setBuffer(n.barriers.buffer, n.barriers.offset, 16); + e.dispatchGroups(mtl.Size.of(12, rows, 1), mtl.Size.of(256, 1, 1)); + } + + /// The seam partials of `hidden` alone (the collapse after an Engram layer, or with no tail before it). + pub fn seamPartials(self: Kernels, e: mtl.ComputeEncoder, hidden: Ref, projection: Ref, part: Ref, shape: ihc.Shape) !void { + try shape.check(); + e.setPipeline(self.tail[@intFromBool(shape.gates != ihc.streams)]); + const args = [_]Ref{ hidden, hidden, hidden, hidden, hidden, hidden, projection, part }; + for (args, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(TailShape{ .rows = shape.rows, .width = shape.width, .two = 0, .partials = 1, .eps = shape.eps, .mode = 0 }, 8); + e.dispatchGroups(mtl.Size.of(12, shape.rows, 1), mtl.Size.of(256, 1, 1)); + } + + pub fn add(self: Kernels, e: mtl.ComputeEncoder, b: Add, shape: ihc.Shape) !void { + try shape.check(); + if (shape.gates != 2 * ihc.streams) return error.MissingHy4PostGates; + e.setPipeline(self.mix); + const args = [_]Ref{ b.residual, b.branch, b.post, b.output }; + for (args, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, args.len); + e.dispatchThreads(mtl.Size.of(ihc.streams * shape.width, shape.rows, 1), mtl.Size.of(256, 1, 1)); + } +}; diff --git a/zig/src/families/hy4_flash/index_groups.zig b/zig/src/families/hy4_flash/index_groups.zig new file mode 100644 index 00000000000..55ca5703e05 --- /dev/null +++ b/zig/src/families/hy4_flash/index_groups.zig @@ -0,0 +1,61 @@ +//! Logical sparse-index groups shared by CUDA and Metal; token slots define group boundaries. +const std = @import("std"); + +pub const slots = 4; + +pub const PoolShape = extern struct { + groups: u32, + width: u32, +}; + +pub const Append = struct { + first_group: usize, + new_groups: usize, + pending_slots: usize, +}; + +/// Each completed group consumes four token slots and uses the first one's rotary position. +pub fn append(previous: usize, count: usize) !Append { + const after = try std.math.add(usize, previous, count); + return .{ + .first_group = previous / slots, + .new_groups = after / slots - previous / slots, + .pending_slots = after % slots, + }; +} + +pub const Frontier = struct { + visible_end: usize, + indexed_groups: usize, + current_group_start: usize, + groups_to_recall: usize, +}; + +/// The sparse selector ranks only closed earlier groups. It always includes the causal part of the current group. +pub fn frontier(query_slot: usize, group_budget: usize) !Frontier { + if (group_budget == 0) return error.ZeroGroupBudget; + const end = try std.math.add(usize, query_slot, 1); + const group = query_slot / slots; + return .{ + .visible_end = end, + .indexed_groups = group, + .current_group_start = group * slots, + .groups_to_recall = @min(group, group_budget - 1), + }; +} + +test "prefix continuation closes the same groups after draft rejection" { + const accepted = try append(2046, 3); + try std.testing.expectEqual(Append{ .first_group = 511, .new_groups = 1, .pending_slots = 1 }, accepted); + const provisioned = try append(2046, 6); + try std.testing.expectEqual(@as(usize, 2), provisioned.new_groups); + const after_rejection = try append(2046, 6 - 3); + try std.testing.expectEqual(accepted, after_rejection); +} + +test "recall excludes the query group from ranking around the 2048-token budget" { + const last = try frontier(2047, 512); + try std.testing.expectEqual(Frontier{ .visible_end = 2048, .indexed_groups = 511, .current_group_start = 2044, .groups_to_recall = 511 }, last); + const first = try frontier(2048, 512); + try std.testing.expectEqual(Frontier{ .visible_end = 2049, .indexed_groups = 512, .current_group_start = 2048, .groups_to_recall = 511 }, first); +} diff --git a/zig/src/families/hy4_flash/index_recall.zig b/zig/src/families/hy4_flash/index_recall.zig new file mode 100644 index 00000000000..9f36e250bd5 --- /dev/null +++ b/zig/src/families/hy4_flash/index_recall.zig @@ -0,0 +1,48 @@ +//! Shapes for scoring completed index groups and expanding their token positions. +const std = @import("std"); +const groups = @import("index_groups.zig"); + +pub const heads = 16; +pub const width = 128; +pub const head_scale: f32 = 0.02209708691207961; // 1 / sqrt(heads * width) + +/// A group's location in the compressed key arena and the query's logical token position. +pub const Row = extern struct { + group_base: u32, + token: u32, +}; + +pub const Shape = extern struct { + rows: u32, + score_groups: u32, + group_budget: u32, + + pub fn check(self: Shape) !void { + if (self.rows == 0 or self.rows > std.math.maxInt(u16) or self.score_groups == 0 or + self.score_groups > 65536 or self.group_budget < 2 or self.group_budget > 512) + return error.BadHy4RecallShape; + } + + pub fn tokenStride(self: Shape) u32 { + return self.group_budget * groups.slots; + } + + pub fn scoreBytes(self: Shape) usize { + return @as(usize, self.rows) * self.score_groups * @sizeOf(f32); + } + + pub fn tokenCount(self: Shape, token: u32) !u32 { + try self.check(); + const recall = try groups.frontier(token, self.group_budget); + if (recall.indexed_groups > self.score_groups) return error.ShortHy4RecallScores; + return @intCast(recall.groups_to_recall * groups.slots + recall.visible_end - recall.current_group_start); + } +}; + +test "the current group's first token consumes a new key at the recall edge" { + const shape: Shape = .{ .rows = 1, .score_groups = 513, .group_budget = 512 }; + try std.testing.expectEqual(@as(u32, 2048), shape.tokenStride()); + try std.testing.expectEqual(@as(u32, 2048), try shape.tokenCount(2047)); + try std.testing.expectEqual(@as(u32, 2045), try shape.tokenCount(2048)); + try std.testing.expectEqual(@as(u32, 2048), try shape.tokenCount(2051)); +} diff --git a/zig/src/families/hy4_flash/index_recall_cuda.zig b/zig/src/families/hy4_flash/index_recall_cuda.zig new file mode 100644 index 00000000000..075b53f283b --- /dev/null +++ b/zig/src/families/hy4_flash/index_recall_cuda.zig @@ -0,0 +1,44 @@ +//! CUDA launches for Hy4-flash's closed-group scores and selection. +const cuda = @import("cuda"); +const recall = @import("index_recall.zig"); + +pub const Buffers = struct { + query: u64, + keys: u64, + weights: u64, + rows: u64, + scores: u64, + tokens: u64, + counts: u64, +}; + +pub const Kernels = struct { + image: cuda.Module, + score: cuda.Function, + select: cuda.Function, + + pub fn load(driver: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var image = try cuda.Module.load(driver, cuda.kernels.hy4_index_recall); + errdefer image.unload(); + return .{ .image = image, .score = try image.function("tf_hy4_group_scores"), .select = try image.function("tf_hy4_recall_groups") }; + } + + pub fn deinit(self: *Kernels) void { + self.image.unload(); + self.* = undefined; + } + + pub fn run(self: Kernels, s: cuda.Stream, b: Buffers, shape: recall.Shape) !void { + try shape.check(); + var score: cuda.Args = .{}; + inline for (.{ b.query, b.keys, b.weights, b.rows, b.scores, shape, recall.head_scale }) |x| score.add(x); + try cuda.launch.launch(self.score, .{ + .grid = .{ .x = (shape.score_groups + 3) / 4, .y = shape.rows }, + .block = .{ .x = 128 }, + }, s, &score); + var select: cuda.Args = .{}; + inline for (.{ b.scores, b.rows, b.tokens, b.counts, shape }) |x| select.add(x); + try cuda.launch.launch(self.select, .{ .grid = .{ .x = shape.rows }, .block = .{ .x = 256 } }, s, &select); + } +}; diff --git a/zig/src/families/hy4_flash/index_recall_metal.zig b/zig/src/families/hy4_flash/index_recall_metal.zig new file mode 100644 index 00000000000..e6616379a73 --- /dev/null +++ b/zig/src/families/hy4_flash/index_recall_metal.zig @@ -0,0 +1,50 @@ +//! Metal launches for Hy4-flash's closed-group scores and selection. +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const recall = @import("index_recall.zig"); + +pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; +pub const Buffers = struct { + query: Ref, + keys: Ref, + weights: Ref, + rows: Ref, + scores: Ref, + tokens: Ref, + counts: Ref, +}; + +pub const Kernels = struct { + score: mtl.Pipeline, + select: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Kernels { + const lib = try mtl.Library.fromSource(device, sources.hy4_flash_index_recall, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var score = try mtl.Pipeline.init(device, lib, "tf_hy4_group_scores", false); + errdefer score.deinit(); + return .{ .score = score, .select = try mtl.Pipeline.init(device, lib, "tf_hy4_recall_groups", false) }; + } + + pub fn deinit(self: *Kernels) void { + self.score.deinit(); + self.select.deinit(); + self.* = undefined; + } + + pub fn run(self: Kernels, e: mtl.ComputeEncoder, b: Buffers, shape: recall.Shape) !void { + try shape.check(); + e.setPipeline(self.score); + const input = [_]Ref{ b.query, b.keys, b.weights, b.rows, b.scores }; + for (input, 0..) |ref, i| e.setBuffer(ref.buffer, ref.offset, i); + e.setValue(shape, input.len); + e.setValue(recall.head_scale, input.len + 1); + e.dispatchGroups(mtl.Size.of((shape.score_groups + 3) / 4, shape.rows, 1), mtl.Size.of(128, 1, 1)); + e.barrier(); + e.setPipeline(self.select); + const selection = [_]Ref{ b.scores, b.rows, b.tokens, b.counts }; + for (selection, 0..) |ref, i| e.setBuffer(ref.buffer, ref.offset, i); + e.setValue(shape, selection.len); + e.dispatchGroups(mtl.Size.of(shape.rows, 1, 1), mtl.Size.of(256, 1, 1)); + } +}; diff --git a/zig/src/families/hy4_flash/indexpool_cuda.zig b/zig/src/families/hy4_flash/indexpool_cuda.zig new file mode 100644 index 00000000000..f6b0cfbb62a --- /dev/null +++ b/zig/src/families/hy4_flash/indexpool_cuda.zig @@ -0,0 +1,26 @@ +//! CUDA launch for Hy4-flash's FP32 sparse-index key pooling. +const cuda = @import("cuda"); +const groups = @import("index_groups.zig"); + +pub const symbol = "tf_hy4_pool_groups"; +pub const threads = 128; + +pub const Bindings = struct { values: u64, gates: u64, position_bias: u64, pooled: u64 }; + +pub fn open(driver: *const cuda.Driver) !cuda.Module { + return cuda.Module.load(driver, cuda.kernels.hy4_indexpool); +} + +pub fn load(module: cuda.Module) !cuda.Function { + return module.function(symbol); +} + +pub fn run(kernel: cuda.Function, stream: cuda.Stream, refs: Bindings, shape: groups.PoolShape) !void { + if (shape.groups == 0 or shape.width == 0) return; + var args: cuda.Args = .{}; + inline for (.{ refs.values, refs.gates, refs.position_bias, refs.pooled, shape.groups, shape.width }) |arg| { + args.add(arg); + } + const columns = (shape.width - 1) / threads + 1; + try cuda.launch.launch(kernel, .{ .grid = .{ .x = shape.groups, .y = columns }, .block = .{ .x = threads } }, stream, &args); +} diff --git a/zig/src/families/hy4_flash/indexpool_metal.zig b/zig/src/families/hy4_flash/indexpool_metal.zig new file mode 100644 index 00000000000..f7528cbd4db --- /dev/null +++ b/zig/src/families/hy4_flash/indexpool_metal.zig @@ -0,0 +1,35 @@ +//! Metal launch for Hy4-flash's FP32 sparse-index key pooling. +const mtl = @import("metal"); +const groups = @import("index_groups.zig"); +const sources = @import("kernel_sources"); + +pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; +pub const Bindings = struct { values: Ref, gates: Ref, position_bias: Ref, pooled: Ref }; + +pub const Pool = struct { + pipeline: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Pool { + const library = try mtl.Library.fromSource(device, sources.hy4_flash_indexpool, mtl.CompileOptions.mlx()); + defer library.deinit(); + return fromLibrary(device, library); + } + + pub fn fromLibrary(device: mtl.Device, library: mtl.Library) !Pool { + return .{ .pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_pool_groups", false) }; + } + + pub fn deinit(self: *Pool) void { + self.pipeline.deinit(); + } + + pub fn run(self: Pool, encoder: mtl.ComputeEncoder, refs: Bindings, shape: groups.PoolShape) void { + if (shape.groups == 0 or shape.width == 0) return; + encoder.setPipeline(self.pipeline); + for ([_]Ref{ refs.values, refs.gates, refs.position_bias, refs.pooled }, 0..) |ref, i| { + encoder.setBuffer(ref.buffer, ref.offset, i); + } + encoder.setValue(shape, 4); + encoder.dispatchThreads(mtl.Size.of(shape.width, shape.groups, 1), mtl.Size.of(32, 1, 1)); + } +}; diff --git a/zig/src/families/hy4_flash/loader.zig b/zig/src/families/hy4_flash/loader.zig new file mode 100644 index 00000000000..4e1ee7964b1 --- /dev/null +++ b/zig/src/families/hy4_flash/loader.zig @@ -0,0 +1,83 @@ +//! Checkpoint ownership and admission for the native Hy4-flash model family. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const weights = @import("weights.zig"); + +pub const Attention = enum { target, draft }; + +pub const Loaded = struct { + config: std.json.Parsed(config.Model), + checkpoint: core.Checkpoint, + bits: u8, + + pub fn open(a: std.mem.Allocator, io: std.Io, directory: []const u8) !Loaded { + const config_path = try std.fs.path.join(a, &.{ directory, "config.json" }); + defer a.free(config_path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, a, .limited(1 << 20)); + defer a.free(text); + const parsed = try config.parse(a, text); + errdefer parsed.deinit(); + const q = parsed.value.quantization orelse return error.UnsupportedHy4Affine; + if (q.group_size != 64 or !std.mem.eql(u8, q.mode, "affine") or (q.bits != 4 and q.bits != 8)) + return error.UnsupportedHy4Affine; + var checkpoint = try core.Checkpoint.openModel(a, io, directory); + errdefer checkpoint.close(); + var validation: Validation = .{ .checkpoint = &checkpoint }; + try weights.check(&validation, parsed.value, q.bits); + return .{ .config = parsed, .checkpoint = checkpoint, .bits = q.bits }; + } + + pub fn close(self: *Loaded) void { + self.checkpoint.close(); + self.config.deinit(); + self.* = undefined; + } + + pub fn attentionTargetLayer(self: *const Loaded, kind: Attention, layer: u32) !u32 { + const model = self.config.value; + return switch (kind) { + .target => if (layer < model.text_config.num_hidden_layers) layer else error.BadAttentionLayer, + .draft => if (layer < model.dfly_target_kv_layers.len) model.dfly_target_kv_layers[layer] else return error.BadAttentionLayer, + }; + } + + /// Return this layer's learned sink, even when its draft attention shares the target's KV. + pub fn attentionSink(self: *Loaded, kind: Attention, layer: u32, output: []f32) ![]f32 { + const layer_config = try self.attentionTargetLayer(kind, layer); + const heads = self.config.value.text_config.headShape(layer_config).heads; + if (output.len < heads) return error.ShortAttentionSinkBuffer; + var buffer: [96]u8 = undefined; + const prefix = switch (kind) { + .target => "model.layers", + .draft => "model.dfly_layers", + }; + const name = try std.fmt.bufPrint(&buffer, "{s}.{d}.self_attn.learnable_sink_param", .{ prefix, layer }); + const result = output[0..heads]; + switch (kind) { + .target => { + const tensor = try self.checkpoint.expect(name, .f32, &.{heads}); + for (result, 0..) |*value, i| value.* = @bitCast(std.mem.readInt(u32, tensor.bytes[4 * i ..][0..4], .little)); + }, + .draft => { + const tensor = try self.checkpoint.expect(name, .bf16, &.{heads}); + for (result, 0..) |*value, i| { + const raw = std.mem.readInt(u16, tensor.bytes[2 * i ..][0..2], .little); + value.* = @bitCast(@as(u32, raw) << 16); + } + }, + } + return result; + } +}; + +const Validation = struct { + checkpoint: *core.Checkpoint, + + pub fn expect(self: *Validation, name: []const u8, format: weights.DType, shape: []const usize) !void { + const dtype: core.checkpoint_host.DType = switch (format) { + inline else => |tag| @field(core.checkpoint_host.DType, @tagName(tag)), + }; + _ = try self.checkpoint.expect(name, dtype, shape); + } +}; diff --git a/zig/src/families/hy4_flash/metal_dense.zig b/zig/src/families/hy4_flash/metal_dense.zig new file mode 100644 index 00000000000..094b5f7ee0b --- /dev/null +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -0,0 +1,589 @@ +//! The native Metal attention and dense feed-forward layer passes for Hy4-flash. +const std = @import("std"); +const mtl = @import("metal"); +const affine = @import("../../core/row_projection.zig"); +const dense = @import("draft_ops"); +const core = @import("core"); +const cfg = @import("config.zig"); +const ihc = @import("ihc.zig"); +const ihc_gpu = @import("ihc_metal.zig"); +const mla_gpu = @import("mla_metal.zig"); +const mha = @import("mla_attention.zig"); +const shape_ = @import("mla_weights.zig"); +const weights = @import("model_weights.zig"); +const rope = @import("rope.zig"); +const gpu_qkv = @import("metal_tensor_qkv.zig"); +const lane = @import("../../core/lane_projection.zig"); +const index = @import("metal_index.zig"); + +pub const Ref = mla_gpu.Ref; + +pub const Buffers = struct { + a: std.mem.Allocator, + d: mtl.Device, + list: std.ArrayList(mtl.Buffer) = .empty, + + pub fn alloc(self: *Buffers, bytes: usize) !mtl.Buffer { + const b = try self.d.buffer(bytes, mtl.ResourceOptions.shared); + errdefer b.deinit(); + try self.list.append(self.a, b); + return b; + } + + pub fn upload(self: *Buffers, bytes: []const u8) !mtl.Buffer { + const b = try self.alloc(bytes.len); + @memcpy(b.slice(u8, bytes.len), bytes); + return b; + } + + pub fn clear(self: *Buffers) void { + for (self.list.items) |b| b.deinit(); + self.list.deinit(self.a); + } + + pub fn matrix(self: *Buffers, w: core.quant.mlx.Host) !affine.Weights { + const view: affine.Weights = .{ + .w = try self.upload(w.words.bytes), + .scales = try self.upload(w.scales.bytes), + .biases = try self.upload(w.biases.bytes), + .n = w.words.shape[0], + .k = w.scales.shape[1] * w.group, + .bits = w.bits, + .group = w.group, + }; + try view.validate(); + return view; + } + + /// A dense projection's weights: packed for the tensor units' lane projection when `tensors` + pub fn linear(self: *Buffers, w: core.quant.mlx.Host, tensors: bool) !Linear { + const n: u32 = @intCast(w.words.shape[0]); + const k: u32 = @intCast(w.scales.shape[1] * w.group); + if (tensors and n % 32 == 0 and w.group == 64 and (w.bits == 4 or w.bits == 8)) { + const packed_ = try gpu_qkv.Packed.upload(self, &.{w}, gpu_qkv.denseLayout(w.bits, n, k)); + return .{ .tensor = .{ .w = packed_.w, .sb = packed_.sb, .n = n, .k = k } }; + } + return .{ .portable = try self.matrix(w) }; + } + + pub fn rows(self: *Buffers, count: u32, columns: u32) !Ref { + return .{ .buffer = try self.alloc(@as(usize, count) * columns * @sizeOf(u16)) }; + } +}; + +/// A dense affine projection [n, k]: the core row kernels, or the tensor units' lane projection over packed weights. +pub const Linear = union(enum) { + portable: affine.Weights, + tensor: struct { w: lane.Ref, sb: lane.Ref, n: u32, k: u32 }, + + pub fn outputs(self: Linear) u32 { + return switch (self) { + .portable => |w| @intCast(w.n), + .tensor => |t| t.n, + }; + } +}; + +pub const Linears = @import("metal_linears.zig").Linears; + +pub const Merge = struct { + project: mtl.Buffer, + bias: mtl.Buffer, + scale: mtl.Buffer, + shape: ihc.Shape, + + pub fn upload(b: *Buffers, w: ihc.Weights) !Merge { + return .{ + .project = try b.upload(w.project.bytes), + .bias = try b.upload(w.bias.bytes), + .scale = try b.upload(w.scale.bytes), + .shape = w.shape, + }; + } +}; + +const InputWeights = union(enum) { + portable: struct { q_a: affine.Weights, q_b: affine.Weights, kv_a: affine.Weights, gates: affine.Weights }, + tensor: struct { qkv: gpu_qkv.Packed, q_b: gpu_qkv.Packed, flavor: usize }, +}; + +pub const Attention = struct { + own: Buffers, + hidden: u32, + query_rank: u32, + heads: u32, + epsilon: f32, + rope: rope.Parameters, + merge: Merge, + norm: mtl.Buffer, + inputs: InputWeights, + q_norm: mtl.Buffer, + kv_norm: mtl.Buffer, + o: Linear, + o_norm: mtl.Buffer, + wk: mtl.Buffer, + wv: mtl.Buffer, + bits: u8 = 4, + sinks: mtl.Buffer, + /// A sparse layer's compressed indexer (null on sliding layers). + index: ?index.Weights = null, + + pub fn upload(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer, t: cfg.Text) !Attention { + return uploadForModel(a, device, w, t, false); + } + + pub fn uploadForModel(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer, t: cfg.Text, use_tensors: bool) !Attention { + if (w.attention.owns_output) return error.Hy4MetalAttentionNeedsFullHeadRange; + var b: Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + const heads = w.attention.heads.count; + const bits = w.project_query.bits; + const inputs: InputWeights = if (use_tensors) + .{ .tensor = .{ + .qkv = try gpu_qkv.Packed.upload(&b, &.{ w.project_query, w.project_kv, w.attention.gate }, gpu_qkv.inputLayout(t, bits, heads)), + .q_b = try gpu_qkv.Packed.upload(&b, &.{w.attention.query}, gpu_qkv.queryLayout(t, bits, heads)), + .flavor = gpu_qkv.flavor(t, heads), + } } + else + .{ .portable = .{ + .q_a = try b.matrix(w.project_query), + .q_b = try b.matrix(w.attention.query), + .kv_a = try b.matrix(w.project_kv), + .gates = try b.matrix(w.attention.gate), + } }; + const out: Attention = .{ + .own = undefined, + .hidden = t.hidden_size, + .query_rank = t.q_lora_rank, + .heads = heads, + .epsilon = t.rms_norm_eps, + .rope = w.position, + .merge = try Merge.upload(&b, w.attention_hc), + .norm = try b.upload(w.attention_norm.bytes), + .inputs = inputs, + .q_norm = try b.upload(w.norm_query.bytes), + .kv_norm = try b.upload(w.norm_kv.bytes), + .o = try b.linear(w.attention.output, use_tensors), + .o_norm = try b.upload(w.attention_output_norm.bytes), + .wk = try b.upload(std.mem.sliceAsBytes(w.absorbed.key)), + .wv = try b.upload(std.mem.sliceAsBytes(w.absorbed.value)), + .bits = if (w.absorbed.packed_rows) |p| p.bits else 4, + .sinks = try b.upload(std.mem.sliceAsBytes(w.sinks[0..heads])), + .index = if (w.index) |*ix| try index.Weights.upload(&b, ix, use_tensors) else null, + }; + return withAllocation(out, b); + } + + pub fn deinit(self: *Attention) void { + self.own.clear(); + self.* = undefined; + } +}; + +pub const Feed = struct { + own: Buffers, + merge: Merge, + norm: mtl.Buffer, + gate: Linear, + up: Linear, + down: Linear, + output_norm: mtl.Buffer, + + pub fn upload(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer) !Feed { + return uploadForModel(a, device, w, false); + } + + pub fn uploadForModel(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer, use_tensors: bool) !Feed { + if (w.feed != .dense) return error.Hy4DenseFeedRequired; + var b: Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + const feed = w.feed.dense; + const out: Feed = .{ + .own = undefined, + .merge = try Merge.upload(&b, w.mlp_hc), + .norm = try b.upload(w.mlp_norm.bytes), + .gate = try b.linear(feed.projections.gate, use_tensors), + .up = try b.linear(feed.projections.up, use_tensors), + .down = try b.linear(feed.projections.down, use_tensors), + .output_norm = try b.upload(feed.norm.bytes), + }; + return withAllocation(out, b); + } + + pub fn deinit(self: *Feed) void { + self.own.clear(); + self.* = undefined; + } +}; + +pub fn withAllocation(out: anytype, b: Buffers) @TypeOf(out) { + var owned = out; + owned.own = b; + return owned; +} + +pub const Scratch = @import("metal_scratch.zig").Scratch; + +pub const Rows = @import("metal_linears.zig").Rows; + +fn twoStep(keys: u32) bool { + return keys >= 1024; +} + +pub const CacheRows = struct { + positions: Ref, + write_slots: Ref, + retained: Ref, + counts: Ref, + cache: Ref, + capacity: u32, + /// When every row's keys are one contiguous run: their ranges and tiles, for the tensor units' flash kernel. + ranges: ?mla_gpu.KeyRanges = null, + /// The widest row's live key count this pass (0: unknown), which sizes the decode attention split. + live_keys: u32 = 0, + /// A sparse layer's indexer for this pass (null: it attends `retained`, the probe's contexts under 2,048). + index: ?index.Pass = null, +}; + +pub const Kernels = struct { + affine: affine.Pipelines, + dense: dense.Ops, + merge: ihc_gpu.Kernels, + projections: mla_gpu.Projections, + attention: mla_gpu.Attention, + tensors: ?gpu_qkv.Kernels = null, + rows: ?Rows = null, + linears: ?Linears = null, + + pub fn load(device: mtl.Device) !Kernels { + var row_project = try affine.Pipelines.load(device); + errdefer row_project.deinit(); + const normalize = try dense.Ops.init(device); + errdefer normalize.deinit(); + var merge = try ihc_gpu.Kernels.load(device); + errdefer merge.deinit(); + var proj = try mla_gpu.Projections.load(device); + errdefer proj.deinit(); + return .{ + .affine = row_project, + .dense = normalize, + .merge = merge, + .projections = proj, + .attention = try mla_gpu.Attention.load(device), + }; + } + + pub fn deinit(self: *Kernels) void { + if (self.linears) |*l| l.deinit(); + if (self.rows) |r| r.deinit(); + if (self.tensors) |t| t.deinit(); + self.attention.deinit(); + self.projections.deinit(); + self.merge.deinit(); + self.dense.deinit(); + self.affine.deinit(); + } + + pub fn loadForModel(a: std.mem.Allocator, device: mtl.Device, t: cfg.Text, bits: u8) !Kernels { + var out = try load(device); + errdefer out.deinit(); + if (device.tensorUnits()) out.tensors = try gpu_qkv.Kernels.load(a, device, t, bits); + if (device.tensorUnits()) out.linears = try Linears.load(a, device, t, bits); + out.rows = try Rows.load(a, device); + if (device.tensorUnits()) out.projections.nax = try mla_gpu.Nax.load(a, device); + return out; + } + + pub fn project(self: *const Kernels, e: mtl.ComputeEncoder, w: affine.Weights, x: Ref, y: Ref, rows: u32) !void { + var call = try affine.call(&self.affine, w, rows, false); + if (self.rows) |r| if (r.choose(w, rows)) |pipe| { + call.pipeline = pipe; + call.groups = w.n / (r.rps * r.sg()); + call.threads = 32 * r.sg(); + }; + e.setPipeline(call.pipeline); + e.setBuffer(x.buffer, x.offset, 0); + e.setBuffer(w.w, w.w_off, 1); + e.setBuffer(w.scales, w.s_off, 2); + e.setBuffer(w.biases, w.b_off, 3); + e.setValue(call.dims, 4); + e.setBuffer(y.buffer, y.offset, 5); + e.dispatchGroups(mtl.Size.of(call.groups, 1, 1), mtl.Size.of(call.threads, 1, 1)); + } + + /// y = x W^T for a dense projection, on whichever kernels its weights were packed for. + pub fn linear(self: *const Kernels, e: mtl.ComputeEncoder, w: Linear, x: Ref, y: Ref, rows: u32) !void { + return self.linearsFrom(e, x, &.{.{ .w = w, .y = y }}, rows); + } + + pub const Out = struct { w: Linear, y: Ref }; + + /// Every projection of the same input x: on tensor units one group-sums pass, a barrier + pub fn linearsFrom(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, outs: []const Out, rows: u32) !void { + if (outs.len == 0) return; + if (outs[0].w == .portable) { + for (outs) |o| try self.project(e, o.w.portable, x, o.y, rows); + return; + } + const all = &(self.linears orelse return error.Hy4LinearsMissing); + const k = outs[0].w.tensor.k; + // small passes: the kernels that add their own group sums (the same words, no sums pass or barrier) + if (rows <= gpu_qkv.inline_rows) inline_sums: { + for (outs) |o| if (all.findInline(o.w.tensor.n, o.w.tensor.k) == null) break :inline_sums; + for (outs) |o| try all.findInline(o.w.tensor.n, o.w.tensor.k).?.encode(e, tref(x), o.w.tensor.w, o.w.tensor.sb, tref(o.y), rows); + return; + } + const first = all.find(outs[0].w.tensor.n, k) orelse return error.Hy4LinearShapeMissing; + const shared = first.reg and first.sums_pipe != null and rows <= Linears.sum_rows; + const stride: u32 = 16 * ((rows + 15) / 16); + if (shared) { + e.setPipeline(first.sums_pipe.?); + e.setBuffer(x.buffer, x.offset, 0); + e.setValue(@as(i32, @intCast(rows)), 1); + e.setBuffer(all.sums.?, 0, 2); + e.setValue(@as(i32, @intCast(stride)), 3); + e.dispatchThreads(.{ .width = stride * (k / 64) }, .{ .width = 256 }); + e.barrier(); + } + for (outs) |o| { + const m = o.w.tensor; + if (m.k != k) return error.Hy4LinearInputsDiffer; + const p = all.find(m.n, m.k) orelse return error.Hy4LinearShapeMissing; + if (shared) + try p.encodeSums(e, tref(x), m.w, m.sb, .{ .ref = .{ .buf = all.sums.? }, .stride = stride }, tref(o.y), rows) + else + try p.encode(e, tref(x), m.w, m.sb, tref(o.y), rows); + } + } + + pub fn dref(x: Ref) dense.Ref { + return .{ .buf = x.buffer, .off = x.offset }; + } + + fn tref(x: Ref) lane.Ref { + return .{ .buf = x.buffer, .off = x.offset }; + } + + pub fn norm(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, gain: mtl.Buffer, y: Ref, rows: u32, width: u32, epsilon: f32) !void { + try self.dense.norm(e, dref(x), .{ .buf = gain }, dref(y), .{ + .rows = rows, + .heads = 1, + .dim = width, + .x_stride = width, + .y_stride = width, + .eps = epsilon, + }); + } + + /// Where a sub-block sits between seams: `ready` when the previous tail already wrote this collapse's partials + pub const Seam = struct { ready: bool = false, headed: bool = false, next: ?Merge = null, next_gain: ?mtl.Buffer = null }; + + /// Decode passes fuse each tail with the next head. + pub fn fusedSeams(rows: u32) bool { + return rows <= ihc_gpu.Kernels.seam_rows; + } + + /// The collapse and input norm in two launches at most (partials unless `ready`, then gates, row and norm). + pub fn collapseSeam(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Merge, gain: mtl.Buffer, s: *const Scratch, ready: bool) !ihc.Shape { + return self.collapseSeamFrom(e, x, w, gain, s, .{ .ready = ready }); + } + + pub fn collapseSeamFrom(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Merge, gain: mtl.Buffer, s: *const Scratch, seam: Seam) !ihc.Shape { + const ready = seam.ready; + var shape = w.shape; + shape.rows = s.shape.rows; + if (seam.headed) return shape; + const part: ihc_gpu.Ref = .{ .buffer = s.ihc_partials.buffer, .offset = s.ihc_partials.offset }; + const hidden: ihc_gpu.Ref = .{ .buffer = x.buffer, .offset = x.offset }; + if (!ready) { + try self.merge.seamPartials(e, hidden, .{ .buffer = w.project }, part, shape); + e.barrier(); + } + try self.merge.headPass(e, .{ + .hidden = hidden, + .partials = part, + .bias = .{ .buffer = w.bias }, + .scale = .{ .buffer = w.scale }, + .gain = .{ .buffer = gain }, + .collapsed = .{ .buffer = s.merged.buffer, .offset = s.merged.offset }, + .normalized = .{ .buffer = s.normalized.buffer, .offset = s.normalized.offset }, + .post = .{ .buffer = s.post.buffer, .offset = s.post.offset }, + }, shape, shape.eps); + e.barrier(); + return shape; + } + + /// A sub-block's end: its branch (two added, for the experts) through the output norm, mixed into `out` + pub fn tail(self: *const Kernels, e: mtl.ComputeEncoder, branch: Ref, branch2: ?Ref, gain: mtl.Buffer, eps: f32, x: Ref, out: Ref, s: *const Scratch, shape: ihc.Shape, next: ?Merge) !void { + return self.tailTo(e, branch, branch2, gain, eps, x, out, s, shape, .{ .next = next }); + } + + pub fn tailTo(self: *const Kernels, e: mtl.ComputeEncoder, branch: Ref, branch2: ?Ref, gain: mtl.Buffer, eps: f32, x: Ref, out: Ref, s: *const Scratch, shape: ihc.Shape, seam: Seam) !void { + const next = seam.next; + if (next) |n| if (seam.next_gain) |ng| if (fusedSeams(shape.rows) and shape.width == 12 * 256) { + const r = ihc_gpu.Ref; + return self.merge.seamPass(e, .{ + .branch = r{ .buffer = branch.buffer, .offset = branch.offset }, + .branch2 = if (branch2) |b2| r{ .buffer = b2.buffer, .offset = b2.offset } else null, + .gain = .{ .buffer = gain }, + .residual = .{ .buffer = x.buffer, .offset = x.offset }, + .post = .{ .buffer = s.post.buffer, .offset = s.post.offset }, + .output = .{ .buffer = out.buffer, .offset = out.offset }, + .next = r{ .buffer = n.project }, + .partials = .{ .buffer = s.ihc_partials.buffer, .offset = s.ihc_partials.offset }, + }, .{ + .bias = .{ .buffer = n.bias }, + .scale = .{ .buffer = n.scale }, + .gain = .{ .buffer = ng }, + .collapsed = .{ .buffer = s.merged.buffer, .offset = s.merged.offset }, + .normalized = .{ .buffer = s.normalized.buffer, .offset = s.normalized.offset }, + .shape = n.shape, + .barriers = .{ .buffer = s.seam_barriers.buffer, .offset = s.seam_barriers.offset }, + }, shape.rows, shape.width, eps); + }; + const r = ihc_gpu.Ref; + self.merge.tailPass(e, .{ + .branch = r{ .buffer = branch.buffer, .offset = branch.offset }, + .branch2 = if (branch2) |b2| r{ .buffer = b2.buffer, .offset = b2.offset } else null, + .gain = .{ .buffer = gain }, + .residual = .{ .buffer = x.buffer, .offset = x.offset }, + .post = .{ .buffer = s.post.buffer, .offset = s.post.offset }, + .output = .{ .buffer = out.buffer, .offset = out.offset }, + .next = if (next) |n| r{ .buffer = n.project } else null, + .partials = .{ .buffer = s.ihc_partials.buffer, .offset = s.ihc_partials.offset }, + }, shape.rows, shape.width, eps, if (next) |n| n.shape.gates else 8); + } + + pub fn collapse(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, w: Merge, gain: mtl.Buffer, s: *const Scratch) !ihc.Shape { + var shape = w.shape; + shape.rows = s.shape.rows; + try self.merge.collapse(e, .{ + .hidden = .{ .buffer = x.buffer, .offset = x.offset }, + .projection = .{ .buffer = w.project }, + .bias = .{ .buffer = w.bias }, + .scale = .{ .buffer = w.scale }, + .output = .{ .buffer = s.merged.buffer, .offset = s.merged.offset }, + .post = .{ .buffer = s.post.buffer, .offset = s.post.offset }, + .partials = .{ .buffer = s.ihc_partials.buffer, .offset = s.ihc_partials.offset }, + }, shape); + e.barrier(); + try self.norm(e, s.merged, gain, s.normalized, shape.rows, shape.width, shape.eps); + e.barrier(); + return shape; + } + + pub fn residual(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, branch: Ref, post: Ref, out: Ref, shape: ihc.Shape) !void { + try self.merge.add(e, .{ + .residual = .{ .buffer = x.buffer, .offset = x.offset }, + .branch = .{ .buffer = branch.buffer, .offset = branch.offset }, + .post = .{ .buffer = post.buffer, .offset = post.offset }, + .output = .{ .buffer = out.buffer, .offset = out.offset }, + }, shape); + } + + /// The caller supplies the retained list for this lane from its sliding or sparse index state. + pub fn attend(self: *const Kernels, e: mtl.ComputeEncoder, w: *const Attention, s: *const Scratch, cache: CacheRows, x: Ref, out: Ref) !void { + return self.attendSeam(e, w, s, cache, x, out, .{}); + } + + pub fn attendSeam(self: *const Kernels, e: mtl.ComputeEncoder, w: *const Attention, s: *const Scratch, cache: CacheRows, x: Ref, out: Ref, seam: Seam) !void { + if (s.shape.heads != w.heads) return error.Hy4WrongAttentionHeadCount; + if (w.inputs == .tensor and (self.tensors == null or s.qkv == null)) return error.ShortHy4Scratch; + const shape = try self.collapseSeamFrom(e, x, w.merge, w.norm, s, seam); + const rows = shape.rows; + var q_a = s.query_a; + var kv = s.kv; + var gates = s.value_logits; + switch (w.inputs) { + .portable => |m| { + try self.project(e, m.q_a, s.normalized, q_a, rows); + try self.project(e, m.kv_a, s.normalized, kv, rows); + try self.project(e, m.gates, s.normalized, gates, rows); + e.barrier(); + try self.norm(e, q_a, w.q_norm, s.query_norm, rows, w.query_rank, w.epsilon); + e.barrier(); + try self.project(e, m.q_b, s.query_norm, s.query, rows); + }, + .tensor => |m| { + const kernels = &self.tensors.?; + const qkv = s.qkv.?; + try kernels.inputFor(m.flavor, rows).encode(e, tref(s.normalized), m.qkv.w, m.qkv.sb, tref(qkv), rows); + e.barrier(); + if (rows == 1) { + q_a = qkv; + kv = .{ .buffer = qkv.buffer, .offset = @as(usize, w.query_rank) * @sizeOf(u16) }; + gates = .{ .buffer = qkv.buffer, .offset = (@as(usize, w.query_rank) + shape_.absorbed_stride) * @sizeOf(u16) }; + } else { + kernels.split(e, tref(qkv), tref(q_a), tref(kv), tref(gates), rows, w.query_rank, w.heads * shape_.value_width); + e.barrier(); + } + try self.norm(e, q_a, w.q_norm, s.query_norm, rows, w.query_rank, w.epsilon); + e.barrier(); + try kernels.queryFor(m.flavor, rows).encode(e, tref(s.query_norm), m.q_b.w, m.q_b.sb, tref(s.query), rows); + }, + } + e.barrier(); + const ix_pass: ?index.Pass = if (cache.index) |p| (if (w.index != null) p else null) else null; + if (ix_pass) |p| { + if (p.scratch.rows != rows) return error.Hy4IndexRowsOutOfStep; + try index.run(p, self, self.projections, e, &w.index.?, s.normalized, s.query_norm, cache.write_slots, cache.positions, s.rotary, w.rope, w.epsilon); + e.barrier(); + } + // past 2,048 keys a sparse layer attends each row's recalled slots + const lists = if (ix_pass) |p| p.scratch.selects() else false; + // rows of a pass across 2,048 keys that sit before it attend as they would in any other pass + const lists_from: ?u32 = if (lists and cache.ranges != null and ix_pass.?.scratch.first < index.keys_a_row) index.keys_a_row - ix_pass.?.scratch.first else null; + try mla_gpu.forward(self.projections, self.attention, e, .{ + .query = s.query, + .key_weights = .{ .buffer = w.wk }, + .value_weights = .{ .buffer = w.wv }, + .value_logits = gates, + .positions = cache.positions, + .rotary_table = s.rotary, + .values = s.values, + .kv = .{ .projection = kv, .gain = .{ .buffer = w.kv_norm }, .write_slots = cache.write_slots, .capacity = cache.capacity, .epsilon = w.epsilon }, + .attention = .{ + .query = s.absorbed, + .cache = cache.cache, + .slots = if (lists) ix_pass.?.cache.tokens else cache.retained, + .counts = if (lists) ix_pass.?.cache.counts else cache.counts, + .sinks = .{ .buffer = w.sinks }, + .scratch = s.attention, + .output = s.latent, + // two steps pay off from two chunks of keys; below that the one-step kernel is quicker + .key_scores = if (twoStep(s.shape.key_stride)) s.key_scores else null, + .ranges = if (lists and lists_from == null) null else cache.ranges, + .lists_from = lists_from, + .flash_parts = s.flash_parts, + .live_keys = if (lists) index.keys_a_row else cache.live_keys, + }, + }, s.shape, w.rope); + e.barrier(); + try self.linear(e, w.o, s.values, s.branch, rows); + e.barrier(); + try self.tailTo(e, s.branch, null, w.o_norm, w.epsilon, x, out, s, shape, seam); + } + + pub fn feed(self: *const Kernels, e: mtl.ComputeEncoder, w: *const Feed, s: *const Scratch, x: Ref, out: Ref) !void { + return self.feedSeam(e, w, s, x, out, .{}); + } + + pub fn feedSeam(self: *const Kernels, e: mtl.ComputeEncoder, w: *const Feed, s: *const Scratch, x: Ref, out: Ref, seam: Seam) !void { + const inner: u32 = w.gate.outputs(); + if (inner > s.inner_capacity) return error.ShortHy4Scratch; + const shape = try self.collapseSeamFrom(e, x, w.merge, w.norm, s, seam); + try self.linearsFrom(e, s.normalized, &.{ .{ .w = w.gate, .y = s.gate }, .{ .w = w.up, .y = s.up } }, shape.rows); + e.barrier(); + try self.dense.swiglu(e, dref(s.gate), dref(s.up), dref(s.inner), .{ + .rows = shape.rows, + .width = inner, + .gate_stride = inner, + .up_stride = inner, + .y_stride = inner, + }); + e.barrier(); + try self.linear(e, w.down, s.inner, s.branch, shape.rows); + e.barrier(); + try self.tailTo(e, s.branch, null, w.output_norm, shape.eps, x, out, s, shape, seam); + } +}; diff --git a/zig/src/families/hy4_flash/metal_draft.zig b/zig/src/families/hy4_flash/metal_draft.zig new file mode 100644 index 00000000000..741149ba6c8 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_draft.zig @@ -0,0 +1,419 @@ +//! DFly2 on Metal. The scheduler supplies the target KV and retained indices for each draft layer. +const std = @import("std"); +const mtl = @import("metal"); +const source = @import("kernel_sources"); +const dense_ops = @import("draft_ops"); +const affine = @import("../../core/row_projection.zig"); +const ck = @import("loader.zig"); +const model = @import("metal_model.zig"); +const common = @import("metal_dense.zig"); +const mla = @import("mla_metal.zig"); +const weights = @import("model_weights.zig"); +const geom = @import("mla_weights.zig"); +const rope = @import("rope.zig"); + +pub const Ref = common.Ref; + +/// TF_HY4_DRAFT_BITS=4 or 8 quantizes DFly2's BF16 linears at load (MLX affine +fn draftBits() !?u8 { + const bits = try @import("sys").environment.read(u32, "TF_HY4_DRAFT_BITS", 16); + return if (bits == 16) null else @intCast(bits); +} + +fn bf16Round(x: f32) u16 { + const u: u32 = @bitCast(x); + return @intCast((u +% 0x7fff +% ((u >> 16) & 1)) >> 16); +} + +fn bf16Value(w: u16) f32 { + return @bitCast(@as(u32, w) << 16); +} + +/// MLX affine quantization of a BF16 [n, k] matrix +fn quantize(b: *common.Buffers, bytes: []const u8, n: u32, k: u32, bits: u8) !affine.Weights { + const group = 64; + const groups = k / group; + const per_row = k * bits / 32; + const words = try b.alloc(@as(usize, n) * per_row * 4); + const scales = try b.alloc(@as(usize, n) * groups * 2); + const biases = try b.alloc(@as(usize, n) * groups * 2); + const wq = words.slice(u32, @as(usize, n) * per_row); + const sq = scales.slice(u16, @as(usize, n) * groups); + const bq = biases.slice(u16, @as(usize, n) * groups); + @memset(wq, 0); + const levels: f32 = @floatFromInt((@as(u32, 1) << @intCast(bits)) - 1); + for (0..n) |r| for (0..groups) |g| { + var lo: f32 = std.math.inf(f32); + var hi: f32 = -std.math.inf(f32); + const base = r * k + g * group; + for (0..group) |i| { + const v = bf16Value(std.mem.readInt(u16, bytes[2 * (base + i) ..][0..2], .little)); + lo = @min(lo, v); + hi = @max(hi, v); + } + var scale = (hi - lo) / levels; + if (!(scale > 0)) scale = 1; + const s16 = bf16Round(scale); + const b16 = bf16Round(lo); + sq[r * groups + g] = s16; + bq[r * groups + g] = b16; + const sf = bf16Value(s16); + const bf = bf16Value(b16); + for (0..group) |i| { + const v = bf16Value(std.mem.readInt(u16, bytes[2 * (base + i) ..][0..2], .little)); + const code: u32 = @intFromFloat(std.math.clamp(@round((v - bf) / sf), 0, levels)); + const at = (g * group + i) * bits; + wq[r * per_row + at / 32] |= code << @intCast(at % 32); + } + }; + const out: affine.Weights = .{ .w = words, .scales = scales, .biases = biases, .n = n, .k = k, .bits = bits, .group = group }; + try out.validate(); + return out; +} + +const Linear = struct { + w: ?mtl.Buffer, + q: ?affine.Weights = null, + n: u32, + k: u32, + fn upload(b: *common.Buffers, t: @import("core").checkpoint_host.Tensor) !Linear { + const n: u32 = @intCast(t.shape[0]); + const k: u32 = @intCast(t.shape[1]); + if (try draftBits()) |bits| if (k % 512 == 0 and n % 8 == 0) { + if (quantize(b, t.bytes, n, k, bits)) |q| return .{ .w = null, .q = q, .n = n, .k = k } else |_| {} + }; + return .{ .w = try b.upload(t.bytes), .n = n, .k = k }; + } + fn run(p: Linear, kernels: *const common.Kernels, e: mtl.ComputeEncoder, x: Ref, y: Ref, rows: u32) !void { + if (p.q) |q| return kernels.project(e, q, x, y, rows); + try kernels.dense.linear(e, dr(x), .{ .buf = p.w.? }, dr(y), .{ + .rows = rows, + .n = p.n, + .k = p.k, + .x_stride = p.k, + .w_stride = p.k, + .y_stride = p.n, + }); + } +}; + +fn reference(b: mtl.Buffer) Ref { + return .{ .buffer = b }; +} + +fn dr(x: Ref) dense_ops.Ref { + return .{ .buf = x.buffer, .off = x.offset }; +} + +fn offset(x: Ref, words: usize) Ref { + return .{ .buffer = x.buffer, .offset = x.offset + words * @sizeOf(u16) }; +} + +const Feed = struct { gate: Linear, up: Linear, down: Linear }; + +pub const Block = struct { + target_kv: u32, + target_index: u32, + heads: u32, + rope: rope.Parameters, + norm: mtl.Buffer, + q_low: Linear, + q_norm: mtl.Buffer, + q_high: Linear, + kv: Linear, + kv_norm: mtl.Buffer, + wk: mtl.Buffer, + wv: mtl.Buffer, + gate: Linear, + o: Linear, + o_norm: mtl.Buffer, + sinks: mtl.Buffer, + mlp_norm: mtl.Buffer, + mlp: Feed, + + fn upload(b: *common.Buffers, host: *ck.Loaded, layer: u32) !Block { + var weights_ = try weights.DraftLayer.read(b.a, host, layer, .{ .rank = 0, .world = 1 }); + defer weights_.deinit(b.a); + const t = host.config.value.text_config; + const heads = weights_.heads.count; + return .{ + .target_kv = weights_.target_kv, + .target_index = weights_.target_index, + .heads = heads, + .rope = try t.rotary(t.layer_types[weights_.target_kv]), + .norm = try b.upload(weights_.input_norm.bytes), + .q_low = try Linear.upload(b, weights_.query_low), + .q_norm = try b.upload(weights_.query_norm.bytes), + .q_high = try Linear.upload(b, weights_.query_high), + .kv = try Linear.upload(b, weights_.kv_low), + .kv_norm = try b.upload(weights_.kv_norm.bytes), + .wk = try b.upload(std.mem.sliceAsBytes(weights_.absorbed.key)), + .wv = try b.upload(std.mem.sliceAsBytes(weights_.absorbed.value)), + .gate = try Linear.upload(b, weights_.gate), + .o = try Linear.upload(b, weights_.output), + .o_norm = try b.upload(weights_.output_norm.bytes), + .sinks = try b.upload(std.mem.sliceAsBytes(weights_.sinks[0..heads])), + .mlp_norm = try b.upload(weights_.mlp_norm.bytes), + .mlp = .{ + .gate = try Linear.upload(b, weights_.mlp.gate), + .up = try Linear.upload(b, weights_.mlp.up), + .down = try Linear.upload(b, weights_.mlp.down), + }, + }; + } +}; + +pub const Draft = struct { + own: common.Buffers, + blocks: []Block, + width: u32, + hidden: u32, + epsilon: f32, + anchor_norm: mtl.Buffer, + hidden_norm: mtl.Buffer, + fusion: Linear, + fusion_gate: mtl.Buffer, + final_norm: mtl.Buffer, + correct_hidden: mtl.Buffer, + correct_embed: mtl.Buffer, + correction: Feed, + fuse: mtl.Pipeline, + residual: mtl.Pipeline, + + pub fn open(a: std.mem.Allocator, d: mtl.Device, host: *ck.Loaded) !Draft { + var b: common.Buffers = .{ .a = a, .d = d }; + errdefer b.clear(); + const cfg = host.config.value; + const t = cfg.text_config; + const blocks = try a.alloc(Block, cfg.dfly_num_hidden_layers); + errdefer a.free(blocks); + for (blocks, 0..) |*layer, i| layer.* = try Block.upload(&b, host, @intCast(i)); + const w = try weights.DraftHead.read(host); + const lib = try mtl.Library.fromSource(d, source.hy4_flash_ihc, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var fuse = try mtl.Pipeline.init(d, lib, "tf_hy4_draft_fuse", false); + errdefer fuse.deinit(); + var out: Draft = .{ + .own = undefined, + .blocks = blocks, + .width = cfg.speculative_config.num_speculative_tokens + 1, + .hidden = t.hidden_size, + .epsilon = t.rms_norm_eps, + .anchor_norm = try b.upload(w.anchor_norm.bytes), + .hidden_norm = try b.upload(w.hidden_norm.bytes), + .fusion = try Linear.upload(&b, w.fusion), + .fusion_gate = try b.upload(w.fusion_gate.bytes), + .final_norm = try b.upload(w.norm.bytes), + .correct_hidden = try b.upload(w.correction_hidden_norm.bytes), + .correct_embed = try b.upload(w.correction_embedding_norm.bytes), + .correction = .{ + .gate = try Linear.upload(&b, w.correction.gate), + .up = try Linear.upload(&b, w.correction.up), + .down = try Linear.upload(&b, w.correction.down), + }, + .fuse = fuse, + .residual = try mtl.Pipeline.init(d, lib, "tf_hy4_draft_residual", false), + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Draft) void { + self.fuse.deinit(); + self.residual.deinit(); + self.own.a.free(self.blocks); + self.own.clear(); + } + + fn norm(self: *const Draft, ops: dense_ops.Ops, e: mtl.ComputeEncoder, x: Ref, gain: mtl.Buffer, y: Ref, rows: u32, dim: u32, xs: u32, ys: u32) !void { + try ops.norm(e, dr(x), .{ .buf = gain }, dr(y), .{ + .rows = rows, + .heads = 1, + .dim = dim, + .x_stride = xs, + .y_stride = ys, + .eps = self.epsilon, + }); + } + + fn add(self: *const Draft, e: mtl.ComputeEncoder, x: Ref, y: Ref, out: Ref, rows: u32, stride: u32) void { + e.setPipeline(self.residual); + for ([_]Ref{ x, y, out }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue([2]u32{ self.hidden, stride }, 3); + e.dispatchThreads(mtl.Size.of(self.hidden, rows, 1), mtl.Size.of(128, 1, 1)); + } + + fn mlp(kernels: *const common.Kernels, e: mtl.ComputeEncoder, w: Feed, temp: *const common.Scratch, x: Ref, y: Ref, rows: u32) !void { + const ops = kernels.dense; + const n = w.gate.n; + if (n > temp.inner_capacity) return error.ShortHy4Scratch; + try w.gate.run(kernels, e, x, temp.gate, rows); + try w.up.run(kernels, e, x, temp.up, rows); + e.barrier(); + try ops.swiglu(e, dr(temp.gate), dr(temp.up), dr(temp.inner), .{ + .rows = rows, + .width = n, + .gate_stride = n, + .up_stride = n, + .y_stride = n, + }); + e.barrier(); + try w.down.run(kernels, e, temp.inner, y, rows); + } + + pub fn encode(self: *const Draft, target: *const model.Model, e: mtl.ComputeEncoder, s: *Frame, ids: Ref, anchors: Ref, lanes: u32, caches: []const model.LayerCache) !void { + s.lanes = 0; + if (lanes == 0 or lanes > s.capacity or caches.len != self.blocks.len) return error.BadHy4DraftFrame; + const begin = s.streams[0]; + const rows = lanes * self.width; + const h = self.hidden; + const ops = target.common.dense; + target.embedRows(e, ids, begin, rows); + try self.norm(ops, e, anchors, self.hidden_norm, offset(s.concat, h), lanes, h, h, 2 * h); + e.barrier(); + try self.norm(ops, e, begin, self.anchor_norm, s.concat, lanes, h, self.width * h, 2 * h); + e.barrier(); + try self.fusion.run(&target.common, e, s.concat, s.delta, lanes); + e.barrier(); + e.setPipeline(self.fuse); + e.setBuffer(begin.buffer, begin.offset, 0); + e.setBuffer(s.delta.buffer, s.delta.offset, 1); + e.setBuffer(self.fusion_gate, 0, 2); + e.setValue([2]u32{ h, self.width }, 3); + e.dispatchThreads(mtl.Size.of(h, lanes, 1), mtl.Size.of(128, 1, 1)); + e.barrier(); + var x = begin; + var y = s.streams[1]; + for (self.blocks, caches) |block, cache| { + try s.common.bind(rows, block.heads, cache.key_stride); + try self.encodeBlock(target, e, block, s, cache.rows, x, y); + e.barrier(); + std.mem.swap(Ref, &x, &y); + } + try self.norm(ops, e, x, self.final_norm, s.normalized, rows, h, h, h); + s.lanes = lanes; + } + + fn encodeBlock(self: *const Draft, target: *const model.Model, e: mtl.ComputeEncoder, w: Block, s: *const Frame, cache: common.CacheRows, x: Ref, y: Ref) !void { + const ops = target.common.dense; + const v = &s.common; + const rows = v.shape.rows; + const h = self.hidden; + try self.norm(ops, e, x, w.norm, v.normalized, rows, h, h, h); + e.barrier(); + try w.q_low.run(&target.common, e, v.normalized, v.query_a, rows); + try w.kv.run(&target.common, e, v.normalized, v.kv, rows); + try w.gate.run(&target.common, e, v.normalized, v.value_logits, rows); + e.barrier(); + try self.norm(ops, e, v.query_a, w.q_norm, v.query_norm, rows, w.q_low.n, w.q_low.n, w.q_low.n); + e.barrier(); + try w.q_high.run(&target.common, e, v.query_norm, v.query, rows); + e.barrier(); + try mla.forward(target.common.projections, target.common.attention, e, .{ + .query = v.query, + .key_weights = reference(w.wk), + .value_weights = reference(w.wv), + .value_logits = v.value_logits, + .positions = cache.positions, + .rotary_table = v.rotary, + .values = v.values, + .kv = .{ .projection = v.kv, .gain = reference(w.kv_norm), .write_slots = cache.write_slots, .capacity = cache.capacity, .epsilon = self.epsilon }, + .attention = .{ + .query = v.absorbed, + .cache = cache.cache, + .slots = cache.retained, + .counts = cache.counts, + .sinks = reference(w.sinks), + .scratch = v.attention, + .output = v.latent, + .key_scores = v.key_scores, + }, + }, v.shape, w.rope); + e.barrier(); + try w.o.run(&target.common, e, v.values, v.branch, rows); + e.barrier(); + try self.norm(ops, e, v.branch, w.o_norm, v.normalized, rows, h, h, h); + e.barrier(); + self.add(e, x, v.normalized, s.after_attention, rows, h); + e.barrier(); + try self.norm(ops, e, s.after_attention, w.mlp_norm, v.normalized, rows, h, h, h); + e.barrier(); + try mlp(&target.common, e, w.mlp, v, v.normalized, v.branch, rows); + e.barrier(); + self.add(e, s.after_attention, v.branch, y, rows, h); + } + + /// Apply the hidden correction at the chosen draft column with the previous proposal's token. + pub fn next(self: *const Draft, target: *const model.Model, e: mtl.ComputeEncoder, s: *const Frame, previous: Ref, column: u32) !Ref { + if (column == 0 or column >= self.width or s.lanes == 0) return error.BadHy4DraftColumn; + const ops = target.common.dense; + const rows = s.lanes; + const h = self.hidden; + const draft = offset(s.normalized, @as(usize, column) * h); + target.embedRows(e, previous, s.previous, rows); + try self.norm(ops, e, draft, self.correct_hidden, s.concat, rows, h, h * self.width, 2 * h); + e.barrier(); + try self.norm(ops, e, s.previous, self.correct_embed, offset(s.concat, h), rows, h, h, 2 * h); + e.barrier(); + try mlp(&target.common, e, self.correction, &s.common, s.concat, s.delta, rows); + e.barrier(); + self.add(e, draft, s.delta, s.previous, rows, h * self.width); + e.barrier(); + try target.readout(e, s.previous, s.logits, rows); + return s.logits; + } +}; + +pub const Frame = struct { + own: common.Buffers, + capacity: u32, + lanes: u32 = 0, + common: common.Scratch, + streams: [2]Ref, + concat: Ref, + delta: Ref, + normalized: Ref, + after_attention: Ref, + previous: Ref, + logits: Ref, + + pub fn init(a: std.mem.Allocator, d: mtl.Device, target: *const model.Model, draft: *const Draft, lanes: u32, keys: u32) !Frame { + if (lanes == 0 or draft.blocks.len == 0) return error.BadHy4DraftFrame; + const rows = try std.math.mul(u32, lanes, draft.width); + const h = draft.hidden; + const t = target.host.config.value.text_config; + var max_inner = draft.correction.gate.n; + var max_heads: u32 = 0; + var target_layer: u32 = 0; + for (draft.blocks) |block| { + max_inner = @max(max_inner, block.mlp.gate.n); + if (block.heads > max_heads) { + max_heads = block.heads; + target_layer = block.target_kv; + } + } + var temp = try common.Scratch.init(a, d, &target.blocks[target_layer].attention, max_inner, keys, rows); + errdefer temp.deinit(); + var b: common.Buffers = .{ .a = a, .d = d }; + errdefer b.clear(); + var out: Frame = .{ + .own = undefined, + .capacity = lanes, + .common = temp, + .streams = .{ try b.rows(rows, h), try b.rows(rows, h) }, + .concat = try b.rows(lanes, 2 * h), + .delta = try b.rows(lanes, h), + .normalized = try b.rows(rows, h), + .after_attention = try b.rows(rows, h), + .previous = try b.rows(lanes, h), + .logits = try b.rows(lanes, t.vocab_size), + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Frame) void { + self.common.deinit(); + self.own.clear(); + } +}; diff --git a/zig/src/families/hy4_flash/metal_engram.zig b/zig/src/families/hy4_flash/metal_engram.zig new file mode 100644 index 00000000000..cebdf742c68 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_engram.zig @@ -0,0 +1,209 @@ +//! Metal Engram weights and apply pass. The large lookup table stays in the checkpoint mapping. +const std = @import("std"); +const core = @import("core"); +const mtl = @import("metal"); +const affine = @import("../../core/row_projection.zig"); +const sources = @import("kernel_sources"); +const common = @import("metal_dense.zig"); +const engram = @import("engram.zig"); +const row_table = @import("engram_rows.zig"); +const weights = @import("model_weights.zig"); +const ihc = @import("ihc.zig"); + +const Ref = common.Ref; +const width = 96; + +/// Where the n-gram tables live (TF_HY4_ENGRAM) +pub const Placement = enum { nvme, ram, gpu }; + +pub fn placement() !Placement { + return @fromBackingInt(@intCast(try @import("sys").environment.read(u32, "TF_HY4_ENGRAM", 0))); +} + +pub const Layer = struct { + own: common.Buffers, + table: row_table.Table, + /// The tables in memory of ours (ram or gpu placement). + resident: ?struct { words: mtl.Buffer, scales: mtl.Buffer, biases: mtl.Buffer, gpu: bool } = null, + lookup_gamma: mtl.Buffer, + key: [ihc.streams]common.Linear, + key_bias: mtl.Buffer, + key_gain: mtl.Buffer, + query_gain: mtl.Buffer, + delta_gain: mtl.Buffer, + value: common.Linear, + value_bias: mtl.Buffer, + value_gain: mtl.Buffer, + fp8: bool, + hidden: u32, + + pub fn upload(a: std.mem.Allocator, d: mtl.Device, w: *const weights.Engram, hidden: u32, fp8: bool) !Layer { + return uploadForModel(a, d, w, hidden, fp8, false); + } + + pub fn uploadForModel(a: std.mem.Allocator, d: mtl.Device, w: *const weights.Engram, hidden: u32, fp8: bool, use_tensors: bool) !Layer { + if (w.table.width != width or hidden == 0) return error.BadHy4EngramShape; + var b: common.Buffers = .{ .a = a, .d = d }; + errdefer b.clear(); + var out: Layer = .{ + .own = undefined, + .table = w.table, + .lookup_gamma = try concatenate(&b, &w.lookup_norm), + .key = undefined, + .key_bias = undefined, + .key_gain = undefined, + .query_gain = undefined, + .delta_gain = undefined, + .value = try b.linear(w.value, use_tensors), + .value_bias = try b.upload(w.value_bias.bytes), + .value_gain = try b.upload(w.pre_gamma.bytes), + .fp8 = fp8, + .hidden = hidden, + }; + switch (try placement()) { + .nvme => {}, + .ram, .gpu => |where| { + const t = &out.table.affine; + const words = try b.upload(t.words.bytes); + const scales = try b.upload(t.scales.bytes); + const biases = try b.upload(t.biases.bytes); + // the host's gather reads the copies from here on + t.words.bytes = words.slice(u8, t.words.bytes.len); + t.scales.bytes = scales.slice(u8, t.scales.bytes.len); + t.biases.bytes = biases.slice(u8, t.biases.bytes.len); + out.resident = .{ .words = words, .scales = scales, .biases = biases, .gpu = where == .gpu }; + }, + } + for (&out.key, w.key) |*dst, src| dst.* = try b.linear(src.key, use_tensors); + inline for (.{ "key_bias", "key_gain", "query_gain", "delta_gain" }, .{ "bias", "key_norm", "query_norm", "residual_scale" }) |dst, field| { + var tensors: [ihc.streams]core.checkpoint_host.Tensor = undefined; + for (&tensors, w.key) |*tensor, src| tensor.* = @field(src, field); + @field(out, dst) = try concatenate(&b, &tensors); + } + out.own = b; + return out; + } + + pub fn deinit(self: *Layer) void { + self.own.clear(); + self.* = undefined; + } +}; + +fn concatenate(b: *common.Buffers, weights_: []const core.checkpoint_host.Tensor) !mtl.Buffer { + const size = weights_[0].bytes.len; + const result = try b.alloc(size * weights_.len); + const bytes = result.slice(u8, size * weights_.len); + for (weights_, 0..) |tensor, i| @memcpy(bytes[i * size ..][0..size], tensor.bytes); + return result; +} + +pub const Scratch = struct { + own: common.Buffers, + capacity: u32, + raw: Ref, + normalized: Ref, + keys: Ref, + value: Ref, + media_mask: Ref, + /// Table rows a token and column, for the GPU gather. + table_rows: Ref, + + pub fn init(a: std.mem.Allocator, d: mtl.Device, capacity: u32, hidden: u32) !Scratch { + if (capacity == 0 or hidden == 0) return error.BadHy4EngramShape; + var b: common.Buffers = .{ .a = a, .d = d }; + errdefer b.clear(); + var out: Scratch = .{ + .own = undefined, + .capacity = capacity, + .raw = try b.rows(capacity, engram.columns * width), + .normalized = try b.rows(capacity, engram.columns * width), + .keys = try b.rows(capacity, ihc.streams * hidden), + .value = try b.rows(capacity, hidden), + .media_mask = .{ .buffer = try b.alloc(@as(usize, capacity) * @sizeOf(u32)) }, + .table_rows = .{ .buffer = try b.alloc(@as(usize, capacity) * engram.columns * @sizeOf(u32)) }, + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Scratch) void { + self.own.clear(); + self.* = undefined; + } + + /// Windows come from committed or speculative lane token history. A media row leaves its hidden streams untouched. + pub fn stage(self: *const Scratch, a: std.mem.Allocator, layer: *const Layer, windows: []const [engram.order]u32, media: []const u32) !void { + if (windows.len == 0 or windows.len > self.capacity or windows.len != media.len) return error.BadHy4EngramRows; + const cells = windows.len * engram.columns * width; + if (layer.resident) |r| if (r.gpu) { + const out = self.table_rows.buffer.slice(u32, windows.len * engram.columns); + for (windows, 0..) |window, t| out[t * engram.columns ..][0..engram.columns].* = layer.table.windowRows(window); + @memcpy(self.media_mask.buffer.slice(u32, media.len), media); + return; + }; + try layer.table.gather(a, windows, self.raw.buffer.slice(u16, cells)); + @memcpy(self.media_mask.buffer.slice(u32, media.len), media); + } +}; + +pub const Kernels = struct { + lookup: mtl.Pipeline, + apply: mtl.Pipeline, + gather: mtl.Pipeline, + + pub fn load(d: mtl.Device) !Kernels { + const library = try mtl.Library.fromSource(d, sources.hy4_flash_engram, mtl.CompileOptions.mlx()); + defer library.deinit(); + var lookup = try mtl.Pipeline.init(d, library, "tf_hy4_engram_lookup", false); + errdefer lookup.deinit(); + var apply = try mtl.Pipeline.init(d, library, "tf_hy4_engram_apply", false); + errdefer apply.deinit(); + return .{ .lookup = lookup, .apply = apply, .gather = try mtl.Pipeline.init(d, library, "tf_hy4_engram_gather", false) }; + } + + pub fn deinit(self: *Kernels) void { + self.lookup.deinit(); + self.apply.deinit(); + self.gather.deinit(); + } + + pub fn forward(self: Kernels, ops: *const common.Kernels, e: mtl.ComputeEncoder, w: *const Layer, s: *const Scratch, x: Ref, output: Ref, rows: u32) !void { + if (rows == 0 or rows > s.capacity) return error.BadHy4EngramRows; + if (w.resident) |r| if (r.gpu) { + const cells: u32 = rows * engram.columns * width; + e.setPipeline(self.gather); + e.setBuffer(r.words, 0, 0); + e.setBuffer(r.scales, 0, 1); + e.setBuffer(r.biases, 0, 2); + e.setBuffer(s.table_rows.buffer, 0, 3); + e.setBuffer(s.raw.buffer, 0, 4); + e.setValue([2]u32{ w.table.affine.bits, cells }, 5); + e.dispatchThreads(mtl.Size.of(cells, 1, 1), mtl.Size.of(256, 1, 1)); + e.barrier(); + }; + e.setPipeline(self.lookup); + e.setBuffer(s.raw.buffer, 0, 0); + e.setBuffer(w.lookup_gamma, 0, 1); + e.setBuffer(s.normalized.buffer, 0, 2); + e.setValue(@as(u32, @intFromBool(w.fp8)), 3); + e.dispatchGroups(mtl.Size.of(engram.columns, rows, 1), mtl.Size.of(32, 1, 1)); + e.barrier(); + var outs: [1 + ihc.streams]common.Kernels.Out = undefined; + outs[0] = .{ .w = w.value, .y = s.value }; + for (w.key, 0..) |projection, i| { + outs[1 + i] = .{ .w = projection, .y = .{ .buffer = s.keys.buffer, .offset = i * rows * w.hidden * @sizeOf(u16) } }; + } + try ops.linearsFrom(e, s.normalized, &outs, rows); + e.barrier(); + e.setPipeline(self.apply); + const buffers = [_]Ref{ + x, s.keys, .{ .buffer = w.key_bias }, .{ .buffer = w.key_gain }, .{ .buffer = w.query_gain }, + .{ .buffer = w.delta_gain }, s.value, .{ .buffer = w.value_bias }, .{ .buffer = w.value_gain }, s.media_mask, + output, + }; + for (buffers, 0..) |b, i| e.setBuffer(b.buffer, b.offset, i); + e.setValue([2]u32{ rows, w.hidden }, buffers.len); + e.dispatchGroups(mtl.Size.of(ihc.streams, rows, 1), mtl.Size.of(128, 1, 1)); + } +}; diff --git a/zig/src/families/hy4_flash/metal_index.zig b/zig/src/families/hy4_flash/metal_index.zig new file mode 100644 index 00000000000..620bcee4158 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_index.zig @@ -0,0 +1,232 @@ +//! Hy4-flash's compressed sparse indexer on Metal, after the reference's CompressedIndexer +const std = @import("std"); +const mtl = @import("metal"); +const source = @import("kernel_sources"); +const dense = @import("metal_dense.zig"); +const mla_gpu = @import("mla_metal.zig"); +const rope = @import("rope.zig"); +const weights = @import("model_weights.zig"); +const recall = @import("index_recall.zig"); + +pub const Ref = dense.Ref; +pub const heads = recall.heads; +pub const width = recall.width; +/// group_topk: 511 closed groups and the query's own. +pub const budget_groups: u32 = 512; +/// A row's recalled key list: 512 groups of four slots. +pub const keys_a_row: u32 = budget_groups * 4; + +pub const Weights = struct { + token_keys: dense.Linear, + token_norm: mtl.Buffer, + query: dense.Linear, + head_weights: dense.Linear, + values: mtl.Buffer, + gates: mtl.Buffer, + bias: mtl.Buffer, + norm: mtl.Buffer, + + /// The projections take the row kernels: the tensor units' packings exist only for the layers' own shapes. + pub fn upload(b: *dense.Buffers, w: *const weights.Index, tensors: bool) !Weights { + _ = tensors; + return .{ + .token_keys = try b.linear(w.token_keys, false), + .token_norm = try b.upload(w.token_norm.bytes), + .query = try b.linear(w.query, false), + .head_weights = try b.linear(w.head_weights, false), + .values = try b.upload(w.group_values.bytes), + .gates = try b.upload(w.group_gates.bytes), + .bias = try b.upload(w.group_bias.bytes), + .norm = try b.upload(w.group_norm.bytes), + }; + } +}; + +pub const Kernels = struct { + keys: mtl.Pipeline, + groups: mtl.Pipeline, + score: mtl.Pipeline, + select: mtl.Pipeline, + + pub fn load(device: mtl.Device) !Kernels { + const build = try mtl.Library.fromSource(device, source.hy4_flash_index_build, mtl.CompileOptions.mlx()); + defer build.deinit(); + const rec = try mtl.Library.fromSource(device, source.hy4_flash_index_recall, mtl.CompileOptions.mlx()); + defer rec.deinit(); + var keys = try mtl.Pipeline.init(device, build, "tf_hy4_index_keys", false); + errdefer keys.deinit(); + var groups = try mtl.Pipeline.init(device, build, "tf_hy4_index_groups", false); + errdefer groups.deinit(); + var score = try mtl.Pipeline.init(device, rec, "tf_hy4_group_scores", false); + errdefer score.deinit(); + return .{ .keys = keys, .groups = groups, .score = score, .select = try mtl.Pipeline.init(device, rec, "tf_hy4_recall_groups", false) }; + } + + pub fn deinit(self: *Kernels) void { + self.keys.deinit(); + self.groups.deinit(); + self.score.deinit(); + self.select.deinit(); + } +}; + +/// A pass's indexer rows: each row's projections, and the groups it touches with their rotary positions. +pub const Scratch = struct { + own: dense.Buffers, + capacity: u32, + keys: Ref, + query: Ref, + head_weights: Ref, + recall_rows: mtl.Buffer, + group_positions: mtl.Buffer, + group_table: Ref, + first: u32 = 0, + rows: u32 = 0, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, rows: u32) !Scratch { + var b: dense.Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + const groups = rows / 4 + 2; + var out: Scratch = .{ + .own = undefined, + .capacity = rows, + .keys = try b.rows(rows, width), + .query = try b.rows(rows, heads * width), + .head_weights = try b.rows(rows, heads), + .recall_rows = try b.alloc(@as(usize, rows) * @sizeOf(recall.Row)), + .group_positions = try b.alloc(@as(usize, groups) * 3 * @sizeOf(i32)), + .group_table = try b.rows(groups, 2 * rope.pairs), + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Scratch) void { + self.own.clear(); + self.* = undefined; + } + + /// The pass's rows sit at positions first.. (consecutive); call before encoding, after the previous pass completed. + pub fn stage(self: *Scratch, first: u32, rows: u32) !void { + if (rows == 0 or rows > self.capacity) return error.BadHy4IndexRows; + self.first = first; + self.rows = rows; + const r = self.recall_rows.slice(recall.Row, rows); + for (r, 0..) |*row, i| row.* = .{ .group_base = 0, .token = first + @as(u32, @intCast(i)) }; + const g0 = first / 4; + const count = (first + rows - 1) / 4 - g0 + 1; + const pos = self.group_positions.slice(i32, count * 3); + for (0..count) |g| pos[g * 3 ..][0..3].* = @splat(@intCast((g0 + g) * 4)); + } + + pub fn groupRange(self: *const Scratch) [2]u32 { + const g0 = self.first / 4; + return .{ g0, (self.first + self.rows - 1) / 4 - g0 + 1 }; + } + + /// Whether any row's attention takes recalled lists: a row at 2,048 or past has more closed groups than it keeps. + pub fn selects(self: *const Scratch) bool { + return self.first + self.rows - 1 >= keys_a_row; + } +}; + +/// A sparse layer's indexer state for one stream, and the pass's shared score rows and this layer's key lists. +pub const Cache = struct { + token_keys: Ref, // [capacity][128] BF16 + group_keys: Ref, // [capacity / 4][128] BF16, RoPE'd at each group's first slot + capacity: u32, // slots (a multiple of 4) + scores: Ref, // [rows][score_groups] fp32, shared by every layer of a pass + score_groups: u32, + tokens: Ref, // [rows][2048] i32: each row's recalled slots, this layer's (the drafter reads the anchor's) + counts: Ref, // [rows] i32 + + pub fn tokenBytes(capacity: u32) usize { + return @as(usize, capacity) * width * 2; + } + + pub fn groupBytes(capacity: u32) usize { + return @as(usize, capacity / 4) * width * 2; + } +}; + +/// What attendSeam needs to run a sparse layer's indexer. +pub const Pass = struct { + kernels: *const Kernels, + scratch: *const Scratch, + cache: Cache, +}; + +const KeysArgs = extern struct { rows: u32, capacity: u32, epsilon: f32 }; +const GroupArgs = extern struct { first: u32, count: u32, capacity_groups: u32, epsilon: f32 }; +const RecallShape = extern struct { rows: u32, score_groups: u32, group_budget: u32 }; + +/// The indexer for the staged rows: `normalized` is the layer's input (the reference's hidden_states) +pub fn run(p: Pass, common: *const dense.Kernels, project: mla_gpu.Projections, e: mtl.ComputeEncoder, w: *const Weights, normalized: Ref, q_resid: Ref, write_slots: Ref, positions: Ref, table: Ref, r: rope.Parameters, epsilon: f32) !void { + encode(p, common, project, e, w, normalized, q_resid, write_slots, positions, table, r, epsilon) catch |err| { + std.log.err("hy4 indexer: {s}", .{@errorName(err)}); + return err; + }; +} + +fn encode(p: Pass, common: *const dense.Kernels, project: mla_gpu.Projections, e: mtl.ComputeEncoder, w: *const Weights, normalized: Ref, q_resid: Ref, write_slots: Ref, positions: Ref, table: Ref, r: rope.Parameters, epsilon: f32) !void { + const k = p.kernels; + const s = p.scratch; + const c = p.cache; + const rows = s.rows; + if (rows == 0) return error.BadHy4IndexRows; + const range = s.groupRange(); + if ((range[0] + range[1]) * 4 > c.capacity) return error.Hy4IndexPastCapacity; + // the projections, and both rotary tables (positions only) + try common.linear(e, w.token_keys, normalized, s.keys, rows); + try common.linear(e, w.head_weights, normalized, s.head_weights, rows); + try common.linear(e, w.query, q_resid, s.query, rows); + project.rotaryTable(e, positions, table, rows, r); + project.rotaryTable(e, .{ .buffer = s.group_positions }, s.group_table, range[1], r); + e.barrier(); + // each row's normalized key at its slot; the query heads' trailing 64 channels rotated in place + e.setPipeline(k.keys); + e.setBuffer(s.keys.buffer, s.keys.offset, 0); + e.setBuffer(w.token_norm, 0, 1); + e.setBuffer(write_slots.buffer, write_slots.offset, 2); + e.setBuffer(c.token_keys.buffer, c.token_keys.offset, 3); + e.setValue(KeysArgs{ .rows = rows, .capacity = c.capacity, .epsilon = epsilon }, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(width, 1, 1)); + const q_rot: Ref = .{ .buffer = s.query.buffer, .offset = s.query.offset + (width - 2 * rope.pairs) * 2 }; + try project.rotate(e, q_rot, table, q_rot, .{ .rows = rows, .heads = heads, .input_stride = width, .output_stride = width }); + e.barrier(); + // the touched groups pooled from the cached keys + e.setPipeline(k.groups); + e.setBuffer(c.token_keys.buffer, c.token_keys.offset, 0); + e.setBuffer(w.values, 0, 1); + e.setBuffer(w.gates, 0, 2); + e.setBuffer(w.bias, 0, 3); + e.setBuffer(w.norm, 0, 4); + e.setBuffer(c.group_keys.buffer, c.group_keys.offset, 5); + e.setValue(GroupArgs{ .first = range[0], .count = range[1], .capacity_groups = c.capacity / 4, .epsilon = epsilon }, 6); + e.dispatchGroups(mtl.Size.of(range[1], 1, 1), mtl.Size.of(width, 1, 1)); + e.barrier(); + const g_rot: Ref = .{ .buffer = c.group_keys.buffer, .offset = c.group_keys.offset + (@as(usize, range[0]) * width + width - 2 * rope.pairs) * 2 }; + try project.rotate(e, g_rot, s.group_table, g_rot, .{ .rows = range[1], .heads = 1, .input_stride = width, .output_stride = width }); + if (!s.selects()) return; + e.barrier(); + const last = s.first + rows - 1; + const shape: RecallShape = .{ .rows = rows, .score_groups = c.score_groups, .group_budget = budget_groups }; + if (last / 4 > c.score_groups) return error.Hy4IndexPastCapacity; + e.setPipeline(k.score); + e.setBuffer(s.query.buffer, s.query.offset, 0); + e.setBuffer(c.group_keys.buffer, c.group_keys.offset, 1); + e.setBuffer(s.head_weights.buffer, s.head_weights.offset, 2); + e.setBuffer(s.recall_rows, 0, 3); + e.setBuffer(c.scores.buffer, c.scores.offset, 4); + e.setValue(shape, 5); + e.setValue(recall.head_scale, 6); + e.dispatchGroups(mtl.Size.of((last / 4 + 3) / 4, rows, 1), mtl.Size.of(128, 1, 1)); + e.barrier(); + e.setPipeline(k.select); + e.setBuffer(c.scores.buffer, c.scores.offset, 0); + e.setBuffer(s.recall_rows, 0, 1); + e.setBuffer(c.tokens.buffer, c.tokens.offset, 2); + e.setBuffer(c.counts.buffer, c.counts.offset, 3); + e.setValue(shape, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); +} diff --git a/zig/src/families/hy4_flash/metal_linears.zig b/zig/src/families/hy4_flash/metal_linears.zig new file mode 100644 index 00000000000..e08cc543819 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_linears.zig @@ -0,0 +1,124 @@ +//! Hy4-flash's dense projection kernels: the tensor units' lane projections by shape, and the row kernels. +const std = @import("std"); +const mtl = @import("metal"); +const affine = @import("../../core/row_projection.zig"); +const cfg = @import("config.zig"); +const ihc = @import("ihc.zig"); +const ihc_gpu = @import("ihc_metal.zig"); +const mla_gpu = @import("mla_metal.zig"); +const mha = @import("mla_attention.zig"); +const shape_ = @import("mla_weights.zig"); +const gpu_qkv = @import("metal_tensor_qkv.zig"); +const lane = @import("../../core/lane_projection.zig"); +const dense = @import("metal_dense.zig"); +const Buffers = dense.Buffers; +const Ref = dense.Ref; +const Attention = dense.Attention; + +/// The lane projections for every dense shape a model has, made once at load +pub const Linears = struct { + shapes: [16][2]u32 = undefined, + projections: [16]lane.Projection = undefined, + /// The same projections adding their own group sums (4-bit reg layouts), for small passes. + inlines: [16]?lane.Projection = @splat(null), + count: usize = 0, + sums: ?mtl.Buffer = null, + pub const sum_rows = gpu_qkv.prompt_rows; + + pub fn load(a: std.mem.Allocator, device: mtl.Device, t: cfg.Text, bits: u8) !Linears { + var out: Linears = .{}; + errdefer out.deinit(); + const v = shape_.value_width; + const wanted = [_][2]u32{ + .{ t.hidden_size, t.swa_num_attention_heads * v }, + .{ t.hidden_size, t.num_attention_heads * v }, + .{ t.routed_expert_hidden_size, t.hidden_size }, + .{ t.moe_intermediate_size * t.n_shared_experts, t.hidden_size }, + .{ t.hidden_size, t.routed_expert_hidden_size }, + .{ t.hidden_size, t.moe_intermediate_size * t.n_shared_experts }, + .{ t.intermediate_size, t.hidden_size }, + .{ t.hidden_size, t.intermediate_size }, + .{ t.vocab_size, t.hidden_size }, + // Engram's value and stream keys over a lookup row: every column's slice of the n-gram embedding + .{ t.hidden_size, @import("engram.zig").columns * (t.engram_n_embed_per_ngram / @import("engram.zig").heads) }, + }; + var groups: usize = 0; + for (wanted) |nk| { + if (out.find(nk[0], nk[1]) != null or nk[0] % 32 != 0) continue; + out.projections[out.count] = try lane.Projection.init(a, device, gpu_qkv.denseLayout(bits, nk[0], nk[1])); + out.inlines[out.count] = if (gpu_qkv.withInlineSums(gpu_qkv.denseLayout(bits, nk[0], nk[1]))) |l| try lane.Projection.init(a, device, l) else null; + out.shapes[out.count] = nk; + out.count += 1; + groups = @max(groups, nk[1] / 64); + } + out.sums = try device.buffer(sum_rows * groups * 4, mtl.ResourceOptions.shared); + return out; + } + + pub fn deinit(self: *Linears) void { + for (self.projections[0..self.count]) |p| p.deinit(); + for (self.inlines[0..self.count]) |p| if (p) |x| x.deinit(); + if (self.sums) |b| b.deinit(); + self.count = 0; + } + + pub fn find(self: *const Linears, n: u32, k: u32) ?*const lane.Projection { + for (self.shapes[0..self.count], self.projections[0..self.count]) |nk, *p| if (nk[0] == n and nk[1] == k) return p; + return null; + } + + pub fn findInline(self: *const Linears, n: u32, k: u32) ?*const lane.Projection { + for (self.shapes[0..self.count], self.inlines[0..self.count]) |nk, *p| if (nk[0] == n and nk[1] == k) if (p.*) |*x| return x; + return null; + } +}; + +/// The row kernels for 2-8 row passes of portable weights +pub const Rows = struct { + q4: mtl.Pipeline, + q8: mtl.Pipeline, + rps: u32 = 2, + /// Greedy tokens on the GPU (first index of the largest logit), so draft columns chain without the host. + argmax: mtl.Pipeline, + + pub fn load(a: std.mem.Allocator, device: mtl.Device) !Rows { + // rows.metal builds on the wide core's tf_rp_rows on every chip, so every chip computes the same bits + const text = try std.mem.concat(a, u8, &.{ affine.source(true), @import("kernel_sources").hy4_flash_rows }); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var q4 = try mtl.Pipeline.init(device, lib, "tf_hy4_rows_r2_q4", false); + errdefer q4.deinit(); + var q8 = try mtl.Pipeline.init(device, lib, "tf_hy4_rows_r2_q8", false); + errdefer q8.deinit(); + return .{ .q4 = q4, .q8 = q8, .argmax = try mtl.Pipeline.init(device, lib, "tf_hy4_argmax", false) }; + } + + pub fn deinit(self: Rows) void { + self.q4.deinit(); + self.q8.deinit(); + self.argmax.deinit(); + } + + /// out[at + r] = the greedy token of logits row r, for `rows` rows of `vocab`. + pub fn pick(self: Rows, e: mtl.ComputeEncoder, logits: Ref, out: Ref, at: u32, rows: u32, vocab: u32) void { + e.setPipeline(self.argmax); + e.setBuffer(logits.buffer, logits.offset, 0); + e.setBuffer(out.buffer, out.offset, 1); + e.setValue([2]u32{ vocab, at }, 2); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(1024, 1, 1)); + } + + pub fn sg(self: Rows) u32 { + return if (self.rps == 1) 8 else 4; + } + + pub fn choose(self: Rows, w: affine.Weights, rows: u32) ?mtl.Pipeline { + if (rows < 2 or w.sum != .f32 or w.n % (self.rps * self.sg()) != 0) return null; + return switch (w.bits) { + 4 => self.q4, + 8 => self.q8, + else => null, + }; + } +}; diff --git a/zig/src/families/hy4_flash/metal_model.zig b/zig/src/families/hy4_flash/metal_model.zig new file mode 100644 index 00000000000..936cbdda962 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_model.zig @@ -0,0 +1,312 @@ +//! The Metal target graph. Lane-owned cache buffers and retained slots are supplied for each layer. +const std = @import("std"); +const mtl = @import("metal"); +const source = @import("kernel_sources"); +const aff = @import("../../core/row_projection.zig"); +const load = @import("loader.zig"); +const weights = @import("model_weights.zig"); +const dense = @import("metal_dense.zig"); +const routed = @import("metal_routed.zig"); +const memory = @import("metal_engram.zig"); +const engram = @import("engram.zig"); +const ihc = @import("ihc.zig"); +const index = @import("metal_index.zig"); + +pub const Ref = dense.Ref; + +const Block = struct { + attention: dense.Attention, + feed: union(enum) { dense: dense.Feed, routed: routed.Layer }, + memory: ?memory.Layer, + + fn upload(a: std.mem.Allocator, device: mtl.Device, host: *load.Loaded, i: u32, use_tensors: bool) !Block { + const config = host.config.value.text_config; + var w = try weights.TargetLayer.read(a, host, i, .{ .rank = 0, .world = 1 }, 1); + defer w.deinit(a); + var attention = try dense.Attention.uploadForModel(a, device, &w, config, use_tensors); + errdefer attention.deinit(); + var mem = if (w.memory) |*v| try memory.Layer.uploadForModel(a, device, v, config.hidden_size, config.engram_fp8_embedding, use_tensors) else null; + errdefer if (mem) |*v| v.deinit(); + return .{ + .attention = attention, + .feed = switch (w.feed) { + .dense => .{ .dense = try dense.Feed.uploadForModel(a, device, &w, use_tensors) }, + .routed => .{ .routed = try routed.Layer.uploadForModel(a, device, &w, config, use_tensors) }, + }, + .memory = mem, + }; + } + + fn deinit(self: *Block) void { + if (self.memory) |*v| v.deinit(); + switch (self.feed) { + inline else => |*v| v.deinit(), + } + self.attention.deinit(); + } +}; + +const Head = struct { + owned: dense.Buffers, + embedding: aff.Weights, + vocab: dense.Linear, + norm: mtl.Buffer, + merge: dense.Merge, + lookup: mtl.Pipeline, + + fn upload(a: std.mem.Allocator, device: mtl.Device, w: weights.Head, tensors: bool) !Head { + var b: dense.Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + const lib = try mtl.Library.fromSource(device, source.embed_norm, mtl.CompileOptions.mlx()); + defer lib.deinit(); + const name: [:0]const u8 = switch (w.embedding.bits) { + 4 => "tf_embed_b4_g64", + 8 => "tf_embed_b8_g64", + else => return error.BadHy4EmbedBits, + }; + var out: Head = .{ + .owned = undefined, + .embedding = try b.matrix(w.embedding), + .vocab = try b.linear(w.lm_head, tensors), + .norm = try b.upload(w.norm.bytes), + .merge = try dense.Merge.upload(&b, w.merge), + .lookup = try mtl.Pipeline.init(device, lib, name, false), + }; + out.owned = b; + return out; + } + + fn deinit(self: *Head) void { + self.lookup.deinit(); + self.owned.clear(); + } + + fn embed(self: Head, e: mtl.ComputeEncoder, ids: Ref, out: Ref, rows: u32) void { + const w = self.embedding; + e.setPipeline(self.lookup); + e.setBuffer(ids.buffer, ids.offset, 0); + e.setBuffer(w.w, w.w_off, 1); + e.setBuffer(w.scales, w.s_off, 2); + e.setBuffer(w.biases, w.b_off, 3); + e.setValue(@as(i32, @intCast(w.k)), 4); + e.setBuffer(out.buffer, out.offset, 5); + e.dispatchThreads(mtl.Size.of(w.k / @as(usize, if (w.bits == 4) 2 else 1), rows, 1), mtl.Size.of(128, 1, 1)); + } +}; + +pub const Model = struct { + allocator: std.mem.Allocator, + host: load.Loaded, + blocks: []Block, + head: Head, + common: dense.Kernels, + routed: routed.Kernels, + memory: memory.Kernels, + /// The sparse layers' compressed indexer (used when a lane cache carries index state). + index: index.Kernels, + + pub fn open(a: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !Model { + var host = try load.Loaded.open(a, io, dir); + errdefer host.close(); + const t = host.config.value.text_config; + var common = try dense.Kernels.loadForModel(a, device, t, host.bits); + errdefer common.deinit(); + var route = try routed.Kernels.loadForModel(a, device, t, host.bits); + errdefer route.deinit(); + var mem = try memory.Kernels.load(device); + errdefer mem.deinit(); + var ix = try index.Kernels.load(device); + errdefer ix.deinit(); + var head = try Head.upload(a, device, try weights.Head.read(&host, 1), common.linears != null); + errdefer head.deinit(); + const blocks = try a.alloc(Block, t.num_hidden_layers); + errdefer a.free(blocks); + var built: usize = 0; + errdefer for (blocks[0..built]) |*block| block.deinit(); + for (blocks, 0..) |*block, i| { + block.* = try Block.upload(a, device, &host, @intCast(i), common.tensors != null); + built += 1; + } + host.checkpoint.release(); + return .{ + .allocator = a, + .host = host, + .blocks = blocks, + .head = head, + .common = common, + .routed = route, + .memory = mem, + .index = ix, + }; + } + + pub fn deinit(self: *Model) void { + for (self.blocks) |*block| block.deinit(); + self.allocator.free(self.blocks); + self.head.deinit(); + self.memory.deinit(); + self.index.deinit(); + self.routed.deinit(); + self.common.deinit(); + self.host.close(); + self.* = undefined; + } + + pub fn encode(self: *Model, e: mtl.ComputeEncoder, frame: *Frame, cache: []const LayerCache) !Ref { + if (frame.rows == 0 or cache.len != self.blocks.len) return error.BadHy4MetalFrame; + var x = frame.streams[0]; + var y = frame.streams[1]; + self.embedRows(e, frame.ids, x, frame.rows * ihc.streams); + e.barrier(); + var mem_ix: usize = 0; + // each sub-block's tail writes the next collapse's partials (an Engram layer between them recomputes them) + var ready = false; + var headed = false; + for (self.blocks, cache, 0..) |*block, lane, bi| { + if (block.memory) |*m| { + try self.memory.forward(&self.common, e, m, &frame.memory[mem_ix], x, y, frame.rows); + e.barrier(); + std.mem.swap(Ref, &x, &y); + mem_ix += 1; + ready = false; + headed = false; + } + try frame.common.bind(frame.rows, block.attention.heads, lane.key_stride); + const feed_merge = switch (block.feed) { + .dense => |*w| w.merge, + .routed => |*w| w.merge, + }; + const feed_gain = switch (block.feed) { + .dense => |*w| w.norm, + .routed => |*w| w.input_norm, + }; + // decode passes run each tail with the next collapse's head in one launch + const fuse = dense.Kernels.fusedSeams(frame.rows); + var rows = lane.rows; + if (lane.index) |c| if (block.attention.index != null) { + rows.index = .{ .kernels = &self.index, .scratch = &frame.index, .cache = c }; + }; + try self.common.attendSeam(e, &block.attention, &frame.common, rows, x, y, .{ .ready = ready, .headed = headed, .next = feed_merge, .next_gain = if (fuse) feed_gain else null }); + e.barrier(); + std.mem.swap(Ref, &x, &y); + const next: ?dense.Merge = if (bi + 1 < self.blocks.len) + (if (self.blocks[bi + 1].memory != null) null else self.blocks[bi + 1].attention.merge) + else + self.head.merge; + const next_gain: ?mtl.Buffer = if (!fuse or next == null) null else if (bi + 1 < self.blocks.len) self.blocks[bi + 1].attention.norm else self.head.norm; + switch (block.feed) { + .dense => |*w| try self.common.feedSeam(e, w, &frame.common, x, y, .{ .ready = true, .headed = fuse, .next = next, .next_gain = next_gain }), + .routed => |*w| try self.routed.forwardSeam(&self.common, e, w, &frame.common, &frame.routed, x, y, .{ .ready = true, .headed = fuse, .next = next, .next_gain = next_gain }), + } + e.barrier(); + std.mem.swap(Ref, &x, &y); + ready = next != null; + headed = next_gain != null; + } + _ = try self.common.collapseSeamFrom(e, x, self.head.merge, self.head.norm, &frame.common, .{ .ready = ready, .headed = headed }); + if (frame.last_logits) { + // a prompt chunk needs only its last row's logits (the same bits: rows are independent) + const h = self.host.config.value.text_config.hidden_size; + const last: Ref = .{ .buffer = frame.common.normalized.buffer, .offset = frame.common.normalized.offset + @as(usize, frame.rows - 1) * h * 2 }; + try self.readout(e, last, frame.logits, 1); + } else try self.readout(e, frame.common.normalized, frame.logits, frame.rows); + return frame.logits; + } + + pub fn embedRows(self: *const Model, e: mtl.ComputeEncoder, ids: Ref, out: Ref, rows: u32) void { + self.head.embed(e, ids, out, rows); + } + + pub fn readout(self: *const Model, e: mtl.ComputeEncoder, x: Ref, out: Ref, rows: u32) !void { + try self.common.linear(e, self.head.vocab, x, out, rows); + } +}; + +/// A layer's cache rows for a pass; a sparse layer's `index` runs the compressed indexer (beyond the probe's 2,048). +pub const LayerCache = struct { rows: dense.CacheRows, key_stride: u32, index: ?index.Cache = null }; + +pub const Frame = struct { + own: dense.Buffers, + capacity: u32, + rows: u32 = 0, + /// Read out only the last row's logits (a prompt chunk); they land in logits row 0. + last_logits: bool = false, + streams: [2]Ref, + ids: Ref, + logits: Ref, + common: dense.Scratch, + routed: routed.Scratch, + memory: []memory.Scratch, + /// The indexer's rows; the caller stages their first position with `index.stage` before a pass with index caches. + index: index.Scratch, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, model: *const Model, rows: u32, key_stride: u32) !Frame { + const t = model.host.config.value.text_config; + if (rows == 0 or rows > routed.prompt_rows) return error.BadHy4MetalFrame; + var needed: usize = 0; + var largest = &model.blocks[0].attention; + for (model.blocks) |*b| { + needed += @intFromBool(b.memory != null); + if (b.attention.heads > largest.heads) largest = &b.attention; + } + const memories = try a.alloc(memory.Scratch, needed); + errdefer a.free(memories); + var made: usize = 0; + errdefer for (memories[0..made]) |*m| m.deinit(); + for (memories) |*m| { + m.* = try memory.Scratch.init(a, device, rows, t.hidden_size); + made += 1; + } + const inner = @max(t.moe_intermediate_size * t.n_shared_experts, t.intermediate_size); + var common = try dense.Scratch.initForModel(a, device, largest, inner, key_stride, rows, model.common.tensors != null); + errdefer common.deinit(); + var route = try routed.Scratch.initForModel(a, device, t, rows, model.routed.tensors != null); + errdefer route.deinit(); + var ix = try index.Scratch.init(a, device, rows); + errdefer ix.deinit(); + var b: dense.Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + var out: Frame = .{ + .own = undefined, + .capacity = rows, + .streams = .{ try b.rows(rows, ihc.streams * t.hidden_size), try b.rows(rows, ihc.streams * t.hidden_size) }, + .ids = .{ .buffer = try b.alloc(@as(usize, rows) * ihc.streams * @sizeOf(u32)) }, + .logits = try b.rows(rows, t.vocab_size), + .common = common, + .routed = route, + .memory = memories, + .index = ix, + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Frame) void { + self.common.deinit(); + self.routed.deinit(); + self.index.deinit(); + for (self.memory) |*m| m.deinit(); + self.own.a.free(self.memory); + self.own.clear(); + self.* = undefined; + } + + /// Call after this frame's previous command buffer completes. History windows are newest token first. + pub fn stage(self: *Frame, model: *const Model, tokens: []const u32, windows: []const [engram.order]u32, media: []const u32) !void { + self.rows = 0; + if (tokens.len == 0 or tokens.len > self.capacity or tokens.len != windows.len or tokens.len != media.len) + return error.BadHy4MetalFrame; + const vocab = model.host.config.value.text_config.vocab_size; + const ids = self.ids.buffer.slice(u32, tokens.len * ihc.streams); + for (tokens, 0..) |token, row| { + if (token >= vocab or windows[row][0] != token) return error.BadHy4Token; + @memset(ids[row * ihc.streams ..][0..ihc.streams], token); + } + var i: usize = 0; + for (model.blocks) |*b| if (b.memory) |*m| { + try self.memory[i].stage(self.own.a, m, windows, media); + i += 1; + }; + self.rows = @intCast(tokens.len); + } +}; diff --git a/zig/src/families/hy4_flash/metal_routed.zig b/zig/src/families/hy4_flash/metal_routed.zig new file mode 100644 index 00000000000..07ad68524b3 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_routed.zig @@ -0,0 +1,349 @@ +//! A Metal routed Hy4-flash feed-forward block, including the shared branch and residual merge. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const affine = @import("../../core/row_projection.zig"); +const route = @import("../../core/moe_route.zig"); +const experts = @import("affine_experts_metal.zig"); +const dense = @import("metal_dense.zig"); +const weights = @import("model_weights.zig"); +const config = @import("config.zig"); +const gpu_experts = @import("metal_tensor_experts.zig"); +const lane = @import("../../core/lane_projection.zig"); + +const Ref = dense.Ref; +const RouteRef = @import("draft_ops").Ref; +const RouteOutputs = route.Outputs(RouteRef); +/// One router window (the core select's limit); prompt chunks up to `prompt_rows` run it a window at a time. +pub const max_rows = 16; +pub const prompt_rows = @import("metal_tensor_qkv.zig").prompt_rows; + +const ExpertWeights = union(enum) { + portable: struct { up: experts.Weights, down: experts.Weights }, + tensor: gpu_experts.Weights, +}; + +pub const Layer = struct { + own: dense.Buffers, + merge: dense.Merge, + input_norm: mtl.Buffer, + output_norm: mtl.Buffer, + router: RouteRef, + correction: RouteRef, + down: dense.Linear, + up: dense.Linear, + expert_weights: ExpertWeights, + shared_gate: dense.Linear, + shared_up: dense.Linear, + shared_down: dense.Linear, + precision: experts.Precision, + size: experts.Shape, + scale: f32, + + pub fn upload(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer, t: config.Text) !Layer { + return uploadForModel(a, device, w, t, false); + } + + pub fn uploadForModel(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer, t: config.Text, use_tensors: bool) !Layer { + if (w.feed != .routed) return error.Hy4RoutedFeedRequired; + const f = w.feed.routed; + if (f.experts.ids.first != 0 or f.experts.ids.count != t.n_routed_experts) return error.Hy4MetalNeedsWholeExpertSet; + var b: dense.Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + const packed_router = try b.alloc(f.router.bytes.len); + const router = try a.alloc(u16, f.router.bytes.len / @sizeOf(u16)); + defer a.free(router); + @memcpy(std.mem.sliceAsBytes(router), f.router.bytes); + route.pack(router, packed_router.slice(u16, router.len), t.n_routed_experts, t.hidden_size); + const precision: experts.Precision = switch (f.experts.gate_up.bits) { + 4 => .q4, + 8 => .q8, + else => return error.BadHy4ExpertBits, + }; + var out: Layer = .{ + .own = undefined, + .merge = try dense.Merge.upload(&b, w.mlp_hc), + .input_norm = try b.upload(w.mlp_norm.bytes), + .output_norm = try b.upload(f.norm.bytes), + .router = .{ .buf = packed_router }, + .correction = .{ .buf = try b.upload(f.correction.bytes) }, + .down = try b.linear(f.down, use_tensors), + .up = try b.linear(f.up, use_tensors), + .expert_weights = if (use_tensors) + .{ .tensor = try gpu_experts.Weights.upload(&b, f.experts.gate_up, f.experts.down) } + else + .{ .portable = .{ .up = try uploadExperts(&b, f.experts.gate_up), .down = try uploadExperts(&b, f.experts.down) } }, + .shared_gate = try b.linear(f.shared.gate, use_tensors), + .shared_up = try b.linear(f.shared.up, use_tensors), + .shared_down = try b.linear(f.shared.down, use_tensors), + .precision = precision, + .size = .{ + .width = t.routed_expert_hidden_size, + .inner = t.moe_intermediate_size, + .first = 0, + .experts = t.n_routed_experts, + .rows = 1, + .pairs = t.num_experts_per_tok, + .swiglu_limit = t.swiglu_limit, + }, + .scale = t.routed_scaling_factor, + }; + try out.size.check(); + out.own = b; + return out; + } + + pub fn deinit(self: *Layer) void { + self.own.clear(); + self.* = undefined; + } +}; + +fn uploadExperts(b: *dense.Buffers, w: @import("core").quant.mlx.Host) !experts.Weights { + return .{ + .words = .{ .buffer = try b.upload(w.words.bytes) }, + .scales = .{ .buffer = try b.upload(w.scales.bytes) }, + .biases = .{ .buffer = try b.upload(w.biases.bytes) }, + }; +} + +fn raw(b: *dense.Buffers, elements: usize) !RouteRef { + return .{ .buf = try b.alloc(elements * @sizeOf(u32)) }; +} + +pub const Scratch = struct { + own: dense.Buffers, + rows: u32, + picks: u32, + logits: RouteRef, + select: RouteOutputs, + expert_rows: ?mtl.Buffer, + tensors: ?gpu_experts.Scratch, + latent: Ref, + weighted: Ref, + pair_activations: Ref, + pair_outputs: mtl.Buffer, + routed: Ref, + shared: Ref, + /// A prompt chunk's expert ids, the identity (job e = expert e). + group_ids: RouteRef, + + pub fn init(a: std.mem.Allocator, d: mtl.Device, t: config.Text, rows: u32) !Scratch { + return initForModel(a, d, t, rows, false); + } + + pub fn initForModel(a: std.mem.Allocator, d: mtl.Device, t: config.Text, rows: u32, use_tensors: bool) !Scratch { + if (rows == 0 or rows > prompt_rows or (rows > max_rows and !use_tensors)) return error.BadHy4RouteRows; + var b: dense.Buffers = .{ .a = a, .d = d }; + errdefer b.clear(); + const slots = t.num_experts_per_tok; + const total = rows * slots; + const e = t.n_routed_experts; + const width = t.routed_expert_hidden_size; + const si = if (use_tensors) null else (try raw(&b, total)).buf; + if (si) |ids| for (ids.slice(i32, total), 0..) |*dst, i| { + dst.* = @intCast(i / slots); + }; + var out: Scratch = .{ + .own = undefined, + .rows = rows, + .picks = slots, + .logits = try raw(&b, rows * e), + .select = .{ + .pick = try raw(&b, total), + .wts = try raw(&b, total), + .ids = try raw(&b, e), + .members = try raw(&b, e * max_rows), + .count = try raw(&b, 1), + .mine = try raw(&b, total), + .theirs = try raw(&b, total), + .counts = try raw(&b, 2), + .word = try raw(&b, 1), + }, + .expert_rows = si, + .tensors = if (use_tensors) try gpu_experts.Scratch.init(&b, rows, slots, width, t.moe_intermediate_size) else null, + .latent = try b.rows(rows, width), + .weighted = try b.rows(rows, width), + .pair_activations = try b.rows(total, t.moe_intermediate_size), + .pair_outputs = (try raw(&b, @as(usize, total) * width)).buf, + .routed = try b.rows(rows, t.hidden_size), + .shared = try b.rows(rows, t.hidden_size), + .group_ids = try raw(&b, e), + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Scratch) void { + self.own.clear(); + self.* = undefined; + } +}; + +pub const Kernels = struct { + shape: route.Shape, + logits: mtl.Pipeline, + select: mtl.Pipeline, + /// A prompt chunk's picks and weights, a threadgroup a row (the core select's per-row arithmetic). + select_rows: mtl.Pipeline, + /// The same picks and weights by ranks, a thread an expert (TF_HY4_SELECT_LOOP keeps the arg-max rounds). + select_rank: mtl.Pipeline, + experts: ?experts.Kernels, + tensors: ?gpu_experts.Kernels, + sum: mtl.Pipeline, + add: mtl.Pipeline, + + pub fn load(a: std.mem.Allocator, device: mtl.Device, t: config.Text) !Kernels { + return loadImpl(a, device, t, null); + } + + pub fn loadForModel(a: std.mem.Allocator, device: mtl.Device, t: config.Text, bits: u8) !Kernels { + return loadImpl(a, device, t, if (device.tensorUnits()) bits else null); + } + + fn loadImpl(a: std.mem.Allocator, device: mtl.Device, t: config.Text, tensor_bits: ?u8) !Kernels { + const shape: route.Shape = .{ .hidden = t.hidden_size, .experts = t.n_routed_experts, .topk = t.num_experts_per_tok, .max_rows = max_rows }; + const core_src = try route.source(a, shape); + defer a.free(core_src); + const src = try std.mem.concat(a, u8, &.{ core_src, sources.hy4_flash_route_rows }); + defer a.free(src); + const routes = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + defer routes.deinit(); + const sums = try mtl.Library.fromSource(device, sources.hy4_flash_affine_experts, mtl.CompileOptions.mlx()); + defer sums.deinit(); + const adds = try mtl.Library.fromSource(device, sources.elementwise, mtl.CompileOptions.mlx()); + defer adds.deinit(); + var logits = try mtl.Pipeline.init(device, routes, route.names[0], false); + errdefer logits.deinit(); + var select = try mtl.Pipeline.init(device, routes, route.names[1], false); + errdefer select.deinit(); + var select_rows = try mtl.Pipeline.init(device, routes, "tf_hy4_route_select_rows", false); + errdefer select_rows.deinit(); + var select_rank = try mtl.Pipeline.init(device, routes, "tf_hy4_route_select_rank", false); + errdefer select_rank.deinit(); + var expert = if (tensor_bits == null) try experts.Kernels.load(device) else null; + errdefer if (expert) |*op| op.deinit(); + const tensors = if (tensor_bits) |bits| try gpu_experts.Kernels.load(a, device, bits) else null; + errdefer if (tensors) |op| op.deinit(); + var sum = try mtl.Pipeline.init(device, sums, "tf_hy4_routed_sum", false); + errdefer sum.deinit(); + return .{ + .shape = shape, + .logits = logits, + .select = select, + .select_rows = select_rows, + .select_rank = select_rank, + .experts = expert, + .tensors = tensors, + .sum = sum, + .add = try mtl.Pipeline.init(device, adds, "tf_add_bf16", false), + }; + } + + pub fn deinit(self: *Kernels) void { + self.logits.deinit(); + self.select.deinit(); + self.select_rows.deinit(); + self.select_rank.deinit(); + if (self.experts) |*op| op.deinit(); + if (self.tensors) |op| op.deinit(); + self.sum.deinit(); + self.add.deinit(); + } + + pub fn forward(self: *const Kernels, shared: *const dense.Kernels, e: mtl.ComputeEncoder, w: *const Layer, d: *const dense.Scratch, s: *const Scratch, x: Ref, out: Ref) !void { + return self.forwardSeam(shared, e, w, d, s, x, out, .{}); + } + + pub fn forwardSeam(self: *const Kernels, shared: *const dense.Kernels, e: mtl.ComputeEncoder, w: *const Layer, d: *const dense.Scratch, s: *const Scratch, x: Ref, out: Ref, seam: dense.Kernels.Seam) !void { + const rows = d.shape.rows; + const inner: u32 = w.shared_gate.outputs(); + if (rows > s.rows or s.picks != self.shape.topk or inner > d.inner_capacity) return error.ShortHy4Scratch; + const merge = try shared.collapseSeamFrom(e, x, w.merge, w.input_norm, d, seam); + try shared.linearsFrom(e, d.normalized, &.{ + .{ .w = w.down, .y = s.latent }, + .{ .w = w.shared_gate, .y = d.gate }, + .{ .w = w.shared_up, .y = d.up }, + }, rows); + route.logits(e, self.logits, self.shape, dense.Kernels.dref(d.normalized), w.router, s.logits, rows); + e.barrier(); + if (rows <= max_rows) { + route.select(e, self.select, s.logits, w.correction, w.scale, rows, .{ 0, w.size.experts }, s.select); + } else { + // every row's picks and weights at once; the expert grouping comes from the picks + const rank = w.size.experts <= 512; + e.setPipeline(if (rank) self.select_rank else self.select_rows); + e.setBuffer(s.logits.buf, s.logits.off, 0); + e.setBuffer(w.correction.buf, w.correction.off, 1); + e.setValue(route.Args{ .rows = @intCast(rows), .lo = 0, .hi = @intCast(w.size.experts), .scale = w.scale }, 2); + e.setBuffer(s.select.pick.buf, s.select.pick.off, 3); + e.setBuffer(s.select.wts.buf, s.select.wts.off, 4); + e.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(if (rank) 512 else 32, 1, 1)); + } + try shared.dense.swiglu(e, dense.Kernels.dref(d.gate), dense.Kernels.dref(d.up), dense.Kernels.dref(d.inner), .{ + .rows = rows, + .width = inner, + .gate_stride = inner, + .up_stride = inner, + .y_stride = inner, + }); + e.barrier(); + var shape = w.size; + shape.rows = rows; + shape.pairs = rows * s.picks; + switch (w.expert_weights) { + .portable => |mat| { + const ops = self.experts orelse return error.Hy4ExpertKernelsMissing; + const ids: experts.Ref = .{ .buffer = s.select.pick.buf }; + try ops.run(e, w.precision, .up, .{ + .input = .{ .buffer = s.latent.buffer }, + .ids = ids, + .src_rows = .{ .buffer = s.expert_rows orelse return error.ShortHy4Scratch }, + .weights = mat.up, + .output = .{ .buffer = s.pair_activations.buffer }, + }, shape); + try shared.linear(e, w.shared_down, d.inner, s.shared, rows); + e.barrier(); + try ops.run(e, w.precision, .down, .{ + .input = .{ .buffer = s.pair_activations.buffer }, + .ids = ids, + .weights = mat.down, + .output = .{ .buffer = s.pair_outputs }, + }, shape); + }, + .tensor => |mat| { + const ops = self.tensors orelse return error.Hy4ExpertKernelsMissing; + const tensor_scratch = s.tensors orelse return error.ShortHy4Scratch; + const latent: lane.Ref = .{ .buf = s.latent.buffer, .off = s.latent.offset }; + const prompt = rows > max_rows; + const jobs = if (prompt) + ops.group(e, tensor_scratch, tensorRef(s.select.pick), tensorRef(s.group_ids), latent, rows, shape.pairs, shape.experts, shape.width) + else + ops.prepare(e, tensor_scratch, .{ + .pick = tensorRef(s.select.pick), + .ids = tensorRef(s.select.ids), + .members = tensorRef(s.select.members), + .count = tensorRef(s.select.count), + }, latent, rows, shape.pairs, max_rows, shape.width); + try shared.linear(e, w.shared_down, d.inner, s.shared, rows); + e.barrier(); + ops.applyJobs(e, mat, tensor_scratch, jobs, latent, .{ .buf = s.pair_activations.buffer, .off = s.pair_activations.offset }, .{ .buf = s.pair_outputs }, shape.pairs, if (prompt) shape.experts else shape.pairs, s.picks, shape.swiglu_limit); + }, + } + e.barrier(); + e.setPipeline(self.sum); + e.setBuffer(s.pair_outputs, 0, 0); + e.setBuffer(s.select.wts.buf, 0, 1); + e.setBuffer(s.weighted.buffer, 0, 2); + e.setValue([2]u32{ shape.width, s.picks }, 3); + e.dispatchThreads(mtl.Size.of(shape.width, rows, 1), mtl.Size.of(128, 1, 1)); + e.barrier(); + try shared.linear(e, w.up, s.weighted, s.routed, rows); + e.barrier(); + try shared.tailTo(e, s.routed, s.shared, w.output_norm, merge.eps, x, out, d, merge, seam); + } +}; + +fn tensorRef(ref: RouteRef) lane.Ref { + return .{ .buf = ref.buf, .off = ref.off }; +} diff --git a/zig/src/families/hy4_flash/metal_scratch.zig b/zig/src/families/hy4_flash/metal_scratch.zig new file mode 100644 index 00000000000..350c784f547 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_scratch.zig @@ -0,0 +1,109 @@ +//! A Hy4-flash pass's per-row scratch, sized once at the widest layer. +const std = @import("std"); +const mtl = @import("metal"); +const affine = @import("../../core/row_projection.zig"); +const cfg = @import("config.zig"); +const ihc = @import("ihc.zig"); +const ihc_gpu = @import("ihc_metal.zig"); +const mla_gpu = @import("mla_metal.zig"); +const mha = @import("mla_attention.zig"); +const shape_ = @import("mla_weights.zig"); +const gpu_qkv = @import("metal_tensor_qkv.zig"); +const lane = @import("../../core/lane_projection.zig"); +const dense = @import("metal_dense.zig"); +const Buffers = dense.Buffers; +const Ref = dense.Ref; +const Attention = dense.Attention; +const withAllocation = dense.withAllocation; + +pub const Scratch = struct { + own: Buffers, + capacity: mha.Shape, + shape: mha.Shape, + inner_capacity: u32, + merged: Ref, + ihc_partials: Ref, + /// A count and a generation a row for the fused seams' in-kernel barrier (zeroed; each launch leaves count 0). + seam_barriers: Ref, + qkv: ?Ref = null, + post: Ref, + normalized: Ref, + query_a: Ref, + query_norm: Ref, + query: Ref, + kv: Ref, + value_logits: Ref, + values: Ref, + absorbed: Ref, + rotary: Ref, + latent: Ref, + attention: Ref, + key_scores: Ref, + flash_parts: ?Ref = null, + branch: Ref, + gate: Ref, + up: Ref, + inner: Ref, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, layer: *const Attention, inner: u32, keys: u32, rows: u32) !Scratch { + return initForModel(a, device, layer, inner, keys, rows, false); + } + + pub fn initForModel(a: std.mem.Allocator, device: mtl.Device, layer: *const Attention, inner: u32, keys: u32, rows: u32, use_tensors: bool) !Scratch { + var b: Buffers = .{ .a = a, .d = device }; + errdefer b.clear(); + const r = rows; + const h = layer.hidden; + const heads = layer.heads; + const shape = try mha.Shape.init(r, heads, keys); + const out: Scratch = .{ + .own = undefined, + .capacity = shape, + .shape = shape, + .inner_capacity = inner, + .merged = try b.rows(r, h), + .ihc_partials = .{ .buffer = try b.alloc(@as(usize, r) * ihc_gpu.partial_floats * @sizeOf(f32)) }, + .seam_barriers = blk: { + const bars = try b.alloc(ihc_gpu.Kernels.seam_rows * 8); + @memset(bars.slice(u8, ihc_gpu.Kernels.seam_rows * 8), 0); + break :blk .{ .buffer = bars }; + }, + .qkv = if (use_tensors) try b.rows(r, layer.query_rank + shape_.absorbed_stride + heads * shape_.value_width) else null, + .post = .{ .buffer = try b.alloc(@as(usize, r) * ihc.streams * @sizeOf(f32)) }, + .normalized = try b.rows(r, h), + .query_a = try b.rows(r, layer.query_rank), + .query_norm = try b.rows(r, layer.query_rank), + .query = try b.rows(r, heads * shape_.query_stride), + .kv = try b.rows(r, shape_.absorbed_stride), + .value_logits = try b.rows(r, heads * shape_.value_width), + .values = try b.rows(r, heads * shape_.value_width), + .absorbed = try b.rows(r, heads * shape_.absorbed_stride), + .rotary = try b.rows(r, shape_.rope), + .latent = try b.rows(r, heads * shape_.latent), + .attention = .{ .buffer = try b.alloc(shape.scratchBytes()) }, + .key_scores = .{ .buffer = try b.alloc(@as(usize, r) * heads * keys * @sizeOf(f32)) }, + .flash_parts = if (use_tensors) blk: { + const parts = try b.alloc(mla_gpu.Nax.partBytes(heads)); + @memset(parts.slice(u8, mla_gpu.Nax.partBytes(heads)), 0); + break :blk .{ .buffer = parts }; + } else null, + .branch = try b.rows(r, h), + .gate = try b.rows(r, inner), + .up = try b.rows(r, inner), + .inner = try b.rows(r, inner), + }; + return withAllocation(out, b); + } + + /// Keep one allocation at the widest layer and bind the current lane batch and head count before encoding. + pub fn bind(self: *Scratch, rows: u32, heads: u32, keys: u32) !void { + if (rows > self.capacity.rows or heads > self.capacity.heads or keys > self.capacity.key_stride) + return error.ShortHy4Scratch; + self.shape = try mha.Shape.init(rows, heads, keys); + } + + pub fn deinit(self: *Scratch) void { + self.own.clear(); + self.* = undefined; + } +}; diff --git a/zig/src/families/hy4_flash/metal_tensor_experts.zig b/zig/src/families/hy4_flash/metal_tensor_experts.zig new file mode 100644 index 00000000000..ba8a697f4d6 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_tensor_experts.zig @@ -0,0 +1,142 @@ +//! TensorOps for Hy4-flash's active experts, retaining FFN gate and up codes byte-for-byte. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const lane = @import("../../core/lane_projection.zig"); +const tensor = lane.affine_mm; +const source = @import("kernel_sources").hy4_flash_tensor_dispatch; + +const Ref = lane.Ref; +const Matrix = struct { w: Ref, s: Ref, b: Ref, n: u32, k: u32 }; + +pub const Weights = struct { + gate: Matrix, + up: Matrix, + down: Matrix, + pub fn upload(owner: anytype, up: core.quant.mlx.Host, down: core.quant.mlx.Host) !Weights { + if (up.group != 64 or down.group != 64 or up.bits != down.bits) return error.BadHy4ExpertLayout; + return .{ + .gate = try read(owner, up, 0), + .up = try read(owner, up, 1), + .down = try read(owner, down, null), + }; + } +}; + +fn read(owner: anytype, w: core.quant.mlx.Host, part: ?usize) !Matrix { + const count = w.words.shape[0]; + const n: u32 = @intCast(w.words.shape[1] / @as(usize, if (part == null) 1 else 2)); + const k: u32 = @intCast(w.scales.shape[2] * w.group); + const tensors = [_][]const u8{ w.words.bytes, w.scales.bytes, w.biases.bytes }; + var packed_: [3]Ref = undefined; + for (tensors, &packed_) |bytes, *dst| { + if (part) |side| { + if (count == 0 or bytes.len % (count * 2) != 0) return error.BadHy4ExpertLayout; + const half = bytes.len / count / 2; + const buf = try owner.alloc(half * count); + const contents = buf.slice(u8, half * count); + for (0..count) |i| @memcpy(contents[i * half ..][0..half], bytes[(i * 2 + side) * half ..][0..half]); + dst.* = .{ .buf = buf }; + } else dst.* = .{ .buf = try owner.upload(bytes) }; + } + return .{ .w = packed_[0], .s = packed_[1], .b = packed_[2], .n = n, .k = k }; +} + +pub const Scratch = struct { + order: Ref, + offsets: Ref, + identity: Ref, + latent_sums: Ref, + act_sums: Ref, + + pub fn init(owner: anytype, rows: usize, picks: usize, width: usize, inner: usize) !Scratch { + const slots = rows * picks; + if (slots > 8192) return error.BadHy4TensorRows; + const identity = try owner.alloc((picks + 1) * @sizeOf(i32)); + for (identity.slice(i32, picks + 1), 0..) |*v, i| v.* = @intCast(i); + return .{ + .order = .{ .buf = try owner.alloc(slots * @sizeOf(i32)) }, + .offsets = .{ .buf = try owner.alloc(@max(slots, 1024) * @sizeOf(i32)) }, + .identity = .{ .buf = identity }, + .latent_sums = .{ .buf = try owner.alloc(rows * (width / 64) * @sizeOf(f32)) }, + .act_sums = .{ .buf = try owner.alloc(slots * (inner / 64) * @sizeOf(f32)) }, + }; + } +}; + +pub const Route = struct { pick: Ref, ids: Ref, members: Ref, count: Ref }; +pub const Jobs = struct { offsets: Ref, order: Ref, ids: Ref }; + +pub const Kernels = struct { + pipes: tensor.Pipes, + compact: mtl.Pipeline, + grouping: mtl.Pipeline, + + pub fn load(a: std.mem.Allocator, d: mtl.Device, bits: u8) !Kernels { + const text = try tensor.source(d, a, .{ .bits = bits, .group = 64, .out_f32 = true, .glu = .clipped_silu, .mapped_experts = true }); + defer a.free(text); + const lib = try mtl.Library.fromSource(d, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var pipes: tensor.Pipes = undefined; + var n: usize = 0; + errdefer for (pipes[0..n]) |p| p.deinit(); + for (&pipes, tensor.names) |*dst, name| { + dst.* = try mtl.Pipeline.init(d, lib, name, false); + n += 1; + } + const lib_compact = try mtl.Library.fromSource(d, source, mtl.CompileOptions.mlx()); + defer lib_compact.deinit(); + var compact = try mtl.Pipeline.init(d, lib_compact, "tf_hy4_active_experts", false); + errdefer compact.deinit(); + return .{ + .pipes = pipes, + .compact = compact, + .grouping = try mtl.Pipeline.init(d, lib_compact, "tf_hy4_group_pairs", false), + }; + } + + pub fn deinit(self: Kernels) void { + for (self.pipes) |p| p.deinit(); + self.compact.deinit(); + self.grouping.deinit(); + } + + /// For one row each expert is unique, so the pick list itself is the active-to-global map. + pub fn prepare(self: Kernels, e: mtl.ComputeEncoder, s: Scratch, route: Route, x: Ref, rows: u32, pairs: u32, max_rows: u32, width: u32) Jobs { + if (rows > 1) { + e.setPipeline(self.compact); + for ([_]Ref{ route.members, route.count, s.offsets, s.order }, 0..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setValue([2]u32{ pairs, max_rows }, 4); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(256, 1, 1)); + } + tensor.rowSums(e, self.pipes, 64, x, s.latent_sums, rows, width); + return if (rows == 1) + .{ .offsets = s.identity, .order = s.identity, .ids = route.pick } + else + .{ .offsets = s.offsets, .order = s.order, .ids = route.ids }; + } + + pub fn apply(self: Kernels, e: mtl.ComputeEncoder, w: Weights, s: Scratch, jobs: Jobs, x: Ref, act: Ref, out: Ref, pairs: u32, picks: u32, limit: f32) void { + self.applyJobs(e, w, s, jobs, x, act, out, pairs, pairs, picks, limit); + } + + /// `apply` over `count` expert jobs (a window's pick list, or every expert for a prompt chunk's grouping). + pub fn applyJobs(self: Kernels, e: mtl.ComputeEncoder, w: Weights, s: Scratch, jobs: Jobs, x: Ref, act: Ref, out: Ref, pairs: u32, count: u32, picks: u32, limit: f32) void { + tensor.gatherGluMapped(e, self.pipes, x, s.latent_sums, w.gate, w.up, jobs.offsets, jobs.order, act, jobs.ids, pairs, count, picks, limit); + e.barrier(); + tensor.rowSums(e, self.pipes, 64, act, s.act_sums, pairs, w.down.k); + e.barrier(); + tensor.gatherToMapped(e, self.pipes, act, s.act_sums, w.down, jobs.offsets, out, jobs.order, jobs.ids, pairs, count); + } + + /// A prompt chunk's grouping (more rows than one router window) + pub fn group(self: Kernels, e: mtl.ComputeEncoder, s: Scratch, pick: Ref, ids: Ref, x: Ref, rows: u32, pairs: u32, experts: u32, width: u32) Jobs { + e.setPipeline(self.grouping); + for ([_]Ref{ pick, s.offsets, s.order, ids }, 0..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + // Metal's uint3 has the same 16-byte ABI as uint4. + e.setValue([4]u32{ pairs, experts, pairs / rows, 0 }, 4); + e.dispatchGroups(mtl.Size.of(1, 1, 1), mtl.Size.of(1024, 1, 1)); + tensor.rowSums(e, self.pipes, 64, x, s.latent_sums, rows, width); + return .{ .offsets = s.offsets, .order = s.order, .ids = ids }; + } +}; diff --git a/zig/src/families/hy4_flash/metal_tensor_qkv.zig b/zig/src/families/hy4_flash/metal_tensor_qkv.zig new file mode 100644 index 00000000000..d85a33fb6ec --- /dev/null +++ b/zig/src/families/hy4_flash/metal_tensor_qkv.zig @@ -0,0 +1,155 @@ +//! Hy4-flash Q/KV projections and gate on Apple GPU tensor units. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const lane = @import("../../core/lane_projection.zig"); +const source = @import("kernel_sources").hy4_flash_tensor_dispatch; +const config = @import("config.zig"); +const mla = @import("mla_weights.zig"); + +pub const Packed = struct { + w: lane.Ref, + sb: lane.Ref, + + pub fn upload(owner: anytype, inputs: []const core.quant.mlx.Host, l: lane.Layout) !Packed { + const words = try owner.a.alloc(u32, l.sourceWords()); + defer owner.a.free(words); + const scales = try owner.a.alloc(u16, l.metadataElements() / 2); + defer owner.a.free(scales); + const bias = try owner.a.alloc(u16, scales.len); + defer owner.a.free(bias); + var wi: usize = 0; + var si: usize = 0; + for (inputs) |input| { + if (input.bits != l.format.bits or input.group != l.format.group or input.scales.shape[1] * input.group != l.k or + input.words.bytes.len % @sizeOf(u32) != 0 or input.scales.bytes.len % @sizeOf(u16) != 0) + return error.BadQkvInput; + const nw = input.words.bytes.len / 4; + const nt = input.scales.bytes.len / 2; + if (nw > words.len - wi or nt > scales.len - si or input.biases.bytes.len != input.scales.bytes.len) + return error.BadQkvInput; + @memcpy(std.mem.sliceAsBytes(words[wi..][0..nw]), input.words.bytes); + @memcpy(std.mem.sliceAsBytes(scales[si..][0..nt]), input.scales.bytes); + @memcpy(std.mem.sliceAsBytes(bias[si..][0..nt]), input.biases.bytes); + wi += nw; + si += nt; + } + if (wi != words.len or si != scales.len) return error.BadQkvInput; + const w = try owner.alloc(l.weightWords() * 4); + const sb = try owner.alloc(l.metadataElements() * 2); + try lane.pack(l, words, scales, bias, w.slice(u32, l.weightWords()), sb.slice(u16, l.metadataElements())); + if (l.reg and l.format.bits == 8) try lane.regOrder8(w.slice(u32, l.weightWords()), l.n, l.k) else if (l.reg) try lane.regOrder(owner.d, &.{.{ .w = .{ .buf = w }, .n = l.n, .k = l.k }}); + return .{ .w = .{ .buf = w }, .sb = .{ .buf = sb } }; + } +}; + +/// Rows one prompt chunk may hold (the routed layer's prompt_rows). +pub const prompt_rows = 512; + +fn layout(bits: u8, n: usize, k: usize, sk: usize) lane.Layout { + return .{ + .n = n, + .k = k, + .sk = sk, + .format = .{ .bits = bits, .group = 64 }, + .reg = true, + .precompute_sums = true, + // a whole prompt chunk in one encode on the reg path (independent 16-row blocks, so the same bits) + .rows = prompt_rows, + .row_blocks = false, + }; +} + +/// Any other dense projection [n, k] on tensor units +pub fn denseLayout(bits: u8, n: usize, k: usize) lane.Layout { + return layout(bits, n, k, if (k < 2048) 2 else if (k <= 4096) 4 else 8); +} + +pub fn inputLayout(t: config.Text, bits: u8, heads: u32) lane.Layout { + return layout(bits, t.q_lora_rank + mla.absorbed_stride + heads * mla.value_width, t.hidden_size, 4); +} + +pub fn queryLayout(t: config.Text, bits: u8, heads: u32) lane.Layout { + return layout(bits, heads * mla.query_stride, t.q_lora_rank, 2); +} + +pub fn flavor(t: config.Text, heads: u32) usize { + return if (heads == t.swa_num_attention_heads) 1 else 0; +} + +/// Passes of at most this many rows take the reg kernels that add their own group sums +pub const inline_rows = 8; + +/// `l` with the kernel adding its split's group sums up front (4-bit reg and 8-bit layouts; null otherwise). +pub fn withInlineSums(l: lane.Layout) ?lane.Layout { + if (!l.reg and l.format.bits != 8) return null; + var out = l; + out.inline_sums = true; + return out; +} + +pub const Kernels = struct { + inputs: [2]lane.Projection, + queries: [2]lane.Projection, + /// The same projections adding their own group sums (4-bit reg layouts), for passes of inline_rows at most. + inline_inputs: [2]?lane.Projection = .{ null, null }, + inline_queries: [2]?lane.Projection = .{ null, null }, + unpack: mtl.Pipeline, + + pub fn load(a: std.mem.Allocator, d: mtl.Device, t: config.Text, bits: u8) !Kernels { + const lib = try mtl.Library.fromSource(d, source, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var unpack = try mtl.Pipeline.init(d, lib, "tf_hy4_qkv_split", false); + errdefer unpack.deinit(); + var out: Kernels = .{ .inputs = undefined, .queries = undefined, .unpack = unpack }; + var made: usize = 0; + errdefer { + for (0..made) |i| { + out.inputs[i].deinit(); + out.queries[i].deinit(); + } + } + for ([_]u32{ t.num_attention_heads, t.swa_num_attention_heads }, 0..) |heads, i| { + var input = try lane.Projection.init(a, d, inputLayout(t, bits, heads)); + errdefer input.deinit(); + out.queries[i] = try lane.Projection.init(a, d, queryLayout(t, bits, heads)); + out.inputs[i] = input; + made += 1; + } + for ([_]u32{ t.num_attention_heads, t.swa_num_attention_heads }, 0..) |heads, i| { + if (withInlineSums(inputLayout(t, bits, heads))) |l| out.inline_inputs[i] = try lane.Projection.init(a, d, l); + if (withInlineSums(queryLayout(t, bits, heads))) |l| out.inline_queries[i] = try lane.Projection.init(a, d, l); + } + return out; + } + + pub fn deinit(self: Kernels) void { + for (self.inputs, self.queries) |a, b| { + a.deinit(); + b.deinit(); + } + for (self.inline_inputs, self.inline_queries) |a, b| { + if (a) |x| x.deinit(); + if (b) |x| x.deinit(); + } + self.unpack.deinit(); + } + + pub fn inputFor(self: *const Kernels, which: usize, rows: u32) *const lane.Projection { + if (rows <= inline_rows) if (self.inline_inputs[which]) |*p| return p; + return &self.inputs[which]; + } + + pub fn queryFor(self: *const Kernels, which: usize, rows: u32) *const lane.Projection { + if (rows <= inline_rows) if (self.inline_queries[which]) |*p| return p; + return &self.queries[which]; + } + + pub fn split(self: Kernels, e: mtl.ComputeEncoder, input: lane.Ref, q: lane.Ref, kv: lane.Ref, gates: lane.Ref, rows: u32, q_rank: u32, gate_cols: u32) void { + e.setPipeline(self.unpack); + for ([_]lane.Ref{ input, q, kv, gates }, 0..) |r, i| e.setBuffer(r.buf, r.off, i); + // Metal's uint3 has the same 16-byte ABI as uint4. + e.setValue([4]u32{ q_rank, mla.absorbed_stride, gate_cols, 0 }, 4); + e.dispatchThreads(mtl.Size.of(q_rank + mla.absorbed_stride + gate_cols, rows, 1), mtl.Size.of(128, 1, 1)); + } +}; diff --git a/zig/src/families/hy4_flash/mla_attention.zig b/zig/src/families/hy4_flash/mla_attention.zig new file mode 100644 index 00000000000..0e4b1728c9b --- /dev/null +++ b/zig/src/families/hy4_flash/mla_attention.zig @@ -0,0 +1,57 @@ +//! The launch shape for absorbed attention over retained physical KV slots. +const std = @import("std"); +const weights = @import("mla_weights.zig"); + +pub const chunk_keys = 512; +pub const score_scale: f32 = 0.0625; // 1 / sqrt(192 + 64), before absorbing the key projection. + +pub const CacheWrite = extern struct { + rows: u32, + capacity: u32, + epsilon: f32, + + pub fn check(self: CacheWrite) !void { + if (self.rows == 0 or self.rows > std.math.maxInt(u16) or self.capacity == 0 or + self.capacity > std.math.maxInt(i32) or !std.math.isFinite(self.epsilon) or self.epsilon <= 0) + return error.BadHy4CacheWrite; + } +}; + +pub const Shape = extern struct { + rows: u32, + heads: u32, + key_stride: u32, + chunks: u32, + + pub fn init(rows: u32, heads: u32, key_stride: u32) !Shape { + if (rows == 0 or heads == 0 or key_stride == 0) return error.EmptyHy4AttentionShape; + const chunks = (key_stride - 1) / chunk_keys + 1; + if (chunks > std.math.maxInt(u16) or rows > std.math.maxInt(u16) or heads > 64) + return error.UnsupportedHy4AttentionShape; + return .{ .rows = rows, .heads = heads, .key_stride = key_stride, .chunks = chunks }; + } + + pub fn partialHeads(self: Shape) usize { + return @as(usize, self.rows) * self.heads * self.chunks; + } + + pub fn scratchBytes(self: Shape) usize { + return self.partialHeads() * (weights.latent + 2) * @sizeOf(f32); + } + + pub fn check(self: Shape) !void { + const derived = try init(self.rows, self.heads, self.key_stride); + if (self.chunks != derived.chunks) return error.WrongHy4AttentionChunks; + } +}; + +test "dispatch geometry covers sliding and sparse tails" { + for ([_]u32{ 511, 512, 513, 2047, 2048, 2049 }, [_]u32{ 1, 1, 2, 4, 4, 5 }) |len, chunks| { + const shape = try Shape.init(8, 32, len); + try shape.check(); + try std.testing.expectEqual(chunks, shape.chunks); + try std.testing.expectEqual(@as(usize, 8 * 32 * (512 + 2) * 4) * chunks, shape.scratchBytes()); + } + try std.testing.expectError(error.EmptyHy4AttentionShape, Shape.init(1, 64, 0)); + try std.testing.expectError(error.UnsupportedHy4AttentionShape, Shape.init(1, 65, 512)); +} diff --git a/zig/src/families/hy4_flash/mla_cuda.zig b/zig/src/families/hy4_flash/mla_cuda.zig new file mode 100644 index 00000000000..f82fecf5ed9 --- /dev/null +++ b/zig/src/families/hy4_flash/mla_cuda.zig @@ -0,0 +1,188 @@ +//! CUDA launches for Hy4-flash's absorbed MLA projections. +const cuda = @import("cuda"); +const weights = @import("mla_weights.zig"); +const attention = @import("mla_attention.zig"); +const rotary = @import("rope.zig"); + +pub const Projections = struct { + image: cuda.Module, + absorb_kernel: cuda.Function, + expand_kernel: cuda.Function, + table_kernel: cuda.Function, + rotate_kernel: cuda.Function, + cache_kernel: cuda.Function, + gate_kernel: cuda.Function, + + pub fn load(driver: *const cuda.Driver) !Projections { + var image = try cuda.Module.load(driver, cuda.kernels.hy4_mla_project); + errdefer image.unload(); + return .{ + .image = image, + .absorb_kernel = try image.function("tf_hy4_absorb_q"), + .expand_kernel = try image.function("tf_hy4_expand_v"), + .table_kernel = try image.function("tf_hy4_rotary_table"), + .rotate_kernel = try image.function("tf_hy4_rotate"), + .cache_kernel = try image.function("tf_hy4_cache_keys"), + .gate_kernel = try image.function("tf_hy4_gate_values"), + }; + } + + pub fn deinit(self: *Projections) void { + self.image.unload(); + self.* = undefined; + } + + fn launch(kernel: cuda.Function, stream: cuda.Stream, input: u64, coefficients: u64, output: u64, rows: u32, heads: u32, column_tiles: u32) !void { + if (rows == 0 or heads == 0) return; + const rows_per_block = @min(rows, 64); + var args: cuda.Args = .{}; + inline for (.{ input, coefficients, output, @as(i64, rows), @as(i64, heads), @as(i64, rows_per_block) }) |x| args.add(x); + try cuda.launch.launch(kernel, .{ + .grid = .{ .x = heads, .y = column_tiles, .z = (rows - 1) / rows_per_block + 1 }, + .block = .{ .x = 128 }, + }, stream, &args); + } + + pub fn absorb(self: Projections, stream: cuda.Stream, query: u64, wk: u64, output: u64, rows: u32, heads: u32) !void { + try launch(self.absorb_kernel, stream, query, wk, output, rows, heads, weights.latent / 32); + } + + pub fn expand(self: Projections, stream: cuda.Stream, latent: u64, wv: u64, output: u64, rows: u32, heads: u32) !void { + try launch(self.expand_kernel, stream, latent, wv, output, rows, heads, weights.value_width / 16); + } + + /// Positions [row][3] i32, table [row][32][cos,sin] BF16. + pub fn rotaryTable(self: Projections, s: cuda.Stream, positions: u64, table: u64, rows: u32, p: rotary.Parameters) !void { + if (rows == 0) return; + var args: cuda.Args = .{}; + inline for (.{ positions, table, p }) |x| args.add(x); + try cuda.launch.launch(self.table_kernel, .{ .grid = .{ .x = rows }, .block = .{ .x = rotary.pairs } }, s, &args); + } + + pub fn rotate(self: Projections, s: cuda.Stream, input: u64, table: u64, output: u64, shape: rotary.View) !void { + try shape.check(); + var args: cuda.Args = .{}; + inline for (.{ input, table, output, shape }) |x| args.add(x); + try cuda.launch.launch(self.rotate_kernel, .{ + .grid = .{ .x = shape.rows, .y = shape.heads }, + .block = .{ .x = rotary.pairs }, + }, s, &args); + } + + /// Normalize and rotate KV projection rows directly into the lane's assigned latent slots. + pub fn cacheKeys(self: Projections, s: cuda.Stream, input: u64, gain: u64, table: u64, slots: u64, cache: u64, shape: attention.CacheWrite) !void { + try shape.check(); + var args: cuda.Args = .{}; + inline for (.{ input, gain, table, slots, cache, shape }) |x| args.add(x); + try cuda.launch.launch(self.cache_kernel, .{ .grid = .{ .x = shape.rows }, .block = .{ .x = 128 } }, s, &args); + } + + pub fn gate(self: Projections, s: cuda.Stream, values: u64, logits: u64, rows: u32, heads: u32) !void { + if (rows == 0) return; + if (rows > 65535 or heads == 0 or heads > 64) return error.BadHy4GateShape; + const columns = heads * weights.value_width; + var args: cuda.Args = .{}; + inline for (.{ values, logits, columns }) |x| args.add(x); + try cuda.launch.launch(self.gate_kernel, .{ .grid = .{ .x = columns / 128, .y = rows }, .block = .{ .x = 128 } }, s, &args); + } +}; + +pub const Attention = struct { + image: cuda.Module, + chunks: cuda.Function, + merge: cuda.Function, + + const head_tile = cuda.mla.heads_tile; + const shared_bytes = cuda.mla.chunksSmem(head_tile); + + pub const Buffers = struct { + query: u64, + cache: u64, + slots: u64, + counts: u64, + sinks: u64, + scratch: u64, + scratch_bytes: usize, + output: u64, + }; + + pub fn load(driver: *const cuda.Driver) !Attention { + var image = try cuda.Module.load(driver, cuda.kernels.hy4_mla_attention); + errdefer image.unload(); + const chunks = try image.function("tf_hy4_attend_chunks"); + try chunks.allowDynamicShared(shared_bytes); + return .{ .image = image, .chunks = chunks, .merge = try image.function("tf_hy4_attend_merge") }; + } + + pub fn deinit(self: *Attention) void { + self.image.unload(); + self.* = undefined; + } + + /// Counts must fit key_stride and all active key slots must address the passed cache. + pub fn attend(self: Attention, s: cuda.Stream, b: Buffers, shape: attention.Shape) !void { + try shape.check(); + if (b.scratch_bytes < shape.scratchBytes()) return error.ShortHy4AttentionScratch; + const partials = shape.partialHeads() * @sizeOf(f32); + const maxima = b.scratch + partials * weights.latent; + const mass = maxima + partials; + const rows: i64 = shape.rows; + const heads: i64 = shape.heads; + var args: cuda.Args = .{}; + inline for (.{ b.query, b.cache, b.slots, b.counts, b.scratch, maxima, mass, rows, heads, @as(i64, shape.key_stride), attention.score_scale }) |x| + args.add(x); + try cuda.launch.launch(self.chunks, .{ + .grid = .{ .x = shape.rows, .y = (shape.heads + head_tile - 1) / head_tile, .z = shape.chunks }, + .block = .{ .x = 256 }, + .shared = shared_bytes, + }, s, &args); + var merge: cuda.Args = .{}; + inline for (.{ b.scratch, maxima, mass, b.sinks, b.output, rows, heads, @as(i32, @intCast(shape.chunks)) }) |x| merge.add(x); + try cuda.launch.launch(self.merge, .{ + .grid = .{ .x = shape.rows, .y = shape.heads }, + .block = .{ .x = 128 }, + }, s, &merge); + } +}; + +pub const KvInput = struct { + projection: u64, + gain: u64, + write_slots: u64, + capacity: u32, + epsilon: f32, +}; + +pub const MlaPass = struct { + query: u64, + key_weights: u64, + value_weights: u64, + value_logits: u64, + positions: u64, + rotary_table: u64, + kv: ?KvInput = null, + attention: Attention.Buffers, + values: u64, +}; + +/// The affine projections feed this pass. The caller owns the KV leases and retained physical key list. +pub fn forward(project: Projections, attend: Attention, s: cuda.Stream, b: MlaPass, shape: attention.Shape, p: rotary.Parameters) !void { + try shape.check(); + if (b.kv) |kv| try (attention.CacheWrite{ .rows = shape.rows, .capacity = kv.capacity, .epsilon = kv.epsilon }).check(); + try project.rotaryTable(s, b.positions, b.rotary_table, shape.rows, p); + try project.absorb(s, b.query, b.key_weights, b.attention.query, shape.rows, shape.heads); + try project.rotate(s, b.query + weights.nope * 2, b.rotary_table, b.attention.query + weights.latent * 2, .{ + .rows = shape.rows, + .heads = shape.heads, + .input_stride = weights.query_stride, + .output_stride = weights.absorbed_stride, + }); + if (b.kv) |kv| try project.cacheKeys(s, kv.projection, kv.gain, b.rotary_table, kv.write_slots, b.attention.cache, .{ + .rows = shape.rows, + .capacity = kv.capacity, + .epsilon = kv.epsilon, + }); + try attend.attend(s, b.attention, shape); + try project.expand(s, b.attention.output, b.value_weights, b.values, shape.rows, shape.heads); + try project.gate(s, b.values, b.value_logits, shape.rows, shape.heads); +} diff --git a/zig/src/families/hy4_flash/mla_metal.zig b/zig/src/families/hy4_flash/mla_metal.zig new file mode 100644 index 00000000000..9aafb9d05af --- /dev/null +++ b/zig/src/families/hy4_flash/mla_metal.zig @@ -0,0 +1,355 @@ +//! Metal launches for Hy4-flash's absorbed MLA projections. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const weights = @import("mla_weights.zig"); +const attention = @import("mla_attention.zig"); +const rotary = @import("rope.zig"); + +pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; +const Args = extern struct { rows: u32, heads: u32 }; + +/// The BF16 absorb and expand-and-gate products on the tensor units, the same tiles at every row count. +pub const Nax = struct { + absorb: mtl.Pipeline, + expand: mtl.Pipeline, + attend_split: mtl.Pipeline, + combine: mtl.Pipeline, + attend: mtl.Pipeline, + + pub fn load(a: std.mem.Allocator, device: mtl.Device) !Nax { + const text = try @import("../../core/lane_projection.zig").frags.source(device, a, sources.hy4_flash_mla_nax); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + var absorb = try mtl.Pipeline.init(device, lib, "tf_hy4_absorb_nax", false); + errdefer absorb.deinit(); + var expand = try mtl.Pipeline.init(device, lib, "tf_hy4_expand_gated_nax", false); + errdefer expand.deinit(); + var attend_split = try mtl.Pipeline.init(device, lib, "tf_hy4_attend_nax_split", false); + errdefer attend_split.deinit(); + var combine = try mtl.Pipeline.init(device, lib, "tf_hy4_attend_combine", false); + errdefer combine.deinit(); + return .{ .absorb = absorb, .expand = expand, .attend_split = attend_split, .combine = combine, .attend = try mtl.Pipeline.init(device, lib, "tf_hy4_attend_nax", false) }; + } + + pub fn deinit(self: Nax) void { + self.absorb.deinit(); + self.expand.deinit(); + self.attend_split.deinit(); + self.combine.deinit(); + self.attend.deinit(); + } + + /// Flash attention over contiguous key ranges: out [rows][heads][512] from the absorbed queries and the cache. + fn splits(shape: attention.Shape, has_parts: bool, live_keys: u32) u32 { + _ = .{ shape, has_parts, live_keys }; + return 1; // row-invariant bits: a split count from the pass's widest row would change other rows' sums + } + + fn flash(self: Nax, e: mtl.ComputeEncoder, b: Attention.Buffers, ranges: KeyRanges, shape: attention.Shape) void { + const n = splits(shape, b.flash_parts != null, b.live_keys); + e.setPipeline(if (n > 1) self.attend_split else self.attend); + for ([_]Ref{ b.query, b.cache, ranges.ranges, ranges.tiles, b.sinks, b.output }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + const args = extern struct { rows: u32, heads: u32, scale: f32, pad: u32 }{ .rows = shape.rows, .heads = shape.heads, .scale = attention.score_scale, .pad = n }; + e.setValue(args, 6); + if (n == 1) return e.dispatchGroups(mtl.Size.of(shape.heads, (shape.rows + 15) / 16, 1), mtl.Size.of(128, 1, 1)); + const parts = b.flash_parts.?; + const ml: Ref = .{ .buffer = parts.buffer, .offset = parts.offset + @as(usize, max_splits) * 16 * shape.heads * weights.latent * 4 }; + e.setBuffer(parts.buffer, parts.offset, 7); + e.setBuffer(ml.buffer, ml.offset, 8); + e.dispatchGroups(mtl.Size.of(shape.heads, 1, n), mtl.Size.of(128, 1, 1)); + e.barrier(); + e.setPipeline(self.combine); + for ([_]Ref{ parts, ml, b.sinks, b.output }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(args, 4); + e.dispatchGroups(mtl.Size.of(shape.heads, shape.rows, 1), mtl.Size.of(128, 1, 1)); + } + + pub const max_splits = 8; + + /// Bytes of the split partials for `heads` heads (16 rows, max_splits runs, O then max and sum). + pub fn partBytes(heads: u32) usize { + return @as(usize, max_splits) * 16 * heads * (weights.latent + 2) * 4; + } + + fn run(pipe: mtl.Pipeline, e: mtl.ComputeEncoder, refs: []const Ref, rows: u32, heads: u32, col_blocks: u32) void { + e.setPipeline(pipe); + for (refs[0..3], 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(Args{ .rows = rows, .heads = heads }, 3); + if (refs.len > 3) e.setBuffer(refs[3].buffer, refs[3].offset, 4); + e.dispatchGroups(mtl.Size.of(col_blocks, heads, (rows + 15) / 16), mtl.Size.of(128, 1, 1)); + } +}; + +/// Each row's keys as one range of key indices [lo, hi) (u32 pairs), and each 32-key tile's first slot +pub const KeyRanges = struct { ranges: Ref, tiles: Ref }; + +pub const Projections = struct { + absorb_pipeline: mtl.Pipeline, + expand_pipeline: mtl.Pipeline, + table_pipeline: mtl.Pipeline, + rotate_pipeline: mtl.Pipeline, + cache_pipeline: mtl.Pipeline, + gate_pipeline: mtl.Pipeline, + /// expand then gate in one launch (bit-equal to the two passes). + expand_gated: mtl.Pipeline, + /// On tensor units: the absorb and expand-and-gate products there instead. + nax: ?Nax = null, + + pub fn load(device: mtl.Device) !Projections { + const library = try mtl.Library.fromSource(device, sources.hy4_flash_mla_project, mtl.CompileOptions.mlx()); + defer library.deinit(); + var absorb_pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_absorb_q", false); + errdefer absorb_pipeline.deinit(); + var expand_pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_expand_v", false); + errdefer expand_pipeline.deinit(); + var table_pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_rotary_table", false); + errdefer table_pipeline.deinit(); + var rotate_pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_rotate", false); + errdefer rotate_pipeline.deinit(); + var cache_pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_cache_keys", false); + errdefer cache_pipeline.deinit(); + var expand_gated = try mtl.Pipeline.init(device, library, "tf_hy4_expand_v_gated", false); + errdefer expand_gated.deinit(); + return .{ + .expand_gated = expand_gated, + .absorb_pipeline = absorb_pipeline, + .expand_pipeline = expand_pipeline, + .table_pipeline = table_pipeline, + .rotate_pipeline = rotate_pipeline, + .cache_pipeline = cache_pipeline, + .gate_pipeline = try mtl.Pipeline.init(device, library, "tf_hy4_gate_values", false), + }; + } + + pub fn deinit(self: *Projections) void { + self.absorb_pipeline.deinit(); + self.expand_pipeline.deinit(); + self.table_pipeline.deinit(); + self.rotate_pipeline.deinit(); + self.cache_pipeline.deinit(); + self.gate_pipeline.deinit(); + self.expand_gated.deinit(); + if (self.nax) |n| n.deinit(); + self.* = undefined; + } + + fn encode(pipeline: mtl.Pipeline, encoder: mtl.ComputeEncoder, refs: [3]Ref, rows: u32, heads: u32, width: u32) !void { + if (rows == 0 or heads == 0) return; + const row_heads = try std.math.mul(u32, rows, heads); + encoder.setPipeline(pipeline); + for (refs, 0..) |r, i| encoder.setBuffer(r.buffer, r.offset, i); + encoder.setValue(Args{ .rows = rows, .heads = heads }, refs.len); + encoder.dispatchThreads(mtl.Size.of(width, row_heads, 1), mtl.Size.of(32, 1, 1)); + } + + pub fn absorb(self: Projections, encoder: mtl.ComputeEncoder, query: Ref, wk: Ref, output: Ref, rows: u32, heads: u32) !void { + try encode(self.absorb_pipeline, encoder, .{ query, wk, output }, rows, heads, weights.latent); + } + + pub fn expand(self: Projections, encoder: mtl.ComputeEncoder, latent: Ref, wv: Ref, output: Ref, rows: u32, heads: u32) !void { + try encode(self.expand_pipeline, encoder, .{ latent, wv, output }, rows, heads, weights.value_width); + } + + /// Positions [row][3] i32, table [row][32][cos,sin] BF16. Order the table before the rotations that use it. + pub fn rotaryTable(self: Projections, e: mtl.ComputeEncoder, positions: Ref, table: Ref, rows: u32, p: rotary.Parameters) void { + if (rows == 0) return; + e.setPipeline(self.table_pipeline); + e.setBuffer(positions.buffer, positions.offset, 0); + e.setBuffer(table.buffer, table.offset, 1); + e.setValue(p, 2); + e.dispatchThreads(mtl.Size.of(rotary.pairs, rows, 1), mtl.Size.of(rotary.pairs, 1, 1)); + } + + pub fn rotate(self: Projections, e: mtl.ComputeEncoder, input: Ref, table: Ref, output: Ref, shape: rotary.View) !void { + try shape.check(); + e.setPipeline(self.rotate_pipeline); + const buffers = [_]Ref{ input, table, output }; + for (buffers, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, buffers.len); + e.dispatchThreads(mtl.Size.of(rotary.pairs, shape.heads, shape.rows), mtl.Size.of(rotary.pairs, 1, 1)); + } + + /// Normalize and rotate KV projection rows directly into the lane's assigned latent slots. + pub fn cacheKeys(self: Projections, e: mtl.ComputeEncoder, input: Ref, gain: Ref, table: Ref, slots: Ref, cache: Ref, shape: attention.CacheWrite) !void { + try shape.check(); + e.setPipeline(self.cache_pipeline); + const buffers = [_]Ref{ input, gain, table, slots, cache }; + for (buffers, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, buffers.len); + e.dispatchGroups(mtl.Size.of(shape.rows, 1, 1), mtl.Size.of(128, 1, 1)); + } + + pub fn gate(self: Projections, e: mtl.ComputeEncoder, values: Ref, logits: Ref, rows: u32, heads: u32) !void { + if (rows == 0) return; + if (heads == 0 or heads > 64) return error.BadHy4GateShape; + const columns = heads * weights.value_width; + e.setPipeline(self.gate_pipeline); + e.setBuffer(values.buffer, values.offset, 0); + e.setBuffer(logits.buffer, logits.offset, 1); + e.setValue(columns, 2); + e.dispatchThreads(mtl.Size.of(columns, rows, 1), mtl.Size.of(128, 1, 1)); + } +}; + +pub const Attention = struct { + chunks: mtl.Pipeline, + merge: mtl.Pipeline, + /// Scores for every key at once, then each chunk's softmax over them (bit-equal to `chunks`). + scores: mtl.Pipeline, + scored: mtl.Pipeline, + + pub const Buffers = struct { + query: Ref, + cache: Ref, + slots: Ref, + counts: Ref, + sinks: Ref, + scratch: Ref, + output: Ref, + /// [rows][heads][key_stride] floats; null runs the one-step chunks kernel. + key_scores: ?Ref = null, + /// Contiguous key ranges: the tensor units' flash kernel instead of the slot lists. + ranges: ?KeyRanges = null, + /// The flash kernel's split partials for decode passes (Nax.partBytes); null keeps one threadgroup a head. + flash_parts: ?Ref = null, + /// The widest row's live key count (0: unknown, the key stride sizes the split). + live_keys: u32 = 0, + /// A pass across 2,048 keys: rows before this one take the flash kernel over `ranges` + lists_from: ?u32 = null, + }; + + pub fn load(device: mtl.Device) !Attention { + const library = try mtl.Library.fromSource(device, sources.hy4_flash_mla_attention, mtl.CompileOptions.mlx()); + defer library.deinit(); + var chunks = try mtl.Pipeline.init(device, library, "tf_hy4_attend_chunks", false); + errdefer chunks.deinit(); + var merge = try mtl.Pipeline.init(device, library, "tf_hy4_attend_merge", false); + errdefer merge.deinit(); + var scores = try mtl.Pipeline.init(device, library, "tf_hy4_attend_scores", false); + errdefer scores.deinit(); + return .{ .chunks = chunks, .merge = merge, .scores = scores, .scored = try mtl.Pipeline.init(device, library, "tf_hy4_attend_scored", false) }; + } + + pub fn deinit(self: *Attention) void { + self.chunks.deinit(); + self.merge.deinit(); + self.scores.deinit(); + self.scored.deinit(); + self.* = undefined; + } + + /// Caller orders the query/cache writers before this dispatch. Counts and physical slots must be valid. + pub fn attend(self: Attention, e: mtl.ComputeEncoder, b: Buffers, shape: attention.Shape) !void { + try shape.check(); + const length = b.scratch.buffer.length(); + if (b.scratch.offset > length or shape.scratchBytes() > length - b.scratch.offset) return error.ShortHy4AttentionScratch; + if (b.key_scores) |ks| { + if (ks.buffer.length() < ks.offset + @as(usize, shape.rows) * shape.heads * shape.key_stride * 4) return error.ShortHy4AttentionScratch; + e.setPipeline(self.scores); + const first = .{ b.query, b.cache, b.slots, b.counts, ks }; + inline for (first, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, first.len); + e.setValue(attention.score_scale, first.len + 1); + e.dispatchGroups(mtl.Size.of((shape.heads + 3) / 4, (shape.key_stride + 63) / 64, shape.rows), mtl.Size.of(128, 1, 1)); + e.barrier(); + e.setPipeline(self.scored); + const second = .{ ks, b.cache, b.slots, b.counts, b.scratch }; + inline for (second, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, second.len); + e.dispatchGroups(mtl.Size.of((shape.heads + 3) / 4, shape.chunks, shape.rows), mtl.Size.of(128, 1, 1)); + } else { + e.setPipeline(self.chunks); + const input = .{ b.query, b.cache, b.slots, b.counts, b.scratch }; + inline for (input, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, input.len); + e.setValue(attention.score_scale, input.len + 1); + e.dispatchGroups(mtl.Size.of((shape.heads + 3) / 4, shape.chunks, shape.rows), mtl.Size.of(128, 1, 1)); + } + e.barrier(); + e.setPipeline(self.merge); + const merge_buffers = .{ b.scratch, b.sinks, b.output }; + inline for (merge_buffers, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(shape, merge_buffers.len); + e.dispatchGroups(mtl.Size.of(shape.heads, shape.rows, 1), mtl.Size.of(128, 1, 1)); + } +}; + +pub const KvInput = struct { + projection: Ref, + gain: Ref, + write_slots: Ref, + capacity: u32, + epsilon: f32, +}; + +/// Decode passes (at most 4 rows): absorb and expand-and-gate as GEMVs over the checkpoint's affine kv_b codes +pub const MlaPass = struct { + query: Ref, + key_weights: Ref, + value_weights: Ref, + value_logits: Ref, + positions: Ref, + rotary_table: Ref, + kv: ?KvInput = null, + attention: Attention.Buffers, + values: Ref, +}; + +fn rowsPast(r: Ref, bytes: usize) Ref { + return .{ .buffer = r.buffer, .offset = r.offset + bytes }; +} + +/// The affine projections feed this pass. The caller owns the KV leases and retained physical key list. +pub fn forward(project: Projections, attend: Attention, e: mtl.ComputeEncoder, b: MlaPass, shape: attention.Shape, p: rotary.Parameters) !void { + try shape.check(); + if (b.kv) |kv| try (attention.CacheWrite{ .rows = shape.rows, .capacity = kv.capacity, .epsilon = kv.epsilon }).check(); + project.rotaryTable(e, b.positions, b.rotary_table, shape.rows, p); + if (project.nax) |n| + Nax.run(n.absorb, e, &.{ b.query, b.key_weights, b.attention.query }, shape.rows, shape.heads, weights.latent / 128) + else + try project.absorb(e, b.query, b.key_weights, b.attention.query, shape.rows, shape.heads); + e.barrier(); + const input: Ref = .{ .buffer = b.query.buffer, .offset = b.query.offset + weights.nope * 2 }; + const output: Ref = .{ + .buffer = b.attention.query.buffer, + .offset = b.attention.query.offset + weights.latent * 2, + }; + try project.rotate(e, input, b.rotary_table, output, .{ + .rows = shape.rows, + .heads = shape.heads, + .input_stride = weights.query_stride, + .output_stride = weights.absorbed_stride, + }); + if (b.kv) |kv| try project.cacheKeys(e, kv.projection, kv.gain, b.rotary_table, kv.write_slots, b.attention.cache, .{ + .rows = shape.rows, + .capacity = kv.capacity, + .epsilon = kv.epsilon, + }); + e.barrier(); + if (b.attention.lists_from) |k| { + const n = project.nax orelse return error.Hy4ListSplitNeedsNax; + const r = b.attention.ranges orelse return error.Hy4ListSplitNeedsRanges; + if (k == 0 or k >= shape.rows) return error.BadHy4ListSplit; + n.flash(e, b.attention, r, try attention.Shape.init(k, shape.heads, shape.key_stride)); + var rest = b.attention; + rest.ranges = null; + rest.lists_from = null; + rest.query = rowsPast(b.attention.query, k * shape.heads * weights.absorbed_stride * 2); + rest.slots = rowsPast(b.attention.slots, k * shape.key_stride * 4); + rest.counts = rowsPast(b.attention.counts, k * 4); + rest.output = rowsPast(b.attention.output, k * shape.heads * weights.latent * 2); + try attend.attend(e, rest, try attention.Shape.init(shape.rows - k, shape.heads, shape.key_stride)); + } else if (project.nax) |n| if (b.attention.ranges) |r| { + n.flash(e, b.attention, r, shape); + } else try attend.attend(e, b.attention, shape) else try attend.attend(e, b.attention, shape); + e.barrier(); + if (shape.heads > 64) return error.BadHy4GateShape; + if (project.nax) |n| return Nax.run(n.expand, e, &.{ b.attention.output, b.value_weights, b.values, b.value_logits }, shape.rows, shape.heads, weights.value_width / 128); + e.setPipeline(project.expand_gated); + for ([_]Ref{ b.attention.output, b.value_weights, b.values }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue(Args{ .rows = shape.rows, .heads = shape.heads }, 3); + e.setBuffer(b.value_logits.buffer, b.value_logits.offset, 4); + e.dispatchThreads(mtl.Size.of(weights.value_width, try std.math.mul(u32, shape.rows, shape.heads), 1), mtl.Size.of(32, 1, 1)); +} diff --git a/zig/src/families/hy4_flash/mla_weights.zig b/zig/src/families/hy4_flash/mla_weights.zig new file mode 100644 index 00000000000..05be7294949 --- /dev/null +++ b/zig/src/families/hy4_flash/mla_weights.zig @@ -0,0 +1,115 @@ +//! Head-local BF16 K and V projections for absorbed Hy4-flash attention. +const std = @import("std"); +const core = @import("core"); +const loader = @import("loader.zig"); + +pub const latent = 512; +pub const nope = 192; +pub const rope = 64; +pub const value_width = 256; +pub const query_stride = nope + rope; +pub const absorbed_stride = latent + rope; + +pub const HeadRange = struct { first: u32, count: u32 }; + +/// The checkpoint's own affine kv_b rows for the selected heads (per head +pub const Packed = struct { + bits: u8, + words: []u8, + scales: []u8, + biases: []u8, + + pub fn deinit(self: Packed, a: std.mem.Allocator) void { + a.free(self.words); + a.free(self.scales); + a.free(self.biases); + } +}; + +pub const Weights = struct { + key: []u16, + value: []u16, + packed_rows: ?Packed = null, + + pub fn deinit(self: *Weights, a: std.mem.Allocator) void { + a.free(self.key); + a.free(self.value); + if (self.packed_rows) |p| p.deinit(a); + self.* = undefined; + } +}; + +const per_head = nope + value_width; +const Input = union(enum) { bf16: []const u8, fp32: []const f32 }; + +fn word(input: Input, at: usize) u16 { + return switch (input) { + .bf16 => |bytes| std.mem.readInt(u16, bytes[2 * at ..][0..2], .little), + .fp32 => |elements| core.quant.convert.bf16(elements[at]), + }; +} + +fn split(a: std.mem.Allocator, input: Input, count: usize) !Weights { + const keys = try a.alloc(u16, count * nope * latent); + errdefer a.free(keys); + const values = try a.alloc(u16, count * value_width * latent); + errdefer a.free(values); + for (0..count) |head| { + const key_start = head * per_head * latent; + const value_start = key_start + nope * latent; + for (keys[head * nope * latent ..][0 .. nope * latent], 0..) |*item, i| item.* = word(input, key_start + i); + for (values[head * value_width * latent ..][0 .. value_width * latent], 0..) |*item, i| item.* = word(input, value_start + i); + } + return .{ .key = keys, .value = values }; +} + +/// The owning rank reads only its selected heads. DFly2 reads its own BF16 projection when sharing target KV. +pub fn read(a: std.mem.Allocator, model: *loader.Loaded, kind: loader.Attention, layer: u32, range: HeadRange) !Weights { + const index = try model.attentionTargetLayer(kind, layer); + const t = model.config.value.text_config; + const shape = t.headShape(index); + if (t.kv_lora_rank != latent or shape.non_rotary != nope or shape.rotary != rope or shape.value != value_width) + return error.UnsupportedHy4MlaGeometry; + if (range.count == 0 or range.first > shape.heads or range.count > shape.heads - range.first) + return error.BadHeadRange; + var key_buffer: [96]u8 = undefined; + const prefix = switch (kind) { + .target => "model.layers", + .draft => "model.dfly_layers", + }; + const base = try std.fmt.bufPrint(&key_buffer, "{s}.{d}.self_attn.kv_b_proj", .{ prefix, layer }); + const from = @as(usize, range.first) * per_head; + const to = from + @as(usize, range.count) * per_head; + const span: core.quant.Span = .{ .from = from, .to = to }; + const rows = @as(usize, shape.heads) * per_head; + var name: [108]u8 = undefined; + const weight_key = try std.fmt.bufPrint(&name, "{s}.weight", .{base}); + switch (kind) { + .draft => { + const raw = try model.checkpoint.expect(weight_key, .bf16, &.{ rows, latent }); + const selected = try core.quant.slice.takeRows(a, raw, &.{span}); + return split(a, .{ .bf16 = selected.bytes }, range.count); + }, + .target => { + const word_count = latent * @as(usize, model.bits) / 32; + const words = try model.checkpoint.expect(weight_key, .u32, &.{ rows, word_count }); + const scale_key = try std.fmt.bufPrint(&name, "{s}.scales", .{base}); + const scales = try model.checkpoint.expect(scale_key, .bf16, &.{ rows, latent / 64 }); + const bias_key = try std.fmt.bufPrint(&name, "{s}.biases", .{base}); + const biases = try model.checkpoint.expect(bias_key, .bf16, &.{ rows, latent / 64 }); + const w_rows = try core.quant.slice.takeRows(a, words, &.{span}); + const s_rows = try core.quant.slice.takeRows(a, scales, &.{span}); + const b_rows = try core.quant.slice.takeRows(a, biases, &.{span}); + const dequant = try core.quant.mlx.dequant(a, w_rows, s_rows, b_rows, 64); + defer a.free(dequant); + var out = try split(a, .{ .fp32 = dequant }, range.count); + errdefer out.deinit(a); + const pw = try a.dupe(u8, w_rows.bytes); + errdefer a.free(pw); + const ps = try a.dupe(u8, s_rows.bytes); + errdefer a.free(ps); + out.packed_rows = .{ .bits = model.bits, .words = pw, .scales = ps, .biases = try a.dupe(u8, b_rows.bytes) }; + return out; + }, + } +} diff --git a/zig/src/families/hy4_flash/model_weights.zig b/zig/src/families/hy4_flash/model_weights.zig new file mode 100644 index 00000000000..d1e130bed81 --- /dev/null +++ b/zig/src/families/hy4_flash/model_weights.zig @@ -0,0 +1,368 @@ +//! Checkpoint-backed weights for the target graph and DFly2. GPU loaders consume one layer at a time. +const std = @import("std"); +const core = @import("core"); +const config = @import("config.zig"); +const checkpoint = @import("loader.zig"); +const ranks = @import("rank_weights.zig"); +const mla = @import("mla_weights.zig"); +const ihc = @import("ihc.zig"); +const engram = @import("engram.zig"); +const engram_rows = @import("engram_rows.zig"); +const rope = @import("rope.zig"); + +const Tensor = core.checkpoint_host.Tensor; +const Affine = core.quant.mlx.Host; +const Allocator = std.mem.Allocator; +const Rank = core.quant.Rank; + +/// Prefix-scoped, checked views. The checkpoint owns these bytes. +const Reader = struct { + model: *checkpoint.Loaded, + prefix: []const u8, + + fn tensor(self: Reader, field: []const u8, format: core.checkpoint_host.DType, dims: []const usize) !Tensor { + var scratch: [160]u8 = undefined; + const key = try std.fmt.bufPrint(&scratch, "{s}{s}", .{ self.prefix, field }); + return self.model.checkpoint.expect(key, format, dims); + } + + fn affine(self: Reader, field: []const u8, dims: []const usize) !Affine { + var scratch: [128]u8 = undefined; + const key = try std.fmt.bufPrint(&scratch, "{s}{s}", .{ self.prefix, field }); + return ranks.affine(self.model, key, dims); + } + + fn bf16(self: Reader, field: []const u8, dims: []const usize) !Tensor { + return self.tensor(field, .bf16, dims); + } +}; + +pub const Head = struct { + embedding: Affine, + lm_head: Affine, + norm: Tensor, + merge: ihc.Weights, + + pub fn read(model: *checkpoint.Loaded, rows: u32) !Head { + const t = model.config.value.text_config; + const r: Reader = .{ .model = model, .prefix = "" }; + return .{ + .embedding = try r.affine("model.embed_tokens", &.{ t.vocab_size, t.hidden_size }), + .lm_head = try r.affine("lm_head", &.{ t.vocab_size, t.hidden_size }), + .norm = try r.bf16("model.norm.weight", &.{t.hidden_size}), + .merge = try ihc.Weights.read(model, .head, rows), + }; + } +}; + +fn Mlp(comptime Matrix: type) type { + return struct { gate: Matrix, up: Matrix, down: Matrix }; +} + +fn affineMlp(r: Reader, h: usize, inner: usize) !Mlp(Affine) { + return .{ + .gate = try r.affine("gate_proj", &.{ inner, h }), + .up = try r.affine("up_proj", &.{ inner, h }), + .down = try r.affine("down_proj", &.{ h, inner }), + }; +} + +fn draftMlp(r: Reader, h: usize, inner: usize) !Mlp(Tensor) { + return .{ + .gate = try r.bf16("gate_proj.weight", &.{ inner, h }), + .up = try r.bf16("up_proj.weight", &.{ inner, h }), + .down = try r.bf16("down_proj.weight", &.{ h, inner }), + }; +} + +pub const Index = struct { + token_keys: Affine, + token_norm: Tensor, + query: Affine, + head_weights: Affine, + group_values: Tensor, + group_gates: Tensor, + group_bias: Tensor, + group_norm: Tensor, + + fn read(r: Reader, t: config.Text) !Index { + const width = t.compressed_indexer_head_dim; + const heads = t.compressed_indexer_num_attention_heads; + return .{ + .token_keys = try r.affine("token_key_projection", &.{ width, t.hidden_size }), + .token_norm = try r.bf16("token_key_norm.weight", &.{width}), + .query = try r.affine("query_projection", &.{ @as(usize, heads) * width, t.q_lora_rank }), + .head_weights = try r.affine("head_weight_projection", &.{ heads, t.hidden_size }), + .group_values = try r.tensor("key_value_projection.weight", .f32, &.{ width, width }), + .group_gates = try r.tensor("key_gate_projection.weight", .f32, &.{ width, width }), + .group_bias = try r.tensor("intra_group_ape", .f32, &.{ t.compressed_indexer_compress_ratio, width }), + .group_norm = try r.tensor("key_norm.weight", .f32, &.{width}), + }; + } +}; + +pub const Routed = struct { + router: Tensor, + correction: Tensor, + down: Affine, + up: Affine, + experts: ranks.Experts, + shared: Mlp(Affine), + norm: Tensor, +}; + +pub const Feed = union(enum) { + dense: struct { projections: Mlp(Affine), norm: Tensor }, + routed: Routed, + + fn read(a: Allocator, model: *checkpoint.Loaded, layer: u32, rank: Rank) !Feed { + const t = model.config.value.text_config; + var buf: [80]u8 = undefined; + const prefix = try std.fmt.bufPrint(&buf, "model.layers.{d}.mlp.", .{layer}); + const r: Reader = .{ .model = model, .prefix = prefix }; + const h = t.hidden_size; + if (t.mlp_layer_types[layer] == .dense) { + return .{ .dense = .{ + .projections = try affineMlp(r, h, t.intermediate_size), + .norm = try r.bf16("post_fc2_norm.weight", &.{h}), + } }; + } + var shared_buf: [96]u8 = undefined; + const shared: Reader = .{ + .model = model, + .prefix = try std.fmt.bufPrint(&shared_buf, "{s}shared_experts.", .{prefix}), + }; + const latent = t.routed_expert_hidden_size; + return .{ .routed = .{ + .router = try r.bf16("gate.weight", &.{ t.n_routed_experts, h }), + .correction = try r.tensor("gate.e_score_correction_bias", .f32, &.{t.n_routed_experts}), + .down = try r.affine("routed_expert_down_proj", &.{ latent, h }), + .up = try r.affine("routed_expert_up_proj", &.{ h, latent }), + .experts = try ranks.Experts.load(a, model, layer, rank), + .shared = try affineMlp(shared, h, @as(usize, t.moe_intermediate_size) * t.n_shared_experts), + .norm = try r.bf16("combine_output_norm.weight", &.{h}), + } }; + } +}; + +pub const Engram = struct { + const Stream = struct { key: Affine, bias: Tensor, key_norm: Tensor, query_norm: Tensor, residual_scale: Tensor }; + + table: engram_rows.Table, + key: [ihc.streams]Stream, + lookup_norm: [engram.columns]Tensor, + value: Affine, + value_bias: Tensor, + pre_gamma: Tensor, + + fn read(model: *checkpoint.Loaded, layer: u32) !Engram { + const t = model.config.value.text_config; + if (t.hc_mult != ihc.streams) return error.BadHy4IhcShape; + var prefix_buf: [76]u8 = undefined; + const r: Reader = .{ + .model = model, + .prefix = try std.fmt.bufPrint(&prefix_buf, "model.layers.{d}.engram_layer.", .{layer}), + }; + const table = try engram_rows.Table.open(model, layer + 1); + const h = t.hidden_size; + const input = table.elementsPerToken(); + var out: Engram = .{ + .table = table, + .key = undefined, + .lookup_norm = undefined, + .value = try r.affine("value_proj", &.{ h, input }), + .value_bias = try r.bf16("value_proj.bias", &.{h}), + .pre_gamma = try r.bf16("unified_pre_gamma", &.{h}), + }; + var name: [72]u8 = undefined; + for (&out.lookup_norm, 0..) |*weight, i| { + weight.* = try r.bf16(try std.fmt.bufPrint(&name, "lookup_per_head_norms.{d}.weight", .{i}), &.{table.width}); + } + for (&out.key, 0..) |*weight, i| { + weight.* = .{ + .key = try r.affine(try std.fmt.bufPrint(&name, "key_projs.{d}", .{i}), &.{ h, input }), + .bias = try r.bf16(try std.fmt.bufPrint(&name, "key_projs.{d}.bias", .{i}), &.{h}), + .key_norm = try r.bf16(try std.fmt.bufPrint(&name, "norm_key.{d}.weight", .{i}), &.{h}), + .query_norm = try r.bf16(try std.fmt.bufPrint(&name, "norm_query.{d}.weight", .{i}), &.{h}), + .residual_scale = try r.bf16(try std.fmt.bufPrint(&name, "unified_per_hc_scales.{d}", .{i}), &.{h}), + }; + } + return out; + } +}; + +pub const TargetLayer = struct { + project_query: Affine, + project_kv: Affine, + norm_query: Tensor, + norm_kv: Tensor, + attention: ranks.Attention, + absorbed: mla.Weights, + sinks: [64]f32, + position: rope.Parameters, + index: ?Index, + memory: ?Engram, + attention_hc: ihc.Weights, + attention_norm: Tensor, + attention_output_norm: Tensor, + mlp_hc: ihc.Weights, + mlp_norm: Tensor, + feed: Feed, + + pub fn read(a: Allocator, model: *checkpoint.Loaded, layer: u32, rank: Rank, rows: u32) !TargetLayer { + _ = try model.attentionTargetLayer(.target, layer); + const t = model.config.value.text_config; + const h = t.hidden_size; + var path: [92]u8 = undefined; + const r: Reader = .{ .model = model, .prefix = try std.fmt.bufPrint(&path, "model.layers.{d}.", .{layer}) }; + var ix_path: [96]u8 = undefined; + const ix: Reader = .{ + .model = model, + .prefix = try std.fmt.bufPrint(&ix_path, "{s}self_attn.compressed_indexer.", .{r.prefix}), + }; + const shape = t.headShape(layer); + var attention = try ranks.Attention.load(a, model, layer, rank); + errdefer attention.deinit(a); + var absorbed = try mla.read(a, model, .target, layer, attention.heads); + errdefer absorbed.deinit(a); + var all_sinks: [64]f32 = undefined; + const sink = try model.attentionSink(.target, layer, &all_sinks); + var packed_sinks: [64]f32 = @splat(0); + const first = attention.heads.first; + const count = attention.heads.count; + @memcpy(packed_sinks[0..count], sink[first..][0..count]); + const kind = t.layer_types[layer]; + return .{ + .project_query = try r.affine("self_attn.q_a_proj", &.{ t.q_lora_rank, h }), + .project_kv = try r.affine("self_attn.kv_a_proj_with_mqa", &.{ @as(usize, t.kv_lora_rank) + shape.rotary, h }), + .norm_query = try r.bf16("self_attn.q_a_layernorm.weight", &.{t.q_lora_rank}), + .norm_kv = try r.bf16("self_attn.kv_a_layernorm.weight", &.{t.kv_lora_rank}), + .attention = attention, + .absorbed = absorbed, + .sinks = packed_sinks, + .position = try t.rotary(kind), + .index = if (kind == .deepseek_sparse_attention) try Index.read(ix, t) else null, + .memory = if (std.mem.indexOfScalar(u32, t.engram_layer_ids, layer + 1) != null) try Engram.read(model, layer) else null, + .attention_hc = try ihc.Weights.read(model, .{ .attention = layer }, rows), + .attention_norm = try r.bf16("input_layernorm.weight", &.{h}), + .attention_output_norm = try r.bf16("self_attn.post_proj_norm.weight", &.{h}), + .mlp_hc = try ihc.Weights.read(model, .{ .feed_forward = layer }, rows), + .mlp_norm = try r.bf16("post_attention_layernorm.weight", &.{h}), + .feed = try Feed.read(a, model, layer, rank), + }; + } + + pub fn deinit(self: *TargetLayer, a: Allocator) void { + self.absorbed.deinit(a); + self.attention.deinit(a); + self.* = undefined; + } +}; + +pub const DraftHead = struct { + anchor_norm: Tensor, + hidden_norm: Tensor, + fusion: Tensor, + fusion_gate: Tensor, + norm: Tensor, + correction_hidden_norm: Tensor, + correction_embedding_norm: Tensor, + correction: Mlp(Tensor), + + pub fn read(model: *checkpoint.Loaded) !DraftHead { + const h = model.config.value.text_config.hidden_size; + const r: Reader = .{ .model = model, .prefix = "model.dfly_layers." }; + const correction: Reader = .{ .model = model, .prefix = "model.dfly_layers.hidden_correction." }; + return .{ + .anchor_norm = try r.bf16("mtp_fusion.enorm.weight", &.{h}), + .hidden_norm = try r.bf16("mtp_fusion.hnorm.weight", &.{h}), + .fusion = try r.bf16("mtp_fusion.eh_proj.weight", &.{ h, @as(usize, h) * 2 }), + .fusion_gate = try r.bf16("mtp_fusion.gate", &.{h}), + .norm = try r.bf16("final_norm.weight", &.{h}), + .correction_hidden_norm = try correction.bf16("hidden_norm.weight", &.{h}), + .correction_embedding_norm = try correction.bf16("embed_norm.weight", &.{h}), + .correction = .{ + .gate = try correction.bf16("gate_proj.weight", &.{ h, @as(usize, h) * 2 }), + .up = try correction.bf16("up_proj.weight", &.{ h, @as(usize, h) * 2 }), + .down = try correction.bf16("down_proj.weight", &.{ h, h }), + }, + }; + } +}; + +pub const DraftLayer = struct { + target_kv: u32, + target_index: u32, + heads: mla.HeadRange, + input_norm: Tensor, + query_low: Tensor, + query_norm: Tensor, + query_high: Tensor, + kv_low: Tensor, + kv_norm: Tensor, + absorbed: mla.Weights, + gate: Tensor, + output: Tensor, + owns_output: bool, + output_norm: Tensor, + sinks: [64]f32, + mlp_norm: Tensor, + mlp: Mlp(Tensor), + + pub fn read(a: Allocator, model: *checkpoint.Loaded, layer: u32, rank: Rank) !DraftLayer { + const target = try model.attentionTargetLayer(.draft, layer); + const t = model.config.value.text_config; + const s = t.headShape(target); + const range = try ranks.Range.init(s.heads, rank, "Hy4-flash DFly2 attention heads"); + const heads: mla.HeadRange = .{ .first = @intCast(range.first), .count = @intCast(range.count) }; + const values = @as(usize, s.heads) * s.value; + const query = @as(usize, s.non_rotary) + s.rotary; + const value_start = range.first * s.value; + const value_end = value_start + range.count * s.value; + const h = t.hidden_size; + var path: [80]u8 = undefined; + const r: Reader = .{ + .model = model, + .prefix = try std.fmt.bufPrint(&path, "model.dfly_layers.{d}.", .{layer}), + }; + var mlp_path: [88]u8 = undefined; + const ffn: Reader = .{ .model = model, .prefix = try std.fmt.bufPrint(&mlp_path, "{s}mlp.", .{r.prefix}) }; + const inner = model.config.value.dfly_intermediate_size orelse try std.math.mul(u32, h, 3); + const o = try r.bf16("self_attn.o_proj.weight", &.{ h, values }); + const output = if (rank.world == 1) o else try core.quant.slice.takeCols(a, o, value_start, value_end); + errdefer if (rank.world != 1) a.free(output.bytes); + var absorbed = try mla.read(a, model, .draft, layer, heads); + errdefer absorbed.deinit(a); + var all_sinks: [64]f32 = undefined; + const sink = try model.attentionSink(.draft, layer, &all_sinks); + var packed_sinks: [64]f32 = @splat(0); + @memcpy(packed_sinks[0..heads.count], sink[heads.first..][0..heads.count]); + const q = try r.bf16("self_attn.q_b_proj.weight", &.{ s.queryRows(), t.q_lora_rank }); + const gate = try r.bf16("self_attn.linear_gate.weight", &.{ values, h }); + return .{ + .target_kv = target, + .target_index = model.config.value.dfly_target_index_layer[layer], + .heads = heads, + .input_norm = try r.bf16("input_layernorm.weight", &.{h}), + .query_low = try r.bf16("self_attn.q_a_proj.weight", &.{ t.q_lora_rank, h }), + .query_norm = try r.bf16("self_attn.q_a_layernorm.weight", &.{t.q_lora_rank}), + .query_high = try core.quant.slice.takeRows(a, q, &.{.{ .from = range.first * query, .to = (range.first + range.count) * query }}), + .kv_low = try r.bf16("self_attn.kv_a_proj_with_mqa.weight", &.{ @as(usize, t.kv_lora_rank) + s.rotary, h }), + .kv_norm = try r.bf16("self_attn.kv_a_layernorm.weight", &.{t.kv_lora_rank}), + .absorbed = absorbed, + .gate = try core.quant.slice.takeRows(a, gate, &.{.{ .from = value_start, .to = value_end }}), + .output = output, + .owns_output = rank.world != 1, + .output_norm = try r.bf16("self_attn.post_proj_norm.weight", &.{h}), + .sinks = packed_sinks, + .mlp_norm = try r.bf16("post_attention_layernorm.weight", &.{h}), + .mlp = try draftMlp(ffn, h, inner), + }; + } + + pub fn deinit(self: *DraftLayer, a: Allocator) void { + self.absorbed.deinit(a); + if (self.owns_output) a.free(self.output.bytes); + self.* = undefined; + } +}; diff --git a/zig/src/families/hy4_flash/moe_cuda.zig b/zig/src/families/hy4_flash/moe_cuda.zig new file mode 100644 index 00000000000..5aa2ffbdb23 --- /dev/null +++ b/zig/src/families/hy4_flash/moe_cuda.zig @@ -0,0 +1,105 @@ +//! CUDA's latent routed branch. The enclosing layer reduces the rank's partial before projecting it back. +const std = @import("std"); +const cuda = @import("cuda"); +const config = @import("config.zig"); +const ranks = @import("rank_weights.zig"); +const affine = cuda.affine_experts; + +pub const Shape = struct { + hidden: u32, + route: cuda.moe_glue.Route, + experts: affine.Shape, + + pub fn init(text: config.Text, rank: ranks.Range, rows: u32) !Shape { + const first = std.math.cast(u32, rank.first) orelse return error.BadHy4Rank; + const count = std.math.cast(u32, rank.count) orelse return error.BadHy4Rank; + if (@as(u64, first) + count > text.n_routed_experts or text.num_experts_per_tok == 0 or + text.n_routed_experts > 512 or text.num_experts_per_tok > @min(32, text.n_routed_experts)) return error.BadHy4Route; + const experts: affine.Shape = .{ + .width = text.routed_expert_hidden_size, + .inner = text.moe_intermediate_size, + .first = first, + .experts = count, + .pairs = try std.math.mul(u32, rows, text.num_experts_per_tok), + .rows = rows, + .swiglu_limit = text.swiglu_limit, + }; + try experts.check(); + return .{ + .hidden = text.hidden_size, + .route = .{ + .experts = text.n_routed_experts, + .topk = text.num_experts_per_tok, + .shared = false, + .normalize = true, + .scale = text.routed_scaling_factor, + .score = true, + }, + .experts = experts, + }; + } +}; + +pub const Weights = struct { + router: u64, + correction_bias: u64, + gate_up: affine.Weights, + down: affine.Weights, + precision: affine.Precision, +}; + +pub const Buffers = struct { + hidden: u64, // BF16 [rows][hidden] + latent: u64, // BF16 [rows][routed width] from the replicated down projection + expert_rows: u64, // i32 [rows][top-k], each entry names the owning input row + logits: u64, // FP32 [rows][global experts] + ids: u64, // int32 [rows][top-k] + probabilities: u64, // FP32 [rows][top-k] + activated: u64, // BF16 [rows * top-k][inner] + contributions: u64, // FP32 [rows * top-k][routed width] + rank_output: u64, // FP32 [rows][routed width], summed over this rank's experts +}; + +pub const Kernels = struct { + router: cuda.route_rows.RouteRows, + glue: cuda.moe_glue.MoeGlue, + experts: affine.Kernels, + + pub fn load(driver: *const cuda.Driver) !Kernels { + var router = try cuda.route_rows.RouteRows.load(driver); + errdefer router.unload(); + var glue = try cuda.moe_glue.MoeGlue.load(driver); + errdefer glue.unload(); + return .{ .router = router, .glue = glue, .experts = try affine.Kernels.load(driver) }; + } + + pub fn deinit(self: *Kernels) void { + self.experts.deinit(); + self.glue.unload(); + self.router.unload(); + self.* = undefined; + } + + pub fn forward(self: *const Kernels, s: cuda.Stream, w: Weights, b: Buffers, shape: Shape) !void { + const a = shape.experts; + try a.check(); + if (b.expert_rows == 0 or !shape.route.score or !shape.route.normalize or shape.route.shared or + @as(usize, a.rows) * shape.route.topk != a.pairs) return error.BadHy4Route; + try self.router.logits(s, b.hidden, shape.hidden, w.router, b.logits, a.rows, shape.hidden, shape.route.experts); + try self.glue.topk(s, b.logits, w.correction_bias, shape.route, b.ids, b.probabilities, a.rows); + try self.experts.run(s, w.precision, .up, .{ + .input = b.latent, + .ids = b.ids, + .src_rows = b.expert_rows, + .weights = w.gate_up, + .output = b.activated, + }, a); + try self.experts.run(s, w.precision, .down, .{ + .input = b.activated, + .ids = b.ids, + .weights = w.down, + .output = b.contributions, + }, a); + try self.glue.combine(s, b.contributions, .f32, b.probabilities, b.rank_output, .f32, a.rows, shape.route.topk, a.width); + } +}; diff --git a/zig/src/families/hy4_flash/rank_weights.zig b/zig/src/families/hy4_flash/rank_weights.zig new file mode 100644 index 00000000000..51158881fad --- /dev/null +++ b/zig/src/families/hy4_flash/rank_weights.zig @@ -0,0 +1,142 @@ +//! Exact partitions of Hy4-flash attention heads and routed experts. +const std = @import("std"); +const core = @import("core"); +const loader = @import("loader.zig"); +const mla = @import("mla_weights.zig"); + +const Affine = core.quant.mlx.Host; +const Span = core.quant.Span; +const Rank = core.quant.Rank; +const group = 64; + +pub const Range = struct { + first: usize, + count: usize, + + pub fn init(whole: usize, r: Rank, name: []const u8) !Range { + if (r.world == 0 or r.rank >= r.world or whole == 0) return error.BadHy4Rank; + const count = try core.quant.slice.even(whole, r.world, name); + return .{ .first = r.rank * count, .count = count }; + } + + fn span(self: Range, width: usize) Span { + return .{ .from = self.first * width, .to = (self.first + self.count) * width }; + } +}; + +/// Q-B and the gate own this rank's output heads. The O projection owns those same input columns. +pub const Attention = struct { + heads: mla.HeadRange, + query: Affine, + gate: Affine, + output: Affine, + owns_output: bool, + + pub fn load(a: std.mem.Allocator, model: *loader.Loaded, layer: u32, rank: Rank) !Attention { + _ = try model.attentionTargetLayer(.target, layer); + const config = model.config.value.text_config; + const shape = config.headShape(layer); + const heads = try Range.init(shape.heads, rank, "Hy4-flash attention heads"); + const query_stride = @as(usize, shape.non_rotary) + shape.rotary; + const value_width = shape.value; + var buffer: [108]u8 = undefined; + const prefix = "model.layers.{d}.self_attn."; + const query = try affine(model, try std.fmt.bufPrint(&buffer, prefix ++ "q_b_proj", .{layer}), &.{ + shape.heads * query_stride, config.q_lora_rank, + }); + const gate = try affine(model, try std.fmt.bufPrint(&buffer, prefix ++ "linear_gate", .{layer}), &.{ + @as(usize, shape.heads) * value_width, config.hidden_size, + }); + const output = try affine(model, try std.fmt.bufPrint(&buffer, prefix ++ "o_proj", .{layer}), &.{ + config.hidden_size, @as(usize, shape.heads) * value_width, + }); + return .{ + .heads = .{ .first = @intCast(heads.first), .count = @intCast(heads.count) }, + .query = try takeRows(a, query, heads.span(query_stride)), + .gate = try takeRows(a, gate, heads.span(value_width)), + .output = if (rank.world == 1) output else try takeCols(a, output, heads.span(value_width)), + .owns_output = rank.world != 1, + }; + } + + pub fn deinit(self: *Attention, a: std.mem.Allocator) void { + if (self.owns_output) { + a.free(self.output.words.bytes); + a.free(self.output.scales.bytes); + a.free(self.output.biases.bytes); + } + self.* = undefined; + } +}; + +/// Each rank reads whole experts from the two stacked affine projections, keeping global expert IDs. +pub const Experts = struct { + ids: Range, + gate_up: Affine, + down: Affine, + + pub fn load(a: std.mem.Allocator, model: *loader.Loaded, layer: u32, rank: Rank) !Experts { + _ = try model.attentionTargetLayer(.target, layer); + const config = model.config.value.text_config; + if (config.mlp_layer_types[layer] != .sparse) return error.BadHy4ExpertLayer; + const total = config.n_routed_experts; + const width = config.moe_intermediate_size; + const latent = config.routed_expert_hidden_size; + const ids = try Range.init(total, rank, "Hy4-flash routed experts"); + var name: [108]u8 = undefined; + const prefix = "model.layers.{d}.mlp.experts."; + const gate_up = try affine(model, try std.fmt.bufPrint(&name, prefix ++ "gate_up_proj", .{layer}), &.{ total, @as(usize, width) * 2, latent }); + const down = try affine(model, try std.fmt.bufPrint(&name, prefix ++ "down_proj", .{layer}), &.{ total, latent, width }); + return .{ + .ids = ids, + .gate_up = try takeRows(a, gate_up, ids.span(1)), + .down = try takeRows(a, down, ids.span(1)), + }; + } +}; + +pub fn affine(model: *loader.Loaded, key: []const u8, dims: []const usize) !Affine { + if (dims.len < 2 or dims.len > 3) return error.BadHy4ProjectionWidth; + var name: [120]u8 = undefined; + var shape: [3]usize = undefined; + @memcpy(shape[0..dims.len], dims); + const k = dims[dims.len - 1]; + if (k == 0 or k % group != 0) return error.BadHy4ProjectionWidth; + shape[dims.len - 1] = k * model.bits / 32; + const words = try model.checkpoint.expect(try std.fmt.bufPrint(&name, "{s}.weight", .{key}), .u32, shape[0..dims.len]); + shape[dims.len - 1] = k / group; + return .{ + .words = words, + .scales = try model.checkpoint.expect(try std.fmt.bufPrint(&name, "{s}.scales", .{key}), .bf16, shape[0..dims.len]), + .biases = try model.checkpoint.expect(try std.fmt.bufPrint(&name, "{s}.biases", .{key}), .bf16, shape[0..dims.len]), + .bits = model.bits, + .group = group, + }; +} + +fn takeRows(a: std.mem.Allocator, p: Affine, span: Span) !Affine { + var cut = p; + cut.words = try core.quant.slice.takeRows(a, p.words, &.{span}); + cut.scales = try core.quant.slice.takeRows(a, p.scales, &.{span}); + cut.biases = try core.quant.slice.takeRows(a, p.biases, &.{span}); + return cut; +} + +fn takeCols(a: std.mem.Allocator, p: Affine, cols: Span) !Affine { + if (cols.from % group != 0 or cols.to % group != 0) return error.BadHy4ProjectionWidth; + var cut = p; + cut.words = try core.quant.slice.takeCols(a, p.words, cols.from * p.bits / 32, cols.to * p.bits / 32); + errdefer a.free(cut.words.bytes); + cut.scales = try core.quant.slice.takeCols(a, p.scales, cols.from / group, cols.to / group); + errdefer a.free(cut.scales.bytes); + cut.biases = try core.quant.slice.takeCols(a, p.biases, cols.from / group, cols.to / group); + return cut; +} + +test "both rank cuts align attention and routed expert partitions" { + try std.testing.expectEqual(Range{ .first = 16, .count = 16 }, try Range.init(32, .{ .rank = 1, .world = 2 }, "sparse")); + try std.testing.expectEqual(Range{ .first = 0, .count = 32 }, try Range.init(64, .{ .rank = 0, .world = 2 }, "sliding")); + const ids = try Range.init(512, .{ .rank = 1, .world = 2 }, "experts"); + try std.testing.expectEqual(Span{ .from = 256, .to = 512 }, ids.span(1)); + try std.testing.expectError(error.BadHy4Rank, Range.init(32, .{ .rank = 0, .world = 0 }, "sparse")); +} diff --git a/zig/src/families/hy4_flash/rope.zig b/zig/src/families/hy4_flash/rope.zig new file mode 100644 index 00000000000..db6f54c41a8 --- /dev/null +++ b/zig/src/families/hy4_flash/rope.zig @@ -0,0 +1,57 @@ +//! Hy4-flash uses adjacent rotary pairs with interleaved time, height and width positions. +const std = @import("std"); + +pub const pairs = 32; +pub const Config = struct { + rope_type: []const u8, + rope_theta: f32, + mrope_interleaved: bool, + mrope_section: [3]u32, + + pub fn parameters(self: Config, width: u32) !Parameters { + if (width != pairs * 2 or !self.mrope_interleaved or !std.mem.eql(u8, self.rope_type, "default") or + !std.math.isFinite(self.rope_theta) or self.rope_theta <= 0) + return error.UnsupportedHy4Rotary; + var result: Parameters = undefined; + var counts: [3]u32 = @splat(0); + for (&result.frequencies, &result.axes, 0..) |*freq, *axis, i| { + axis.* = switch (i % 3) { + 1 => if (i / 3 < self.mrope_section[1]) 1 else 0, + 2 => if (i / 3 < self.mrope_section[2]) 2 else 0, + else => 0, + }; + counts[axis.*] += 1; + freq.* = 1 / std.math.pow(f32, self.rope_theta, @as(f32, @floatFromInt(i)) / pairs); + } + if (!std.mem.eql(u32, &counts, &self.mrope_section)) return error.UnsupportedHy4Rotary; + return result; + } +}; + +pub const Parameters = extern struct { frequencies: [pairs]f32, axes: [pairs]u32 }; + +/// Strides are in BF16 elements. Both base pointers address the first rotary element of head zero. +pub const View = extern struct { + rows: u32, + heads: u32, + input_stride: u32, + output_stride: u32, + + pub fn check(self: View) !void { + if (self.rows == 0 or self.rows > std.math.maxInt(u16) or self.heads == 0 or self.heads > 64 or + self.input_stride < 2 * pairs or self.output_stride < 2 * pairs) return error.BadHy4RotaryView; + } +}; + +test "checkpoint rotary tables use distinct frequency bases and exactly twelve time pairs" { + const config = @import("config.zig"); + const parsed = try config.parse(std.testing.allocator, @embedFile("config_fixture.json")); + defer parsed.deinit(); + const sliding = try parsed.value.text_config.rotary(.sliding_attention); + const sparse = try parsed.value.text_config.rotary(.deepseek_sparse_attention); + try std.testing.expectEqualSlices(u32, &sliding.axes, &sparse.axes); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2 }, sliding.axes[0..3]); + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2, 0, 0 }, sliding.axes[27..32]); + try std.testing.expectApproxEqAbs(@as(f32, 0.01), sliding.frequencies[16], 0.0000001); + try std.testing.expectApproxEqAbs(@as(f32, 0.00031622777), sparse.frequencies[16], 0.0000001); +} diff --git a/zig/src/families/hy4_flash/serve_draft.zig b/zig/src/families/hy4_flash/serve_draft.zig new file mode 100644 index 00000000000..4498b238d4a --- /dev/null +++ b/zig/src/families/hy4_flash/serve_draft.zig @@ -0,0 +1,95 @@ +//! DFly2 drafts for a served Hy4-flash stream, from the anchor row's final hidden. +const std = @import("std"); +const mtl = @import("metal"); +const target = @import("metal_model.zig"); +const index = @import("metal_index.zig"); +const serve = @import("serve_metal.zig"); +const Metal = serve.Metal; +const Cache = serve.Cache; +const prompt_rows = serve.prompt_rows; +const draft_stride = serve.draft_stride; + +pub fn run(self: *Metal, c: *Cache, anchor_row: u32, bonus: u32, depth: u32) !void { + const w = self.draft.width; + const count = @min(depth, w - 1); + c.nheld = 0; + if (count == 0) return; + const p = c.len; + if (p + w > self.capacity) return; + self.bind(c); + const ids = self.d_ids.slice(u32, w); + @memset(ids, self.mask_token); + ids[0] = bonus; + const pos3 = self.d_positions.slice(i32, w * 3); + const wr = self.d_writes.slice(i32, w); + for (0..w) |i| { + const at = p + @as(u32, @intCast(i)); + pos3[i * 3 ..][0..3].* = @splat(@intCast(at)); + wr[i] = @intCast(at); + } + // each block's keys: past 2,048 the anchor's recalled list in its target layer, then the draft's own rows + for (self.draft.blocks, self.d_keys, self.d_counts) |block, kb, cb_| { + const keys = kb.slice(u32, @as(usize, w) * draft_stride); + const counts = cb_.slice(u32, w); + var base: []const i32 = &.{}; + if (c.selected) { + const all = self.ix_tokens[block.target_index].?.slice(i32, @as(usize, prompt_rows) * index.keys_a_row); + const n: usize = @intCast(self.ix_counts[block.target_index].?.slice(i32, prompt_rows)[anchor_row]); + base = all[@as(usize, anchor_row) * index.keys_a_row ..][0..n]; + } + for (0..w) |i| { + const at = p + @as(u32, @intCast(i)); + const row_keys = keys[i * draft_stride ..][0..draft_stride]; + var k: usize = 0; + if (c.selected) { + for (base) |slot| if (slot >= 0 and @as(u32, @intCast(slot)) < p) { + row_keys[k] = @intCast(slot); + k += 1; + }; + for (p..at + 1) |slot| { + row_keys[k] = @intCast(slot); + k += 1; + } + } else { + for (0..at + 1) |slot| row_keys[slot] = @intCast(slot); + k = at + 1; + } + counts[i] = @intCast(k); + } + } + const h = self.draft.hidden; + const hidden = self.frame.common.normalized; + const anchor: target.Ref = .{ .buffer = hidden.buffer, .offset = hidden.offset + @as(usize, anchor_row) * h * 2 }; + const pick = self.model.common.rows orelse return error.Hy4NeedsRowKernels; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.concurrent); + encode: { + self.draft.encode(&self.model, e, &self.dframe, .{ .buffer = self.d_ids }, anchor, 1, self.d_caches) catch |err| { + e.end(); + return err; + }; + e.barrier(); + for (0..count) |col| { + const previous: target.Ref = if (col == 0) .{ .buffer = self.d_ids } else .{ .buffer = self.d_tokens, .offset = (col - 1) * 4 }; + const logits = self.draft.next(&self.model, e, &self.dframe, previous, @intCast(col + 1)) catch |err| { + e.end(); + return err; + }; + e.barrier(); + pick.pick(e, logits, .{ .buffer = self.d_tokens }, @intCast(col), 1, self.vocab); + e.barrier(); + } + break :encode; + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.log.err("hy4: draft pass failed: {s}", .{why}); + return error.Hy4GpuFailed; + } + @memcpy(c.held[0..count], self.d_tokens.slice(u32, count)); + c.nheld = count; +} diff --git a/zig/src/families/hy4_flash/serve_metal.zig b/zig/src/families/hy4_flash/serve_metal.zig new file mode 100644 index 00000000000..e5e06d54be6 --- /dev/null +++ b/zig/src/families/hy4_flash/serve_metal.zig @@ -0,0 +1,600 @@ +//! Hy4-flash behind the lane engine on Metal +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const target = @import("metal_model.zig"); +const dfly = @import("metal_draft.zig"); +const index = @import("metal_index.zig"); +const engram = @import("engram.zig"); +const be = lanes.backend; + +pub const key_width = 576; // BF16 words in a latent KV slot: 512 latent + 64 rope +pub const window: u32 = 512; // the sliding layers' keys +pub const prompt_rows: u32 = 512; // a prompt chunk's rows +pub const max_window: u32 = 6; // the pending row and DFly2's five drafts +pub const draft_stride: u32 = 2560; // a draft row's keys at most: a recalled list (2,048) and its own rows + +pub const Options = struct { + capacity: u32, // slots a stream's caches hold (a multiple of 512) +}; + +/// One stream's caches. +pub const Cache = struct { + kv: []mtl.Buffer, + token_keys: []?mtl.Buffer, + group_keys: []?mtl.Buffer, + len: u32 = 0, // slots written and kept + hist: std.ArrayList(u32) = .empty, // the token at each kept slot + held: [max_window]u32 = @splat(0), + nheld: u32 = 0, + logits: []u16, // the last pass's last row + anchor: u32 = 0, // the row of the last pass whose final hidden the drafter reads (with no kept rows given) + selected: bool = false, // the last pass's sparse layers attended recalled lists + + fn deinit(self: *Cache, gpa: std.mem.Allocator) void { + for (self.kv) |b| b.deinit(); + for (self.token_keys) |b| if (b) |x| x.deinit(); + for (self.group_keys) |b| if (b) |x| x.deinit(); + gpa.free(self.kv); + gpa.free(self.token_keys); + gpa.free(self.group_keys); + gpa.free(self.logits); + self.hist.deinit(gpa); + } +}; + +pub const Metal = struct { + gpa: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + model: target.Model, + draft: dfly.Draft, + frame: target.Frame, + dframe: dfly.Frame, + capacity: u32, + vocab: u32, + pad: u32, + mask_token: u32, + sliding: []bool, + lanes: []target.LayerCache, + positions: mtl.Buffer, + writes: mtl.Buffer, + slide_keys: mtl.Buffer, + slide_counts: mtl.Buffer, + sparse_keys: mtl.Buffer, + sparse_counts: mtl.Buffer, + slide_ranges: mtl.Buffer, + sparse_ranges: mtl.Buffer, + tiles: mtl.Buffer, + scores: mtl.Buffer, + ix_tokens: []?mtl.Buffer, + ix_counts: []?mtl.Buffer, + d_ids: mtl.Buffer, + d_tokens: mtl.Buffer, + d_positions: mtl.Buffer, + d_writes: mtl.Buffer, + d_keys: []mtl.Buffer, + d_counts: []mtl.Buffer, + d_caches: []target.LayerCache, + caches: std.AutoHashMapUnmanaged(*lanes.Stream, *Cache) = .empty, + kept: ?*Cache = null, // the last released stream's caches, for a prompt that shares their prefix + costs: [max_window]lanes.allocate.Cost = undefined, + draft_ms: f64 = 0, + /// The residency set's hook: caches made after the set is built join it. + follow: ?mtl.ResidencySet.Follow = null, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, options: Options) !*Metal { + if (options.capacity < 2048 or options.capacity % 512 != 0 or options.capacity / 4 > 65536) return error.BadHy4Capacity; + const out = try gpa.create(Metal); + errdefer gpa.destroy(out); + const device = try mtl.Device.init(); + errdefer device.deinit(); + const queue = try device.queue(); + errdefer queue.deinit(); + out.* = undefined; + out.gpa = gpa; + out.device = device; + out.queue = queue; + out.capacity = options.capacity; + out.caches = .empty; + out.kept = null; + out.draft_ms = 0; + out.follow = null; + out.model = try target.Model.open(gpa, io, device, dir); + errdefer out.model.deinit(); + const t = out.model.host.config.value.text_config; + out.vocab = t.vocab_size; + out.pad = t.engram_pad_id; + out.mask_token = out.model.host.config.value.dfly_mask_token_id; + out.draft = try dfly.Draft.open(gpa, device, &out.model.host); + errdefer out.draft.deinit(); + if (out.draft.width > max_window) return error.Hy4DraftTooWide; + out.frame = try target.Frame.init(gpa, device, &out.model, prompt_rows, index.keys_a_row); + errdefer out.frame.deinit(); + out.dframe = try dfly.Frame.init(gpa, device, &out.model, &out.draft, 1, draft_stride); + errdefer out.dframe.deinit(); + const layers = out.model.blocks.len; + const opts = mtl.ResourceOptions.shared; + const C = options.capacity; + out.positions = try device.buffer(prompt_rows * 3 * 4, opts); + out.writes = try device.buffer(prompt_rows * 4, opts); + out.slide_keys = try device.buffer(prompt_rows * window * 4, opts); + out.slide_counts = try device.buffer(prompt_rows * 4, opts); + out.sparse_keys = try device.buffer(prompt_rows * index.keys_a_row * 4, opts); + out.sparse_counts = try device.buffer(prompt_rows * 4, opts); + out.slide_ranges = try device.buffer(prompt_rows * 8, opts); + out.sparse_ranges = try device.buffer(prompt_rows * 8, opts); + out.tiles = try device.buffer(C / 32 * 4, opts); + for (out.tiles.slice(u32, C / 32), 0..) |*x, i| x.* = @intCast(32 * i); + out.scores = try device.buffer(@as(usize, prompt_rows) * (C / 4) * 4, mtl.ResourceOptions.private); + out.sliding = try gpa.alloc(bool, layers); + out.lanes = try gpa.alloc(target.LayerCache, layers); + out.ix_tokens = try gpa.alloc(?mtl.Buffer, layers); + out.ix_counts = try gpa.alloc(?mtl.Buffer, layers); + for (0..layers) |l| { + const slide = t.layer_types[l] == .sliding_attention; + out.sliding[l] = slide; + out.ix_tokens[l] = if (slide) null else try device.buffer(@as(usize, prompt_rows) * index.keys_a_row * 4, opts); + out.ix_counts[l] = if (slide) null else try device.buffer(prompt_rows * 4, opts); + out.lanes[l] = .{ + .rows = .{ + .positions = .{ .buffer = out.positions }, + .write_slots = .{ .buffer = out.writes }, + .retained = .{ .buffer = if (slide) out.slide_keys else out.sparse_keys }, + .counts = .{ .buffer = if (slide) out.slide_counts else out.sparse_counts }, + .cache = .{ .buffer = out.positions }, // bound to a stream's caches before each pass + .capacity = C, + .ranges = .{ .ranges = .{ .buffer = if (slide) out.slide_ranges else out.sparse_ranges }, .tiles = .{ .buffer = out.tiles } }, + }, + .key_stride = if (slide) window else index.keys_a_row, + }; + } + const w = out.draft.width; + out.d_ids = try device.buffer(w * 4, opts); + out.d_tokens = try device.buffer(16 * 4, opts); + out.d_positions = try device.buffer(w * 3 * 4, opts); + out.d_writes = try device.buffer(w * 4, opts); + const blocks = out.draft.blocks.len; + out.d_keys = try gpa.alloc(mtl.Buffer, blocks); + out.d_counts = try gpa.alloc(mtl.Buffer, blocks); + out.d_caches = try gpa.alloc(target.LayerCache, blocks); + for (out.d_keys, out.d_counts, out.d_caches) |*k, *c, *dc| { + k.* = try device.buffer(@as(usize, w) * draft_stride * 4, opts); + c.* = try device.buffer(w * 4, opts); + dc.* = .{ .rows = .{ + .positions = .{ .buffer = out.d_positions }, + .write_slots = .{ .buffer = out.d_writes }, + .retained = .{ .buffer = k.* }, + .counts = .{ .buffer = c.* }, + .cache = .{ .buffer = out.positions }, + .capacity = C, + }, .key_stride = draft_stride }; + } + return out; + } + + pub fn deinit(self: *Metal) void { + var it = self.caches.valueIterator(); + while (it.next()) |c| { + c.*.deinit(self.gpa); + self.gpa.destroy(c.*); + } + self.caches.deinit(self.gpa); + if (self.kept) |c| { + c.deinit(self.gpa); + self.gpa.destroy(c); + } + for (self.d_keys) |b| b.deinit(); + for (self.d_counts) |b| b.deinit(); + for (self.ix_tokens) |b| if (b) |x| x.deinit(); + for (self.ix_counts) |b| if (b) |x| x.deinit(); + for ([_]mtl.Buffer{ self.positions, self.writes, self.slide_keys, self.slide_counts, self.sparse_keys, self.sparse_counts, self.slide_ranges, self.sparse_ranges, self.tiles, self.scores, self.d_ids, self.d_tokens, self.d_positions, self.d_writes }) |b| b.deinit(); + self.gpa.free(self.d_keys); + self.gpa.free(self.d_counts); + self.gpa.free(self.d_caches); + self.gpa.free(self.ix_tokens); + self.gpa.free(self.ix_counts); + self.gpa.free(self.lanes); + self.gpa.free(self.sliding); + self.dframe.deinit(); + self.frame.deinit(); + self.draft.deinit(); + self.model.deinit(); + self.queue.deinit(); + self.device.deinit(); + self.gpa.destroy(self); + } + + /// Every Metal buffer the model, drafter, frames, pass state and kept caches hold, for one residency set. + pub fn residentBuffers(self: *Metal, list: *std.ArrayList(mtl.Buffer)) !void { + return @import("serve_resident.zig").buffers(self, list); + } + + /// Bytes one stream's caches take at `capacity` slots. + pub fn cacheBytes(self: *const Metal, capacity: u32) u64 { + var sparse: u64 = 0; + for (self.sliding) |s| sparse += @intFromBool(!s); + return @as(u64, self.sliding.len) * capacity * key_width * 2 + sparse * (index.Cache.tokenBytes(capacity) + index.Cache.groupBytes(capacity)); + } + + fn newCache(self: *Metal) !*Cache { + const c = try self.gpa.create(Cache); + errdefer self.gpa.destroy(c); + const layers = self.sliding.len; + const opts = mtl.ResourceOptions.private; + const kv = try self.gpa.alloc(mtl.Buffer, layers); + errdefer self.gpa.free(kv); + const tk = try self.gpa.alloc(?mtl.Buffer, layers); + errdefer self.gpa.free(tk); + const gk = try self.gpa.alloc(?mtl.Buffer, layers); + errdefer self.gpa.free(gk); + @memset(tk, null); + @memset(gk, null); + var made: usize = 0; + errdefer for (kv[0..made], tk[0..made], gk[0..made]) |b, x, y| { + b.deinit(); + if (x) |v| v.deinit(); + if (y) |v| v.deinit(); + }; + for (0..layers) |l| { + kv[l] = try self.device.buffer(@as(usize, self.capacity) * key_width * 2, opts); + if (!self.sliding[l]) { + tk[l] = try self.device.buffer(index.Cache.tokenBytes(self.capacity), opts); + gk[l] = try self.device.buffer(index.Cache.groupBytes(self.capacity), opts); + } + made += 1; + } + c.* = .{ .kv = kv, .token_keys = tk, .group_keys = gk, .logits = try self.gpa.alloc(u16, self.vocab) }; + // touch every page now: a fresh buffer's first GPU writes otherwise cost seconds inside a request + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = self.queue.commandBuffer(); + const blit = cb.blit(); + for (0..layers) |l| { + blit.fill(kv[l], 0, @as(usize, self.capacity) * key_width * 2, 0); + if (tk[l]) |b| blit.fill(b, 0, index.Cache.tokenBytes(self.capacity), 0); + if (gk[l]) |b| blit.fill(b, 0, index.Cache.groupBytes(self.capacity), 0); + } + blit.end(); + cb.commit(); + cb.wait(); + if (self.follow) |f| for (0..layers) |l| { + f.join(f.ctx, kv[l]); + if (tk[l]) |b| f.join(f.ctx, b); + if (gk[l]) |b| f.join(f.ctx, b); + }; + return c; + } + + /// Point the layers' caches at `c` for the next pass. + pub fn bind(self: *Metal, c: *const Cache) void { + for (self.lanes, 0..) |*lane, l| { + lane.rows.cache = .{ .buffer = c.kv[l] }; + lane.index = if (self.sliding[l]) null else .{ + .token_keys = .{ .buffer = c.token_keys[l].? }, + .group_keys = .{ .buffer = c.group_keys[l].? }, + .capacity = self.capacity, + .scores = .{ .buffer = self.scores }, + .score_groups = self.capacity / 4, + .tokens = .{ .buffer = self.ix_tokens[l].? }, + .counts = .{ .buffer = self.ix_counts[l].? }, + }; + } + for (self.d_caches, self.draft.blocks) |*dc, block| dc.rows.cache = .{ .buffer = c.kv[block.target_kv] }; + } + + /// Engram windows and ids for `tokens` at slots start.. (the cache's history holds the tokens before start). + fn stage(self: *Metal, c: *const Cache, start: u32, tokens: []const u32) !void { + const n = tokens.len; + var windows: [prompt_rows][engram.order]u32 = undefined; + var media: [prompt_rows]u32 = @splat(0); + for (tokens, 0..) |tk, r| { + const pos = start + @as(u32, @intCast(r)); + windows[r][0] = tk; + for (1..engram.order) |lag| { + windows[r][lag] = if (lag <= r) tokens[r - lag] else if (lag <= pos) c.hist.items[pos - lag] else self.pad; + } + } + try self.frame.stage(&self.model, tokens, windows[0..n], media[0..n]); + } + + /// Positions, write slots and the key lists and ranges of `n` rows at start.., and the indexer's rows. + fn layout(self: *Metal, start: u32, n: u32) !void { + const pos3 = self.positions.slice(i32, prompt_rows * 3); + const wr = self.writes.slice(i32, prompt_rows); + const last_end = start + n; + try self.frame.index.stage(start, n); + const lists = self.frame.index.selects(); + const sparse_stride: u32 = if (lists) index.keys_a_row else ((last_end + window - 1) / window) * window; + const sk = self.slide_keys.slice(u32, prompt_rows * window); + const sc = self.slide_counts.slice(u32, prompt_rows); + const pk = self.sparse_keys.slice(u32, prompt_rows * index.keys_a_row); + const pc = self.sparse_counts.slice(u32, prompt_rows); + for (0..n) |r| { + const pos = start + @as(u32, @intCast(r)); + const end = pos + 1; + pos3[r * 3 ..][0..3].* = @splat(@intCast(pos)); + wr[r] = @intCast(pos); + const count = @min(end, window); + for (0..count) |j| sk[r * window + j] = end - count + @as(u32, @intCast(j)); + sc[r] = count; + if (!lists) { + for (0..end) |j| pk[r * sparse_stride + j] = @intCast(j); + pc[r] = end; + } + self.slide_ranges.slice([2]u32, prompt_rows)[r] = .{ end - count, end }; + self.sparse_ranges.slice([2]u32, prompt_rows)[r] = .{ 0, end }; + } + for (self.lanes, self.sliding) |*lane, slide| { + lane.key_stride = if (slide) window else sparse_stride; + lane.rows.live_keys = if (slide) @min(last_end, window) else if (lists) index.keys_a_row else last_end; + } + } + + /// One target pass over `tokens` at the cache's end: every row's logits when `all`, else the last row's. + fn pass(self: *Metal, c: *Cache, tokens: []const u32, all: bool) !void { + const n: u32 = @intCast(tokens.len); + if (n == 0 or n > prompt_rows) return error.BadHy4Pass; + const start = c.len; + if (start + n > self.capacity) return error.Hy4ContextFull; + self.bind(c); + try self.stage(c, start, tokens); + try self.layout(start, n); + self.frame.last_logits = !all and n > 1; + defer self.frame.last_logits = false; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.concurrent); + _ = self.model.encode(e, &self.frame, self.lanes) catch |err| { + e.end(); + return err; + }; + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.log.err("hy4: target pass failed: {s}", .{why}); + return error.Hy4GpuFailed; + } + c.len += n; + try c.hist.appendSlice(self.gpa, tokens); + c.anchor = n - 1; + c.selected = self.frame.index.selects(); + const rows: usize = if (self.frame.last_logits) 1 else n; + @memcpy(c.logits, self.frame.logits.buffer.slice(u16, rows * self.vocab)[(rows - 1) * self.vocab ..][0..self.vocab]); + } + + fn logitsRow(self: *const Metal, r: usize) []const u16 { + return self.frame.logits.buffer.slice(u16, (r + 1) * self.vocab)[r * self.vocab ..][0..self.vocab]; + } + + pub fn facts(self: *const Metal) lanes.Model { + return .{ + .exact_width = max_window, + .mtp = true, + .speculate = true, + .speculate_early = false, + .drafts = self.draft.width - 1, + .window_costs = &self.costs, + .mtp_step_ms = self.draft_ms, + .max_streams = 1, + .streams_exact = true, + }; + } + + pub fn backend(self: *Metal) be.Backend { + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } }; + } + + fn cast(ptr: *anyopaque) *Metal { + return @ptrCast(@alignCast(ptr)); + } + + fn cacheOf(self: *Metal, s: *lanes.Stream) !*Cache { + return self.caches.get(s) orelse error.UnknownHy4Stream; + } + + /// A prompt chunk, the verify widths and a draft once, timing each width for the lane core's depth rule. + pub fn warm(self: *Metal) !void { + const c = try self.newCache(); + errdefer { + c.deinit(self.gpa); + self.gpa.destroy(c); + } + var ids: [prompt_rows]u32 = undefined; + for (&ids, 0..) |*x, i| x.* = @intCast(1000 + i * 37 % 20000); + ids[0] = 120000; + try self.pass(c, ids[0..prompt_rows], false); + for (1..max_window + 1) |width| { + var times: [3]f64 = undefined; + for (×) |*tm| { + const t0 = mtl.clock.seconds(); + try self.pass(c, ids[0..width], true); + tm.* = mtl.clock.seconds() - t0; + c.len -= @intCast(width); + c.hist.items.len -= width; + } + std.mem.sort(f64, ×, {}, std.sort.asc(f64)); + self.costs[width - 1] = .{ .width = @intCast(width), .ms = 1000 * times[1] }; + } + try self.runDraft(c, c.anchor, ids[1], 3); // the first draft compiles its pipelines + const t0 = mtl.clock.seconds(); + try self.runDraft(c, c.anchor, ids[1], 3); + self.draft_ms = 1000 * (mtl.clock.seconds() - t0) / 3; + // every page of the caches touched once, then kept for the first stream + c.len = 0; + c.hist.items.len = 0; + c.nheld = 0; + self.kept = c; + std.log.info("hy4: window ms by width {d:.1} {d:.1} {d:.1} {d:.1} {d:.1} {d:.1}, draft {d:.2} ms a token", .{ self.costs[0].ms, self.costs[1].ms, self.costs[2].ms, self.costs[3].ms, self.costs[4].ms, self.costs[5].ms, self.draft_ms }); + } + + fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) !void { + const self = cast(ptr); + const ids = s.prompt(); + if (ids.len == 0 or self.caches.contains(s)) return error.InvalidHy4Prompt; + if (ids.len + s.max_new + max_window > self.capacity) return error.Hy4ContextFull; + // the kept caches, when this prompt starts with their tokens (keep at least one prompt token to run) + var c: *Cache = undefined; + var reused: u32 = 0; + if (self.kept) |k| { + var same: usize = 0; + const most = @min(k.hist.items.len, ids.len - 1); + while (same < most and k.hist.items[same] == ids[same]) same += 1; + // the caches are reused either way (fresh pages cost seconds to first touch): only the shared prefix stays + if (same < 64) same = 0; + c = k; + self.kept = null; + c.len = @intCast(same); + c.hist.items.len = same; + c.nheld = 0; + reused = @intCast(same); + } else c = try self.newCache(); + errdefer { + c.deinit(self.gpa); + self.gpa.destroy(c); + } + try self.caches.put(self.gpa, s, c); + errdefer _ = self.caches.remove(s); + s.cached = reused; + var at: usize = reused; + while (at < ids.len) { + if (s.isCancelled()) return error.Cancelled; + const end = @min(ids.len, at + prompt_rows); + try self.pass(c, ids[at..end], false); + lanes.prefill_widths.completed(self.gpa, s, end - at); + at = end; + } + } + + fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) !u64 { + const self = cast(ptr); + const c = try self.cacheOf(s); + if (position != c.len) return error.InvalidHy4Position; + return try lanes.sampling_row.draw(self.gpa, c.logits, s.sampling, position, &.{}); + } + + fn firstMaskedFn(ptr: *anyopaque, s: *lanes.Stream, position: u64, mask: []const u32) !u64 { + const self = cast(ptr); + const c = try self.cacheOf(s); + if (position != c.len) return error.InvalidHy4Position; + return try lanes.sampling_row.draw(self.gpa, c.logits, s.sampling, position, mask); + } + + fn queueFn(ptr: *anyopaque, s: *lanes.Stream, f: be.Feed, position: u64) !u64 { + const self = cast(ptr); + const c = try self.cacheOf(s); + if (position != c.len + 1) return error.InvalidHy4Position; + const token: u32 = switch (f) { + .value => |v| v, + .handle => |h| @intCast(h), + }; + c.nheld = 0; + try self.pass(c, &.{token}, false); + return try lanes.sampling_row.draw(self.gpa, c.logits, s.sampling, position, &.{}); + } + + fn readFn(ptr: *anyopaque, handle: u64) !u32 { + if (handle >= cast(ptr).vocab) return error.InvalidHy4Token; + return @intCast(handle); + } + + fn firstRowFn(ptr: *anyopaque, s: *lanes.Stream) !lanes.LogprobRow { + const self = cast(ptr); + const l = (try self.cacheOf(s)).logits; + return row(l, @intCast(argmax(l)), s.logprobs orelse 0); + } + + /// The window's pending token and drafts in one pass, every row drawn; `keep` rolls the rest back. + fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const self = cast(ptr); + const words = (self.vocab + 31) / 32; + if (windows.len != out.len) return error.InvalidHy4Windows; + for (windows, out) |w, o| { + const rows = w.rows(); + if (rows > max_window or w.parents != null or o.sampled.len != rows or o.drafts.len != rows - 1) return error.UnsupportedHy4Window; + const c = try self.cacheOf(w.stream); + if (w.held > c.nheld) return error.Hy4DraftsNotHeld; + for (w.positions, 0..) |p, r| if (p != c.len + r + 1) return error.InvalidHy4Position; + var ids: [max_window]u32 = undefined; + ids[0] = w.pending; + @memcpy(ids[1..][0..w.held], c.held[0..w.held]); + @memcpy(ids[1 + w.held ..][0..w.tokens.len], w.tokens); + c.nheld = 0; + try self.pass(c, ids[0..rows], true); + @memcpy(o.drafts, ids[1..rows]); + for (0..rows) |r| { + const l = self.logitsRow(r); + const mask = if (w.masks.len >= (r + 1) * words) w.masks[r * words ..][0..words] else &.{}; + o.sampled[r] = try lanes.sampling_row.draw(self.gpa, l, w.stream.sampling, w.positions[r], mask); + if (o.rows.len == rows) o.rows[r] = row(l, o.sampled[r], w.stream.logprobs orelse 0); + } + } + } + + fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const self = cast(ptr); + for (windows, paths) |w, path| { + const c = try self.cacheOf(w.stream); + for (path, 0..) |r, i| if (r != i) return error.UnsupportedHy4Tree; + const rows: u32 = @intCast(w.rows()); + if (path.len == 0 or path.len > rows or rows > c.len) return error.UnsupportedHy4Window; + c.len = c.len - rows + @as(u32, @intCast(path.len)); + c.hist.items.len = c.len; + c.anchor = @intCast(path.len - 1); + } + } + + /// DFly2 from the anchor row's final hidden + pub fn runDraft(self: *Metal, c: *Cache, anchor_row: u32, bonus: u32, depth: u32) !void { + return @import("serve_draft.zig").run(self, c, anchor_row, bonus, depth); + } + + fn draftFn(ptr: *anyopaque, requests: []const be.DraftRequest) !void { + const self = cast(ptr); + for (requests) |r| { + const c = try self.cacheOf(r.stream); + c.nheld = 0; + var anchor_row = c.anchor; + if (r.rows) |rows| { + if (rows.len == 0) return error.UnsupportedHy4Window; + for (rows, 0..) |x, i| if (x != i) return error.UnsupportedHy4Tree; + anchor_row = rows[rows.len - 1]; + } + const bonus: u32 = if (r.follow.len > 0) r.follow[r.follow.len - 1] else switch (r.first orelse return error.NoFirstToken) { + .value => |v| v, + .handle => |hd| @intCast(hd), + }; + if (r.position != @as(u64, c.len) + 1) return error.InvalidHy4Position; + try self.runDraft(c, anchor_row, bonus, r.depth); + } + } + + fn heldFn(ptr: *anyopaque, s: *lanes.Stream, out: []u32) !void { + const c = try cast(ptr).cacheOf(s); + if (out.len > c.nheld) return error.Hy4DraftsNotHeld; + @memcpy(out, c.held[0..out.len]); + } + + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { + const self = cast(ptr); + const entry = self.caches.fetchRemove(s) orelse return; + if (self.kept) |k| { + k.deinit(self.gpa); + self.gpa.destroy(k); + } + entry.value.nheld = 0; + self.kept = entry.value; + } +}; + +fn argmax(l: []const u16) usize { + var best: usize = 0; + for (l, 0..) |w, i| if (@as(f32, @bitCast(@as(u32, w) << 16)) > @as(f32, @bitCast(@as(u32, l[best]) << 16))) { + best = i; + }; + return best; +} + +const row = @import("../step5/backend.zig").row; diff --git a/zig/src/families/hy4_flash/serve_resident.zig b/zig/src/families/hy4_flash/serve_resident.zig new file mode 100644 index 00000000000..1cb35aca44c --- /dev/null +++ b/zig/src/families/hy4_flash/serve_resident.zig @@ -0,0 +1,78 @@ +//! Every Metal buffer a served Hy4-flash model holds, gathered once for its residency set. +const std = @import("std"); +const mtl = @import("metal"); +const target = @import("metal_model.zig"); +const dfly = @import("metal_draft.zig"); +const Metal = @import("serve_metal.zig").Metal; + +pub fn buffers(self: *Metal, list: *std.ArrayList(mtl.Buffer)) !void { + try gather(target.Model, &self.model, list, self.gpa); + try gather(dfly.Draft, &self.draft, list, self.gpa); + try gather(target.Frame, &self.frame, list, self.gpa); + try gather(dfly.Frame, &self.dframe, list, self.gpa); + for ([_]mtl.Buffer{ self.positions, self.writes, self.slide_keys, self.slide_counts, self.sparse_keys, self.sparse_counts, self.slide_ranges, self.sparse_ranges, self.tiles, self.scores, self.d_ids, self.d_tokens, self.d_positions, self.d_writes }) |b| try list.append(self.gpa, b); + try list.appendSlice(self.gpa, self.d_keys); + try list.appendSlice(self.gpa, self.d_counts); + for (self.ix_tokens, self.ix_counts) |x, y| { + if (x) |b| try list.append(self.gpa, b); + if (y) |b| try list.append(self.gpa, b); + } + if (self.kept) |c| { + try list.appendSlice(self.gpa, c.kv); + for (c.token_keys, c.group_keys) |x, y| { + if (x) |b| try list.append(self.gpa, b); + if (y) |b| try list.append(self.gpa, b); + } + } + // one entry a buffer + std.mem.sort(mtl.Buffer, list.items, {}, struct { + fn less(_: void, x: mtl.Buffer, y: mtl.Buffer) bool { + return @intFromPtr(x.id) < @intFromPtr(y.id); + } + }.less); + var n: usize = 0; + for (list.items) |b| { + if (n > 0 and list.items[n - 1].id == b.id) continue; + list.items[n] = b; + n += 1; + } + list.items.len = n; +} + +/// Whether a value of T can hold a Metal buffer (structs, optionals, arrays, slices and unions of them). +fn holds(comptime T: type, comptime depth: u32) bool { + if (T == mtl.Buffer) return true; + if (depth == 0) return false; + return switch (@typeInfo(T)) { + .@"struct" => |st| blk: { + for (st.field_types, st.field_attrs) |F, attrs| if (!attrs.@"comptime" and holds(F, depth - 1)) break :blk true; + break :blk false; + }, + .optional => |o| holds(o.child, depth - 1), + .array => |ar| holds(ar.child, depth - 1), + .pointer => |ptr| ptr.size == .slice and holds(ptr.child, depth - 1), + .@"union" => |u| blk: { + if (u.tag_type == null) break :blk false; + for (u.field_types) |F| if (holds(F, depth - 1)) break :blk true; + break :blk false; + }, + else => false, + }; +} + +fn gather(comptime T: type, v: *const T, list: *std.ArrayList(mtl.Buffer), gpa: std.mem.Allocator) !void { + if (T == mtl.Buffer) return list.append(gpa, v.*); + if (comptime !holds(T, 8)) return; + switch (@typeInfo(T)) { + .@"struct" => |st| inline for (st.field_names, st.field_types, st.field_attrs) |f, F, attrs| { + if (!attrs.@"comptime") try gather(F, &@field(v.*, f), list, gpa); + }, + .optional => |o| if (v.*) |*x| try gather(o.child, x, list, gpa), + .array => |ar| for (v) |*x| try gather(ar.child, x, list, gpa), + .pointer => |ptr| if (ptr.size == .slice) for (v.*) |*x| try gather(ptr.child, x, list, gpa), + .@"union" => switch (v.*) { + inline else => |*x| try gather(@TypeOf(x.*), x, list, gpa), + }, + else => {}, + } +} diff --git a/zig/src/families/hy4_flash/weights.zig b/zig/src/families/hy4_flash/weights.zig new file mode 100644 index 00000000000..bd54995199c --- /dev/null +++ b/zig/src/families/hy4_flash/weights.zig @@ -0,0 +1,184 @@ +//! Required tensor names and logical dimensions for the Hy4-flash backbone and DFly2. +const std = @import("std"); +const config = @import("config.zig"); + +pub const Model = config.Model; + +pub const Affine = struct { + bits: u8, + group_size: u16, + + pub fn check(self: Affine, weights: anytype, prefix: []const u8, name: []const u8, logical: []const usize) !void { + if ((self.bits != 4 and self.bits != 8) or + (self.group_size != 32 and self.group_size != 64) or + logical.len < 2 or logical.len > 3) return error.UnsupportedHy4Affine; + const last = logical.len - 1; + const width = logical[last]; + if (width == 0 or width % self.group_size != 0) return error.UnsupportedHy4Affine; + var shape: [3]usize = undefined; + @memcpy(shape[0..logical.len], logical); + shape[last] = try std.math.mul(usize, width, self.bits) / 32; + try expect(weights, prefix, name, ".weight", .u32, shape[0..logical.len]); + shape[last] = width / self.group_size; + try expect(weights, prefix, name, ".scales", .bf16, shape[0..logical.len]); + try expect(weights, prefix, name, ".biases", .bf16, shape[0..logical.len]); + } +}; + +pub const DType = enum { bf16, f32, i32, u32 }; + +fn expect(weights: anytype, prefix: []const u8, name: []const u8, suffix: []const u8, dtype: DType, shape: []const usize) !void { + var name_buffer: [200]u8 = undefined; + const full = try std.fmt.bufPrint(&name_buffer, "{s}{s}{s}", .{ prefix, name, suffix }); + _ = try weights.expect(full, dtype, shape); +} + +fn checkLayerNorms(weights: anytype, layer: []const u8, t: config.Text) !void { + for ([_][]const u8{ "input_layernorm", "post_attention_layernorm", "self_attn.post_proj_norm" }) |name| { + try expect(weights, layer, name, ".weight", .bf16, &.{t.hidden_size}); + } + try expect(weights, layer, "self_attn.q_a_layernorm", ".weight", .bf16, &.{t.q_lora_rank}); + try expect(weights, layer, "self_attn.kv_a_layernorm", ".weight", .bf16, &.{t.kv_lora_rank}); +} + +fn affineMlp(weights: anytype, layer: []const u8, comptime mlp: []const u8, affine: Affine, h: usize, inner: usize) !void { + try affine.check(weights, layer, mlp ++ "gate_proj", &.{ inner, h }); + try affine.check(weights, layer, mlp ++ "up_proj", &.{ inner, h }); + try affine.check(weights, layer, mlp ++ "down_proj", &.{ h, inner }); +} + +fn checkEngram(weights: anytype, t: config.Text, layer: []const u8, number: u32, affine: Affine) !void { + const orders = t.engram_max_ngram_size - 1; + const rows = try t.engramRows(number); + const head_width = t.engram_n_embed_per_ngram / t.engram_n_head_per_ngram; + const input = @as(usize, orders) * t.engram_n_embed_per_ngram; + const table_affine: Affine = .{ .bits = affine.bits, .group_size = 32 }; + try table_affine.check(weights, layer, "engram_layer.multi_head_embedding.embedding", &.{ rows, head_width }); + try expect(weights, layer, "engram_layer.lookup_table", "", .i32, &.{t.engram_lookup_table_size}); + try affine.check(weights, layer, "engram_layer.value_proj", &.{ t.hidden_size, input }); + try expect(weights, layer, "engram_layer.value_proj", ".bias", .bf16, &.{t.hidden_size}); + try expect(weights, layer, "engram_layer.unified_pre_gamma", "", .bf16, &.{t.hidden_size}); + for (0..@as(usize, orders) * t.engram_n_head_per_ngram) |head| { + var buffer: [68]u8 = undefined; + const name = try std.fmt.bufPrint(&buffer, "engram_layer.lookup_per_head_norms.{d}", .{head}); + try expect(weights, layer, name, ".weight", .bf16, &.{head_width}); + } + for (0..t.hc_mult) |stream| { + var buffer: [68]u8 = undefined; + const key = try std.fmt.bufPrint(&buffer, "engram_layer.key_projs.{d}", .{stream}); + try affine.check(weights, layer, key, &.{ t.hidden_size, input }); + try expect(weights, layer, key, ".bias", .bf16, &.{t.hidden_size}); + const fields = [_][]const u8{ "norm_key", "norm_query", "unified_per_hc_scales" }; + for (fields, [_][]const u8{ ".weight", ".weight", "" }) |field, suffix| { + const name = try std.fmt.bufPrint(&buffer, "engram_layer.{s}.{d}", .{ field, stream }); + try expect(weights, layer, name, suffix, .bf16, &.{t.hidden_size}); + } + } +} + +pub fn check(weights: anytype, model: config.Model, bits: u8) !void { + try model.validate(); + const t = model.text_config; + const affine: Affine = .{ .bits = bits, .group_size = 64 }; + const h = t.hidden_size; + const hcs = t.hc_mult; + try affine.check(weights, "model.", "embed_tokens", &.{ t.vocab_size, h }); + try affine.check(weights, "", "lm_head", &.{ t.vocab_size, h }); + try expect(weights, "model.", "norm.weight", "", .bf16, &.{h}); + try expect(weights, "model.hc_head.", "hc_head_fn", "", .f32, &.{ hcs, @as(usize, hcs) * h }); + try expect(weights, "model.hc_head.", "hc_head_base", "", .f32, &.{hcs}); + try expect(weights, "model.hc_head.", "hc_head_scale", "", .f32, &.{1}); + for (0..t.num_hidden_layers) |index| { + var prefix_buffer: [56]u8 = undefined; + const layer = try std.fmt.bufPrint(&prefix_buffer, "model.layers.{d}.", .{index}); + const heads = t.headShape(@intCast(index)); + const values = @as(usize, heads.heads) * heads.value; + try checkLayerNorms(weights, layer, t); + try affine.check(weights, layer, "self_attn.q_a_proj", &.{ t.q_lora_rank, h }); + try affine.check(weights, layer, "self_attn.q_b_proj", &.{ heads.queryRows(), t.q_lora_rank }); + try affine.check(weights, layer, "self_attn.kv_a_proj_with_mqa", &.{ @as(usize, t.kv_lora_rank) + heads.rotary, h }); + try affine.check(weights, layer, "self_attn.kv_b_proj", &.{ heads.kvRows(), t.kv_lora_rank }); + try affine.check(weights, layer, "self_attn.linear_gate", &.{ values, h }); + try affine.check(weights, layer, "self_attn.o_proj", &.{ h, values }); + try expect(weights, layer, "self_attn.learnable_sink_param", "", .f32, &.{heads.heads}); + for ([_][]const u8{ "hc_attn_layer.hc_pre.", "hc_mlp_layer.hc_pre." }) |hc| { + try expect(weights, layer, hc, "hc_fn", .f32, &.{ @as(usize, hcs) * 2, @as(usize, hcs) * h }); + try expect(weights, layer, hc, "hc_base", .f32, &.{@as(usize, hcs) * 2}); + try expect(weights, layer, hc, "hc_scale", .f32, &.{2}); + } + if (t.layer_types[index] == .deepseek_sparse_attention) { + const c = t.compressed_indexer_head_dim; + const num_heads = t.compressed_indexer_num_attention_heads; + const prefix = "self_attn.compressed_indexer."; + try affine.check(weights, layer, prefix ++ "token_key_projection", &.{ c, h }); + try affine.check(weights, layer, prefix ++ "query_projection", &.{ @as(usize, num_heads) * c, t.q_lora_rank }); + try affine.check(weights, layer, prefix ++ "head_weight_projection", &.{ num_heads, h }); + try expect(weights, layer, prefix, "key_value_projection.weight", .f32, &.{ c, c }); + try expect(weights, layer, prefix, "key_gate_projection.weight", .f32, &.{ c, c }); + try expect(weights, layer, prefix, "intra_group_ape", .f32, &.{ t.compressed_indexer_compress_ratio, c }); + try expect(weights, layer, prefix, "key_norm.weight", .f32, &.{c}); + try expect(weights, layer, prefix, "token_key_norm.weight", .bf16, &.{c}); + } + if (t.mlp_layer_types[index] == .sparse) { + const expert = t.n_routed_experts; + const inner = t.moe_intermediate_size; + const latent = t.routed_expert_hidden_size; + try expect(weights, layer, "mlp.gate.weight", "", .bf16, &.{ expert, h }); + try expect(weights, layer, "mlp.gate.e_score_correction_bias", "", .f32, &.{expert}); + try affine.check(weights, layer, "mlp.routed_expert_down_proj", &.{ latent, h }); + try affine.check(weights, layer, "mlp.routed_expert_up_proj", &.{ h, latent }); + try affine.check(weights, layer, "mlp.experts.gate_up_proj", &.{ expert, @as(usize, inner) * 2, latent }); + try affine.check(weights, layer, "mlp.experts.down_proj", &.{ expert, latent, inner }); + try affineMlp(weights, layer, "mlp.shared_experts.", affine, h, @as(usize, inner) * t.n_shared_experts); + try expect(weights, layer, "mlp.combine_output_norm", ".weight", .bf16, &.{h}); + } else { + try affineMlp(weights, layer, "mlp.", affine, h, t.intermediate_size); + try expect(weights, layer, "mlp.post_fc2_norm", ".weight", .bf16, &.{h}); + } + if (std.mem.indexOfScalar(u32, t.engram_layer_ids, @intCast(index + 1)) != null) { + try checkEngram(weights, t, layer, @intCast(index + 1), affine); + } + } + + try expect(weights, "vit.embeddings.", "patch_embedding.weight", "", .bf16, &.{ model.vision_config.hidden_size, 3, model.vision_config.patch_size, model.vision_config.patch_size }); + try checkDraft(weights, model); +} + +fn checkDraft(weights: anytype, model: config.Model) !void { + const t = model.text_config; + const h = t.hidden_size; + const inner = model.dfly_intermediate_size orelse try std.math.mul(u32, h, 3); + const root = "model.dfly_layers."; + const fusion = root ++ "mtp_fusion."; + const correction = root ++ "hidden_correction."; + try expect(weights, root, "final_norm.weight", "", .bf16, &.{h}); + try expect(weights, root ++ "confidence_head.", "proj.weight", "", .bf16, &.{ 1, h }); + try expect(weights, root ++ "confidence_head.", "proj.bias", "", .bf16, &.{1}); + for ([_][]const u8{ "enorm.weight", "hnorm.weight", "gate" }) |name| { + try expect(weights, fusion, name, "", .bf16, &.{h}); + } + try expect(weights, fusion, "eh_proj.weight", "", .bf16, &.{ h, @as(usize, h) * 2 }); + for ([_][]const u8{ "embed_norm.weight", "hidden_norm.weight" }) |name| { + try expect(weights, correction, name, "", .bf16, &.{h}); + } + try expect(weights, correction, "gate_proj.weight", "", .bf16, &.{ h, @as(usize, h) * 2 }); + try expect(weights, correction, "up_proj.weight", "", .bf16, &.{ h, @as(usize, h) * 2 }); + try expect(weights, correction, "down_proj.weight", "", .bf16, &.{ h, h }); + for (model.dfly_target_kv_layers, 0..) |target_layer, draft_layer| { + var prefix_buffer: [60]u8 = undefined; + const layer = try std.fmt.bufPrint(&prefix_buffer, root ++ "{d}.", .{draft_layer}); + const heads = t.headShape(target_layer); + const channels = @as(usize, heads.heads) * heads.value; + try checkLayerNorms(weights, layer, t); + try expect(weights, layer, "self_attn.q_a_proj.weight", "", .bf16, &.{ t.q_lora_rank, h }); + try expect(weights, layer, "self_attn.q_b_proj.weight", "", .bf16, &.{ heads.queryRows(), t.q_lora_rank }); + try expect(weights, layer, "self_attn.kv_a_proj_with_mqa.weight", "", .bf16, &.{ @as(usize, t.kv_lora_rank) + heads.rotary, h }); + try expect(weights, layer, "self_attn.kv_b_proj.weight", "", .bf16, &.{ heads.kvRows(), t.kv_lora_rank }); + try expect(weights, layer, "self_attn.linear_gate.weight", "", .bf16, &.{ channels, h }); + try expect(weights, layer, "self_attn.o_proj.weight", "", .bf16, &.{ h, channels }); + try expect(weights, layer, "self_attn.learnable_sink_param", "", .bf16, &.{heads.heads}); + try expect(weights, layer, "mlp.gate_proj.weight", "", .bf16, &.{ inner, h }); + try expect(weights, layer, "mlp.up_proj.weight", "", .bf16, &.{ inner, h }); + try expect(weights, layer, "mlp.down_proj.weight", "", .bf16, &.{ h, inner }); + } +} diff --git a/zig/src/native/hy4_metal.zig b/zig/src/native/hy4_metal.zig new file mode 100644 index 00000000000..9c714940ba9 --- /dev/null +++ b/zig/src/native/hy4_metal.zig @@ -0,0 +1,81 @@ +//! Hy4-flash served by the lane host on Metal +const std = @import("std"); +const mtl = @import("metal"); +const api = @import("engine_api"); +const tf = @import("tensorfold"); +const lanes = tf.lanes; +const hy4 = tf.hy4_flash; + +const default_context: u32 = 131072; +const most_context: u32 = 262144; + +const Host = struct { + gpa: std.mem.Allocator, + metal: *hy4.Metal, + resident: ?mtl.resident.Resident = null, // every buffer wired between requests (the idle ticker keeps it) + warm: mtl.keepalive.Target = undefined, + config: lanes.Config, + clock: lanes.backend.WallClock, + core: lanes.Engine, + host: api.LaneHost, + + fn close(ctx: *anyopaque) void { + const h: *Host = @ptrCast(@alignCast(ctx)); + h.host.stop(); + h.core.deinit(); + h.config.deinit(h.gpa); + h.metal.follow = null; + if (h.resident) |*r| r.deinit(); + h.metal.deinit(); + h.gpa.destroy(h); + } +}; + +pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (try o.slideRefusal(a, "Macs")) |why| { + problem.* = why; + return null; + } + if (o.vision != null) { + problem.* = "--vision: the native Hy4-flash engine reads text only; serve without --vision"; + return null; + } + const asked: i64 = o.context orelse default_context; + if (asked < 4096 or asked > most_context) { + problem.* = try std.fmt.allocPrint(a, "--context {d}: the native Hy4-flash engine serves 4,096 to {d} tokens", .{ asked, most_context }); + return null; + } + // caches hold the window, a verify window past it, rounded to whole 512-slot pages + const capacity: u32 = @intCast(((@as(u64, @intCast(asked)) + hy4.max_window + 511) / 512) * 512); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const metal = hy4.Metal.init(gpa, io, o.dir, .{ .capacity = capacity }) catch |err| { + problem.* = try std.fmt.allocPrint(a, "the native Hy4-flash engine cannot load this checkpoint ({s})", .{@errorName(err)}); + return null; + }; + errdefer metal.deinit(); + std.log.info("hy4: {d}-token window, {d:.1} GiB of caches a stream", .{ asked, @as(f64, @floatFromInt(metal.cacheBytes(capacity))) / (1 << 30) }); + try metal.warm(); + const h = try gpa.create(Host); + errdefer gpa.destroy(h); + h.gpa = gpa; + h.metal = metal; + h.config = try lanes.Config.init(gpa, metal.facts(), hy4.max_window, hy4.max_window - 1); + errdefer h.config.deinit(gpa); + h.clock = .{ .io = io }; + h.core = lanes.Engine.init(gpa, &h.config, metal.backend(), h.clock.clock()); + errdefer h.core.deinit(); + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = 1, .context_window = @intCast(asked), .prefill_step = hy4.prompt_rows, .decode_share = o.decode_share, .structures = true, .logprobs = true }); + // weights, scratch and the kept caches in one residency set: idle GPU pages otherwise cost seconds to come back + var list: std.ArrayList(mtl.Buffer) = .empty; + defer list.deinit(gpa); + try metal.residentBuffers(&list); + h.resident = try mtl.resident.Resident.hold(gpa, io, metal.device, metal.queue, list.items, "hy4"); + if (h.resident) |*r| { + metal.follow = r.follow(); + h.warm = r.target(); + } else h.warm = .{ .queue = metal.queue }; + h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; + try h.host.start(); + return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 09292ac997e..28c525386ce 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -65,6 +65,7 @@ pub const families: []const api.Family = &.{ .{ .model_type = "step5_vl", .formats = &.{"mlx-q2g128"} }, .{ .model_type = "spark2_5", .formats = &.{ "bf16", "mlx-q2g64", "mlx-q3g64", "mlx-q4g64", "mlx-q5g64", "mlx-q6g64", "mlx-q8g64" } }, .{ .model_type = "minimax_m3_vl", .formats = &.{ "mlx-q3g64", "mlx-q8g64" } }, + .{ .model_type = "hy_v4_flash", .formats = &.{ "mlx-q4g64", "mlx-q8g64" } }, .{ .model_type = "qwen3", .formats = &.{"bf16"} }, .{ .model_type = "llama", .formats = &.{ "bf16", "compressed-tensors-int4-g32" } }, .{ .model_type = "flint", .formats = &.{"mlx-q4g64"} }, @@ -147,6 +148,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c return @import("kimi_metal.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen4") or std.mem.eql(u8, o.model_type, "qwen4_text")) return @import("qwen4_metal.zig").open(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen3")) return @import("qwen3_metal.zig").open(a, gpa, io, o, problem); + if (std.mem.eql(u8, o.model_type, "hy_v4_flash")) return @import("hy4_metal.zig").open(a, gpa, io, o, problem); const dense = ownsQwen27(a, io, o.model_type, o.dir); if (try refusal(a, o, dense)) |why| { problem.* = why; diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 08798f31876..b88cbd6c0e8 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -193,6 +193,8 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSV41_ENGRAM_QD", .scope = .dsv41, .kind = .u32, .forms = "a whole reader-thread count from 0 to 4294967295 (0 reads serially)" }, .{ .name = "TF_DSV41_ENGRAM_READERS", .scope = .dsv41, .kind = .u32, .max = 32, .forms = "a whole reader-thread count from 0 to 32 (0 reads serially)" }, .{ .name = "TF_DSV41_GEN_STREAMS", .scope = .dsv41, .kind = .size, .min = 1, .forms = "a whole request count from 1 to the native size maximum" }, + .{ .name = "TF_HY4_ENGRAM", .scope = .metal, .kind = .word, .words = &.{ "nvme", "ram", "gpu" }, .forms = "nvme, ram or gpu (where Hy4-flash's Engram tables live; default nvme)" }, + .{ .name = "TF_HY4_DRAFT_BITS", .scope = .metal, .kind = .u32, .only = &.{ 4, 8, 16 }, .forms = "4, 8 or 16 (Hy4-flash's DFly2 linears quantized at load; default 16, BF16)" }, .{ .name = "TF_DSV41_CONTEXT", .scope = .dsv41, .kind = .u64, .min = 1, .max = std.math.maxInt(i64), .forms = "a whole position count from 1 to 9223372036854775807" }, .{ .name = "TF_DSV41_SLOTS", .scope = .dsv41, .kind = .u32, .min = 1, .max = 16, .forms = "a whole slot count from 1 to 16" }, .{ .name = "TF_DSV41_NUCLEUS", .scope = .dsv41, .kind = .u32, .forms = "a whole candidate count from 0 to 4294967295 (0 disables the nucleus)" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index ef7b4d5a8cf..353ae012e9c 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -192,6 +192,8 @@ const valid = [_]Case{ .{ .name = "TF_NEMOTRON_WORLD", .raw = "2", .n = 2 }, .{ .name = "TF_MINIMAX_RANK", .raw = "1", .n = 1 }, .{ .name = "TF_MINIMAX_WORLD", .raw = "2", .n = 2 }, + .{ .name = "TF_HY4_ENGRAM", .raw = "gpu", .n = 2 }, + .{ .name = "TF_HY4_DRAFT_BITS", .raw = "8", .n = 8 }, }; test "environment: valid forms remain raw numbers before existing consumer clamps and defaults" { diff --git a/zig/src/server/hf_hy4.zig b/zig/src/server/hf_hy4.zig new file mode 100644 index 00000000000..7ccef9b801f --- /dev/null +++ b/zig/src/server/hf_hy4.zig @@ -0,0 +1,59 @@ +//! Hy4-flash's reasoning and tool-call tokens read as the GLM spellings the server parses +const std = @import("std"); + +const spellings = [_][2][]const u8{ + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, +}; + +/// The Hy4-flash token a GLM marker spelling stands for, or null. +pub fn spelling(piece: []const u8) ?[]const u8 { + for (spellings) |pair| if (pair[1].len > 0 and std.mem.eql(u8, piece, pair[1])) return pair[0]; + return null; +} + +/// Whether a tokenizer holds Hy4-flash's marker tokens. +pub fn active(tok: anytype) bool { + return tok.specialTokenId("") != null and tok.specialTokenId("") != null; +} + +/// `raw` decoded text, with each Hy4-flash marker token in its GLM spelling when `tok` is Hy4-flash's. +pub fn mapped(tok: anytype, a: std.mem.Allocator, raw: []u8) std.mem.Allocator.Error![]u8 { + return if (active(tok)) decode(a, raw) else raw; +} + +/// Decoded text with each Hy4-flash marker token in its GLM spelling. +pub fn decode(a: std.mem.Allocator, raw: []u8) std.mem.Allocator.Error![]u8 { + if (std.mem.indexOf(u8, raw, ":opensource>") == null) return raw; + var out: std.ArrayList(u8) = .empty; + var at: usize = 0; + outer: while (at < raw.len) { + if (raw[at] == '<') for (spellings) |pair| if (std.mem.startsWith(u8, raw[at..], pair[0])) { + try out.appendSlice(a, pair[1]); + at += pair[0].len; + continue :outer; + }; + try out.append(a, raw[at]); + at += 1; + } + return out.toOwnedSlice(a); +} + +test "Hy4-flash markers decode as the GLM spellings and map back" { + const a = std.testing.allocator; + const src = try a.dupe(u8, "xfkv"); + defer a.free(src); + const text = try decode(a, src); + defer a.free(text); + try std.testing.expectEqualStrings("xfkv", text); + try std.testing.expectEqualStrings("", spelling("").?); + try std.testing.expect(spelling("plain") == null); +} diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index 1a5c73eea3a..e1b0022d17a 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -324,7 +324,7 @@ pub const HfText = struct { fn encodeFn(ctx: *anyopaque, a: Allocator, s: []const u8, add_special: bool) model_text.Error![]u32 { const t = self(ctx); - const ids = t.tok.encode(a, s) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else error.Template; + const ids = t.tok.encode(a, if (@import("hf_hy4.zig").active(&t.tok)) @import("hf_hy4.zig").spelling(s) orelse s else s) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else error.Template; if (!add_special or (t.prefix.len == 0 and t.suffix.len == 0)) return ids; return std.mem.concat(a, u32, &.{ t.prefix, ids, t.suffix }); } @@ -347,11 +347,11 @@ pub const HfText = struct { } fn decodeFn(ctx: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { - return self(ctx).tok.decode(a, ids, false) catch |e| if (e == error.OutOfMemory) error.OutOfMemory else a.dupe(u8, "\u{fffd}"); + return @import("hf_hy4.zig").mapped(&self(ctx).tok, a, self(ctx).tok.decode(a, ids, false) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else a.dupe(u8, "\u{fffd}")); } fn tokenIdFn(ctx: *anyopaque, piece: []const u8) ?u32 { - return self(ctx).tok.specialTokenId(piece); + return self(ctx).tok.specialTokenId(if (@import("hf_hy4.zig").active(&self(ctx).tok)) @import("hf_hy4.zig").spelling(piece) orelse piece else piece); } fn tokenStringFn(ctx: *anyopaque, a: Allocator, id: u32) Allocator.Error![]u8 { diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 6da355cfc0b..a74d99301a2 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -76,6 +76,7 @@ pub const gemma4 = @import("families/gemma4/gemma4.zig"); 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 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/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 7c79a04bf67..43f36cf054c 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -93,7 +93,7 @@ zig/src/cuda/experts.zig 8bfc2f15a742cceba87dd7eb8e80f3f1b4e3f7eb323b557eb1bb4bf zig/src/cuda/fp8.zig a9caf312cb451dc95572b493e69ae211dd1e8b5be5b2c48cae3febd5d9327143 raw series patches 65-pr-1024.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/graph.zig 17639aaef0298c934b3f5ad3511925169c096ae57ede8ebee655faa838844f7b raw zig/src/cuda/grouped.zig 5fa1f39394b701eab59383bc7ed214ea3e17652a1229236df49f5281e6e764b5 raw commits e1be0806d; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate -zig/src/cuda/kernels.zig 035a0f6efce81061d63dd8eec74bedccf2a9aadaddfbc75438580c41f0606b88 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered); #1295: the six Muse Spark images registered; #3413 (the flashnext_hcn image registered) +zig/src/cuda/kernels.zig dd70e5224f9898ee77842eb6c7dc8e62637c077e385490bf2c546ae1e8cad9e4 raw main 42735f94f0 (#2335: the mla image registered), f35900e60c (#2709: the dots_mocr image registered), #1630 (the experts_bf16 image registered), #2914 (covers: the release SM check), #1631 (the nemo_audio image registered), #1767 (the idol image registered), (Hy4-flash images registered) zig/src/cuda/launch.zig 9ec64848834d82ddcea85a6123e975c95a5ae2bf85c2a71772244794b0bcd705 raw series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/memory.zig c140f1700e0f257a3ac09b1bfaa4a0d704d1922ccbffc3d453d75be0fef4b617 raw commits 5dcf77d7c, f630f1a90, e9bf05ffd, 881cccaa4, a34cb6ded; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate, this change (DeviceBuffer.allocVia allocates through a given hook; alloc is allocVia with the installed one, unchanged) zig/src/cuda/modelopt.zig 648c9ba58197af0ce905f8792383502fc44a52c45d1413fe9e21d28d04c22253 raw @@ -105,7 +105,7 @@ zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7 zig/src/cuda/qlinear.zig 680c653d110b53e52918bb13f7c54c12ffac4097959319281dc7509c085c062f raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/qmmf.zig 577b24e8dc1a00e975c75075bf9636af55d2614780d05fcb6ed488cc68d37778 raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig 5dbca351bbf6a42cd83d7b615d4e4624809444d7d2e714b1d71d8eec53c6e606 raw main 42735f94f0 (#2335: cuda.mla exported) +zig/src/cuda/root.zig d0d978fc3f6df100e6bcb1c479b567382d5950a9728b8b74a76a188e7cba32b7 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash) zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw