From 2a1d731976a7c39f00a93581b96fd03b732d5acd Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:28:04 +0000 Subject: [PATCH 01/12] hy4_flash: native Hy4-flash family on Metal and CUDA (loader, weights, MLA, iHC, Engram, indexer kernels, DFly2 drafter, host tests) --- build.zig | 1 + zig/build/cuda_kernels.zig | 7 + zig/build/hy4_flash.zig | 23 + zig/kernels/cuda/affine_experts.cu | 82 +++ zig/kernels/cuda/hy4_flash/attention_sink.cu | 21 + zig/kernels/cuda/hy4_flash/ihc.cu | 59 +++ zig/kernels/cuda/hy4_flash/index_recall.cu | 58 ++ zig/kernels/cuda/hy4_flash/indexpool.cu | 32 ++ zig/kernels/cuda/hy4_flash/mla_attention.cu | 37 ++ zig/kernels/cuda/hy4_flash/mla_project.cu | 85 +++ zig/kernels/metal/core/affine_mm.metal | 20 +- .../metal/hy4_flash/affine_experts.metal | 97 ++++ .../metal/hy4_flash/attention_sink.metal | 30 ++ zig/kernels/metal/hy4_flash/engram.metal | 118 +++++ zig/kernels/metal/hy4_flash/ihc.metal | 96 ++++ .../metal/hy4_flash/index_recall.metal | 117 +++++ zig/kernels/metal/hy4_flash/indexpool.metal | 37 ++ .../metal/hy4_flash/mla_attention.metal | 86 +++ zig/kernels/metal/hy4_flash/mla_project.metal | 134 +++++ .../metal/hy4_flash/tensor_dispatch.metal | 36 ++ zig/kernels/metal/sources.zig | 16 +- zig/src/core/affine_mm.zig | 36 +- zig/src/cuda/affine_experts.zig | 77 +++ zig/src/cuda/kernels.zig | 7 + zig/src/cuda/root.zig | 1 + .../hy4_flash/affine_experts_metal.zig | 72 +++ .../families/hy4_flash/attention_slots.zig | 66 +++ zig/src/families/hy4_flash/config.zig | 220 ++++++++ .../families/hy4_flash/config_fixture.json | 494 ++++++++++++++++++ zig/src/families/hy4_flash/cuda_dense.zig | 266 ++++++++++ .../families/hy4_flash/cuda_projection.zig | 130 +++++ zig/src/families/hy4_flash/dfly2_inputs.zig | 56 ++ zig/src/families/hy4_flash/engram.zig | 82 +++ zig/src/families/hy4_flash/engram_rows.zig | 74 +++ zig/src/families/hy4_flash/forward.zig | 136 +++++ zig/src/families/hy4_flash/host_tests.zig | 56 ++ zig/src/families/hy4_flash/ihc.zig | 63 +++ zig/src/families/hy4_flash/ihc_cuda.zig | 43 ++ zig/src/families/hy4_flash/ihc_metal.zig | 46 ++ zig/src/families/hy4_flash/index_groups.zig | 61 +++ zig/src/families/hy4_flash/index_recall.zig | 48 ++ .../families/hy4_flash/index_recall_cuda.zig | 44 ++ .../families/hy4_flash/index_recall_metal.zig | 50 ++ zig/src/families/hy4_flash/indexpool_cuda.zig | 26 + .../families/hy4_flash/indexpool_metal.zig | 35 ++ zig/src/families/hy4_flash/loader.zig | 83 +++ zig/src/families/hy4_flash/metal_dense.zig | 458 ++++++++++++++++ zig/src/families/hy4_flash/metal_draft.zig | 352 +++++++++++++ zig/src/families/hy4_flash/metal_engram.zig | 156 ++++++ zig/src/families/hy4_flash/metal_model.zig | 265 ++++++++++ zig/src/families/hy4_flash/metal_routed.zig | 317 +++++++++++ .../hy4_flash/metal_tensor_experts.zig | 121 +++++ .../families/hy4_flash/metal_tensor_qkv.zig | 112 ++++ zig/src/families/hy4_flash/mla_attention.zig | 57 ++ zig/src/families/hy4_flash/mla_cuda.zig | 188 +++++++ zig/src/families/hy4_flash/mla_metal.zig | 208 ++++++++ zig/src/families/hy4_flash/mla_weights.zig | 89 ++++ zig/src/families/hy4_flash/model_weights.zig | 368 +++++++++++++ zig/src/families/hy4_flash/moe_cuda.zig | 105 ++++ zig/src/families/hy4_flash/rank_weights.zig | 143 +++++ zig/src/families/hy4_flash/rope.zig | 57 ++ zig/src/families/hy4_flash/weights.zig | 184 +++++++ 62 files changed, 6632 insertions(+), 12 deletions(-) create mode 100644 zig/build/hy4_flash.zig create mode 100644 zig/kernels/cuda/affine_experts.cu create mode 100644 zig/kernels/cuda/hy4_flash/attention_sink.cu create mode 100644 zig/kernels/cuda/hy4_flash/ihc.cu create mode 100644 zig/kernels/cuda/hy4_flash/index_recall.cu create mode 100644 zig/kernels/cuda/hy4_flash/indexpool.cu create mode 100644 zig/kernels/cuda/hy4_flash/mla_attention.cu create mode 100644 zig/kernels/cuda/hy4_flash/mla_project.cu create mode 100644 zig/kernels/metal/hy4_flash/affine_experts.metal create mode 100644 zig/kernels/metal/hy4_flash/attention_sink.metal create mode 100644 zig/kernels/metal/hy4_flash/engram.metal create mode 100644 zig/kernels/metal/hy4_flash/ihc.metal create mode 100644 zig/kernels/metal/hy4_flash/index_recall.metal create mode 100644 zig/kernels/metal/hy4_flash/indexpool.metal create mode 100644 zig/kernels/metal/hy4_flash/mla_attention.metal create mode 100644 zig/kernels/metal/hy4_flash/mla_project.metal create mode 100644 zig/kernels/metal/hy4_flash/tensor_dispatch.metal create mode 100644 zig/src/cuda/affine_experts.zig create mode 100644 zig/src/families/hy4_flash/affine_experts_metal.zig create mode 100644 zig/src/families/hy4_flash/attention_slots.zig create mode 100644 zig/src/families/hy4_flash/config.zig create mode 100644 zig/src/families/hy4_flash/config_fixture.json create mode 100644 zig/src/families/hy4_flash/cuda_dense.zig create mode 100644 zig/src/families/hy4_flash/cuda_projection.zig create mode 100644 zig/src/families/hy4_flash/dfly2_inputs.zig create mode 100644 zig/src/families/hy4_flash/engram.zig create mode 100644 zig/src/families/hy4_flash/engram_rows.zig create mode 100644 zig/src/families/hy4_flash/forward.zig create mode 100644 zig/src/families/hy4_flash/host_tests.zig create mode 100644 zig/src/families/hy4_flash/ihc.zig create mode 100644 zig/src/families/hy4_flash/ihc_cuda.zig create mode 100644 zig/src/families/hy4_flash/ihc_metal.zig create mode 100644 zig/src/families/hy4_flash/index_groups.zig create mode 100644 zig/src/families/hy4_flash/index_recall.zig create mode 100644 zig/src/families/hy4_flash/index_recall_cuda.zig create mode 100644 zig/src/families/hy4_flash/index_recall_metal.zig create mode 100644 zig/src/families/hy4_flash/indexpool_cuda.zig create mode 100644 zig/src/families/hy4_flash/indexpool_metal.zig create mode 100644 zig/src/families/hy4_flash/loader.zig create mode 100644 zig/src/families/hy4_flash/metal_dense.zig create mode 100644 zig/src/families/hy4_flash/metal_draft.zig create mode 100644 zig/src/families/hy4_flash/metal_engram.zig create mode 100644 zig/src/families/hy4_flash/metal_model.zig create mode 100644 zig/src/families/hy4_flash/metal_routed.zig create mode 100644 zig/src/families/hy4_flash/metal_tensor_experts.zig create mode 100644 zig/src/families/hy4_flash/metal_tensor_qkv.zig create mode 100644 zig/src/families/hy4_flash/mla_attention.zig create mode 100644 zig/src/families/hy4_flash/mla_cuda.zig create mode 100644 zig/src/families/hy4_flash/mla_metal.zig create mode 100644 zig/src/families/hy4_flash/mla_weights.zig create mode 100644 zig/src/families/hy4_flash/model_weights.zig create mode 100644 zig/src/families/hy4_flash/moe_cuda.zig create mode 100644 zig/src/families/hy4_flash/rank_weights.zig create mode 100644 zig/src/families/hy4_flash/rope.zig create mode 100644 zig/src/families/hy4_flash/weights.zig 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/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/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..1b549d0e745 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/engram.metal @@ -0,0 +1,118 @@ +// 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); + } +} diff --git a/zig/kernels/metal/hy4_flash/ihc.metal b/zig/kernels/metal/hy4_flash/ihc.metal new file mode 100644 index 00000000000..6272d6c2e82 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/ihc.metal @@ -0,0 +1,96 @@ +// 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); + } +} + +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])); +} 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..23b8651d9d0 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/mla_attention.metal @@ -0,0 +1,86 @@ +// 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)); +} 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..66d3b374b93 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/mla_project.metal @@ -0,0 +1,134 @@ +// 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); +} 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..013a7f23df7 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal @@ -0,0 +1,36 @@ +// 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]; +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index 5f80a87466f..75c87ddd977 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -3,6 +3,16 @@ /// 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_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_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 +118,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 +131,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/cuda/affine_experts.zig b/zig/src/cuda/affine_experts.zig new file mode 100644 index 00000000000..e0ae8d02d81 --- /dev/null +++ b/zig/src/cuda/affine_experts.zig @@ -0,0 +1,77 @@ +//! 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. + /// IDs outside this rank's slice write zeros, preserving the global route ordering on each rank. + 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..6bba4f9d84b --- /dev/null +++ b/zig/src/families/hy4_flash/engram_rows.zig @@ -0,0 +1,74 @@ +//! 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. +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, + }; + } + + 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. + /// Output is raw BF16 embedding rows [token][hash head][width], before FP8 simulation or normalization. + 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 }; + } + } + + 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..21c7940c325 --- /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.DType, rows: usize, width: usize, bytes: []const u8) core.checkpoint.Tensor { + var result: core.checkpoint.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..1511cf70f7e --- /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.Tensor, + bias: core.checkpoint.Tensor, + scale: core.checkpoint.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..4dc558d1f93 --- /dev/null +++ b/zig/src/families/hy4_flash/ihc_metal.zig @@ -0,0 +1,46 @@ +//! 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 }; +pub const Collapse = struct { hidden: Ref, projection: Ref, bias: Ref, scale: Ref, output: Ref, post: ?Ref = null }; +pub const Add = struct { residual: Ref, branch: Ref, post: Ref, output: Ref }; +pub const Kernels = struct { + pre: 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 pre = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_collapse", false); + errdefer pre.deinit(); + return .{ .pre = pre, .mix = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_add", false) }; + } + + pub fn deinit(self: *Kernels) void { + self.pre.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; + e.setPipeline(self.pre); + 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)); + } + + 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..74bc658e938 --- /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.DType = switch (format) { + inline else => |tag| @field(core.checkpoint.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..25fb533a89d --- /dev/null +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -0,0 +1,458 @@ +//! The native Metal attention and dense feed-forward layer passes for Hy4-flash. +const std = @import("std"); +const mtl = @import("metal"); +const affine = @import("row_projection"); +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("lane_projection"); + +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; + } + + pub fn rows(self: *Buffers, count: u32, columns: u32) !Ref { + return .{ .buffer = try self.alloc(@as(usize, count) * columns * @sizeOf(u16)) }; + } +}; + +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: affine.Weights, + o_norm: mtl.Buffer, + wk: mtl.Buffer, + wv: mtl.Buffer, + sinks: mtl.Buffer, + + 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.matrix(w.attention.output), + .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)), + .sinks = try b.upload(std.mem.sliceAsBytes(w.sinks[0..heads])), + }; + 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: affine.Weights, + up: affine.Weights, + down: affine.Weights, + output_norm: mtl.Buffer, + + pub fn upload(a: std.mem.Allocator, device: mtl.Device, w: *const weights.TargetLayer) !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.matrix(feed.projections.gate), + .up = try b.matrix(feed.projections.up), + .down = try b.matrix(feed.projections.down), + .output_norm = try b.upload(feed.norm.bytes), + }; + return withAllocation(out, b); + } + + pub fn deinit(self: *Feed) void { + self.own.clear(); + self.* = undefined; + } +}; + +fn withAllocation(out: anytype, b: Buffers) @TypeOf(out) { + var owned = out; + owned.own = b; + return owned; +} + +pub const Scratch = struct { + own: Buffers, + capacity: mha.Shape, + shape: mha.Shape, + inner_capacity: u32, + merged: 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, + 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), + .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()) }, + .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; + } +}; + +pub const CacheRows = struct { + positions: Ref, + write_slots: Ref, + retained: Ref, + counts: Ref, + cache: Ref, + capacity: u32, +}; + +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, + + 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.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); + return out; + } + + pub fn project(self: *const Kernels, e: mtl.ComputeEncoder, w: affine.Weights, x: Ref, y: Ref, rows: u32) !void { + const call = try affine.call(&self.affine, w, rows, false); + 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)); + } + + 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, + }); + } + + 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 }, + }, 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 { + 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.collapse(e, x, w.merge, w.norm, s); + 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.inputs[m.flavor].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.queries[m.flavor].encode(e, tref(s.query_norm), m.q_b.w, m.q_b.sb, tref(s.query), rows); + }, + } + e.barrier(); + 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 = cache.retained, + .counts = cache.counts, + .sinks = .{ .buffer = w.sinks }, + .scratch = s.attention, + .output = s.latent, + }, + }, s.shape, w.rope); + e.barrier(); + try self.project(e, w.o, s.values, s.branch, rows); + e.barrier(); + try self.norm(e, s.branch, w.o_norm, s.normalized, rows, w.hidden, w.epsilon); + e.barrier(); + try self.residual(e, x, s.normalized, s.post, out, shape); + } + + pub fn feed(self: *const Kernels, e: mtl.ComputeEncoder, w: *const Feed, s: *const Scratch, x: Ref, out: Ref) !void { + const inner: u32 = @intCast(w.gate.n); + if (inner > s.inner_capacity) return error.ShortHy4Scratch; + const shape = try self.collapse(e, x, w.merge, w.norm, s); + try self.project(e, w.gate, s.normalized, s.gate, shape.rows); + try self.project(e, w.up, s.normalized, 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.project(e, w.down, s.inner, s.branch, shape.rows); + e.barrier(); + try self.norm(e, s.branch, w.output_norm, s.normalized, shape.rows, shape.width, shape.eps); + e.barrier(); + try self.residual(e, x, s.normalized, s.post, out, shape); + } +}; 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..e2fa13518b3 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_draft.zig @@ -0,0 +1,352 @@ +//! 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 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; + +const Linear = struct { + w: mtl.Buffer, + n: u32, + k: u32, + fn upload(b: *common.Buffers, t: @import("core").checkpoint.Tensor) !Linear { + return .{ .w = try b.upload(t.bytes), .n = @intCast(t.shape[0]), .k = @intCast(t.shape[1]) }; + } + fn run(p: Linear, ops: dense_ops.Ops, e: mtl.ComputeEncoder, x: Ref, y: Ref, rows: u32) !void { + try ops.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(ops: dense_ops.Ops, e: mtl.ComputeEncoder, w: Feed, temp: *const common.Scratch, x: Ref, y: Ref, rows: u32) !void { + const n = w.gate.n; + if (n > temp.inner_capacity) return error.ShortHy4Scratch; + try w.gate.run(ops, e, x, temp.gate, rows); + try w.up.run(ops, 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(ops, 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(ops, 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(ops, e, v.normalized, v.query_a, rows); + try w.kv.run(ops, e, v.normalized, v.kv, rows); + try w.gate.run(ops, 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(ops, 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, + }, + }, v.shape, w.rope); + e.barrier(); + try w.o.run(ops, 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(ops, 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(ops, 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..ed04541246d --- /dev/null +++ b/zig/src/families/hy4_flash/metal_engram.zig @@ -0,0 +1,156 @@ +//! 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("row_projection"); +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; + +pub const Layer = struct { + own: common.Buffers, + table: row_table.Table, + lookup_gamma: mtl.Buffer, + key: [ihc.streams]affine.Weights, + key_bias: mtl.Buffer, + key_gain: mtl.Buffer, + query_gain: mtl.Buffer, + delta_gain: mtl.Buffer, + value: affine.Weights, + 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 { + 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.matrix(w.value), + .value_bias = try b.upload(w.value_bias.bytes), + .value_gain = try b.upload(w.pre_gamma.bytes), + .fp8 = fp8, + .hidden = hidden, + }; + for (&out.key, w.key) |*dst, src| dst.* = try b.matrix(src.key); + 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.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.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, + + 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)) }, + }; + 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; + 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, + + 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(); + return .{ .lookup = lookup, .apply = try mtl.Pipeline.init(d, library, "tf_hy4_engram_apply", false) }; + } + + pub fn deinit(self: *Kernels) void { + self.lookup.deinit(); + self.apply.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; + 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(); + try ops.project(e, w.value, s.normalized, s.value, rows); + for (w.key, 0..) |projection, i| { + const dst: Ref = .{ .buffer = s.keys.buffer, .offset = i * rows * w.hidden * @sizeOf(u16) }; + try ops.project(e, projection, s.normalized, dst, 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_model.zig b/zig/src/families/hy4_flash/metal_model.zig new file mode 100644 index 00000000000..8e4c11cff91 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_model.zig @@ -0,0 +1,265 @@ +//! 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("row_projection"); +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"); + +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.upload(a, device, v, config.hidden_size, config.engram_fp8_embedding) else null; + errdefer if (mem) |*v| v.deinit(); + return .{ + .attention = attention, + .feed = switch (w.feed) { + .dense => .{ .dense = try dense.Feed.upload(a, device, &w) }, + .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: aff.Weights, + norm: mtl.Buffer, + merge: dense.Merge, + lookup: mtl.Pipeline, + + fn upload(a: std.mem.Allocator, device: mtl.Device, w: weights.Head) !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.matrix(w.lm_head), + .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, + + 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 head = try Head.upload(a, device, try weights.Head.read(&host, 1)); + 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, + }; + } + + pub fn deinit(self: *Model) void { + for (self.blocks) |*block| block.deinit(); + self.allocator.free(self.blocks); + self.head.deinit(); + self.memory.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; + for (self.blocks, cache) |*block, lane| { + 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; + } + try frame.common.bind(frame.rows, block.attention.heads, lane.key_stride); + try self.common.attend(e, &block.attention, &frame.common, lane.rows, x, y); + e.barrier(); + std.mem.swap(Ref, &x, &y); + switch (block.feed) { + .dense => |*w| try self.common.feed(e, w, &frame.common, x, y), + .routed => |*w| try self.routed.forward(&self.common, e, w, &frame.common, &frame.routed, x, y), + } + e.barrier(); + std.mem.swap(Ref, &x, &y); + } + _ = try self.common.collapse(e, x, self.head.merge, self.head.norm, &frame.common); + 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.project(e, self.head.vocab, x, out, rows); + } +}; + +pub const LayerCache = struct { rows: dense.CacheRows, key_stride: u32 }; + +pub const Frame = struct { + own: dense.Buffers, + capacity: u32, + rows: u32 = 0, + streams: [2]Ref, + ids: Ref, + logits: Ref, + common: dense.Scratch, + routed: routed.Scratch, + memory: []memory.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.max_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 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, + }; + out.own = b; + return out; + } + + pub fn deinit(self: *Frame) void { + self.common.deinit(); + self.routed.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..095e068c0b6 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_routed.zig @@ -0,0 +1,317 @@ +//! 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("row_projection"); +const route = @import("moe_route"); +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("lane_projection"); + +const Ref = dense.Ref; +const RouteRef = @import("draft_ops").Ref; +const RouteOutputs = route.Outputs(RouteRef); +pub const max_rows = 16; + +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: affine.Weights, + up: affine.Weights, + expert_weights: ExpertWeights, + shared_gate: affine.Weights, + shared_up: affine.Weights, + shared_down: affine.Weights, + 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.matrix(f.down), + .up = try b.matrix(f.up), + .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.matrix(f.shared.gate), + .shared_up = try b.matrix(f.shared.up), + .shared_down = try b.matrix(f.shared.down), + .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, + + 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 > max_rows) 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), + }; + 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, + 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 src = try route.source(a, shape); + 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 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, + .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(); + 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 { + const rows = d.shape.rows; + const inner: u32 = @intCast(w.shared_gate.n); + if (rows > s.rows or s.picks != self.shape.topk or inner > d.inner_capacity) return error.ShortHy4Scratch; + const merge = try shared.collapse(e, x, w.merge, w.input_norm, d); + try shared.project(e, w.down, d.normalized, s.latent, rows); + try shared.project(e, w.shared_gate, d.normalized, d.gate, rows); + try shared.project(e, w.shared_up, d.normalized, d.up, rows); + route.logits(e, self.logits, self.shape, dense.Kernels.dref(d.normalized), w.router, s.logits, rows); + e.barrier(); + route.select(e, self.select, s.logits, w.correction, w.scale, rows, .{ 0, w.size.experts }, s.select); + 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.project(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 jobs = 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.project(e, w.shared_down, d.inner, s.shared, rows); + e.barrier(); + ops.apply(e, mat, tensor_scratch, jobs, latent, .{ .buf = s.pair_activations.buffer, .off = s.pair_activations.offset }, .{ .buf = s.pair_outputs }, 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.project(e, w.up, s.weighted, s.routed, rows); + e.barrier(); + e.setPipeline(self.add); + e.setBuffer(s.routed.buffer, 0, 0); + e.setBuffer(s.shared.buffer, 0, 1); + e.setValue(@as(i32, @intCast(rows * merge.width)), 2); + e.setBuffer(d.branch.buffer, 0, 3); + e.dispatchThreads(mtl.Size.of(rows * merge.width, 1, 1), mtl.Size.of(128, 1, 1)); + e.barrier(); + try shared.norm(e, d.branch, w.output_norm, d.normalized, rows, merge.width, merge.eps); + e.barrier(); + try shared.residual(e, x, d.normalized, d.post, out, merge); + } +}; + +fn tensorRef(ref: RouteRef) lane.Ref { + return .{ .buf = ref.buf, .off = ref.off }; +} 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..a36f01a379d --- /dev/null +++ b/zig/src/families/hy4_flash/metal_tensor_experts.zig @@ -0,0 +1,121 @@ +//! 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("lane_projection"); +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 > 256) 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(slots * @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, + + 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(); + return .{ + .pipes = pipes, + .compact = try mtl.Pipeline.init(d, lib_compact, "tf_hy4_active_experts", false), + }; + } + + pub fn deinit(self: Kernels) void { + for (self.pipes) |p| p.deinit(); + self.compact.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 { + tensor.gatherGluMapped(e, self.pipes, x, s.latent_sums, w.gate, w.up, jobs.offsets, jobs.order, act, jobs.ids, pairs, pairs, 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, pairs); + } +}; 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..cbe7b009525 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_tensor_qkv.zig @@ -0,0 +1,112 @@ +//! 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("lane_projection"); +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) try lane.regOrder(owner.d, &.{.{ .w = .{ .buf = w }, .n = l.n, .k = l.k }}); + return .{ .w = .{ .buf = w }, .sb = .{ .buf = sb } }; + } +}; + +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 = bits == 4, + .precompute_sums = bits == 4, + }; +} + +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; +} + +pub const Kernels = struct { + inputs: [2]lane.Projection, + queries: [2]lane.Projection, + 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; + } + return out; + } + + pub fn deinit(self: Kernels) void { + for (self.inputs, self.queries) |a, b| { + a.deinit(); + b.deinit(); + } + self.unpack.deinit(); + } + + 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..1b7fe2aa8da --- /dev/null +++ b/zig/src/families/hy4_flash/mla_metal.zig @@ -0,0 +1,208 @@ +//! 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 }; + +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, + + 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(); + return .{ + .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.* = 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, + + pub const Buffers = struct { + query: Ref, + cache: Ref, + slots: Ref, + counts: Ref, + sinks: Ref, + scratch: Ref, + output: Ref, + }; + + 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(); + return .{ .chunks = chunks, .merge = try mtl.Pipeline.init(device, library, "tf_hy4_attend_merge", false) }; + } + + pub fn deinit(self: *Attention) void { + self.chunks.deinit(); + self.merge.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; + 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, +}; + +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, +}; + +/// 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); + 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(); + try attend.attend(e, b.attention, shape); + e.barrier(); + try project.expand(e, b.attention.output, b.value_weights, b.values, shape.rows, shape.heads); + e.barrier(); + try project.gate(e, b.values, b.value_logits, shape.rows, shape.heads); +} 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..803dd9430b4 --- /dev/null +++ b/zig/src/families/hy4_flash/mla_weights.zig @@ -0,0 +1,89 @@ +//! 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 }; + +pub const Weights = struct { + key: []u16, + value: []u16, + + pub fn deinit(self: *Weights, a: std.mem.Allocator) void { + a.free(self.key); + a.free(self.value); + 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 dequant = try core.quant.mlx.dequant(a, try core.quant.slice.takeRows(a, words, &.{span}), try core.quant.slice.takeRows(a, scales, &.{span}), try core.quant.slice.takeRows(a, biases, &.{span}), 64); + defer a.free(dequant); + return split(a, .{ .fp32 = dequant }, range.count); + }, + } +} 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..bd6dc88d7ff --- /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.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.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..82668b630c5 --- /dev/null +++ b/zig/src/families/hy4_flash/rank_weights.zig @@ -0,0 +1,143 @@ +//! 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. +/// Q-A and KV-A are shared between ranks. The sink and absorbed K/V projection follow the head range. +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/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 }); + } +} From cc35dae571eeb3fc323b37df1da97014b2d77664 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:30:54 +0000 Subject: [PATCH 02/12] hy4_flash: serve Hy4-flash from tensorfold-native on Metal; decode speed work; compressed indexer past 2,048 keys - Serving: the lane host with one stream, 512-row prompt chunks, DFly2 verify windows of up to six rows drawn on the host with the stream's sampler, the last stream's caches reused for a prompt that starts with their tokens, and every buffer in one residency set. Hy4's :opensource marker tokens read as the GLM spellings the server already parses. - Long context: past 2,048 keys each sparse layer recalls its 511 best closed four-token groups plus its own (the reference's compressed indexer); token keys cached each pass, touched groups re-pooled in fp32. An fp64 check of the recall matches at 6K, and 6K-token NLL equals full attention. - Decode: IHC collapse and seams over threadgroups, row and tensor projections, decode GEMVs for 1-2 rows, expert pair GEMVs, split-key decode attention, rank-based router select, 512-row prompt chunks. - Probe: tf-hy4-speed (greedy ids and their hash, ms a token, per-stage GPU profile, NLL over a text). --- CHANGELOG.md | 2 + zig/build/hy4_probe.zig | 40 + zig/build/metal_targets.zig | 6 + zig/hy4_engine/lane_projection.zig | 21 + zig/hy4_engine/moe_route.zig | 10 + zig/hy4_engine/row_projection.zig | 18 + zig/kernels/metal/hy4_flash/engram.metal | 29 + zig/kernels/metal/hy4_flash/ihc.metal | 455 +++++++ zig/kernels/metal/hy4_flash/index_build.metal | 89 ++ .../metal/hy4_flash/mla_attention.metal | 104 ++ zig/kernels/metal/hy4_flash/mla_nax.metal | 283 ++++ zig/kernels/metal/hy4_flash/mla_project.metal | 25 + zig/kernels/metal/hy4_flash/route_rows.metal | 82 ++ zig/kernels/metal/hy4_flash/rows.metal | 770 +++++++++++ .../metal/hy4_flash/tensor_dispatch.metal | 52 + zig/kernels/metal/sources.zig | 4 + zig/src/core/lane_projection.zig | 3 +- zig/src/core/root.zig | 1 + zig/src/families/hy4_flash/engram_rows.zig | 21 + zig/src/families/hy4_flash/host_tests.zig | 4 +- zig/src/families/hy4_flash/ihc.zig | 6 +- zig/src/families/hy4_flash/ihc_metal.zig | 125 +- zig/src/families/hy4_flash/loader.zig | 4 +- zig/src/families/hy4_flash/metal_dense.zig | 538 +++++++- zig/src/families/hy4_flash/metal_draft.zig | 105 +- zig/src/families/hy4_flash/metal_engram.zig | 76 +- zig/src/families/hy4_flash/metal_index.zig | 237 ++++ zig/src/families/hy4_flash/metal_model.zig | 77 +- zig/src/families/hy4_flash/metal_routed.zig | 193 ++- .../hy4_flash/metal_tensor_experts.zig | 32 +- .../families/hy4_flash/metal_tensor_qkv.zig | 12 + zig/src/families/hy4_flash/mla_metal.zig | 185 ++- zig/src/families/hy4_flash/mla_weights.zig | 31 +- zig/src/families/hy4_flash/model_weights.zig | 4 +- zig/src/families/hy4_flash/serve_metal.zig | 757 +++++++++++ zig/src/families/hy4_flash/speed_probe.zig | 1151 +++++++++++++++++ zig/src/families/hy4_flash/split_metal.zig | 172 +++ zig/src/native/hy4_metal.zig | 82 ++ zig/src/native/metal.zig | 2 + zig/src/server/hf_text.zig | 48 +- zig/src/tensorfold.zig | 1 + 41 files changed, 5706 insertions(+), 151 deletions(-) create mode 100644 zig/build/hy4_probe.zig create mode 100644 zig/hy4_engine/lane_projection.zig create mode 100644 zig/hy4_engine/moe_route.zig create mode 100644 zig/hy4_engine/row_projection.zig create mode 100644 zig/kernels/metal/hy4_flash/index_build.metal create mode 100644 zig/kernels/metal/hy4_flash/mla_nax.metal create mode 100644 zig/kernels/metal/hy4_flash/route_rows.metal create mode 100644 zig/kernels/metal/hy4_flash/rows.metal create mode 100644 zig/src/families/hy4_flash/metal_index.zig create mode 100644 zig/src/families/hy4_flash/serve_metal.zig create mode 100644 zig/src/families/hy4_flash/speed_probe.zig create mode 100644 zig/src/families/hy4_flash/split_metal.zig create mode 100644 zig/src/native/hy4_metal.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index 4692a3cf5a2..4f1e25381d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -233,6 +233,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML. +- 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). + - Tests: the Zig cache restat tests read `.lib_dir` from `zig env` instead of guessing a `lib` folder beside the executable, so they work with Homebrew Zig (#3786, fixes #3785). Thanks to @AIFlowML. - `tensorfold web`: after a PATH miss, the launcher looks in uv's tool directory for an existing Web executable before offering an install; PATH still wins and installing still needs an explicit yes (#3748, fixes #3747). Thanks to @AIFlowML. diff --git a/zig/build/hy4_probe.zig b/zig/build/hy4_probe.zig new file mode 100644 index 00000000000..a09ffe54182 --- /dev/null +++ b/zig/build/hy4_probe.zig @@ -0,0 +1,40 @@ +//! tf-hy4-speed: the Hy4-flash Metal graph's greedy decode speed and per-stage GPU profile on a real checkpoint. +const std = @import("std"); + +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, real_metal: *std.Build.Module, sources: *std.Build.Module) void { + const metal = b.createModule(.{ + .root_source_file = b.path("zig/src/families/hy4_flash/split_metal.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "real_metal", .module = real_metal }}, + }); + const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "tokenizer", .module = tokenizer }} }); + core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); + const with_metal: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources } }; + const row = b.createModule(.{ .root_source_file = b.path("zig/src/core/row_projection.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = with_metal }); + const lane = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_projection.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = with_metal }); + const route = b.createModule(.{ .root_source_file = b.path("zig/src/core/moe_route.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = with_metal }); + const draft_ops = b.createModule(.{ .root_source_file = b.path("zig/src/core/draft_ops.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ + .{ .name = "metal", .module = metal }, + .{ .name = "draft_ops_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/draft_ops_sources.zig") }) }, + } }); + const hash = b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize }); + const exe = b.addExecutable(.{ .name = "tf-hy4-speed", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/families/hy4_flash/speed_probe.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal }, + .{ .name = "kernel_sources", .module = sources }, + .{ .name = "core", .module = core }, + .{ .name = "row_projection", .module = row }, + .{ .name = "lane_projection", .module = lane }, + .{ .name = "moe_route", .module = route }, + .{ .name = "draft_ops", .module = draft_ops }, + .{ .name = "engram_hash_core", .module = hash }, + }, + }) }); + b.step("tf-hy4-speed", "Hy4-flash Metal greedy decode: IDs, hash, ms a token, per-stage GPU profile").dependOn(&b.addInstallArtifact(exe, .{}).step); +} diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index b00995dcff3..945604c3101 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -420,6 +420,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s }) }); b.step("tf-row-check", "The core row projection on synthetic 4-bit matrices: widths bit-equal, a CPU reference, indexed experts").dependOn(&b.addInstallArtifact(row_check, .{}).step); core_checks.rowWidths(b, target, optimize, metal, row_mod); + @import("hy4_probe.zig").steps(b, target, optimize, metal, sources); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = row_mod })).step); core_checks.tileQmm(b, target, optimize, metal, sources, test_step); core_checks.kvPages(b, target, optimize, metal, sources, test_step); @@ -554,6 +555,11 @@ 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 } }, }); + // Hy4-flash's family files import these by name (the speed probe builds them alone): the engine's own, re-exported + for ([_][]const u8{ "row_projection", "lane_projection", "moe_route" }) |name| { + engine.addImport(name, b.createModule(.{ .root_source_file = b.path(b.fmt("zig/hy4_engine/{s}.zig", .{name})), .target = target, .optimize = optimize, .imports = &.{.{ .name = "tensorfold", .module = engine }} })); + } + 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/hy4_engine/lane_projection.zig b/zig/hy4_engine/lane_projection.zig new file mode 100644 index 00000000000..4ccced197a0 --- /dev/null +++ b/zig/hy4_engine/lane_projection.zig @@ -0,0 +1,21 @@ +//! The engine's lane_projection for the Hy4-flash family files, which import it by name (the speed probe builds it alone). +const m = @import("tensorfold").lane_projection; +pub const frags = m.frags; +pub const affine_mm = m.affine_mm; +pub const weight_layout = m.weight_layout; +pub const reg_layout = m.reg_layout; +pub const metadata_layout = m.metadata_layout; +pub const Output = m.Output; +pub const Format = m.Format; +pub const Layout = m.Layout; +pub const source = m.source; +pub const pack = m.pack; +pub const regBlock = m.regBlock; +pub const Order = m.Order; +pub const RegOrder = m.RegOrder; +pub const regOrder = m.regOrder; +pub const Ref = m.Ref; +pub const Projection = m.Projection; +pub const reg_rows = m.reg_rows; +pub const max_reg_rows = m.max_reg_rows; +pub const Sums = m.Sums; diff --git a/zig/hy4_engine/moe_route.zig b/zig/hy4_engine/moe_route.zig new file mode 100644 index 00000000000..5e9d7803f04 --- /dev/null +++ b/zig/hy4_engine/moe_route.zig @@ -0,0 +1,10 @@ +//! The engine's moe_route for the Hy4-flash family files, which import it by name (the speed probe builds it alone). +const m = @import("tensorfold").moe_route; +pub const Shape = m.Shape; +pub const source = m.source; +pub const names = m.names; +pub const logits = m.logits; +pub const Args = m.Args; +pub const Outputs = m.Outputs; +pub const select = m.select; +pub const pack = m.pack; diff --git a/zig/hy4_engine/row_projection.zig b/zig/hy4_engine/row_projection.zig new file mode 100644 index 00000000000..58391df883c --- /dev/null +++ b/zig/hy4_engine/row_projection.zig @@ -0,0 +1,18 @@ +//! The engine's row_projection for the Hy4-flash family files, which import it by name (the speed probe builds it alone). +const m = @import("tensorfold").row_projection; +pub const simd = m.simd; +pub const simd_bits = m.simd_bits; +pub const batch = m.batch; +pub const columns = m.columns; +pub const groups = m.groups; +pub const bit_widths = m.bit_widths; +pub const Sum = m.Sum; +pub const Weights = m.Weights; +pub const affine = m.affine; +pub const Experts = m.Experts; +pub const Pipelines = m.Pipelines; +pub const source = m.source; +pub const Call = m.Call; +pub const call = m.call; +pub const callStrided = m.callStrided; +pub const callIndexed = m.callIndexed; diff --git a/zig/kernels/metal/hy4_flash/engram.metal b/zig/kernels/metal/hy4_flash/engram.metal index 1b549d0e745..8a4eb7b2ef0 100644 --- a/zig/kernels/metal/hy4_flash/engram.metal +++ b/zig/kernels/metal/hy4_flash/engram.metal @@ -116,3 +116,32 @@ kernel void tf_hy4_engram_apply( 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, plus the bias (two fp32 +// roundings, as the host's dequant does), rounded to BF16 ties-to-even as the host's gather writes it, so every +// placement stages the same bits. rows[token * 16 + column] = table row; out [token][column][96]; a.x bits, a.y cells. +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 index 6272d6c2e82..0fb90dea616 100644 --- a/zig/kernels/metal/hy4_flash/ihc.metal +++ b/zig/kernels/metal/hy4_flash/ihc.metal @@ -60,6 +60,141 @@ kernel void tf_hy4_ihc_collapse( } } +// tf_hy4_ihc_collapse with the gate count fixed at compile time: the same thread partition, fma chains, simd +// butterflies and partial sums in the same order, so the same bits, but the eight gate sums live in registers +// and the loads of an iteration issue together instead of through an indexed stack array. +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. tf_hy4_ihc_partials runs each of the 256-thread version's eight simdgroups as +// its own threadgroup (simdgroup s on core s instead of all eight on one core): thread t = 32 s + lane keeps its +// stride-256 fma chain and butterfly, and lane 0 stores the simdgroup's sums as part[row][gate][s] (gate 8: sum of +// squares). tf_hy4_ihc_finish then adds the eight partials in the same order and writes the collapsed row. +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): every slice derives the same gates from +// the same partials in the same order, and slice 0 alone stores the post gates. +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)]], @@ -94,3 +229,323 @@ kernel void tf_hy4_draft_residual( 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: a sub-block's branch (one input, or two added in bfloat as the expert branches are) through its output RMS +// norm (bf16(x * inv) * gain, as the norm kernel rounds), mixed into the four residual streams with the post gates +// (rounded as tf_hy4_ihc_add), and, when the next collapse's weights are given, that collapse's fp32 partial sums +// over the mixed streams. 12 threadgroups of 256 threads a row, each element once; every threadgroup derives the norm +// scale itself from the branch row (6 KB) and stores its 19 sums at part[row][sum][tg] (16 slots a sum). +// mode 0: partials only of the given streams (no branch; after an Engram layer). +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, so the head gets the collapsed row's sum of squares +// as pre^T Gram pre instead of a second pass over the row: part[row][9 + k][tg]. +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; its stream + // order is the flat order's, so the gate sums keep their bits) + 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), the collapsed row +// (as tf_hy4_ihc_finish), then the sub-block's input RMS norm with the row's sum of squares from the tail's stream +// products: 12 threadgroups of 256 a row, a column a thread, no pass over the whole row. +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): the row's 12 threadgroups meet at an in-kernel barrier +// between them (all are resident: at most 16 rows a launch), so the head's gates and Gram sums come from every +// threadgroup's partials without a second launch. A thread owns one column (width 3072 = 12 x 256) and keeps its +// four mixed stream values in registers across the barrier. The partials cross threadgroups as device atomics. +// The same arithmetic as ihc_tail then ihc_head (the same sums in the same orders), so the same bits. +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..fb63488a218 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/index_build.metal @@ -0,0 +1,89 @@ +// Hy4-flash's compressed indexer, the parts before scoring: each row's normalized token key into the layer's key +// cache, and each four-slot group's pooled, normalized key (fp32 inside, BF16 out; RoPE runs after, on the cache). +#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, then +// times the BF16 gain (a BF16 product), written at the row's cache slot. +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): the four token keys through the fp32 value and gate +// projections ([out][in]), the slot softmax of the gates plus the intra-group position bias, the weighted sum, and +// the fp32 key norm, rounded to BF16 at the group's cache row. The four slots of a group are its tokens' cache +// slots 4g..4g+3. +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/mla_attention.metal b/zig/kernels/metal/hy4_flash/mla_attention.metal index 23b8651d9d0..4ad6ad5d72e 100644 --- a/zig/kernels/metal/hy4_flash/mla_attention.metal +++ b/zig/kernels/metal/hy4_flash/mla_attention.metal @@ -84,3 +84,107 @@ kernel void tf_hy4_attend_merge( } 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. tf_hy4_attend_scores computes every retained key's score with +// tf_hy4_attend_chunks's lane split, fma order and butterfly (so each score's bits are the same), 64 keys a +// simdgroup and four heads a threadgroup, all keys at once. tf_hy4_attend_scored then runs each chunk's online +// softmax over those scores in the original key order, the same recurrence step for step, and writes the same +// partials for tf_hy4_attend_merge. Scores: [row][head][key_stride] floats. +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: all 128 threads load 16 keys' latent rows into threadgroup + // memory together (one memory round trip a tile, not one a key), then each head steps through the tile. + 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): running maxima by a prefix max across lanes (max is exact, so + // the same values as the key-by-key scan), each key's exponentials by the same formula on the same operands. + 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..aec151e524d --- /dev/null +++ b/zig/kernels/metal/hy4_flash/mla_nax.metal @@ -0,0 +1,283 @@ +// Hy4-flash's absorbed-MLA BF16 products on the tensor units (nax.h's 16x32x16 op): every row count runs the same +// tiles, so prompt chunks and decode rows get the same bits. One head a threadgroup column, 16 rows by 128 outputs a +// threadgroup (4 simdgroups of 16 x 32). +#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]; the gate as +// tf_hy4_gate_values: the value rounded, times its rounded sigmoid, rounded. +[[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: one head and 16 query rows a threadgroup, 32-key tiles at +// absolute key indices (so a row's tiles and their order are its own, whatever rows share its block; tiles outside a +// row's range are exact no-ops for it). S = Q K^T with the 576 key columns split over the 4 simdgroups and their +// partials added in a fixed order; an online softmax a row; O += P V with each simdgroup owning 128 latent columns; +// the learned sink joins at the end. ranges[r] = [lo, hi) key indices; tiles[t] = the slot of key index 32 t (a +// tile's 32 slots are consecutive). +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 +// unnormalized O, running max and sum (fp32) for tf_hy4_attend_combine instead of the sink and the division. +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: out = sum_z O_z e^(m_z - M) / L, +// L = sum_z l_z e^(m_z - M) + e^(sink - M), M the largest of the maxima and the sink. Grid (heads, rows), 128 threads. +[[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 index 66d3b374b93..c9b471ba25b 100644 --- a/zig/kernels/metal/hy4_flash/mla_project.metal +++ b/zig/kernels/metal/hy4_flash/mla_project.metal @@ -132,3 +132,28 @@ kernel void tf_hy4_expand_v( } expanded[ulong(row_head) * 256 + column] = hy4_mla_round(sum); } + +// tf_hy4_expand_v then tf_hy4_gate_values in one launch: the expanded value rounded as before, then gated by the +// rounded sigmoid of its logit exactly as the gate pass does, so the same bits without the second pass. +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..77e01bab580 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/route_rows.metal @@ -0,0 +1,82 @@ + +// Appended to the core router source (its TF_E, TF_TOPK, PER, RouteArgs and tf_sigmoid_precise). A prompt chunk's +// picks and weights: tf_route_select's per-row top-k (sigmoid + bias, ties to the lower id, weights normalized and +// scaled) step for step, one simdgroup a row and a threadgroup per row, so every row runs at once. +[[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), each expert's rank the +// count of experts ahead of it (larger sigmoid + bias, ties to the lower id), so the top-k write themselves in pick +// order; then the weights normalized in that order as the loop does. The same picks, order and weights (same +// sigmoid, same sums), without the k sequential arg-max rounds. +[[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..c99237e2563 --- /dev/null +++ b/zig/kernels/metal/hy4_flash/rows.metal @@ -0,0 +1,770 @@ + +// Hy4-flash lane windows (compiled after the chip's core row projection source, whose helpers it calls). +// Each output column's per-row arithmetic is tf_rp_rows's, as in the plain and wide kernels, so rows give the same +// bits however many share a pass. Here every weight is read once for up to 8 rows, with RPS columns a simdgroup and +// SG simdgroups a threadgroup, and no 64-thread cap, so a 2- to 8-row window costs about what one row does. +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]. +// SH: 3+ row blocks unpack each code once for all their rows (the core's shared branch) instead of once a pair. +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. +// a.x: vocabulary, a.y: where row 0's token goes in OUT. +[[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; + } +} + +// tf_add_bf16 (A + B in bfloat) feeding tf_draft_rms in one launch: the routed and shared expert branches summed as +// each norm thread reads them, with the norm's thread split, sums and roundings, so the same bits and no add pass. +struct Hy4Norm { uint rows, heads, dim, x_stride, y_stride, round_normalized; float eps; }; +[[kernel]] void tf_hy4_add_rms(device const bfloat* A [[buffer(0)]], device const bfloat* B [[buffer(1)]], + device const bfloat* W [[buffer(2)]], constant Hy4Norm& a [[buffer(3)]], + device bfloat* Y [[buffer(4)]], uint2 block [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint2 threads [[threads_per_threadgroup]]) { + threadgroup float sums[32], inverse[1]; + float value = 0.0f; + const size_t base = size_t(block.y) * a.x_stride + block.x * a.dim; + for (uint first = 4 * t; first < a.dim; first += 4 * threads.x) + for (uint j = 0; j < 4 && first + j < a.dim; j++) { + const bfloat s = A[base + first + j] + B[base + first + j]; + float x = float(s); + value += x * x; + } + value = simd_sum(value); + if (sg == 0) sums[lane] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0) sums[sg] = value; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float total = simd_sum(sums[lane]); + if (lane == 0) inverse[0] = precise::rsqrt(total / float(a.dim) + a.eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint first = 4 * t; first < a.dim; first += 4 * threads.x) + for (uint j = 0; j < 4 && first + j < a.dim; j++) { + const uint col = first + j; + const bfloat s = A[base + col] + B[base + col]; + float normalized = float(s) * inverse[0]; + normalized = float(bfloat(normalized)); + Y[size_t(block.y) * a.y_stride + block.x * a.dim + col] = bfloat(normalized * float(W[col])); + } +} + +// Decode-sized passes (1-8 rows) of an MLX-affine 4- or 8-bit [n, k] matrix (groups of 64): fp32 sums, each weight +// read once with 16-byte loads. A simdgroup owns QR output columns; lane l takes 32 consecutive inputs of every +// 1024 (half a group): it holds those columns' weight words, scales and biases, then streams each row's 32 inputs +// through them. y[r][n] = sum over groups of scale * (x . q) + bias * sum(x). dims: K, N, GS (64), rows. +template +[[kernel]] void tf_hy4_qmv(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], rows = min(dims[3], 8); + constexpr int SG = 4, WPL = 32 * BITS / 32; // weight words a lane takes a step (4 at 4 bits, 8 at 8) + const int col0 = (int(tg.x) * SG + int(sg)) * QR; + if (col0 >= N) return; + const int words_row = K * BITS / 32, groups_row = K / 64; + float acc[8][QR]; + for (int r = 0; r < 8; ++r) + for (int j = 0; j < QR; ++j) acc[r][j] = 0.0f; + for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { + uint w[QR][WPL]; + float scale[QR], bias[QR]; + const int g = k0 / 64; + for (int j = 0; j < QR; ++j) { + const int n = col0 + j; + const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); + for (int v = 0; v < WPL / 4; ++v) { + const uint4 w4 = wp[v]; + w[j][4 * v] = w4.x; w[j][4 * v + 1] = w4.y; w[j][4 * v + 2] = w4.z; w[j][4 * v + 3] = w4.w; + } + scale[j] = float(S[size_t(n) * groups_row + g]); + bias[j] = float(B[size_t(n) * groups_row + g]); + } + for (int r = 0; r < rows; ++r) { + const device uint4* xp = (const device uint4*)(X + size_t(r) * K + k0); + float dot[QR]; + for (int j = 0; j < QR; ++j) dot[j] = 0.0f; + float xsum = 0.0f; + for (int v = 0; v < 4; ++v) { + const uint4 x4 = xp[v]; + const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; + for (int u = 0; u < 4; ++u) { + const int i = v * 8 + u * 2; // input index within the lane's 32 + const float x0 = as_type(xw[u] << 16), x1 = as_type(xw[u] & 0xffff0000u); + xsum += x0 + x1; + for (int j = 0; j < QR; ++j) { + float q0, q1; + if (BITS == 4) { + const uint word = w[j][i / 8]; + q0 = float((word >> (4 * (i % 8))) & 0xfu); + q1 = float((word >> (4 * (i % 8 + 1))) & 0xfu); + } else { + const uint word = w[j][i / 4]; + q0 = float((word >> (8 * (i % 4))) & 0xffu); + q1 = float((word >> (8 * (i % 4 + 1))) & 0xffu); + } + dot[j] = fma(x1, q1, fma(x0, q0, dot[j])); + } + } + } + for (int j = 0; j < QR; ++j) acc[r][j] = fma(scale[j], dot[j], fma(bias[j], xsum, acc[r][j])); + } + } + for (int r = 0; r < rows; ++r) { + for (int j = 0; j < QR; ++j) { + const float v = simd_sum(acc[r][j]); + if (lane == 0) OUT[size_t(r) * N + col0 + j] = bfloat(v); + } + } +} + +template [[host_name("tf_hy4_qmv_q4")]] [[kernel]] decltype(tf_hy4_qmv<4, 4>) tf_hy4_qmv<4, 4>; +template [[host_name("tf_hy4_qmv_q8")]] [[kernel]] decltype(tf_hy4_qmv<8, 4>) tf_hy4_qmv<8, 4>; + +// tf_hy4_qmv with the weights unpacked once a step for every row: two output columns a simdgroup, their 64 codes +// as floats in registers, each row's 32 inputs streamed past them (multi-row passes pay one unpack, not one a row). +template +[[kernel]] void tf_hy4_qmv2(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], rows = min(dims[3], 8); + constexpr int SG = 4, QR = 2, WPL = BITS; + const int col0 = (int(tg.x) * SG + int(sg)) * QR; + if (col0 >= N) return; + const int words_row = K * BITS / 32, groups_row = K / 64; + float acc[8][QR]; + for (int r = 0; r < 8; ++r) + for (int j = 0; j < QR; ++j) acc[r][j] = 0.0f; + for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { + float q[QR][32]; + float scale[QR], bias[QR]; + const int g = k0 / 64; + for (int j = 0; j < QR; ++j) { + const int n = col0 + j; + const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); + for (int v = 0; v < WPL / 4; ++v) { + const uint4 w4 = wp[v]; + const uint words[4] = {w4.x, w4.y, w4.z, w4.w}; + for (int u = 0; u < 4; ++u) { + if (BITS == 4) { + for (int b = 0; b < 8; ++b) q[j][(v * 4 + u) * 8 + b] = float((words[u] >> (4 * b)) & 0xfu); + } else { + for (int b = 0; b < 4; ++b) q[j][(v * 4 + u) * 4 + b] = float((words[u] >> (8 * b)) & 0xffu); + } + } + } + scale[j] = float(S[size_t(n) * groups_row + g]); + bias[j] = float(B[size_t(n) * groups_row + g]); + } + for (int r = 0; r < rows; ++r) { + const device uint4* xp = (const device uint4*)(X + size_t(r) * K + k0); + float dot[QR] = {0.0f, 0.0f}; + float xsum = 0.0f; + for (int v = 0; v < 4; ++v) { + const uint4 x4 = xp[v]; + const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; + for (int u = 0; u < 4; ++u) { + const int i = v * 8 + u * 2; + const float x0 = as_type(xw[u] << 16), x1 = as_type(xw[u] & 0xffff0000u); + xsum += x0 + x1; + for (int j = 0; j < QR; ++j) dot[j] = fma(x1, q[j][i + 1], fma(x0, q[j][i], dot[j])); + } + } + for (int j = 0; j < QR; ++j) acc[r][j] = fma(scale[j], dot[j], fma(bias[j], xsum, acc[r][j])); + } + } + for (int r = 0; r < rows; ++r) + for (int j = 0; j < QR; ++j) { + const float v = simd_sum(acc[r][j]); + if (lane == 0) OUT[size_t(r) * N + col0 + j] = bfloat(v); + } +} + +template [[host_name("tf_hy4_qmv2_q4")]] [[kernel]] decltype(tf_hy4_qmv2<4>) tf_hy4_qmv2<4>; +template [[host_name("tf_hy4_qmv2_q8")]] [[kernel]] decltype(tf_hy4_qmv2<8>) tf_hy4_qmv2<8>; + +// tf_hy4_qmv2 for decode passes with the row count fixed at compile time (R = 1 to 4) and QR output columns a +// simdgroup: each lane's 32 inputs are read once for QR columns, and the QR weight loads of a step issue together. +// The same sums per (row, column) as tf_hy4_qmv2 (fma over the 32 codes in order, then scale and bias, then the +// simdgroup sum), so the same bits. +template +[[kernel]] void tf_hy4_qmv3(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]; + constexpr int SG = 4; + const int col0 = (int(tg.x) * SG + int(sg)) * QR; + if (col0 >= N) return; + const int words_row = K * BITS / 32, groups_row = K / 64; + float acc[R][QR]; + for (int r = 0; r < R; ++r) + for (int j = 0; j < QR; ++j) acc[r][j] = 0.0f; + for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { + const int g = k0 / 64; + uint4 wv[QR][BITS / 4]; + float scale[QR], bias[QR]; + for (int j = 0; j < QR; ++j) { + const int n = col0 + j; + const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); + for (int v = 0; v < BITS / 4; ++v) wv[j][v] = wp[v]; + scale[j] = float(S[size_t(n) * groups_row + g]); + bias[j] = float(B[size_t(n) * groups_row + g]); + } + for (int r = 0; r < R; ++r) { + const device uint4* xp = (const device uint4*)(X + size_t(r) * K + k0); + float xs[32]; + float xsum = 0.0f; + for (int v = 0; v < 4; ++v) { + const uint4 x4 = xp[v]; + const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; + for (int u = 0; u < 4; ++u) { + xs[v * 8 + u * 2] = as_type(xw[u] << 16); + xs[v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); + xsum += xs[v * 8 + u * 2] + xs[v * 8 + u * 2 + 1]; + } + } + for (int j = 0; j < QR; ++j) { + float dot = 0.0f; + for (int v = 0; v < BITS / 4; ++v) { + const uint words[4] = {wv[j][v].x, wv[j][v].y, wv[j][v].z, wv[j][v].w}; + for (int u = 0; u < 4; ++u) { + if (BITS == 4) { + for (int b = 0; b < 8; ++b) dot = fma(xs[(v * 4 + u) * 8 + b], float((words[u] >> (4 * b)) & 0xfu), dot); + } else { + for (int b = 0; b < 4; ++b) dot = fma(xs[(v * 4 + u) * 4 + b], float((words[u] >> (8 * b)) & 0xffu), dot); + } + } + } + acc[r][j] = fma(scale[j], dot, fma(bias[j], xsum, acc[r][j])); + } + } + } + for (int r = 0; r < R; ++r) + for (int j = 0; j < QR; ++j) { + const float v = simd_sum(acc[r][j]); + if (lane == 0) OUT[size_t(r) * N + col0 + j] = bfloat(v); + } +} + +template [[host_name("tf_hy4_qmv3_r1_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 1, 4>) tf_hy4_qmv3<4, 1, 4>; +template [[host_name("tf_hy4_qmv3_r2_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 2, 4>) tf_hy4_qmv3<4, 2, 4>; +template [[host_name("tf_hy4_qmv3_r1_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 1, 4>) tf_hy4_qmv3<8, 1, 4>; +template [[host_name("tf_hy4_qmv3_r2_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 2, 4>) tf_hy4_qmv3<8, 2, 4>; +template [[host_name("tf_hy4_qmv3_r3_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 3, 4>) tf_hy4_qmv3<4, 3, 4>; +template [[host_name("tf_hy4_qmv3_r4_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 4, 4>) tf_hy4_qmv3<4, 4, 4>; +template [[host_name("tf_hy4_qmv3_r3_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 3, 4>) tf_hy4_qmv3<8, 3, 4>; +template [[host_name("tf_hy4_qmv3_r4_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 4, 4>) tf_hy4_qmv3<8, 4, 4>; +template [[host_name("tf_hy4_qmv3x8_r1_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 1, 8>) tf_hy4_qmv3<4, 1, 8>; +template [[host_name("tf_hy4_qmv3x8_r2_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 2, 8>) tf_hy4_qmv3<4, 2, 8>; +template [[host_name("tf_hy4_qmv3x8_r1_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 1, 8>) tf_hy4_qmv3<8, 1, 8>; +template [[host_name("tf_hy4_qmv3x8_r2_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 2, 8>) tf_hy4_qmv3<8, 2, 8>; +template [[host_name("tf_hy4_qmv3x8_r3_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 3, 8>) tf_hy4_qmv3<4, 3, 8>; +template [[host_name("tf_hy4_qmv3x8_r4_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 4, 8>) tf_hy4_qmv3<4, 4, 8>; +template [[host_name("tf_hy4_qmv3x8_r3_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 3, 8>) tf_hy4_qmv3<8, 3, 8>; +template [[host_name("tf_hy4_qmv3x8_r4_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 4, 8>) tf_hy4_qmv3<8, 4, 8>; + +// ---- Routed experts for 1-2 row passes: each (row, pick) pair's gate/up and down as GEMVs over that expert's +// MLX-layout matrices (fp32 sums, each weight read once), the clipped SwiGLU rounded as the tensor gather's epilogue. +struct Hy4ExpertShape { uint pairs, picks, k, n; float limit; }; + +// QR = 2 output columns a simdgroup: their codes unpacked once a step, the row's 32 inputs a lane streamed past. +template +inline void hy4_qmv_cols2(const device bfloat* x, const device uint32_t* W, const device bfloat* S, + const device bfloat* B, int K, int col0, uint lane, thread float (&acc)[2]) { + const int words_row = K * BITS / 32, groups_row = K / 64; + acc[0] = 0.0f; acc[1] = 0.0f; + for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { + const int g = k0 / 64; + const device uint4* xp = (const device uint4*)(x + k0); + float xs[32]; + float xsum = 0.0f; + for (int v = 0; v < 4; ++v) { + const uint4 x4 = xp[v]; + const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; + for (int u = 0; u < 4; ++u) { + xs[v * 8 + u * 2] = as_type(xw[u] << 16); + xs[v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); + xsum += xs[v * 8 + u * 2] + xs[v * 8 + u * 2 + 1]; + } + } + for (int j = 0; j < 2; ++j) { + const int n = col0 + j; + const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); + float dot = 0.0f; + for (int v = 0; v < BITS / 4; ++v) { + const uint4 w4 = wp[v]; + const uint words[4] = {w4.x, w4.y, w4.z, w4.w}; + for (int u = 0; u < 4; ++u) { + if (BITS == 4) { + for (int b = 0; b < 8; ++b) dot = fma(xs[(v * 4 + u) * 8 + b], float((words[u] >> (4 * b)) & 0xfu), dot); + } else { + for (int b = 0; b < 4; ++b) dot = fma(xs[(v * 4 + u) * 4 + b], float((words[u] >> (8 * b)) & 0xffu), dot); + } + } + } + acc[j] = fma(float(S[size_t(n) * groups_row + g]), dot, fma(float(B[size_t(n) * groups_row + g]), xsum, acc[j])); + } + } + acc[0] = simd_sum(acc[0]); + acc[1] = simd_sum(acc[1]); +} + +inline bfloat hy4_expert_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)); + const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); + return sl * up; +} + +// act[pair][n] = swiglu(gate_e x_row, up_e x_row); x = latent [rows][k]; grid (n / 8, pairs), 4 simdgroups. +template +[[kernel]] void tf_hy4_expert_glu(const device bfloat* latent [[buffer(0)]], const device int* pick [[buffer(1)]], + const device uint32_t* GW [[buffer(2)]], const device bfloat* GS [[buffer(3)]], + const device bfloat* GB [[buffer(4)]], const device uint32_t* UW [[buffer(5)]], + const device bfloat* US [[buffer(6)]], const device bfloat* UB [[buffer(7)]], + device bfloat* act [[buffer(8)]], constant Hy4ExpertShape& a [[buffer(9)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint p = tg.y; + if (p >= a.pairs) return; + const int col0 = (int(tg.x) * 4 + int(sg)) * 2; + if (col0 >= int(a.n)) return; + const int K = int(a.k), N = int(a.n); + const ulong e = ulong(pick[p]); + const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); + const device bfloat* x = latent + ulong(p / a.picks) * K; + float g[2], u[2]; + hy4_qmv_cols2(x, GW + e * wstride, GS + e * sstride, GB + e * sstride, K, col0, lane, g); + hy4_qmv_cols2(x, UW + e * wstride, US + e * sstride, UB + e * sstride, K, col0, lane, u); + if (lane == 0) + for (int j = 0; j < 2; ++j) act[ulong(p) * N + col0 + j] = hy4_expert_swiglu(g[j], u[j], a.limit); +} + +// out[pair][n] (fp32) = down_e act[pair]; grid (n / 8, pairs). +template +[[kernel]] void tf_hy4_expert_down(const device bfloat* act [[buffer(0)]], const device int* pick [[buffer(1)]], + const device uint32_t* DW [[buffer(2)]], const device bfloat* DS [[buffer(3)]], + const device bfloat* DB [[buffer(4)]], device float* out [[buffer(5)]], + constant Hy4ExpertShape& a [[buffer(6)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint p = tg.y; + if (p >= a.pairs) return; + const int col0 = (int(tg.x) * 4 + int(sg)) * 2; + if (col0 >= int(a.n)) return; + const int K = int(a.k), N = int(a.n); + const ulong e = ulong(pick[p]); + const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); + float d[2]; + hy4_qmv_cols2(act + ulong(p) * K, DW + e * wstride, DS + e * sstride, DB + e * sstride, K, col0, lane, d); + if (lane == 0) + for (int j = 0; j < 2; ++j) out[ulong(p) * N + col0 + j] = d[j]; +} + +// tf_hy4_expert_down with tf_hy4_routed_sum folded in: threadgroup (column block, row) takes the row's picks in +// order and adds weight * down(act) as the routed sum does (fma in slot order), writing the bf16 weighted row. +// The same bits as the two launches, without the fp32 pair outputs. +template +[[kernel]] void tf_hy4_expert_down_sum(const device bfloat* act [[buffer(0)]], const device int* pick [[buffer(1)]], + const device uint32_t* DW [[buffer(2)]], const device bfloat* DS [[buffer(3)]], + const device bfloat* DB [[buffer(4)]], device bfloat* weighted [[buffer(5)]], + constant Hy4ExpertShape& a [[buffer(6)]], const device float* wts [[buffer(7)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const uint r = tg.y; + if (r * a.picks >= a.pairs) return; + const int col0 = (int(tg.x) * 4 + int(sg)) * 2; + if (col0 >= int(a.n)) return; + const int K = int(a.k), N = int(a.n); + const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); + float sum[2] = {0.0f, 0.0f}; + for (uint slot = 0; slot < a.picks; ++slot) { + const uint p = r * a.picks + slot; + const ulong e = ulong(pick[p]); + float d[2]; + hy4_qmv_cols2(act + ulong(p) * K, DW + e * wstride, DS + e * sstride, DB + e * sstride, K, col0, lane, d); + const float w = wts[p]; + sum[0] = fma(w, d[0], sum[0]); + sum[1] = fma(w, d[1], sum[1]); + } + if (lane == 0) + for (int j = 0; j < 2; ++j) weighted[ulong(r) * N + col0 + j] = bfloat(sum[j]); +} + +template [[host_name("tf_hy4_expert_down_sum_q4")]] [[kernel]] decltype(tf_hy4_expert_down_sum<4>) tf_hy4_expert_down_sum<4>; +template [[host_name("tf_hy4_expert_down_sum_q8")]] [[kernel]] decltype(tf_hy4_expert_down_sum<8>) tf_hy4_expert_down_sum<8>; + +template [[host_name("tf_hy4_expert_glu_q4")]] [[kernel]] decltype(tf_hy4_expert_glu<4>) tf_hy4_expert_glu<4>; +template [[host_name("tf_hy4_expert_glu_q8")]] [[kernel]] decltype(tf_hy4_expert_glu<8>) tf_hy4_expert_glu<8>; +template [[host_name("tf_hy4_expert_down_q4")]] [[kernel]] decltype(tf_hy4_expert_down<4>) tf_hy4_expert_down<4>; +template [[host_name("tf_hy4_expert_down_q8")]] [[kernel]] decltype(tf_hy4_expert_down<8>) tf_hy4_expert_down<8>; + +// ---- Routed experts for 3-16 row passes, grouped by expert: the router window's jobs (ids[j], member pairs at +// members[j * 16 ..], -1 padded, count[0] jobs), each active expert's codes unpacked once for all its member rows. +// A member row's sums run in hy4_qmv_cols2's order, so every pair's result equals the 1-2 row path's bits. +template +inline void hy4_qmv_cols2_group(const device bfloat* x0, thread const int (&xrow)[M], int count, int ldx, + const device uint32_t* W, const device bfloat* S, const device bfloat* B, int K, + int col0, uint lane, thread float (&acc)[M][2]) { + const int words_row = K * BITS / 32, groups_row = K / 64; + for (int m = 0; m < M; ++m) { acc[m][0] = 0.0f; acc[m][1] = 0.0f; } + for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { + const int g = k0 / 64; + float q[2][32]; + float sc[2], bi[2]; + for (int j = 0; j < 2; ++j) { + const int n = col0 + j; + const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); + for (int v = 0; v < BITS / 4; ++v) { + const uint4 w4 = wp[v]; + const uint words[4] = {w4.x, w4.y, w4.z, w4.w}; + for (int u = 0; u < 4; ++u) { + if (BITS == 4) { + for (int b = 0; b < 8; ++b) q[j][(v * 4 + u) * 8 + b] = float((words[u] >> (4 * b)) & 0xfu); + } else { + for (int b = 0; b < 4; ++b) q[j][(v * 4 + u) * 4 + b] = float((words[u] >> (8 * b)) & 0xffu); + } + } + } + sc[j] = float(S[size_t(n) * groups_row + g]); + bi[j] = float(B[size_t(n) * groups_row + g]); + } + for (int m = 0; m < M; ++m) { + if (m >= count) break; + const device uint4* xp = (const device uint4*)(x0 + size_t(xrow[m]) * ldx + k0); + float xs[32]; + float xsum = 0.0f; + for (int v = 0; v < 4; ++v) { + const uint4 x4 = xp[v]; + const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; + for (int u = 0; u < 4; ++u) { + xs[v * 8 + u * 2] = as_type(xw[u] << 16); + xs[v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); + xsum += xs[v * 8 + u * 2] + xs[v * 8 + u * 2 + 1]; + } + } + for (int j = 0; j < 2; ++j) { + float dot = 0.0f; + for (int i = 0; i < 32; ++i) dot = fma(xs[i], q[j][i], dot); + acc[m][j] = fma(sc[j], dot, fma(bi[j], xsum, acc[m][j])); + } + } + } + for (int m = 0; m < M; ++m) { + if (m >= count) break; + acc[m][0] = simd_sum(acc[m][0]); + acc[m][1] = simd_sum(acc[m][1]); + } +} + +// act[pair][n] for every member pair of job tg.y; grid (n / 8, job bound), 4 simdgroups. +template +[[kernel]] void tf_hy4_expert_glu_groups(const device bfloat* latent [[buffer(0)]], const device int* ids [[buffer(1)]], + const device int* members [[buffer(2)]], const device int* count [[buffer(3)]], + const device uint32_t* GW [[buffer(4)]], const device bfloat* GS [[buffer(5)]], + const device bfloat* GB [[buffer(6)]], const device uint32_t* UW [[buffer(7)]], + const device bfloat* US [[buffer(8)]], const device bfloat* UB [[buffer(9)]], + device bfloat* act [[buffer(10)]], constant Hy4ExpertShape& a [[buffer(11)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const int job = int(tg.y); + if (job >= count[0]) return; + const int col0 = (int(tg.x) * 4 + int(sg)) * 2; + if (col0 >= int(a.n)) return; + const int K = int(a.k), N = int(a.n); + const ulong e = ulong(ids[job]); + const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); + const device int* mem = members + job * 16; + for (int c0 = 0; c0 < 16; c0 += M) { + int pair[M], xrow[M]; + int n = 0; + for (int m = 0; m < M; ++m) { + const int p = mem[c0 + m]; + pair[m] = p; + xrow[m] = p >= 0 ? p / int(a.picks) : 0; + n += p >= 0 ? 1 : 0; + } + if (n == 0) break; + float g[M][2], u[M][2]; + hy4_qmv_cols2_group(latent, xrow, n, K, GW + e * wstride, GS + e * sstride, GB + e * sstride, K, col0, lane, g); + hy4_qmv_cols2_group(latent, xrow, n, K, UW + e * wstride, US + e * sstride, UB + e * sstride, K, col0, lane, u); + if (lane == 0) + for (int m = 0; m < M; ++m) { + if (m >= n) break; + for (int j = 0; j < 2; ++j) act[ulong(pair[m]) * N + col0 + j] = hy4_expert_swiglu(g[m][j], u[m][j], a.limit); + } + if (n < M) break; + } +} + +// out[pair][n] (fp32) = down_e act[pair] for every member pair of job tg.y; grid (n / 8, job bound). +template +[[kernel]] void tf_hy4_expert_down_groups(const device bfloat* act [[buffer(0)]], const device int* ids [[buffer(1)]], + const device int* members [[buffer(2)]], const device int* count [[buffer(3)]], + const device uint32_t* DW [[buffer(4)]], const device bfloat* DS [[buffer(5)]], + const device bfloat* DB [[buffer(6)]], device float* out [[buffer(7)]], + constant Hy4ExpertShape& a [[buffer(8)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + const int job = int(tg.y); + if (job >= count[0]) return; + const int col0 = (int(tg.x) * 4 + int(sg)) * 2; + if (col0 >= int(a.n)) return; + const int K = int(a.k), N = int(a.n); + const ulong e = ulong(ids[job]); + const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); + const device int* mem = members + job * 16; + for (int c0 = 0; c0 < 16; c0 += M) { + int pair[M]; + int n = 0; + for (int m = 0; m < M; ++m) { + const int p = mem[c0 + m]; + pair[m] = p >= 0 ? p : 0; + n += p >= 0 ? 1 : 0; + } + if (n == 0) break; + float d[M][2]; + hy4_qmv_cols2_group(act, pair, n, K, DW + e * wstride, DS + e * sstride, DB + e * sstride, K, col0, lane, d); + if (lane == 0) + for (int m = 0; m < M; ++m) { + if (m >= n) break; + for (int j = 0; j < 2; ++j) out[ulong(pair[m]) * N + col0 + j] = d[m][j]; + } + if (n < M) break; + } +} + +template [[host_name("tf_hy4_expert_glu_groups_q4")]] [[kernel]] decltype(tf_hy4_expert_glu_groups<4, 4>) tf_hy4_expert_glu_groups<4, 4>; +template [[host_name("tf_hy4_expert_glu_groups_q8")]] [[kernel]] decltype(tf_hy4_expert_glu_groups<8, 4>) tf_hy4_expert_glu_groups<8, 4>; +template [[host_name("tf_hy4_expert_down_groups_q4")]] [[kernel]] decltype(tf_hy4_expert_down_groups<4, 4>) tf_hy4_expert_down_groups<4, 4>; +template [[host_name("tf_hy4_expert_down_groups_q8")]] [[kernel]] decltype(tf_hy4_expert_down_groups<8, 4>) tf_hy4_expert_down_groups<8, 4>; + +// ---- MLA absorb and expand-and-gate for 1-4 row passes over kv_b's affine codes: per head 448 rows (192 key, +// then 256 value), each 512 latent values in groups of 64; w = fma(scale, code, bias) in fp32 as read. ---- +struct Hy4MlaQArgs { uint rows, heads; }; + +// absorbed[row][head][c] (c < 512, stride 576) = sum_d query[row][head][d] * key[head][d][c], d < 192. +// Grid (2 halves of 256 columns, heads), 8 simdgroups splitting d (rows d = sg + 8 i, four loads in flight a step); +// a lane holds 8 adjacent columns; the 8 partials meet in two threadgroup steps in a fixed order. +template +[[kernel]] void tf_hy4_absorb_qmv(const device bfloat* query [[buffer(0)]], const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], + device bfloat* absorbed [[buffer(4)]], constant Hy4MlaQArgs& a [[buffer(5)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint t [[thread_index_in_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { + constexpr int R = 4, SG = 8, D = 192, U = 4, WPR = 512 * BITS / 32; + const int h = int(tg.y), heads = int(a.heads), rows = min(int(a.rows), R); + const int c0 = int(tg.x) * 256 + int(lane) * 8, g = c0 / 64; + threadgroup float qs[R][D]; + threadgroup float part[SG / 2][R][256]; + for (int i = int(t); i < rows * D; i += SG * 32) { + const int r = i / D, d = i % D; + qs[r][d] = float(query[(ulong(r) * heads + h) * 256 + d]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float acc[R][8]; + for (int r = 0; r < R; ++r) + for (int k = 0; k < 8; ++k) acc[r][k] = 0.0f; + const ulong base = ulong(h) * 448; + for (int d0 = int(sg); d0 < D; d0 += SG * U) { + uint2 words[U]; + float s[U], b[U]; + for (int u = 0; u < U; ++u) { + const ulong row = base + d0 + SG * u; + if (BITS == 4) words[u] = uint2(W[row * WPR + c0 / 8], 0u); + else words[u] = *(const device uint2*)(W + row * WPR + c0 / 4); + s[u] = float(S[row * 8 + g]); + b[u] = float(B[row * 8 + g]); + } + for (int u = 0; u < U; ++u) { + float w[8]; + if (BITS == 4) { + for (int k = 0; k < 8; ++k) w[k] = fma(s[u], float((words[u].x >> (4 * k)) & 0xfu), b[u]); + } else { + for (int k = 0; k < 4; ++k) { + w[k] = fma(s[u], float((words[u].x >> (8 * k)) & 0xffu), b[u]); + w[4 + k] = fma(s[u], float((words[u].y >> (8 * k)) & 0xffu), b[u]); + } + } + const int d = d0 + SG * u; + for (int r = 0; r < R; ++r) { + if (r >= rows) break; + const float q = qs[r][d]; + for (int k = 0; k < 8; ++k) acc[r][k] = fma(q, w[k], acc[r][k]); + } + } + } + // simdgroups 4-7 hand theirs to 0-3, which then hold the pair sums + if (sg >= SG / 2) + for (int r = 0; r < R; ++r) { + if (r >= rows) break; + for (int k = 0; k < 8; ++k) part[sg - SG / 2][r][lane * 8 + k] = acc[r][k]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg < SG / 2) + for (int r = 0; r < R; ++r) { + if (r >= rows) break; + for (int k = 0; k < 8; ++k) acc[r][k] += part[sg][r][lane * 8 + k]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg < SG / 2) + for (int r = 0; r < R; ++r) { + if (r >= rows) break; + for (int k = 0; k < 8; ++k) part[sg][r][lane * 8 + k] = acc[r][k]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int i = int(t); i < rows * 256; i += SG * 32) { + const int r = i / 256, c = i % 256; + const float v = ((part[0][r][c] + part[1][r][c]) + part[2][r][c]) + part[3][r][c]; + absorbed[(ulong(r) * heads + h) * 576 + tg.x * 256 + c] = bfloat(v); + } +} + +// values[row][head][e] = bf16(bf16(sum_c latent[row][head][c] * value[head][e][c]) * bf16(sigmoid(logit))), e < 256. +// Grid (256 / 8, heads), 4 simdgroups of two outputs; a lane holds 16 latent columns (one scale group's quarter). +template +[[kernel]] void tf_hy4_expand_gated_qmv(const device bfloat* latent [[buffer(0)]], const device uint32_t* W [[buffer(1)]], + const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], + device bfloat* values [[buffer(4)]], constant Hy4MlaQArgs& a [[buffer(5)]], + const device bfloat* logits [[buffer(6)]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint3 tg [[threadgroup_position_in_grid]]) { + constexpr int R = 4, WPR = 512 * BITS / 32; + const int h = int(tg.y), heads = int(a.heads), rows = min(int(a.rows), R); + const int e0 = (int(tg.x) * 4 + int(sg)) * 2; + const int c0 = int(lane) * 16, g = c0 / 64; + float x[R][16], xs[R]; + for (int r = 0; r < R; ++r) { + xs[r] = 0.0f; + if (r >= rows) continue; + const device uint4* xp = (const device uint4*)(latent + (ulong(r) * heads + h) * 512 + c0); + for (int v = 0; v < 2; ++v) { + const uint4 x4 = xp[v]; + const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; + for (int u = 0; u < 4; ++u) { + x[r][v * 8 + u * 2] = as_type(xw[u] << 16); + x[r][v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); + xs[r] += x[r][v * 8 + u * 2] + x[r][v * 8 + u * 2 + 1]; + } + } + } + for (int j = 0; j < 2; ++j) { + const int e = e0 + j; + const ulong row = ulong(h) * 448 + 192 + e; + const float s = float(S[row * 8 + g]), b = float(B[row * 8 + g]); + float q[16]; + if (BITS == 4) { + const uint2 ww = *(const device uint2*)(W + row * WPR + c0 / 8); + for (int k = 0; k < 8; ++k) { + q[k] = float((ww.x >> (4 * k)) & 0xfu); + q[8 + k] = float((ww.y >> (4 * k)) & 0xfu); + } + } else { + const uint4 ww = *(const device uint4*)(W + row * WPR + c0 / 4); + const uint words[4] = {ww.x, ww.y, ww.z, ww.w}; + for (int u = 0; u < 4; ++u) + for (int k = 0; k < 4; ++k) q[u * 4 + k] = float((words[u] >> (8 * k)) & 0xffu); + } + for (int r = 0; r < R; ++r) { + if (r >= rows) break; + float dot = 0.0f; + for (int i = 0; i < 16; ++i) dot = fma(x[r][i], q[i], dot); + const float v = simd_sum(fma(s, dot, b * xs[r])); + if (lane == 0) { + const ulong at = (ulong(r) * heads + h) * 256 + e; + const bfloat value = bfloat(v); + const bfloat gate = bfloat(1.0f / (1.0f + precise::exp(-float(logits[at])))); + values[at] = bfloat(float(value) * float(gate)); + } + } + } +} + +template [[host_name("tf_hy4_absorb_qmv_q4")]] [[kernel]] decltype(tf_hy4_absorb_qmv<4>) tf_hy4_absorb_qmv<4>; +template [[host_name("tf_hy4_absorb_qmv_q8")]] [[kernel]] decltype(tf_hy4_absorb_qmv<8>) tf_hy4_absorb_qmv<8>; +template [[host_name("tf_hy4_expand_gated_qmv_q4")]] [[kernel]] decltype(tf_hy4_expand_gated_qmv<4>) tf_hy4_expand_gated_qmv<4>; +template [[host_name("tf_hy4_expand_gated_qmv_q8")]] [[kernel]] decltype(tf_hy4_expand_gated_qmv<8>) tf_hy4_expand_gated_qmv<8>; diff --git a/zig/kernels/metal/hy4_flash/tensor_dispatch.metal b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal index 013a7f23df7..98bedb4dba1 100644 --- a/zig/kernels/metal/hy4_flash/tensor_dispatch.metal +++ b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal @@ -34,3 +34,55 @@ kernel void tf_hy4_active_experts( 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: job e is expert e (ids the identity), its +// pairs in pair order, as the router's per-window grouping orders them. Every row's picks are distinct experts, so +// a pair's rank in its expert is the earlier rows of the chunk that picked it: whole 64-row blocks by count, then +// the pair's own block by its rows' expert bitmaps. One threadgroup of 1024 threads; a.x pairs (topk a row, rows at +// most 512), a.y experts (at most 512), a.z topk. +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 75c87ddd977..ef8cd4cab78 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -5,10 +5,14 @@ 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"); diff --git a/zig/src/core/lane_projection.zig b/zig/src/core/lane_projection.zig index 14e6029d370..2330db0bf4f 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"); 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/families/hy4_flash/engram_rows.zig b/zig/src/families/hy4_flash/engram_rows.zig index 6bba4f9d84b..efc1d130919 100644 --- a/zig/src/families/hy4_flash/engram_rows.zig +++ b/zig/src/families/hy4_flash/engram_rows.zig @@ -7,6 +7,19 @@ 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, @@ -42,6 +55,11 @@ pub const Table = struct { }; } + /// 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; } @@ -61,6 +79,9 @@ pub const Table = struct { } } + // Ask for every row's pages at once (asynchronous read-ahead), so cold rows' faults overlap rather than queue + // one by one in the copies below. + 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); diff --git a/zig/src/families/hy4_flash/host_tests.zig b/zig/src/families/hy4_flash/host_tests.zig index 21c7940c325..c5e1b265d1f 100644 --- a/zig/src/families/hy4_flash/host_tests.zig +++ b/zig/src/families/hy4_flash/host_tests.zig @@ -14,8 +14,8 @@ test { _ = @import("forward.zig"); } -fn tensor(dtype: core.checkpoint.DType, rows: usize, width: usize, bytes: []const u8) core.checkpoint.Tensor { - var result: core.checkpoint.Tensor = .{ .dtype = dtype, .rank = 2, .shape = @splat(0), .bytes = bytes }; +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; } diff --git a/zig/src/families/hy4_flash/ihc.zig b/zig/src/families/hy4_flash/ihc.zig index 1511cf70f7e..70e66a8dc2b 100644 --- a/zig/src/families/hy4_flash/ihc.zig +++ b/zig/src/families/hy4_flash/ihc.zig @@ -23,9 +23,9 @@ pub const Shape = extern struct { }; pub const Weights = struct { - project: core.checkpoint.Tensor, - bias: core.checkpoint.Tensor, - scale: core.checkpoint.Tensor, + 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 { diff --git a/zig/src/families/hy4_flash/ihc_metal.zig b/zig/src/families/hy4_flash/ihc_metal.zig index 4dc558d1f93..dd1fedf4e3d 100644 --- a/zig/src/families/hy4_flash/ihc_metal.zig +++ b/zig/src/families/hy4_flash/ihc_metal.zig @@ -4,22 +4,52 @@ const sources = @import("kernel_sources"); const ihc = @import("ihc.zig"); pub const Ref = struct { buffer: mtl.Buffer, offset: usize = 0 }; -pub const Collapse = struct { hidden: Ref, projection: Ref, bias: Ref, scale: Ref, output: Ref, post: ?Ref = null }; +/// `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 { - pre: mtl.Pipeline, + /// 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 pre = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_collapse", false); - errdefer pre.deinit(); - return .{ .pre = pre, .mix = try mtl.Pipeline.init(device, library, "tf_hy4_ihc_add", false) }; + 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.pre.deinit(); + 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; } @@ -27,13 +57,94 @@ pub const Kernels = struct { 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; - e.setPipeline(self.pre); + 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; with `next` (the next + /// collapse's projection, `gates` of them) also that collapse's partials. + 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; diff --git a/zig/src/families/hy4_flash/loader.zig b/zig/src/families/hy4_flash/loader.zig index 74bc658e938..4e1ee7964b1 100644 --- a/zig/src/families/hy4_flash/loader.zig +++ b/zig/src/families/hy4_flash/loader.zig @@ -75,8 +75,8 @@ 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.DType = switch (format) { - inline else => |tag| @field(core.checkpoint.DType, @tagName(tag)), + 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 index 25fb533a89d..1bb82c47cb3 100644 --- a/zig/src/families/hy4_flash/metal_dense.zig +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -14,6 +14,7 @@ const weights = @import("model_weights.zig"); const rope = @import("rope.zig"); const gpu_qkv = @import("metal_tensor_qkv.zig"); const lane = @import("lane_projection"); +const index = @import("metal_index.zig"); pub const Ref = mla_gpu.Ref; @@ -54,11 +55,130 @@ pub const Buffers = struct { return view; } + /// A dense projection's weights: packed for the tensor units' lane projection when `tensors`, else the row kernels'. + 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) and std.c.getenv("TF_HY4_DENSE_ROWS") == null) { + const packed_ = try gpu_qkv.Packed.upload(self, &.{w}, gpu_qkv.denseLayout(w.bits, n, k)); + // decode-sized passes read the checkpoint layout through the decode kernels + const plain = if (decodeRows() > 0) try self.matrix(w) else null; + return .{ .tensor = .{ .w = packed_.w, .sb = packed_.sb, .n = n, .k = k, .plain = plain } }; + } + 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. +/// Passes of at most this many rows (one-row decode, the drafter's columns) take the decode GEMV: fp32 sums, each +/// weight read once, in a different order from the tensor units' (TF_HY4_DECODE_ROWS, default 2, where the GEMV is +/// the faster; 0 keeps the tensor units everywhere). Quality is the same either way (fp32 sums, NLL-checked). +/// A probe's override of decodeRows (kernel checks). +pub var decode_rows_override: ?u32 = null; + +fn envRows(name: [*:0]const u8, default: u32) u32 { + const v = std.c.getenv(name) orelse return default; + return std.fmt.parseInt(u32, std.mem.span(v), 10) catch default; +} + +/// Routed-expert passes of at most this many rows (6: the lane verify widths) run every (row, pick) pair as GEMVs +/// (TF_HY4_EXPERT_PAIRS); against the tensor gathers 4 rows 24.6 -> 23.1 ms, 5 rows 26.6 -> 24.4, 6 rows 27.8 -> 26.4. +pub fn expertPairRows() u32 { + return envRows("TF_HY4_EXPERT_PAIRS", @max(decodeRows(), 6)); +} + +/// Attention passes of at most this many rows (4 at most) read kv_b's affine codes (TF_HY4_MLA_Q; 0: the BF16 copies). +/// One row by default: 15.85 -> 15.29 ms a token; from two rows the fp32 dequant is compute-bound, slower than BF16 +/// on tensor units (4 rows: 23.0 -> 24.2 ms). +pub fn mlaRows() u32 { + return @min(envRows("TF_HY4_MLA_Q", 1), 4); +} + +/// Larger passes up to this many rows (at most one router window, 16) run the grouped GEMVs (TF_HY4_EXPERT_GROUPS). +pub fn expertGroupRows() u32 { + return @min(envRows("TF_HY4_EXPERT_GROUPS", 0), 16); +} + +pub fn decodeRows() u32 { + if (decode_rows_override) |v| return v; + const v = std.c.getenv("TF_HY4_DECODE_ROWS") orelse return 2; + return std.fmt.parseInt(u32, std.mem.span(v), 10) catch 2; +} + +pub const Linear = union(enum) { + portable: affine.Weights, + tensor: struct { w: lane.Ref, sb: lane.Ref, n: u32, k: u32, plain: ?affine.Weights = null }, + + /// The checkpoint-layout weights the decode kernels read, when this projection has them. + fn plainWeights(self: Linear) ?affine.Weights { + return switch (self) { + .portable => |w| w, + .tensor => |t| t.plain, + }; + } + + pub fn outputs(self: Linear) u32 { + return switch (self) { + .portable => |w| @intCast(w.n), + .tensor => |t| t.n, + }; + } +}; + +/// The lane projections for every dense shape a model has, made once at load, and one group-sums buffer that the +/// projections reading the same input share (sums once, then every main kernel without a barrier between them). +pub const Linears = struct { + shapes: [16][2]u32 = undefined, + projections: [16]lane.Projection = undefined, + count: usize = 0, + sums: ?mtl.Buffer = null, + 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.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(); + if (self.sums) |b| b.deinit(); + self.count = 0; + } + + 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 const Merge = struct { project: mtl.Buffer, bias: mtl.Buffer, @@ -92,11 +212,16 @@ pub const Attention = struct { inputs: InputWeights, q_norm: mtl.Buffer, kv_norm: mtl.Buffer, - o: affine.Weights, + o: Linear, o_norm: mtl.Buffer, wk: mtl.Buffer, wv: mtl.Buffer, + /// kv_b's affine codes, scales and biases for the decode GEMVs (null under TF_HY4_MLA_BF16). + kv_q: ?[3]mtl.Buffer = null, + 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); @@ -133,11 +258,14 @@ pub const Attention = struct { .inputs = inputs, .q_norm = try b.upload(w.norm_query.bytes), .kv_norm = try b.upload(w.norm_kv.bytes), - .o = try b.matrix(w.attention.output), + .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, + .kv_q = if (w.absorbed.packed_rows) |p| if (std.c.getenv("TF_HY4_MLA_BF16") == null) .{ try b.upload(p.words), try b.upload(p.scales), try b.upload(p.biases) } else null else null, .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); } @@ -152,12 +280,16 @@ pub const Feed = struct { own: Buffers, merge: Merge, norm: mtl.Buffer, - gate: affine.Weights, - up: affine.Weights, - down: affine.Weights, + 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(); @@ -166,9 +298,9 @@ pub const Feed = struct { .own = undefined, .merge = try Merge.upload(&b, w.mlp_hc), .norm = try b.upload(w.mlp_norm.bytes), - .gate = try b.matrix(feed.projections.gate), - .up = try b.matrix(feed.projections.up), - .down = try b.matrix(feed.projections.down), + .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); @@ -192,6 +324,9 @@ pub const Scratch = struct { 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, @@ -205,6 +340,8 @@ pub const Scratch = struct { rotary: Ref, latent: Ref, attention: Ref, + key_scores: Ref, + flash_parts: ?Ref = null, branch: Ref, gate: Ref, up: Ref, @@ -227,6 +364,12 @@ pub const Scratch = struct { .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), @@ -240,6 +383,12 @@ pub const Scratch = struct { .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), @@ -261,6 +410,140 @@ pub const Scratch = struct { } }; +/// Lane windows of 2-8 rows through one weight read: tf_hy4_rows, the core row projection's per-row arithmetic +/// (bit-equal to its plain kernel at every row count) with RPS columns a simdgroup and 4 simdgroups a threadgroup. +pub const Rows = struct { + q4: mtl.Pipeline, + q8: mtl.Pipeline, + rps: u32, + /// Greedy tokens on the GPU (first index of the largest logit), so draft columns chain without the host. + argmax: mtl.Pipeline, + /// Decode-sized passes (1-8 rows) of 4- and 8-bit group-64 matrices, each weight read once. + qmv4: mtl.Pipeline, + qmv8: mtl.Pipeline, + /// Output columns a decode GEMV threadgroup covers. + qmv_cols: u32 = 8, + /// 1- to 4-row decode GEMVs with four columns a simdgroup ([bits 4, 8][rows 1-4]; the same bits as qmv2, + /// 14.83 -> 14.23 ms a token); TF_HY4_QMV=2 keeps qmv2, TF_HY4_QMV=8 takes eight columns a simdgroup. + qmv3: ?[2][4]mtl.Pipeline = null, + qmv3_cols: u32 = 16, + /// Routed experts for 1-2 row passes: gate/up into the clipped SwiGLU, then down (q4, q8). + expert_glu: [2]mtl.Pipeline, + expert_down: [2]mtl.Pipeline, + /// Routed experts for 3-16 row passes, grouped by the router window's jobs (each expert's codes unpacked once). + expert_glu_groups: [2]mtl.Pipeline, + expert_down_groups: [2]mtl.Pipeline, + /// The expert down GEMVs with the routed weighted sum folded in (q4, q8; TF_HY4_NO_DOWN_SUM keeps two launches). + expert_down_sum: [2]mtl.Pipeline, + /// MLA absorb and expand-and-gate for 1-4 row passes over kv_b's affine codes (q4, q8). + absorb_q: [2]mtl.Pipeline, + expand_q: [2]mtl.Pipeline, + /// The expert branches' add fused into the norm that reads them (bit-equal to add then norm). + add_norm: mtl.Pipeline, + + pub fn load(a: std.mem.Allocator, device: mtl.Device) !Rows { + const text = try std.mem.concat(a, u8, &.{ affine.source(device.tensorUnits()), @import("kernel_sources").hy4_flash_rows }); + defer a.free(text); + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + // TF_HY4_ROWS: the variant, r2 (default), r4, r2s, r1s or r1 (columns a simdgroup; s: shared unpack) + const variant: []const u8 = if (std.c.getenv("TF_HY4_ROWS")) |v| std.mem.span(v) else "r2"; + const rps: u32 = if (variant[1] == '1') 1 else if (variant[1] == '4') 4 else 2; + var name4: [32]u8 = undefined; + var name8: [32]u8 = undefined; + var q4 = try mtl.Pipeline.init(device, lib, try std.fmt.bufPrint(&name4, "tf_hy4_rows_{s}_q4", .{variant}), false); + errdefer q4.deinit(); + var q8 = try mtl.Pipeline.init(device, lib, try std.fmt.bufPrint(&name8, "tf_hy4_rows_{s}_q8", .{variant}), false); + errdefer q8.deinit(); + var argmax = try mtl.Pipeline.init(device, lib, "tf_hy4_argmax", false); + errdefer argmax.deinit(); + // TF_HY4_QMV=1 keeps the first decode GEMV (four columns a simdgroup, codes unpacked a row at a time) + const first = if (std.c.getenv("TF_HY4_QMV")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; + var qmv4 = try mtl.Pipeline.init(device, lib, if (first) "tf_hy4_qmv_q4" else "tf_hy4_qmv2_q4", false); + errdefer qmv4.deinit(); + var qmv8 = try mtl.Pipeline.init(device, lib, if (first) "tf_hy4_qmv_q8" else "tf_hy4_qmv2_q8", false); + errdefer qmv8.deinit(); + var qmv3: ?[2][4]mtl.Pipeline = null; + const qmv_mode: []const u8 = if (std.c.getenv("TF_HY4_QMV")) |v| std.mem.span(v) else "3"; + const wide8 = std.mem.eql(u8, qmv_mode, "8"); + if (std.mem.eql(u8, qmv_mode, "3") or wide8) { + var p3: [2][4]mtl.Pipeline = undefined; + const set4 = [_][4][:0]const u8{ .{ "tf_hy4_qmv3_r1_q4", "tf_hy4_qmv3_r2_q4", "tf_hy4_qmv3_r3_q4", "tf_hy4_qmv3_r4_q4" }, .{ "tf_hy4_qmv3_r1_q8", "tf_hy4_qmv3_r2_q8", "tf_hy4_qmv3_r3_q8", "tf_hy4_qmv3_r4_q8" } }; + const set8 = [_][4][:0]const u8{ .{ "tf_hy4_qmv3x8_r1_q4", "tf_hy4_qmv3x8_r2_q4", "tf_hy4_qmv3x8_r3_q4", "tf_hy4_qmv3x8_r4_q4" }, .{ "tf_hy4_qmv3x8_r1_q8", "tf_hy4_qmv3x8_r2_q8", "tf_hy4_qmv3x8_r3_q8", "tf_hy4_qmv3x8_r4_q8" } }; + for (if (wide8) set8 else set4, 0..) |names, bi| { + for (names, 0..) |name, ri| p3[bi][ri] = try mtl.Pipeline.init(device, lib, name, false); + } + qmv3 = p3; + } + errdefer if (qmv3) |p3| for (p3) |row| for (row) |pipe| pipe.deinit(); + var experts: [14]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (experts[0..made]) |pipe| pipe.deinit(); + for ([_][:0]const u8{ "tf_hy4_expert_glu_q4", "tf_hy4_expert_glu_q8", "tf_hy4_expert_down_q4", "tf_hy4_expert_down_q8", "tf_hy4_expert_glu_groups_q4", "tf_hy4_expert_glu_groups_q8", "tf_hy4_expert_down_groups_q4", "tf_hy4_expert_down_groups_q8", "tf_hy4_absorb_qmv_q4", "tf_hy4_absorb_qmv_q8", "tf_hy4_expand_gated_qmv_q4", "tf_hy4_expand_gated_qmv_q8", "tf_hy4_expert_down_sum_q4", "tf_hy4_expert_down_sum_q8" }, &experts) |name, *dst| { + dst.* = try mtl.Pipeline.init(device, lib, name, false); + made += 1; + } + return .{ .q4 = q4, .q8 = q8, .rps = rps, .argmax = argmax, .qmv4 = qmv4, .qmv8 = qmv8, .qmv_cols = if (first) 16 else 8, .qmv3 = qmv3, .qmv3_cols = if (wide8) 32 else 16, .expert_glu = .{ experts[0], experts[1] }, .expert_down = .{ experts[2], experts[3] }, .expert_glu_groups = .{ experts[4], experts[5] }, .expert_down_groups = .{ experts[6], experts[7] }, .absorb_q = .{ experts[8], experts[9] }, .expand_q = .{ experts[10], experts[11] }, .expert_down_sum = .{ experts[12], experts[13] }, .add_norm = try mtl.Pipeline.init(device, lib, "tf_hy4_add_rms", false) }; + } + + pub fn deinit(self: Rows) void { + self.q4.deinit(); + self.q8.deinit(); + self.argmax.deinit(); + self.qmv4.deinit(); + self.qmv8.deinit(); + if (self.qmv3) |p3| for (p3) |row| for (row) |pipe| pipe.deinit(); + for (self.expert_glu) |pipe| pipe.deinit(); + for (self.expert_down) |pipe| pipe.deinit(); + for (self.expert_glu_groups) |pipe| pipe.deinit(); + for (self.expert_down_groups) |pipe| pipe.deinit(); + for (self.absorb_q) |pipe| pipe.deinit(); + for (self.expand_q) |pipe| pipe.deinit(); + for (self.expert_down_sum) |pipe| pipe.deinit(); + self.add_norm.deinit(); + } + + /// y = norm(a + b) * gain over `rows` rows of `width`, as dense.Ops.add then dense.Ops.norm. + pub fn addNorm(self: Rows, e: mtl.ComputeEncoder, x: Ref, branch: Ref, gain: mtl.Buffer, y: Ref, rows: u32, width: u32, epsilon: f32) !void { + const p: dense.Norm = .{ .rows = rows, .heads = 1, .dim = width, .x_stride = width, .y_stride = width, .eps = epsilon }; + const threads = try dense.normThreads(p); + e.setPipeline(self.add_norm); + e.setBuffer(x.buffer, x.offset, 0); + e.setBuffer(branch.buffer, branch.offset, 1); + e.setBuffer(gain, 0, 2); + e.setValue(p, 3); + e.setBuffer(y.buffer, y.offset, 4); + e.dispatchGroups(mtl.Size.of(1, rows, 1), mtl.Size.of(threads, 1, 1)); + } + + /// 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)); + } + + fn sg(self: Rows) u32 { + return if (self.rps == 1) 8 else 4; + } + + 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, + }; + } +}; + +fn twoStep(keys: u32) bool { + if (std.c.getenv("TF_HY4_ATTEND")) |v| return std.mem.eql(u8, std.mem.span(v), "two"); + return keys >= 1024; +} + pub const CacheRows = struct { positions: Ref, write_slots: Ref, @@ -268,6 +551,12 @@ pub const CacheRows = struct { 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 { @@ -277,6 +566,8 @@ pub const Kernels = struct { 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); @@ -297,6 +588,8 @@ pub const Kernels = struct { } 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(); @@ -309,11 +602,41 @@ pub const Kernels = struct { 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() and std.c.getenv("TF_HY4_DENSE_ROWS") == null) out.linears = try Linears.load(a, device, t, bits); + if (std.c.getenv("TF_HY4_ROWS_OFF") == null) out.rows = try Rows.load(a, device); + if (device.tensorUnits() and std.c.getenv("TF_HY4_MLA_FMA") == null) 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 { - const call = try affine.call(&self.affine, w, rows, false); + if (self.rows) |r| if (r.qmv3) |p3| if (rows <= decodeRows() and rows <= 4 and w.group == 64 and w.sum == .f32 and w.n % r.qmv3_cols == 0 and w.k % 32 == 0 and (w.bits == 4 or w.bits == 8)) { + e.setPipeline(p3[@intFromBool(w.bits == 8)][rows - 1]); + 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([6]i32{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), 1, 1 }, 4); + e.setBuffer(y.buffer, y.offset, 5); + e.dispatchGroups(mtl.Size.of(w.n / r.qmv3_cols, 1, 1), mtl.Size.of(128, 1, 1)); + return; + }; + if (self.rows) |r| if (rows <= decodeRows() and rows <= 8 and w.group == 64 and w.sum == .f32 and w.n % r.qmv_cols == 0 and w.k % 32 == 0 and (w.bits == 4 or w.bits == 8)) { + e.setPipeline(if (w.bits == 4) r.qmv4 else r.qmv8); + 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([6]i32{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), 1, 1 }, 4); + e.setBuffer(y.buffer, y.offset, 5); + e.dispatchGroups(mtl.Size.of(w.n / r.qmv_cols, 1, 1), mtl.Size.of(128, 1, 1)); + return; + }; + 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); @@ -324,6 +647,51 @@ pub const Kernels = struct { 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, then each projection's + /// main kernel with those sums and no barrier between them (the sums are what each would have made itself). + pub fn linearsFrom(self: *const Kernels, e: mtl.ComputeEncoder, x: Ref, outs: []const Out, rows: u32) !void { + if (outs.len == 0) return; + if (rows <= decodeRows()) decode: { + for (outs) |o| if (o.w.plainWeights() == null) break :decode; + for (outs) |o| try self.project(e, o.w.plainWeights().?, x, o.y, rows); + 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; + 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 }; } @@ -343,6 +711,103 @@ pub const Kernels = struct { }); } + /// Where a sub-block sits between seams: `ready` when the previous tail already wrote this collapse's partials, + /// `next` the collapse after this sub-block (its tail writes that one's partials). + /// ready: the collapse's partials are written; headed: its gates, row and norm too (a fused seam before it). + /// next_gain: the next sub-block's input norm, which lets the tail run that collapse's head in its launch. + 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 (TF_HY4_SEAM_FUSE=0 keeps two launches). + pub fn fusedSeams(rows: u32) bool { + if (seamsOff() or rows > ihc_gpu.Kernels.seam_rows) return false; + const v = std.c.getenv("TF_HY4_SEAM_FUSE") orelse return true; + return !std.mem.eql(u8, std.mem.span(v), "0"); + } + + fn seamsOff() bool { + return std.c.getenv("TF_HY4_NO_SEAMS") != null; + } + + /// 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; + if (seamsOff()) return self.collapse(e, x, w, gain, s); + 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`, and the + /// next collapse's partials when there is one. + 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); + }; + if (seamsOff()) { + if (branch2) |b2| { + if (self.rows) |r| try r.addNorm(e, branch, b2, gain, s.normalized, shape.rows, shape.width, eps) else return error.Hy4SeamsNeedRows; + } else try self.norm(e, branch, gain, s.normalized, shape.rows, shape.width, eps); + e.barrier(); + return self.residual(e, x, s.normalized, s.post, out, shape); + } + 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; @@ -353,6 +818,7 @@ pub const Kernels = struct { .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); @@ -371,9 +837,13 @@ pub const Kernels = struct { /// 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.collapse(e, x, w.merge, w.norm, s); + 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; @@ -407,7 +877,23 @@ pub const Kernels = struct { }, } 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; + const quantized: ?mla_gpu.Quantized = if (self.rows) |r| if (w.kv_q) |q| if (rows <= mlaRows() and (w.bits == 4 or w.bits == 8)) .{ + .absorb = r.absorb_q[@intFromBool(w.bits == 8)], + .expand = r.expand_q[@intFromBool(w.bits == 8)], + .words = .{ .buffer = q[0] }, + .scales = .{ .buffer = q[1] }, + .biases = .{ .buffer = q[2] }, + } else null else null else null; try mla_gpu.forward(self.projections, self.attention, e, .{ + .quantized = quantized, .query = s.query, .key_weights = .{ .buffer = w.wk }, .value_weights = .{ .buffer = w.wv }, @@ -419,27 +905,33 @@ pub const Kernels = struct { .attention = .{ .query = s.absorbed, .cache = cache.cache, - .slots = cache.retained, - .counts = cache.counts, + .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 or std.c.getenv("TF_HY4_ATTEND_LISTS") != null) null else cache.ranges, + .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.project(e, w.o, s.values, s.branch, rows); - e.barrier(); - try self.norm(e, s.branch, w.o_norm, s.normalized, rows, w.hidden, w.epsilon); + try self.linear(e, w.o, s.values, s.branch, rows); e.barrier(); - try self.residual(e, x, s.normalized, s.post, out, shape); + 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 { - const inner: u32 = @intCast(w.gate.n); + 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.collapse(e, x, w.merge, w.norm, s); - try self.project(e, w.gate, s.normalized, s.gate, shape.rows); - try self.project(e, w.up, s.normalized, s.up, shape.rows); + 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, @@ -449,10 +941,8 @@ pub const Kernels = struct { .y_stride = inner, }); e.barrier(); - try self.project(e, w.down, s.inner, s.branch, shape.rows); - e.barrier(); - try self.norm(e, s.branch, w.output_norm, s.normalized, shape.rows, shape.width, shape.eps); + try self.linear(e, w.down, s.inner, s.branch, shape.rows); e.barrier(); - try self.residual(e, x, s.normalized, s.post, out, shape); + 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 index e2fa13518b3..ac4559adea6 100644 --- a/zig/src/families/hy4_flash/metal_draft.zig +++ b/zig/src/families/hy4_flash/metal_draft.zig @@ -3,6 +3,7 @@ const std = @import("std"); const mtl = @import("metal"); const source = @import("kernel_sources"); const dense_ops = @import("draft_ops"); +const affine = @import("row_projection"); const ck = @import("loader.zig"); const model = @import("metal_model.zig"); const common = @import("metal_dense.zig"); @@ -13,15 +14,83 @@ 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, groups of 64) so they run on the +/// target's row kernels, one weight read a block. The draft only proposes: the target verifies every token, so the +/// output is unchanged and only acceptance can move. Unset or 16 keeps BF16. +fn draftBits() ?u8 { + const v = std.c.getenv("TF_HY4_DRAFT_BITS") orelse return null; + const bits = std.fmt.parseInt(u8, std.mem.span(v), 10) catch return null; + return if (bits == 4 or bits == 8) bits else null; +} + +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: per group of 64 a bf16 scale and bias (the group's minimum), +/// codes round((w - bias) / scale), packed low bits first into u32 words. +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, + w: ?mtl.Buffer, + q: ?affine.Weights = null, n: u32, k: u32, - fn upload(b: *common.Buffers, t: @import("core").checkpoint.Tensor) !Linear { - return .{ .w = try b.upload(t.bytes), .n = @intCast(t.shape[0]), .k = @intCast(t.shape[1]) }; + 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 (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, ops: dense_ops.Ops, e: mtl.ComputeEncoder, x: Ref, y: Ref, rows: u32) !void { - try ops.linear(e, dr(x), .{ .buf = p.w }, dr(y), .{ + 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, @@ -178,11 +247,12 @@ pub const Draft = struct { e.dispatchThreads(mtl.Size.of(self.hidden, rows, 1), mtl.Size.of(128, 1, 1)); } - fn mlp(ops: dense_ops.Ops, e: mtl.ComputeEncoder, w: Feed, temp: *const common.Scratch, x: Ref, y: Ref, rows: u32) !void { + 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(ops, e, x, temp.gate, rows); - try w.up.run(ops, e, x, temp.up, rows); + 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, @@ -192,7 +262,7 @@ pub const Draft = struct { .y_stride = n, }); e.barrier(); - try w.down.run(ops, e, temp.inner, y, rows); + 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 { @@ -207,7 +277,7 @@ pub const Draft = struct { 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(ops, e, s.concat, s.delta, lanes); + 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); @@ -235,13 +305,13 @@ pub const Draft = struct { 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(ops, e, v.normalized, v.query_a, rows); - try w.kv.run(ops, e, v.normalized, v.kv, rows); - try w.gate.run(ops, e, v.normalized, v.value_logits, rows); + 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(ops, e, v.query_norm, v.query, rows); + 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, @@ -260,10 +330,11 @@ pub const Draft = struct { .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(ops, e, v.values, v.branch, rows); + 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(); @@ -271,7 +342,7 @@ pub const Draft = struct { e.barrier(); try self.norm(ops, e, s.after_attention, w.mlp_norm, v.normalized, rows, h, h, h); e.barrier(); - try mlp(ops, e, w.mlp, v, v.normalized, v.branch, rows); + 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); } @@ -288,7 +359,7 @@ pub const Draft = struct { 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(ops, e, self.correction, &s.common, s.concat, s.delta, rows); + 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(); diff --git a/zig/src/families/hy4_flash/metal_engram.zig b/zig/src/families/hy4_flash/metal_engram.zig index ed04541246d..720ae4d9bed 100644 --- a/zig/src/families/hy4_flash/metal_engram.zig +++ b/zig/src/families/hy4_flash/metal_engram.zig @@ -13,22 +13,38 @@ const ihc = @import("ihc.zig"); const Ref = common.Ref; const width = 96; +/// Where the n-gram tables live (TF_HY4_ENGRAM): nvme reads the checkpoint's mapping (pages on demand, read +/// ahead a step at a time); ram copies the tables into resident memory for the host's gather; gpu keeps them in GPU +/// memory and gathers there, the host only hashing the windows. All three stage the same bits. +pub const Placement = enum { nvme, ram, gpu }; + +pub fn placement() Placement { + const v = std.mem.span(std.c.getenv("TF_HY4_ENGRAM") orelse return .nvme); + return std.meta.stringToEnum(Placement, v) orelse .nvme; +} + 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]affine.Weights, + key: [ihc.streams]common.Linear, key_bias: mtl.Buffer, key_gain: mtl.Buffer, query_gain: mtl.Buffer, delta_gain: mtl.Buffer, - value: affine.Weights, + 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(); @@ -41,15 +57,29 @@ pub const Layer = struct { .key_gain = undefined, .query_gain = undefined, .delta_gain = undefined, - .value = try b.matrix(w.value), + .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, }; - for (&out.key, w.key) |*dst, src| dst.* = try b.matrix(src.key); + switch (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.Tensor = undefined; + 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); } @@ -63,7 +93,7 @@ pub const Layer = struct { } }; -fn concatenate(b: *common.Buffers, weights_: []const core.checkpoint.Tensor) !mtl.Buffer { +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); @@ -79,6 +109,8 @@ pub const Scratch = struct { 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; @@ -92,6 +124,7 @@ pub const Scratch = struct { .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; @@ -106,6 +139,12 @@ pub const Scratch = struct { 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); } @@ -114,22 +153,38 @@ pub const Scratch = struct { 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(); - return .{ .lookup = lookup, .apply = try mtl.Pipeline.init(d, library, "tf_hy4_engram_apply", false) }; + 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); @@ -137,11 +192,12 @@ pub const Kernels = struct { 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(); - try ops.project(e, w.value, s.normalized, s.value, rows); + var outs: [1 + ihc.streams]common.Kernels.Out = undefined; + outs[0] = .{ .w = w.value, .y = s.value }; for (w.key, 0..) |projection, i| { - const dst: Ref = .{ .buffer = s.keys.buffer, .offset = i * rows * w.hidden * @sizeOf(u16) }; - try ops.project(e, projection, s.normalized, dst, rows); + 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{ 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..087a50203b9 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_index.zig @@ -0,0 +1,237 @@ +//! Hy4-flash's compressed sparse indexer on Metal, after the reference's CompressedIndexer: every pass caches its +//! rows' normalized token keys and re-pools the four-slot groups those rows touch (a group is read only once it +//! closed, so a pass that wrote part of one leaves nothing stale), and from 2,048 keys on each row attends its 511 +//! best-scoring closed groups plus its own group's causal part. Slots are positions here. +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), `q_resid` +/// the normalized q_a rows. Leaves the key lists in `c.tokens` and `c.counts` when the scratch selects. Ends +/// without a trailing barrier. +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_model.zig b/zig/src/families/hy4_flash/metal_model.zig index 8e4c11cff91..f63699c709d 100644 --- a/zig/src/families/hy4_flash/metal_model.zig +++ b/zig/src/families/hy4_flash/metal_model.zig @@ -10,6 +10,7 @@ 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; @@ -24,12 +25,12 @@ const Block = struct { 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.upload(a, device, v, config.hidden_size, config.engram_fp8_embedding) else null; + 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.upload(a, device, &w) }, + .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, @@ -48,12 +49,12 @@ const Block = struct { const Head = struct { owned: dense.Buffers, embedding: aff.Weights, - vocab: 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) !Head { + 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()); @@ -66,7 +67,7 @@ const Head = struct { var out: Head = .{ .owned = undefined, .embedding = try b.matrix(w.embedding), - .vocab = try b.matrix(w.lm_head), + .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), @@ -101,6 +102,8 @@ pub const Model = struct { 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); @@ -112,7 +115,9 @@ pub const Model = struct { errdefer route.deinit(); var mem = try memory.Kernels.load(device); errdefer mem.deinit(); - var head = try Head.upload(a, device, try weights.Head.read(&host, 1)); + 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); @@ -131,6 +136,7 @@ pub const Model = struct { .common = common, .routed = route, .memory = mem, + .index = ix, }; } @@ -139,6 +145,7 @@ pub const Model = struct { self.allocator.free(self.blocks); self.head.deinit(); self.memory.deinit(); + self.index.deinit(); self.routed.deinit(); self.common.deinit(); self.host.close(); @@ -152,26 +159,57 @@ pub const Model = struct { self.embedRows(e, frame.ids, x, frame.rows * ihc.streams); e.barrier(); var mem_ix: usize = 0; - for (self.blocks, cache) |*block, lane| { + // 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); - try self.common.attend(e, &block.attention, &frame.common, lane.rows, x, y); + 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.feed(e, w, &frame.common, x, y), - .routed => |*w| try self.routed.forward(&self.common, e, w, &frame.common, &frame.routed, x, y), + .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.collapse(e, x, self.head.merge, self.head.norm, &frame.common); - try self.readout(e, frame.common.normalized, frame.logits, frame.rows); + _ = 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; } @@ -180,26 +218,31 @@ pub const Model = struct { } pub fn readout(self: *const Model, e: mtl.ComputeEncoder, x: Ref, out: Ref, rows: u32) !void { - try self.common.project(e, self.head.vocab, x, out, rows); + try self.common.linear(e, self.head.vocab, x, out, rows); } }; -pub const LayerCache = struct { rows: dense.CacheRows, key_stride: u32 }; +/// 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.max_rows) return error.BadHy4MetalFrame; + 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| { @@ -219,6 +262,8 @@ pub const Frame = struct { 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 = .{ @@ -230,6 +275,7 @@ pub const Frame = struct { .common = common, .routed = route, .memory = memories, + .index = ix, }; out.own = b; return out; @@ -238,6 +284,7 @@ pub const Frame = struct { 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(); diff --git a/zig/src/families/hy4_flash/metal_routed.zig b/zig/src/families/hy4_flash/metal_routed.zig index 095e068c0b6..c839d4cac00 100644 --- a/zig/src/families/hy4_flash/metal_routed.zig +++ b/zig/src/families/hy4_flash/metal_routed.zig @@ -14,7 +14,9 @@ const lane = @import("lane_projection"); 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 }, @@ -28,12 +30,12 @@ pub const Layer = struct { output_norm: mtl.Buffer, router: RouteRef, correction: RouteRef, - down: affine.Weights, - up: affine.Weights, + down: dense.Linear, + up: dense.Linear, expert_weights: ExpertWeights, - shared_gate: affine.Weights, - shared_up: affine.Weights, - shared_down: affine.Weights, + shared_gate: dense.Linear, + shared_up: dense.Linear, + shared_down: dense.Linear, precision: experts.Precision, size: experts.Shape, scale: f32, @@ -65,15 +67,15 @@ pub const Layer = struct { .output_norm = try b.upload(f.norm.bytes), .router = .{ .buf = packed_router }, .correction = .{ .buf = try b.upload(f.correction.bytes) }, - .down = try b.matrix(f.down), - .up = try b.matrix(f.up), + .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.matrix(f.shared.gate), - .shared_up = try b.matrix(f.shared.up), - .shared_down = try b.matrix(f.shared.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, @@ -123,13 +125,15 @@ pub const Scratch = struct { 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 > max_rows) return error.BadHy4RouteRows; + 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; @@ -164,6 +168,7 @@ pub const Scratch = struct { .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; @@ -179,6 +184,10 @@ 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, @@ -194,7 +203,9 @@ pub const Kernels = struct { 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 src = try route.source(a, shape); + 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(); @@ -206,6 +217,10 @@ pub const Kernels = struct { 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; @@ -216,6 +231,8 @@ pub const Kernels = struct { .shape = shape, .logits = logits, .select = select, + .select_rows = select_rows, + .select_rank = select_rank, .experts = expert, .tensors = tensors, .sum = sum, @@ -226,6 +243,8 @@ pub const Kernels = struct { 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(); @@ -233,16 +252,38 @@ pub const Kernels = struct { } 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 = @intCast(w.shared_gate.n); + 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.collapse(e, x, w.merge, w.input_norm, d); - try shared.project(e, w.down, d.normalized, s.latent, rows); - try shared.project(e, w.shared_gate, d.normalized, d.gate, rows); - try shared.project(e, w.shared_up, d.normalized, d.up, rows); + 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(); - route.select(e, self.select, s.logits, w.correction, w.scale, rows, .{ 0, w.size.experts }, s.select); + // the pair GEMVs need only the picks and weights: the per-row select (the same arithmetic) skips the core + // select's expert grouping (TF_HY4_CORE_SELECT keeps it) + const pairs = w.expert_weights == .tensor and rows <= dense.expertPairRows() and rows > dense.expertGroupRows() and + shared.rows != null and std.c.getenv("TF_HY4_EXPERT_GATHER") == null; + if (rows <= max_rows and !(pairs and std.c.getenv("TF_HY4_CORE_SELECT") == null)) { + 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 and std.c.getenv("TF_HY4_SELECT_LOOP") == null; + 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, @@ -254,6 +295,7 @@ pub const Kernels = struct { var shape = w.size; shape.rows = rows; shape.pairs = rows * s.picks; + var summed = false; switch (w.expert_weights) { .portable => |mat| { const ops = self.experts orelse return error.Hy4ExpertKernelsMissing; @@ -265,7 +307,7 @@ pub const Kernels = struct { .weights = mat.up, .output = .{ .buffer = s.pair_activations.buffer }, }, shape); - try shared.project(e, w.shared_down, d.inner, s.shared, rows); + 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 }, @@ -274,41 +316,100 @@ pub const Kernels = struct { .output = .{ .buffer = s.pair_outputs }, }, shape); }, - .tensor => |mat| { + .tensor => |mat| if (rows > dense.expertPairRows() and rows <= dense.expertGroupRows() and rows <= max_rows and shared.rows != null and std.c.getenv("TF_HY4_EXPERT_GATHER") == null) { + // 3-16 rows: the router window's expert jobs as GEMVs, each expert's codes unpacked once for its rows + const r = shared.rows.?; + const which: usize = @intFromBool(w.precision == .q8); + const bound = @min(shape.pairs, shape.experts); + const glu_shape = [5]u32{ shape.pairs, s.picks, shape.width, shape.inner, @bitCast(shape.swiglu_limit) }; + e.setPipeline(r.expert_glu_groups[which]); + e.setBuffer(s.latent.buffer, s.latent.offset, 0); + e.setBuffer(s.select.ids.buf, s.select.ids.off, 1); + e.setBuffer(s.select.members.buf, s.select.members.off, 2); + e.setBuffer(s.select.count.buf, s.select.count.off, 3); + for ([_]@import("lane_projection").Ref{ mat.gate.w, mat.gate.s, mat.gate.b, mat.up.w, mat.up.s, mat.up.b }, 4..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 10); + e.setValue(glu_shape, 11); + e.dispatchGroups(mtl.Size.of(shape.inner / 8, bound, 1), mtl.Size.of(128, 1, 1)); + try shared.linear(e, w.shared_down, d.inner, s.shared, rows); + e.barrier(); + const down_shape = [5]u32{ shape.pairs, s.picks, shape.inner, shape.width, @bitCast(shape.swiglu_limit) }; + e.setPipeline(r.expert_down_groups[which]); + e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 0); + e.setBuffer(s.select.ids.buf, s.select.ids.off, 1); + e.setBuffer(s.select.members.buf, s.select.members.off, 2); + e.setBuffer(s.select.count.buf, s.select.count.off, 3); + for ([_]@import("lane_projection").Ref{ mat.down.w, mat.down.s, mat.down.b }, 4..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setBuffer(s.pair_outputs, 0, 7); + e.setValue(down_shape, 8); + e.dispatchGroups(mtl.Size.of(shape.width / 8, bound, 1), mtl.Size.of(128, 1, 1)); + } else if (rows <= dense.expertPairRows() and shared.rows != null and std.c.getenv("TF_HY4_EXPERT_GATHER") == null) { + // 1-2 rows: every (row, pick) pair's expert as GEMVs (each weight read once), no grouping pass + const r = shared.rows.?; + const which: usize = @intFromBool(w.precision == .q8); + const glu_shape = [5]u32{ shape.pairs, s.picks, shape.width, shape.inner, @bitCast(shape.swiglu_limit) }; + e.setPipeline(r.expert_glu[which]); + e.setBuffer(s.latent.buffer, s.latent.offset, 0); + e.setBuffer(s.select.pick.buf, s.select.pick.off, 1); + for ([_]@import("lane_projection").Ref{ mat.gate.w, mat.gate.s, mat.gate.b, mat.up.w, mat.up.s, mat.up.b }, 2..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 8); + e.setValue(glu_shape, 9); + e.dispatchGroups(mtl.Size.of(shape.inner / 8, shape.pairs, 1), mtl.Size.of(128, 1, 1)); + try shared.linear(e, w.shared_down, d.inner, s.shared, rows); + e.barrier(); + const down_shape = [5]u32{ shape.pairs, s.picks, shape.inner, shape.width, @bitCast(shape.swiglu_limit) }; + if (std.c.getenv("TF_HY4_NO_DOWN_SUM") == null) { + // down and the routed weighted sum in one launch, straight into the weighted rows + e.setPipeline(r.expert_down_sum[which]); + e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 0); + e.setBuffer(s.select.pick.buf, s.select.pick.off, 1); + for ([_]@import("lane_projection").Ref{ mat.down.w, mat.down.s, mat.down.b }, 2..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setBuffer(s.weighted.buffer, s.weighted.offset, 5); + e.setValue(down_shape, 6); + e.setBuffer(s.select.wts.buf, s.select.wts.off, 7); + e.dispatchGroups(mtl.Size.of(shape.width / 8, rows, 1), mtl.Size.of(128, 1, 1)); + summed = true; + } else { + e.setPipeline(r.expert_down[which]); + e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 0); + e.setBuffer(s.select.pick.buf, s.select.pick.off, 1); + for ([_]@import("lane_projection").Ref{ mat.down.w, mat.down.s, mat.down.b }, 2..) |ref, i| e.setBuffer(ref.buf, ref.off, i); + e.setBuffer(s.pair_outputs, 0, 5); + e.setValue(down_shape, 6); + e.dispatchGroups(mtl.Size.of(shape.width / 8, shape.pairs, 1), mtl.Size.of(128, 1, 1)); + } + } else { 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 jobs = 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.project(e, w.shared_down, d.inner, s.shared, rows); + 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.apply(e, mat, tensor_scratch, jobs, latent, .{ .buf = s.pair_activations.buffer, .off = s.pair_activations.offset }, .{ .buf = s.pair_outputs }, shape.pairs, s.picks, shape.swiglu_limit); + 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.project(e, w.up, s.weighted, s.routed, rows); - e.barrier(); - e.setPipeline(self.add); - e.setBuffer(s.routed.buffer, 0, 0); - e.setBuffer(s.shared.buffer, 0, 1); - e.setValue(@as(i32, @intCast(rows * merge.width)), 2); - e.setBuffer(d.branch.buffer, 0, 3); - e.dispatchThreads(mtl.Size.of(rows * merge.width, 1, 1), mtl.Size.of(128, 1, 1)); - e.barrier(); - try shared.norm(e, d.branch, w.output_norm, d.normalized, rows, merge.width, merge.eps); + if (!summed) { + 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.residual(e, x, d.normalized, d.post, out, merge); + try shared.tailTo(e, s.routed, s.shared, w.output_norm, merge.eps, x, out, d, merge, seam); } }; diff --git a/zig/src/families/hy4_flash/metal_tensor_experts.zig b/zig/src/families/hy4_flash/metal_tensor_experts.zig index a36f01a379d..a9c0458fcd1 100644 --- a/zig/src/families/hy4_flash/metal_tensor_experts.zig +++ b/zig/src/families/hy4_flash/metal_tensor_experts.zig @@ -51,12 +51,12 @@ pub const Scratch = struct { pub fn init(owner: anytype, rows: usize, picks: usize, width: usize, inner: usize) !Scratch { const slots = rows * picks; - if (slots > 256) return error.BadHy4TensorRows; + 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(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)) }, @@ -70,6 +70,7 @@ 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 }); @@ -85,15 +86,19 @@ pub const Kernels = struct { } 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 = try mtl.Pipeline.init(d, lib_compact, "tf_hy4_active_experts", false), + .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. @@ -112,10 +117,27 @@ pub const Kernels = struct { } 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 { - tensor.gatherGluMapped(e, self.pipes, x, s.latent_sums, w.gate, w.up, jobs.offsets, jobs.order, act, jobs.ids, pairs, pairs, picks, limit); + 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, pairs); + 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): job e = expert e, pairs in pair order, and the + /// latent's row sums. `ids` and `offsets` hold `experts` entries, `order` every pair. + 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 index cbe7b009525..58bee4f9e1e 100644 --- a/zig/src/families/hy4_flash/metal_tensor_qkv.zig +++ b/zig/src/families/hy4_flash/metal_tensor_qkv.zig @@ -43,6 +43,9 @@ pub const Packed = struct { } }; +/// 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, @@ -51,9 +54,18 @@ fn layout(bits: u8, n: usize, k: usize, sk: usize) lane.Layout { .format = .{ .bits = bits, .group = 64 }, .reg = bits == 4, .precompute_sums = bits == 4, + // a whole prompt chunk in one encode on the reg path (independent 16-row blocks, so the same bits) + .rows = prompt_rows, + .row_blocks = bits != 4, }; } +/// Any other dense projection [n, k] on tensor units: the QKV layout, with split-K by depth (2 under 2048, 4 to 4096, +/// else 8). Every row's bits are the same however many rows share the encode (independent 16-row blocks). +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); } diff --git a/zig/src/families/hy4_flash/mla_metal.zig b/zig/src/families/hy4_flash/mla_metal.zig index 1b7fe2aa8da..814efbc8696 100644 --- a/zig/src/families/hy4_flash/mla_metal.zig +++ b/zig/src/families/hy4_flash/mla_metal.zig @@ -9,6 +9,89 @@ 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("lane_projection").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. + /// Decode passes (one row block) split the keys over up to 8 threadgroups a head (a run of 4+ tiles each) and + /// join them in a second launch (TF_HY4_FLASH_SPLIT=N fixes N, 1 turns it off). + /// A split a 32-key tile, up to max_splits (two tiles already run faster split and joined than in one + /// threadgroup); with the live key count unknown, a split every 128 keys of the stride. + fn splits(shape: attention.Shape, has_parts: bool, live_keys: u32) u32 { + if (!has_parts or shape.rows > 16) return 1; + if (std.c.getenv("TF_HY4_FLASH_SPLIT")) |v| return std.math.clamp(std.fmt.parseInt(u32, std.mem.span(v), 10) catch 1, 1, max_splits); + if (live_keys > 0) return std.math.clamp((live_keys + 31) / 32, 1, max_splits); + return std.math.clamp(shape.key_stride / 128, 1, max_splits); + } + + 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: the flash +/// kernel's inputs when every row attends a contiguous run of keys (prompt chunks, sliding windows, short contexts). +pub const KeyRanges = struct { ranges: Ref, tiles: Ref }; + pub const Projections = struct { absorb_pipeline: mtl.Pipeline, expand_pipeline: mtl.Pipeline, @@ -16,6 +99,10 @@ pub const Projections = struct { 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()); @@ -30,7 +117,10 @@ pub const Projections = struct { 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, @@ -47,6 +137,8 @@ pub const Projections = struct { self.rotate_pipeline.deinit(); self.cache_pipeline.deinit(); self.gate_pipeline.deinit(); + self.expand_gated.deinit(); + if (self.nax) |n| n.deinit(); self.* = undefined; } @@ -111,6 +203,9 @@ pub const Projections = struct { 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, @@ -120,6 +215,14 @@ pub const Attention = struct { 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, }; pub fn load(device: mtl.Device) !Attention { @@ -127,12 +230,18 @@ pub const Attention = struct { defer library.deinit(); var chunks = try mtl.Pipeline.init(device, library, "tf_hy4_attend_chunks", false); errdefer chunks.deinit(); - return .{ .chunks = chunks, .merge = try mtl.Pipeline.init(device, library, "tf_hy4_attend_merge", false) }; + 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; } @@ -141,12 +250,28 @@ pub const Attention = struct { try shape.check(); const length = b.scratch.buffer.length(); if (b.scratch.offset > length or shape.scratchBytes() > length - b.scratch.offset) return error.ShortHy4AttentionScratch; - 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)); + 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 }; @@ -164,7 +289,24 @@ pub const KvInput = struct { epsilon: f32, }; +/// Decode passes (at most 4 rows): absorb and expand-and-gate as GEMVs over the checkpoint's affine kv_b codes +/// (fp32 dequant on the fly, a quarter of the BF16 copies' bytes at 4 bits). +pub const Quantized = struct { + absorb: mtl.Pipeline, + expand: mtl.Pipeline, + words: Ref, + scales: Ref, + biases: Ref, + + fn bind(q: Quantized, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, input: Ref, output: Ref, rows: u32, heads: u32) void { + e.setPipeline(pipe); + for ([_]Ref{ input, q.words, q.scales, q.biases, output }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setValue([2]u32{ rows, heads }, 5); + } +}; + pub const MlaPass = struct { + quantized: ?Quantized = null, query: Ref, key_weights: Ref, value_weights: Ref, @@ -181,7 +323,14 @@ pub fn forward(project: Projections, attend: Attention, e: mtl.ComputeEncoder, b 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); - try project.absorb(e, b.query, b.key_weights, b.attention.query, shape.rows, shape.heads); + if (b.quantized) |q| { + if (shape.rows > 4) return error.BadHy4QuantizedMlaRows; + q.bind(e, q.absorb, b.query, b.attention.query, shape.rows, shape.heads); + e.dispatchGroups(mtl.Size.of(weights.latent / 256, shape.heads, 1), mtl.Size.of(256, 1, 1)); + } else 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 = .{ @@ -200,9 +349,21 @@ pub fn forward(project: Projections, attend: Attention, e: mtl.ComputeEncoder, b .epsilon = kv.epsilon, }); e.barrier(); - try attend.attend(e, b.attention, shape); - e.barrier(); - try project.expand(e, b.attention.output, b.value_weights, b.values, shape.rows, shape.heads); + 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(); - try project.gate(e, b.values, b.value_logits, shape.rows, shape.heads); + if (shape.heads > 64) return error.BadHy4GateShape; + if (b.quantized) |q| { + q.bind(e, q.expand, b.attention.output, b.values, shape.rows, shape.heads); + e.setBuffer(b.value_logits.buffer, b.value_logits.offset, 6); + e.dispatchGroups(mtl.Size.of(weights.value_width / 8, shape.heads, 1), mtl.Size.of(128, 1, 1)); + return; + } + 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 index 803dd9430b4..56e2d8821d0 100644 --- a/zig/src/families/hy4_flash/mla_weights.zig +++ b/zig/src/families/hy4_flash/mla_weights.zig @@ -12,13 +12,30 @@ 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: 192 key rows, then 256 value rows, each +/// 512 latent values in groups of 64), for decode GEMVs that read the codes instead of the BF16 copies. +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; } }; @@ -81,9 +98,19 @@ pub fn read(a: std.mem.Allocator, model: *loader.Loaded, kind: loader.Attention, 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 dequant = try core.quant.mlx.dequant(a, try core.quant.slice.takeRows(a, words, &.{span}), try core.quant.slice.takeRows(a, scales, &.{span}), try core.quant.slice.takeRows(a, biases, &.{span}), 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); - return split(a, .{ .fp32 = dequant }, range.count); + 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 index bd6dc88d7ff..d1e130bed81 100644 --- a/zig/src/families/hy4_flash/model_weights.zig +++ b/zig/src/families/hy4_flash/model_weights.zig @@ -10,7 +10,7 @@ const engram = @import("engram.zig"); const engram_rows = @import("engram_rows.zig"); const rope = @import("rope.zig"); -const Tensor = core.checkpoint.Tensor; +const Tensor = core.checkpoint_host.Tensor; const Affine = core.quant.mlx.Host; const Allocator = std.mem.Allocator; const Rank = core.quant.Rank; @@ -20,7 +20,7 @@ const Reader = struct { model: *checkpoint.Loaded, prefix: []const u8, - fn tensor(self: Reader, field: []const u8, format: core.checkpoint.DType, dims: []const usize) !Tensor { + 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); 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..287c98092fe --- /dev/null +++ b/zig/src/families/hy4_flash/serve_metal.zig @@ -0,0 +1,757 @@ +//! Hy4-flash behind the lane engine on Metal: one stream at a time with its own caches (every layer's latent KV a +//! slot a position, the sparse layers' indexer keys), 512-row prompt chunks, one-row steps and DFly2 verify windows +//! of up to six rows, each row drawn on the host with the stream's keyed sampler. A released stream's caches stay +//! for the next prompt that starts with the same tokens (an agent's next turn), which then prefills only the rest. +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 +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. +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 { + 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; + } + + /// 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. + 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: `depth` greedy drafts after `bonus` at slot c.len, held for the + /// next verify. The draft writes its blocks' KV into the shared target layers at slots the verify rewrites first. + fn runDraft(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; + } + + 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 logit(word: u16) f32 { + return @bitCast(@as(u32, word) << 16); +} + +fn argmax(l: []const u16) usize { + var best: usize = 0; + for (l, 0..) |w, i| if (logit(w) > logit(l[best])) { + best = i; + }; + return best; +} + +const row = @import("../step5/backend.zig").row; + +/// 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/speed_probe.zig b/zig/src/families/hy4_flash/speed_probe.zig new file mode 100644 index 00000000000..d4dfb50def4 --- /dev/null +++ b/zig/src/families/hy4_flash/speed_probe.zig @@ -0,0 +1,1151 @@ +//! tf-hy4-speed: greedy Hy4-flash decode on the native Metal graph, for speed A/B and per-stage GPU profiles. +//! Contexts stay under 2048 slots, so sparse layers attend every earlier key and no indexer pass is needed. +//! +//! tf-hy4-speed MODEL_DIR GEN [--profile STEPS] [--long TOKENS] [--chunk ROWS] +//! +//! Prints each prompt's generated IDs and their FNV-1a hash (the exactness check between builds), decode ms a token +//! (wall and GPU), and with --profile the GPU time of every barrier-delimited stage, summed per token by its pipelines. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const target = @import("metal_model.zig"); +const ihc = @import("ihc.zig"); +const engram = @import("engram.zig"); +const dfly = @import("metal_draft.zig"); + +/// Cache slots (TF_HY4_CAPACITY, a multiple of 512; past 2,048 sparse layers attend every key unless TF_HY4_INDEX). +var capacity: u32 = 2048; +const index = @import("metal_index.zig"); +const key_width = 576; // BF16 words in a latent KV slot: 512 latent + 64 rope +const window: u32 = 512; +const bos: u32 = 120000; +const max_rows = 512; // a prompt chunk's rows (one router window is 16) + +const prompts = [_][]const u8{ + "The capital of France is", + "Write a short story about a lighthouse keeper who finds a message in a bottle.", + "def merge_sort(values):\n \"\"\"Sort a list of numbers.\"\"\"\n", + "Explain why the sky is blue in three sentences.", +}; + +const long_text = + "The history of the printing press begins long before Gutenberg. Carved wooden blocks were inked and pressed " ++ + "onto paper in East Asia for centuries, and movable type made of clay and later metal appeared well before it " ++ + "reached Europe. What changed in the fifteenth century was the combination of an oil-based ink, a hand mould " ++ + "that cast uniform letters quickly, and a screw press adapted from wine making. Together they made books cheap " ++ + "enough that ideas could travel faster than the authorities who wanted to control them. "; + +const Name = struct { id: usize, name: []const u8 }; + +fn collect(comptime T: type, v: *const T, comptime path: []const u8, list: *std.ArrayList(Name), a: std.mem.Allocator) !void { + if (T == mtl.Pipeline) return list.append(a, .{ .id = @intFromPtr(v.id), .name = path }); + switch (@typeInfo(T)) { + .@"struct" => |s| inline for (s.field_names, s.field_types, s.field_attrs) |f, F, attrs| { + if (!attrs.@"comptime") try collect(F, &@field(v.*, f), path ++ "." ++ f, list, a); + }, + .optional => |o| if (v.*) |*x| try collect(o.child, x, path, list, a), + .array => |ar| for (v) |*x| try collect(ar.child, x, path ++ "[]", list, a), + .@"union" => |u| if (u.tag_type != null) switch (v.*) { + inline else => |*x, tag| try collect(@TypeOf(x.*), x, path ++ "." ++ @tagName(tag), list, a), + }, + else => {}, + } +} + +fn nameOf(names: []const Name, id: usize) []const u8 { + for (names) |n| if (n.id == id) return n.name; + return "?"; +} + +fn bf16(word: u16) f32 { + return @bitCast(@as(u32, word) << 16); +} + +fn argmax(row: []const u16) !u32 { + var best: u32 = 0; + var top: f32 = -std.math.inf(f32); + for (row, 0..) |w, i| { + const v = bf16(w); + if (std.math.isNan(v)) return error.NanLogit; + if (v > top) { + top = v; + best = @intCast(i); + } + } + return best; +} + +const Stage = struct { label: []const u8, ns: f64 = 0, count: usize = 0 }; +const Pass = struct { next: u32, gpu: f64 }; + +/// DFly2 drafting and greedy lane verification. The draft writes its block's KV into the target layers it shares, +/// at positions the verify pass rewrites before any read, so rejection needs no rollback. +const Lanes = struct { + draft: dfly.Draft, + frame: dfly.Frame, + ids: mtl.Buffer, + previous: mtl.Buffer, + tokens: mtl.Buffer, + positions: mtl.Buffer, + writes: mtl.Buffer, + keys: mtl.Buffer, + counts: mtl.Buffer, + caches: []target.LayerCache, + mask: u32, + rounds: usize = 0, + kept: usize = 0, + proposed: usize = 0, + draft_gpu: f64 = 0, + verify_gpu: f64 = 0, + profile_rounds: u32 = 0, + stage_wall: f64 = 0, + copy_rounds: usize = 0, + + fn init(a: std.mem.Allocator, run: *Run) !Lanes { + var draft = try dfly.Draft.open(a, run.device, &run.model.host); + errdefer draft.deinit(); + const frame = try dfly.Frame.init(a, run.device, run.model, &draft, 1, capacity); + const opts = mtl.ResourceOptions.shared; + const w = draft.width; + const out: Lanes = .{ + .draft = draft, + .frame = frame, + .ids = try run.device.buffer(w * 4, opts), + .previous = try run.device.buffer(4, opts), + .tokens = try run.device.buffer(16 * 4, opts), + .positions = try run.device.buffer(w * 3 * 4, opts), + .writes = try run.device.buffer(w * 4, opts), + .keys = try run.device.buffer(@as(usize, w) * capacity * 4, opts), + .counts = try run.device.buffer(w * 4, opts), + .caches = try a.alloc(target.LayerCache, draft.blocks.len), + .mask = run.model.host.config.value.dfly_mask_token_id, + }; + for (out.caches, draft.blocks) |*c, block| c.* = .{ .rows = .{ + .positions = .{ .buffer = out.positions }, + .write_slots = .{ .buffer = out.writes }, + .retained = .{ .buffer = out.keys }, + .counts = .{ .buffer = out.counts }, + .cache = .{ .buffer = run.caches[block.target_kv] }, + .capacity = capacity, + }, .key_stride = capacity }; + return out; + } + + fn submit(run: *Run, cb: mtl.CommandBuffer) !f64 { + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("draft command buffer failed: {s}\n", .{why}); + return error.Hy4ProbeCommandFailed; + } + _ = run; + return cb.gpuSeconds(); + } + + /// Encode and commit the DFly2 chain for `count` tokens after `bonus` at position `p`, from the target's final + /// hidden row `source`: the block pass, then per column the correction, readout and a GPU argmax whose token the + /// next column reads, so one command buffer and no host trips. Read the tokens after `land`. + fn launch(self: *Lanes, run: *Run, p: u32, bonus: u32, source: u32, count: u32) !struct { cb: mtl.CommandBuffer, segs: usize, c0: mtl.counters.ClockSample } { + const w = self.draft.width; + const ids = self.ids.slice(u32, w); + @memset(ids, self.mask); + ids[0] = bonus; + const pos3 = self.positions.slice(i32, w * 3); + const wr = self.writes.slice(i32, w); + const stride: u32 = ((p + w + window - 1) / window) * window; + const keys = self.keys.slice(u32, @as(usize, w) * capacity); + const counts = self.counts.slice(u32, w); + for (0..w) |i| { + const at = p + @as(u32, @intCast(i)); + pos3[i * 3 ..][0..3].* = @splat(@intCast(at)); + wr[i] = @intCast(at); + for (0..at + 1) |j| keys[i * stride + j] = @intCast(j); + counts[i] = at + 1; + } + for (self.caches) |*c| c.key_stride = stride; + const h = self.draft.hidden; + const hidden = run.frame.common.normalized; + const anchor: target.Ref = .{ .buffer = hidden.buffer, .offset = hidden.offset + @as(usize, source) * h * 2 }; + const rows = run.model.common.rows orelse return error.Hy4ProbeNeedsRowKernels; + const cb = run.queue.commandBuffer().retain(); + const profile = self.profile_rounds > 0; + var split = if (profile) try mtl.Splitter.timed(cb, run.pass.?, run.samples.?, run.segments) else mtl.Splitter.plain(cb, run.segments); + const c0 = if (profile) mtl.counters.sampleClocks(run.device) else mtl.counters.ClockSample{}; + const e = split.encoder(); + try self.draft.encode(run.model, e, &self.frame, .{ .buffer = self.ids }, anchor, 1, self.caches); + e.barrier(); + for (0..count) |c| { + const previous: target.Ref = if (c == 0) .{ .buffer = self.ids } else .{ .buffer = self.tokens, .offset = (c - 1) * 4 }; + const logits = try self.draft.next(run.model, e, &self.frame, previous, @intCast(c + 1)); + e.barrier(); + rows.pick(e, logits, .{ .buffer = self.tokens }, @intCast(c), 1, run.vocab); + e.barrier(); + } + const segs = split.finish(); + cb.commit(); + return .{ .cb = cb, .segs = segs, .c0 = c0 }; + } + + fn land(self: *Lanes, run: *Run, l: anytype, count: u32, out: []u32) !void { + l.cb.wait(); + defer l.cb.release(); + if (l.cb.failure()) |why| { + std.debug.print("draft command buffer failed: {s}\n", .{why}); + return error.Hy4ProbeCommandFailed; + } + self.draft_gpu += l.cb.gpuSeconds(); + if (self.profile_rounds > 0) try run.account(l.segs, l.c0, mtl.counters.sampleClocks(run.device)); + @memcpy(out[0..count], self.tokens.slice(u32, count)); + } +}; + +const Run = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + model: *target.Model, + frame: *target.Frame, + positions: mtl.Buffer, + writes: mtl.Buffer, + slide_keys: mtl.Buffer, + slide_counts: mtl.Buffer, + sparse_keys: mtl.Buffer, + sparse_counts: mtl.Buffer, + /// Each row's key range [lo, hi) for sliding and for sparse layers, and each 32-key tile's first slot (slots + /// are positions here), for the tensor units' flash kernel. + slide_ranges: mtl.Buffer, + sparse_ranges: mtl.Buffer, + tiles: mtl.Buffer, + caches: []mtl.Buffer, + lanes: []target.LayerCache, + sliding: []bool, + /// TF_HY4_INDEX: the compressed indexer's caches (sparse layers), so contexts past 2,048 recall groups. + indexed: bool = false, + picks: mtl.Buffer, + all_logits: bool = false, + pad: u32, + vocab: u32, + // profile + names: []const Name, + pass: ?mtl.counters.ComputePass = null, + samples: ?mtl.counters.SampleBuffer = null, + segments: []mtl.Segment, + stages: std.StringArrayHashMapUnmanaged(Stage) = .empty, + profiled: usize = 0, + + /// One forward over `tokens` at positions start.. with full history `history` (tokens before start). + fn step(self: *Run, history: []const u32, start: u32, tokens: []const u32, profile: bool) !Pass { + return self.stepRows(history, start, tokens, profile, null); + } + + /// Engram windows and the frame's ids for `tokens` at positions start.. (history holds the tokens before). + fn stage(self: *Run, history: []const u32, start: u32, tokens: []const u32) !void { + const n: u32 = @intCast(tokens.len); + var windows: [max_rows][engram.order]u32 = undefined; + var media: [max_rows]u32 = @splat(0); + for (tokens, 0..) |t, r| { + const pos = start + @as(u32, @intCast(r)); + windows[r][0] = t; + for (1..engram.order) |lag| { + windows[r][lag] = if (lag <= r) tokens[r - lag] else if (lag <= pos) history[pos - lag] else self.pad; + } + } + try self.frame.stage(self.model, tokens, windows[0..n], media[0..n]); + } + + /// Positions, write slots and every layer's key list for `n` rows at start.. + fn layout(self: *Run, start: u32, n: u32) void { + const pos3 = self.positions.slice(i32, max_rows * 3); + const wr = self.writes.slice(i32, max_rows); + const last_end = start + n; + const sparse_stride: u32 = ((last_end + window - 1) / window) * window; + const sk = self.slide_keys.slice(u32, max_rows * window); + const sc = self.slide_counts.slice(u32, max_rows); + const pk = self.sparse_keys.slice(u32, max_rows * capacity); + const pc = self.sparse_counts.slice(u32, max_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; + for (0..end) |j| pk[r * sparse_stride + j] = @intCast(j); + pc[r] = end; + self.slide_ranges.slice([2]u32, max_rows)[r] = .{ end - count, end }; + self.sparse_ranges.slice([2]u32, max_rows)[r] = .{ 0, end }; + } + const lists = self.indexed and last_end - 1 >= index.keys_a_row; + if (self.indexed) self.frame.index.stage(start, n) catch unreachable; + for (self.lanes, self.sliding) |*lane, slide| { + lane.key_stride = if (slide) window else if (lists) index.keys_a_row else sparse_stride; + lane.rows.live_keys = if (slide) @min(last_end, window) else last_end; + } + } + + /// The target pass over the staged rows with every row's greedy token into `picks`, encoded, not committed. + fn encodePicks(self: *Run, n: u32) !mtl.CommandBuffer { + const rows = self.model.common.rows orelse return error.Hy4ProbeNeedsRowKernels; + const cb = self.queue.commandBuffer().retain(); + var split = mtl.Splitter.plain(cb, self.segments); + const e = split.encoder(); + const logits = try self.model.encode(e, self.frame, self.lanes); + e.barrier(); + rows.pick(e, logits, .{ .buffer = self.picks }, 0, n, self.vocab); + _ = split.finish(); + return cb; + } + + /// `step`, with every row's greedy token in `each` when given. + fn stepRows(self: *Run, history: []const u32, start: u32, tokens: []const u32, profile: bool, each: ?[]u32) !Pass { + const n: u32 = @intCast(tokens.len); + try self.stage(history, start, tokens); + self.layout(start, n); + // prompt chunks (no per-row picks asked) read out only their last row + self.frame.last_logits = each == null and n > 1 and !self.all_logits; + defer self.frame.last_logits = false; + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = self.queue.commandBuffer(); + var split = if (profile) + try mtl.Splitter.timed(cb, self.pass.?, self.samples.?, self.segments) + else + mtl.Splitter.plain(cb, self.segments); + const c0 = if (profile) mtl.counters.sampleClocks(self.device) else mtl.counters.ClockSample{}; + const logits = try self.model.encode(split.encoder(), self.frame, self.lanes); + const segs = split.finish(); + cb.commit(); + cb.wait(); + if (cb.failure()) |why| { + std.debug.print("command buffer failed: {s}\n", .{why}); + return error.Hy4ProbeCommandFailed; + } + if (profile) try self.account(segs, c0, mtl.counters.sampleClocks(self.device)); + const out_rows: usize = if (self.frame.last_logits) 1 else n; + const all = logits.buffer.slice(u16, out_rows * self.vocab); + if (each) |out| for (0..n) |r| { + out[r] = try argmax(all[r * self.vocab ..][0..self.vocab]); + }; + return .{ .next = try argmax(all[(out_rows - 1) * self.vocab ..][0..self.vocab]), .gpu = cb.gpuSeconds() }; + } + + fn account(self: *Run, segs: usize, c0: mtl.counters.ClockSample, c1: mtl.counters.ClockSample) !void { + const resolved = try self.samples.?.resolveCompleted(2 * segs); + defer resolved.deinit(); + const v = resolved.values(); + const ratio = @as(f64, @floatFromInt(c1.cpu - c0.cpu)) / @as(f64, @floatFromInt(c1.gpu - c0.gpu)); + for (self.segments[0..segs], 0..) |seg, i| { + const t0 = v[2 * i].timestamp; + const t1 = v[2 * i + 1].timestamp; + if (t0 == mtl.counters.error_value or t1 == mtl.counters.error_value or t1 < t0) continue; + var label: std.ArrayList(u8) = .empty; + for (seg.pipelines[0..seg.named], 0..) |id, k| { + if (k != 0) try label.appendSlice(self.a, " + "); + try label.appendSlice(self.a, nameOf(self.names, id)); + } + if (seg.dispatches > seg.named) try label.print(self.a, " (+{d} dispatches)", .{seg.dispatches - seg.named}); + const key = try label.toOwnedSlice(self.a); + const got = try self.stages.getOrPut(self.a, key); + if (!got.found_existing) got.value_ptr.* = .{ .label = key } else self.a.free(key); + got.value_ptr.ns += @as(f64, @floatFromInt(t1 - t0)) * ratio; + got.value_ptr.count += 1; + } + self.profiled += 1; + } +}; + +/// Copy drafts: the tokens that followed the latest earlier match of the context's last 3 to 8 tokens (the longest +/// match wins), up to `out.len`. Returns how many it found; 0 when nothing earlier matches 3 tokens. +fn copyDraft(context: []const u32, out: []u32) usize { + const n = context.len; + if (n < 4 or out.len == 0) return 0; + var best_len: usize = 0; + var best_end: usize = 0; + var end: usize = n - 1; + while (end > 0) { + end -= 1; + var m: usize = 0; + while (m < 8 and m <= end and context[end - m] == context[n - 1 - m]) m += 1; + if (m > best_len and end + 1 < n) { + best_len = m; + best_end = end; + if (m == 8) break; + } + } + if (best_len < 3) return 0; + const take = @min(out.len, n - 1 - best_end); + @memcpy(out[0..take], context[best_end + 1 ..][0..take]); + return take; +} + +/// TF_HY4_FLASH=slide or sparse limits the flash kernel to one kind of layer (a diagnostic). +fn bf(word: u16) f64 { + return @floatCast(@as(f32, @bitCast(@as(u32, word) << 16))); +} + +/// TF_HY4_ACHECK: one 1-row pass at `at`, then the last layer's attention output against an fp64 reference from the +/// same absorbed query, cache rows and sink (softmax over its key range plus the sink, P V over the 512 latent columns). +fn attentionCheck(run: *Run, hist: []const u32, at: u32) !void { + run.all_logits = false; + _ = try run.step(hist, at, hist[at .. at + 1], false); + const layer = run.model.blocks.len - 1; + const block = &run.model.blocks[layer]; + const heads = block.attention.heads; + const s = &run.frame.common; + const q = s.absorbed.buffer.slice(u16, (s.absorbed.offset / 2) + heads * 576)[s.absorbed.offset / 2 ..]; + const out = s.latent.buffer.slice(u16, (s.latent.offset / 2) + heads * 512)[s.latent.offset / 2 ..]; + const cache = run.caches[layer].slice(u16, capacity * 576); + const sinks = block.attention.sinks.slice(f32, heads); + const range = (if (run.sliding[layer]) run.slide_ranges else run.sparse_ranges).slice([2]u32, max_rows)[0]; + const keys = range[1] - range[0]; + const sc = try run.a.alloc(f64, keys); + defer run.a.free(sc); + var err2: f64 = 0; + var ref2: f64 = 0; + var round2: f64 = 0; + var worst: f64 = 0; + for (0..heads) |h| { + var top: f64 = sinks[h]; + for (0..keys) |j| { + const k = cache[(range[0] + j) * 576 ..][0..576]; + var dot: f64 = 0; + for (0..576) |d| dot += bf(q[h * 576 + d]) * bf(k[d]); + sc[j] = dot * 0.0625; + top = @max(top, sc[j]); + } + var denom: f64 = @exp(@as(f64, sinks[h]) - top); + for (sc) |*v| { + v.* = @exp(v.* - top); + denom += v.*; + } + for (0..512) |c| { + var acc: f64 = 0; + for (0..keys) |j| acc += sc[j] * bf(cache[(range[0] + j) * 576 + c]); + const ref = acc / denom; + const got = bf(out[h * 512 + c]); + const rounded: f64 = @floatCast(@as(f32, @floatCast(ref))); + const r16 = bf(@truncate(@as(u32, @bitCast(@as(f32, @floatCast(rounded)))) >> 16)); + err2 += (got - ref) * (got - ref); + round2 += (r16 - ref) * (r16 - ref); + ref2 += ref * ref; + worst = @max(worst, @abs(got - ref)); + } + } + std.debug.print("ACHECK layer {d} ({s}, {d} heads, keys [{d}, {d})): relative rms error {e:.3} (bf16 truncation of the reference {e:.3}), max |error| {e:.3}\n", .{ layer, if (run.sliding[layer]) "sliding" else "sparse", heads, range[0], range[1], @sqrt(err2 / ref2), @sqrt(round2 / ref2), worst }); +} + +/// TF_HY4_ICHECK (with TF_HY4_INDEX): after a pass, the last sparse layer's indexer against fp64 from the GPU's own +/// inputs: the last row's token-key norm, sampled group keys pooled from the cached token keys (and RoPE'd), and +/// the last row's 511 recalled groups against an fp64 ranking of the GPU's query, group keys and head weights. +fn indexCheck(run: *Run) !void { + var layer: usize = run.model.blocks.len; + while (layer > 0) { + layer -= 1; + if (!run.sliding[layer]) break; + } + const iw = run.model.blocks[layer].attention.index orelse return; + const c = run.lanes[layer].index orelse return; + const sc = &run.frame.index; + const rows = sc.rows; + const pos = sc.first + rows - 1; + const eps: f64 = run.model.host.config.value.text_config.rms_norm_eps; + const tk = c.token_keys.buffer.slice(u16, @as(usize, capacity) * 128); + const gk = c.group_keys.buffer.slice(u16, @as(usize, capacity / 4) * 128); + // the token key norm of the last row + { + const x = sc.keys.buffer.slice(u16, @as(usize, rows) * 128)[(rows - 1) * 128 ..][0..128]; + const gain = iw.token_norm.slice(u16, 128); + var ss: f64 = 0; + for (x) |v| ss += @as(f64, bf(v)) * bf(v); + const inv = 1 / @sqrt(ss / 128 + eps); + var worst: f64 = 0; + var off: usize = 0; + for (0..128) |d| { + const want = bf(gain[d]) * bf(rne(bf(x[d]) * inv)); + const got = bf(tk[pos * 128 + d]); + worst = @max(worst, @abs(got - want)); + if (rne(want) != tk[pos * 128 + d]) off += 1; + } + std.debug.print("ICHECK token key at {d}: {d}/128 off the rounded fp64, worst {e:.3}\n", .{ pos, off, worst }); + } + // group keys: pooled in fp64 from the cached token keys, normalized, rotated at the group's first slot + const vw = iw.values.slice(f32, 128 * 128); + const gw = iw.gates.slice(f32, 128 * 128); + const bias = iw.bias.slice(f32, 4 * 128); + const nw = iw.norm.slice(f32, 128); + const p = run.model.blocks[layer].attention.rope; + const closed = pos / 4; + var worst_g: f64 = 0; + var off_g: usize = 0; + var top_g: f64 = 0; + const samples = [_]u32{ 0, 1, closed / 3, closed / 2, closed -| 2, closed -| 1 }; + for (samples) |g| { + var pooled: [128]f64 = undefined; + var v: [4][128]f64 = undefined; + var z: [4][128]f64 = undefined; + for (0..4) |slot| for (0..128) |o| { + var sv: f64 = 0; + var sg: f64 = 0; + for (0..128) |k| { + const xk: f64 = bf(tk[(@as(usize, g) * 4 + slot) * 128 + k]); + sv += @as(f64, vw[o * 128 + k]) * xk; + sg += @as(f64, gw[o * 128 + k]) * xk; + } + v[slot][o] = sv; + z[slot][o] = sg + bias[slot * 128 + o]; + }; + var ss: f64 = 0; + for (0..128) |o| { + var m: f64 = -std.math.inf(f64); + for (0..4) |slot| m = @max(m, z[slot][o]); + var den: f64 = 0; + for (0..4) |slot| den += @exp(z[slot][o] - m); + var acc: f64 = 0; + for (0..4) |slot| acc += v[slot][o] * @exp(z[slot][o] - m) / den; + pooled[o] = acc; + ss += acc * acc; + } + const inv = 1 / @sqrt(ss / 128 + eps); + var key: [128]f64 = undefined; + for (0..128) |o| key[o] = bf(rne(nw[o] * pooled[o] * inv)); + for (0..32) |i| { + const phase: f64 = @as(f64, @floatFromInt(g * 4)) * p.frequencies[i]; + const cs: f64 = bf(rne(@cos(phase))); + const sn: f64 = bf(rne(@sin(phase))); + const a0 = key[64 + 2 * i]; + const b0 = key[64 + 2 * i + 1]; + key[64 + 2 * i] = a0 * cs - b0 * sn; + key[64 + 2 * i + 1] = b0 * cs + a0 * sn; + } + for (0..128) |o| { + const got: f64 = bf(gk[@as(usize, g) * 128 + o]); + worst_g = @max(worst_g, @abs(got - key[o])); + top_g = @max(top_g, @abs(key[o])); + if (rne(key[o]) != gk[@as(usize, g) * 128 + o]) off_g += 1; + } + } + std.debug.print("ICHECK group keys ({d} groups): {d}/{d} off the rounded fp64, worst {e:.3} of max |k| {d:.3}\n", .{ samples.len, off_g, samples.len * 128, worst_g, top_g }); + if (closed < index.budget_groups) { + std.debug.print("ICHECK recall: row at {d} keeps every group\n", .{pos}); + return; + } + // the last row's ranking + const q = sc.query.buffer.slice(u16, @as(usize, rows) * 2048)[(rows - 1) * 2048 ..][0..2048]; + const hw = sc.head_weights.buffer.slice(u16, @as(usize, rows) * 16)[(rows - 1) * 16 ..][0..16]; + const scores = try run.a.alloc(f64, closed); + defer run.a.free(scores); + for (scores, 0..) |*sco, g| { + var acc: f64 = 0; + for (0..16) |h| { + var dot: f64 = 0; + for (0..128) |d| dot += @as(f64, bf(q[h * 128 + d])) * bf(gk[g * 128 + d]); + acc += @as(f64, bf(hw[h])) * @as(f64, @import("index_recall.zig").head_scale) * @max(dot, 0); + } + sco.* = acc; + } + const order = try run.a.alloc(u32, closed); + defer run.a.free(order); + for (order, 0..) |*o, i| o.* = @intCast(i); + std.mem.sort(u32, order, scores, struct { + fn more(sv: []f64, x: u32, y: u32) bool { + return sv[x] > sv[y]; + } + }.more); + const keep = index.budget_groups - 1; + const want = try run.a.alloc(bool, closed); + defer run.a.free(want); + @memset(want, false); + for (order[0..keep]) |g| want[g] = true; + const threshold = scores[order[keep - 1]]; + const list = c.tokens.buffer.slice(i32, @as(usize, rows) * index.keys_a_row)[(rows - 1) * index.keys_a_row ..][0..index.keys_a_row]; + const count = c.counts.buffer.slice(i32, rows)[rows - 1]; + var missing: usize = 0; + var worst_gap: f64 = 0; + for (0..keep) |i| { + const g: usize = @intCast(@divTrunc(list[i * 4], 4)); + if (g >= closed or !want[g]) { + missing += 1; + if (g < closed) worst_gap = @max(worst_gap, (threshold - scores[g]) / @max(@abs(threshold), 1e-30)); + } + } + var own_ok = true; + for (keep * 4..@as(usize, @intCast(count))) |i| own_ok = own_ok and list[i] == @as(i32, @intCast(closed * 4 + (i - keep * 4))); + std.debug.print("ICHECK recall at {d}: {d} slots, {d}/{d} groups outside the fp64 top {d} (worst relative gap {e:.2} at threshold {d:.4}), own group {s}\n", .{ pos, count, missing, keep, keep, worst_gap, threshold, if (own_ok) "ok" else "WRONG" }); +} + +fn rne(v: f64) u16 { + const f: f32 = @floatCast(v); + const b: u32 = @bitCast(f); + return @truncate((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +fn flashFor(slide: bool) bool { + const v = std.mem.span(std.c.getenv("TF_HY4_FLASH") orelse return true); + return if (std.mem.eql(u8, v, "slide")) slide else if (std.mem.eql(u8, v, "sparse")) !slide else true; +} + +fn fnv(ids: []const u32) u64 { + var h: u64 = 0xcbf29ce484222325; + for (ids) |id| for (std.mem.asBytes(&id)) |b| { + h ^= b; + h *%= 0x100000001b3; + }; + return h; +} + +pub fn main(init: std.process.Init) !void { + const a = std.heap.page_allocator; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 3) { + std.debug.print("usage: tf-hy4-speed MODEL_DIR GEN [--profile STEPS] [--long TOKENS] [--chunk ROWS]\n", .{}); + return error.Usage; + } + const dir = args[1]; + const gen = try std.fmt.parseInt(u32, args[2], 10); + if (std.c.getenv("TF_HY4_CAPACITY")) |v| capacity = std.fmt.parseInt(u32, std.mem.span(v), 10) catch 2048; + if (capacity < 2048 or capacity % 512 != 0) return error.BadCapacity; + var profile_steps: u32 = 0; + var long_tokens: u32 = 0; + var chunk: u32 = 16; + var rows_time = false; + var lane_rows: u32 = 0; + var warm_engram = false; + var text_path: ?[]const u8 = null; + var nll = false; + const nll_dump = std.c.getenv("TF_HY4_NLL_DUMP") != null; + var copies = false; + const adapt: ?[2]u32 = if (std.c.getenv("TF_HY4_ADAPT")) |v| blk: { + var it = std.mem.splitScalar(u8, std.mem.span(v), ','); + const lo = std.fmt.parseInt(u32, it.next() orelse "2", 10) catch 2; + const hi = std.fmt.parseInt(u32, it.next() orelse "6", 10) catch 6; + break :blk .{ @max(2, lo), @min(6, hi) }; + } else null; + const profile_prompt: usize = if (std.c.getenv("TF_HY4_PROFILE_PROMPT")) |v| (std.fmt.parseInt(usize, std.mem.span(v), 10) catch 0) else 0; + var i: usize = 3; + if (args.len > 3 and std.mem.eql(u8, args[3], "--rows-time")) { + rows_time = true; + i = 4; + } + while (i + 1 < args.len) : (i += 2) { + if (std.mem.eql(u8, args[i], "--profile")) profile_steps = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--long")) long_tokens = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--chunk")) chunk = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--lanes")) lane_rows = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--text")) { + text_path = args[i + 1]; + } else if (std.mem.eql(u8, args[i], "--nll")) { + nll = std.mem.eql(u8, args[i + 1], "1"); + } else if (std.mem.eql(u8, args[i], "--copies")) { + copies = std.mem.eql(u8, args[i + 1], "1"); + } else if (std.mem.eql(u8, args[i], "--warm-engram")) { + warm_engram = std.mem.eql(u8, args[i + 1], "1"); + } else return error.Usage; + } + if (chunk == 0 or chunk > max_rows) return error.BadChunk; + + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + std.debug.print("device {s}, tensor units {}\n", .{ device.name(), device.tensorUnits() }); + + const tok_path = try std.fs.path.join(a, &.{ dir, "tokenizer.json" }); + var tok = try core.tokenizer.loadTokenizer(io, a, tok_path); + defer tok.deinit(); + + const t_load = mtl.clock.seconds(); + var model = try target.Model.open(a, io, device, dir); + defer model.deinit(); + const t = model.host.config.value.text_config; + if (warm_engram) { + // Read every Engram table page once, so lookups find their rows in RAM (a resident-table server). + const tw = mtl.clock.seconds(); + var bytes: usize = 0; + var sink: u8 = 0; + for (model.blocks) |*b| if (b.memory) |*m| { + const tab = m.table.affine; + for ([_][]const u8{ tab.words.bytes, tab.scales.bytes, tab.biases.bytes }) |region| { + var at: usize = 0; + while (at < region.len) : (at += 16384) sink +%= @as(*const volatile u8, ®ion[at]).*; + bytes += region.len; + } + }; + std.debug.print("warmed {d:.1} GB of Engram tables in {d:.1}s ({d})\n", .{ @as(f64, @floatFromInt(bytes)) / 1e9, mtl.clock.seconds() - tw, sink }); + } + var frame = try target.Frame.init(a, device, &model, max_rows, capacity); + defer frame.deinit(); + std.debug.print("{d}-bit model loaded in {d:.3}s, device allocations {d:.3} GB\n", .{ model.host.bits, mtl.clock.seconds() - t_load, @as(f64, @floatFromInt(device.allocated())) / 1e9 }); + + const opts = mtl.ResourceOptions.shared; + var run: Run = .{ + .a = a, + .device = device, + .queue = queue, + .model = &model, + .frame = &frame, + .positions = try device.buffer(max_rows * 3 * 4, opts), + .writes = try device.buffer(max_rows * 4, opts), + .slide_keys = try device.buffer(max_rows * window * 4, opts), + .slide_counts = try device.buffer(max_rows * 4, opts), + .sparse_keys = try device.buffer(max_rows * capacity * 4, opts), + .sparse_counts = try device.buffer(max_rows * 4, opts), + .slide_ranges = try device.buffer(max_rows * 8, opts), + .sparse_ranges = try device.buffer(max_rows * 8, opts), + .tiles = try device.buffer(capacity / 32 * 4, opts), + .caches = try a.alloc(mtl.Buffer, model.blocks.len), + .lanes = try a.alloc(target.LayerCache, model.blocks.len), + .sliding = try a.alloc(bool, model.blocks.len), + .picks = try device.buffer(max_rows * 4, opts), + .pad = t.engram_pad_id, + .vocab = t.vocab_size, + .names = &.{}, + .segments = try a.alloc(mtl.Segment, mtl.max_segments), + }; + for (run.caches, run.lanes, run.sliding, 0..) |*c, *lane, *slide, l| { + c.* = try device.buffer(@as(usize, capacity) * key_width * 2, opts); + slide.* = t.layer_types[l] == .sliding_attention; + lane.* = .{ .rows = .{ + .positions = .{ .buffer = run.positions }, + .write_slots = .{ .buffer = run.writes }, + .retained = .{ .buffer = if (slide.*) run.slide_keys else run.sparse_keys }, + .counts = .{ .buffer = if (slide.*) run.slide_counts else run.sparse_counts }, + .cache = .{ .buffer = c.* }, + .capacity = capacity, + .ranges = if (std.c.getenv("TF_HY4_NO_FLASH") == null and flashFor(slide.*)) .{ .ranges = .{ .buffer = if (slide.*) run.slide_ranges else run.sparse_ranges }, .tiles = .{ .buffer = run.tiles } } else null, + }, .key_stride = if (slide.*) window else capacity }; + } + for (run.tiles.slice(u32, capacity / 32), 0..) |*t_, i_| t_.* = @intCast(32 * i_); + if (std.c.getenv("TF_HY4_INDEX") != null) { + // one score row a pass row, shared by the sparse layers; each sparse layer's own token and group keys and lists + const scores = try device.buffer(@as(usize, max_rows) * (capacity / 4) * 4, mtl.ResourceOptions.private); + for (run.lanes, run.sliding) |*lane, slide| { + if (slide) continue; + lane.index = .{ + .token_keys = .{ .buffer = try device.buffer(index.Cache.tokenBytes(capacity), opts) }, + .group_keys = .{ .buffer = try device.buffer(index.Cache.groupBytes(capacity), opts) }, + .capacity = capacity, + .scores = .{ .buffer = scores }, + .score_groups = capacity / 4, + .tokens = .{ .buffer = try device.buffer(@as(usize, max_rows) * index.keys_a_row * 4, opts) }, + .counts = .{ .buffer = try device.buffer(max_rows * 4, opts) }, + }; + } + run.indexed = true; + std.debug.print("indexer on: {d} slots\n", .{capacity}); + } + var skip_list: []const usize = &.{}; + if (std.c.getenv("TF_HY4_SKIP")) |list| { + // timing only (--rows-time): drop dispatches whose pipeline name contains any comma-separated part, from the + // timed passes on (after a real warm-up), always with the router's select dropped too, so the picks stay + // the warm-up's real ones and every variant reads the same experts + var names: std.ArrayList(Name) = .empty; + try collect(@TypeOf(model.common), &model.common, "common", &names, a); + try collect(@TypeOf(model.routed), &model.routed, "routed", &names, a); + try collect(@TypeOf(model.memory), &model.memory, "engram", &names, a); + var ids: std.ArrayList(usize) = .empty; + var it = std.mem.splitScalar(u8, std.mem.span(list), ','); + while (it.next()) |part| for (names.items) |n| if (part.len > 0 and std.mem.indexOf(u8, n.name, part) != null) { + try ids.append(a, n.id); + std.debug.print("skip: {s}\n", .{n.name}); + }; + for (names.items) |n| if (std.mem.indexOf(u8, n.name, "routed.select") != null) try ids.append(a, n.id); + skip_list = ids.items; + } + if (profile_steps > 0) { + var names: std.ArrayList(Name) = .empty; + try collect(@TypeOf(model.common), &model.common, "common", &names, a); + try collect(@TypeOf(model.routed), &model.routed, "routed", &names, a); + try collect(@TypeOf(model.memory), &model.memory, "engram", &names, a); + try collect(mtl.Pipeline, &model.head.lookup, "head.embed", &names, a); + run.names = names.items; + run.pass = try mtl.counters.ComputePass.init(); + run.samples = try mtl.counters.SampleBuffer.init(device, 2 * mtl.max_segments); + std.debug.print("profile: {d} named pipelines, counter mode {s}\n", .{ names.items.len, @tagName(mtl.counters.query(device).mode()) }); + } + + // Build the prompt list: the short set, and optionally a long prompt near `long_tokens` tokens. + var lists: std.ArrayList([]u32) = .empty; + for (prompts) |p| { + const ids = try tok.encode(a, p); + const with = try a.alloc(u32, ids.len + 1); + with[0] = bos; + @memcpy(with[1..], ids); + try lists.append(a, with); + } + if (long_tokens > 0) { + var text: std.ArrayList(u8) = .empty; + var ids = try tok.encode(a, ""); + while (ids.len < long_tokens) { + try text.appendSlice(a, long_text); + ids = try tok.encode(a, text.items); + } + try text.appendSlice(a, "\nSummarize the passage above in one paragraph.\n"); + ids = try tok.encode(a, text.items); + const with = try a.alloc(u32, ids.len + 1); + with[0] = bos; + @memcpy(with[1..], ids); + try lists.append(a, with); + } + + if (text_path) |path| { + // one prompt from a file: its first 1,900 tokens after BOS + const body = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 22)); + const ids = try tok.encode(a, body); + const n = @min(ids.len, if (std.c.getenv("TF_HY4_TEXT_TOKENS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 1900 else 1900); + const with = try a.alloc(u32, n + 1); + with[0] = bos; + @memcpy(with[1..], ids[0..n]); + lists.items.len = 0; + try lists.append(a, with); + } + // Lanes: a first, untimed copy of prompt 0 warms the draft and multi-row pipelines. + const warm_lanes = lane_rows > 1; + if (warm_lanes) try lists.insert(a, 0, lists.items[0]); + var total_wall: f64 = 0; + var total_gpu: f64 = 0; + var total_tokens: usize = 0; + var all_ids: std.ArrayList(u32) = .empty; + if (std.c.getenv("TF_HY4_KCHECK")) |_| { + // every dense kernel against an fp64 reference on real weights and random rows + const dense = @import("metal_dense.zig"); + const Case = struct { name: []const u8, w: dense.Linear }; + const b1 = &model.blocks[1]; + const b2 = &model.blocks[2]; + var cases: std.ArrayList(Case) = .empty; + try cases.append(a, .{ .name = "o (sparse layer)", .w = b1.attention.o }); + try cases.append(a, .{ .name = "o (sliding layer)", .w = b2.attention.o }); + try cases.append(a, .{ .name = "latent down", .w = b1.feed.routed.down }); + try cases.append(a, .{ .name = "latent up", .w = b1.feed.routed.up }); + try cases.append(a, .{ .name = "shared gate", .w = b1.feed.routed.shared_gate }); + try cases.append(a, .{ .name = "shared down", .w = b1.feed.routed.shared_down }); + try cases.append(a, .{ .name = "lm_head", .w = model.head.vocab }); + var prng = std.Random.DefaultPrng.init(7); + const rnd = prng.random(); + for (cases.items) |c| { + const plain = switch (c.w) { + .portable => |w| w, + .tensor => |tw| tw.plain orelse return error.KcheckNeedsPlain, + }; + const n: usize = plain.n; + const k: usize = plain.k; + for ([_]u32{ 1, 4 }) |rows| { + const xb = try device.buffer(rows * k * 2, opts); + const xs = xb.slice(u16, rows * k); + for (xs) |*v| v.* = @truncate(@as(u32, @bitCast(@as(f32, @floatCast(rnd.floatNorm(f64))))) >> 16); + // fp64 reference + const ref = try a.alloc(f64, rows * n); + const words = plain.w.slice(u32, plain.w.length() / 4); + const scales = plain.scales.slice(u16, plain.scales.length() / 2); + const biases = plain.biases.slice(u16, plain.biases.length() / 2); + const per_row = k * plain.bits / 32; + const groups = k / plain.group; + for (0..rows) |r| for (0..n) |o| { + var acc: f64 = 0; + for (0..k) |col| { + const bitpos = col * plain.bits; + const word = words[o * per_row + bitpos / 32]; + const q: f64 = @floatFromInt((word >> @intCast(bitpos % 32)) & ((@as(u32, 1) << @intCast(plain.bits)) - 1)); + const g = col / plain.group; + const wv = bf16(scales[o * groups + g]) * q + bf16(biases[o * groups + g]); + acc += @as(f64, bf16(xs[r * k + col])) * wv; + } + ref[r * n + o] = acc; + }; + var worst: [3]f64 = @splat(0); + var scale_max: f64 = 0; + for (ref) |v| scale_max = @max(scale_max, @abs(v)); + for ([_]?u32{ 8, 0, 0 }, 0..) |override, kind| { + const yb = try device.buffer(rows * n * 2, opts); + const p2 = mtl.objc.Pool.push(); + defer p2.pop(); + const cb = queue.commandBuffer(); + var split = mtl.Splitter.plain(cb, run.segments); + const e = split.encoder(); + dense.decode_rows_override = override; + switch (kind) { + 0 => try model.common.project(e, plain, .{ .buffer = xb }, .{ .buffer = yb }, rows), + 1 => try model.common.project(e, plain, .{ .buffer = xb }, .{ .buffer = yb }, rows), + else => if (c.w == .tensor) try model.common.linear(e, c.w, .{ .buffer = xb }, .{ .buffer = yb }, rows), + } + dense.decode_rows_override = null; + _ = split.finish(); + cb.commit(); + cb.wait(); + if (kind == 2 and c.w != .tensor) continue; + const ys = yb.slice(u16, rows * n); + for (0..rows * n) |idx| worst[kind] = @max(worst[kind], @abs(@as(f64, bf16(ys[idx])) - ref[idx])); + } + std.debug.print("KCHECK {s:18} n {d:6} k {d:5} bits {d} rows {d}: max |y| {d:.4}; max error: decode GEMV {d:.5}, row kernels {d:.5}, tensor lanes {d:.5}\n", .{ c.name, n, k, plain.bits, rows, scale_max, worst[0], worst[1], worst[2] }); + } + } + return; + } + if (std.c.getenv("TF_HY4_BOS_TOP")) |_| { + // the first token's logits after BOS alone, against the MLX reference's top five + var hist: [1]u32 = .{bos}; + _ = try run.step(&hist, 0, hist[0..1], false); + const row = frame.logits.buffer.slice(u16, run.vocab); + var top: [5]u32 = @splat(0); + var used: [5]bool = @splat(false); + _ = &used; + for (0..5) |k| { + var best: f32 = -std.math.inf(f32); + var id: u32 = 0; + for (row, 0..) |w, t_| { + const v = bf16(w); + var seen = false; + for (top[0..k]) |p_| seen = seen or p_ == t_; + if (!seen and v > best) { + best = v; + id = @intCast(t_); + } + } + top[k] = id; + std.debug.print("BOS TOP {d}: id {d} logit {d:.4}\n", .{ k, id, bf16(row[id]) }); + } + return; + } + if (std.c.getenv("TF_HY4_BARRIER_TEST")) |_| { + // the cost of a dispatch and of a barrier on this GPU: 1400 tiny argmax launches over 64 values + const rows = model.common.rows orelse return error.Hy4ProbeNeedsRowKernels; + for ([_]bool{ false, true }) |barriers| { + var best: f64 = 1e9; + for (0..5) |_| { + const p2 = mtl.objc.Pool.push(); + defer p2.pop(); + const cb = queue.commandBuffer(); + var split = mtl.Splitter.plain(cb, run.segments); + const e = split.encoder(); + for (0..1400) |_| { + rows.pick(e, frame.logits, .{ .buffer = run.picks }, 0, 1, 64); + if (barriers) e.barrier(); + } + _ = split.finish(); + cb.commit(); + cb.wait(); + best = @min(best, cb.gpuSeconds()); + } + std.debug.print("BARRIER TEST: 1400 tiny dispatches {s}: {d:.3} ms GPU ({d:.2} us each)\n", .{ if (barriers) "each followed by a barrier" else "with no barriers", 1000 * best, 1e6 * best / 1400.0 }); + } + return; + } + var lanes: ?Lanes = if (lane_rows > 1) try Lanes.init(a, &run) else null; + if (lanes) |*l| { + if (lane_rows > l.draft.width) return error.Hy4ProbeTooManyLaneRows; + std.debug.print("lanes: DFly2 {d} layers, block {d}, verifying {d} rows a round\n", .{ l.draft.blocks.len, l.draft.width, lane_rows }); + if (run.pass != null) { + var more: std.ArrayList(Name) = .empty; + try more.appendSlice(a, run.names); + try collect(mtl.Pipeline, &l.draft.fuse, "draft.fuse", &more, a); + try collect(mtl.Pipeline, &l.draft.residual, "draft.residual", &more, a); + run.names = more.items; + } + } + // warm the pipelines and caches: a short untimed decode + { + var hist: [64]u32 = undefined; + hist[0] = bos; + var next = (try run.step(&hist, 0, hist[0..1], false)).next; + for (1..8) |p| { + hist[p] = next; + next = (try run.step(&hist, @intCast(p), hist[p .. p + 1], false)).next; + } + } + if (rows_time) { + // One prompt, `gen` plain tokens, then target passes over R real rows at a fixed position (rewritten each time). + // With --long or --text: that long prompt instead of the short set's second, and passes that fit the cache. + const prompt = if (long_tokens > 0 or text_path != null) lists.items[lists.items.len - 1] else lists.items[1]; + const hist = try a.alloc(u32, prompt.len + gen + max_rows); + @memcpy(hist[0..prompt.len], prompt); + var start: u32 = 0; + var next: u32 = 0; + while (start < prompt.len) { + const n: u32 = @min(chunk, @as(u32, @intCast(prompt.len)) - start); + next = (try run.step(hist, start, hist[start .. start + n], false)).next; + start += n; + } + var pos: u32 = @intCast(prompt.len); + const ahead: usize = if (long_tokens > 0 or text_path != null) 16 else max_rows; + for (0..gen + ahead - 1) |_| { + hist[pos] = next; + next = (try run.step(hist, pos, hist[pos .. pos + 1], false)).next; + pos += 1; + } + const at: u32 = @intCast(prompt.len + gen / 2); + var one: f64 = 0; + run.all_logits = true; + if (skip_list.len > 0) { + // one real pass of every timed width first, so each row's picks are its own + _ = try run.step(hist, at, hist[at .. at + 16], false); + mtl.skip_ids = skip_list; + } + for ([_]u32{ 1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 32, 64, 128, 256, 512 }) |rows| { + if (at + rows + 1 > capacity) break; + var times: [7]f64 = undefined; + for (×) |*tm| tm.* = (try run.step(hist, at, hist[at .. at + rows], false)).gpu; + std.mem.sort(f64, ×, {}, std.sort.asc(f64)); + if (rows == 1) one = times[3]; + std.debug.print("ROWS {d:2}: {d:.3} ms GPU a pass (median of 7, min {d:.3}), {d:.2}x one row, {d:.3} ms a row\n", .{ rows, 1000 * times[3], 1000 * times[0], times[3] / one, 1000 * times[3] / @as(f64, @floatFromInt(rows)) }); + } + mtl.skip_ids = &.{}; + if (std.c.getenv("TF_HY4_ACHECK") != null) try attentionCheck(&run, hist, at); + if (profile_steps == 0) return; + // --profile ROWS in this mode: profile three passes of ROWS rows + for (0..3) |_| _ = try run.step(hist, at, hist[at .. at + profile_steps], true); + lists.items.len = 0; + } + for (lists.items, 0..) |prompt, pi| { + if (prompt.len + gen + 1 > capacity) return error.Hy4ProbeContextTooLong; + const hist = try a.alloc(u32, prompt.len + gen + 16); + @memcpy(hist[0..prompt.len], prompt); + const tp = mtl.clock.seconds(); + var start: u32 = 0; + var next: u32 = 0; + var nll_sum: f64 = 0; + var nll_count: usize = 0; + run.all_logits = nll; + while (start < prompt.len) { + const n: u32 = @min(chunk, @as(u32, @intCast(prompt.len)) - start); + next = (try run.step(hist, start, hist[start .. start + n], false)).next; + if (nll) { + // teacher-forced: each row's log-probability of the prompt's next token + const all = run.frame.logits.buffer.slice(u16, @as(usize, n) * run.vocab); + for (0..n) |r| { + const at = start + r + 1; + if (at >= prompt.len) break; + const row = all[r * run.vocab ..][0..run.vocab]; + var top: f64 = -std.math.inf(f64); + for (row) |w| top = @max(top, bf16(w)); + var z: f64 = 0; + for (row) |w| z += @exp(@as(f64, bf16(w)) - top); + const tok_nll = top + @log(z) - bf16(row[hist[at]]); + nll_sum += tok_nll; + nll_count += 1; + if (nll_dump) std.debug.print("TOKNLL {d} {d:.6}\n", .{ at, tok_nll }); + } + } + start += n; + } + run.all_logits = false; + if (std.c.getenv("TF_HY4_ICHECK") != null and run.indexed) try indexCheck(&run); + if (nll and nll_count > 0) std.debug.print("NLL: {d:.5} nats a token over {d} tokens (perplexity {d:.4})\n", .{ nll_sum / @as(f64, @floatFromInt(nll_count)), nll_count, @exp(nll_sum / @as(f64, @floatFromInt(nll_count))) }); + const prefill = mtl.clock.seconds() - tp; + var pos: u32 = @intCast(prompt.len); + var wall: f64 = 0; + var gpu: f64 = 0; + if (lanes) |*l| { + // hist[pos] is the bonus token (not yet in the cache); the last pass's final row is the anchor. + var source: u32 = (@as(u32, @intCast(prompt.len)) - 1) % chunk; + const goal: u32 = @intCast(prompt.len + gen); + const t0 = mtl.clock.seconds(); + const g0 = l.draft_gpu + l.verify_gpu; + var width: u32 = lane_rows; + while (pos < goal) { + const round_pool = mtl.objc.Pool.push(); + defer round_pool.pop(); + const rows: u32 = @min(width, goal - pos); + var drafts: [8]u32 = undefined; + l.profile_rounds = @intFromBool(profile_steps > 0 and pi == 0 and l.rounds >= 2 and l.rounds < 2 + profile_steps); + // the draft runs while the host encodes the verify pass over placeholder rows + hist[pos] = next; + const copied = if (copies and rows > 1) copyDraft(hist[0 .. pos + 1], drafts[0 .. rows - 1]) else 0; + const flight = if (rows > 1 and copied < rows - 1) try l.launch(&run, pos, next, source, rows - 1) else null; + if (copied == rows - 1) l.copy_rounds += 1; + @memset(hist[pos + 1 .. pos + rows], l.mask); + try run.stage(hist, pos, hist[pos .. pos + rows]); + run.layout(pos, rows); + const verify = try run.encodePicks(rows); + defer verify.release(); + if (flight) |f| try l.land(&run, f, rows - 1, drafts[0 .. rows - 1]); + @memcpy(hist[pos + 1 .. pos + rows], drafts[0 .. rows - 1]); + const ts = mtl.clock.seconds(); + try run.stage(hist, pos, hist[pos .. pos + rows]); + l.stage_wall += mtl.clock.seconds() - ts; + verify.commit(); + verify.wait(); + if (verify.failure()) |why| { + std.debug.print("verify command buffer failed: {s}\n", .{why}); + return error.Hy4ProbeCommandFailed; + } + l.verify_gpu += verify.gpuSeconds(); + const picks = run.picks.slice(u32, rows); + var j: u32 = 0; + while (j + 1 < rows and picks[j] == drafts[j]) j += 1; + l.rounds += 1; + l.kept += j; + l.proposed += rows - 1; + source = j; + pos += j + 1; + next = picks[j]; + // TF_HY4_ADAPT=lo,hi: widen after a round that kept every draft, narrow after one that kept none + if (adapt) |range| { + if (j + 1 == rows and width < range[1]) width += 1 else if (j == 0 and width > range[0]) width -= 1; + } + } + wall = mtl.clock.seconds() - t0; + gpu = l.draft_gpu + l.verify_gpu - g0; + } else for (0..gen) |g| { + hist[pos] = next; + const profile = profile_steps > 0 and pi == profile_prompt and g >= 2 and g < 2 + profile_steps; + const t0 = mtl.clock.seconds(); + const r = try run.step(hist, pos, hist[pos .. pos + 1], profile); + if (!profile) { + wall += mtl.clock.seconds() - t0; + gpu += r.gpu; + } + next = r.next; + pos += 1; + } + const timed: f64 = @floatFromInt(gen - @min(gen, if (pi == 0 and lanes == null) profile_steps else 0)); + const ids = hist[prompt.len .. prompt.len + gen]; + if (warm_lanes and pi == 0) { + if (lanes) |*l| { + l.rounds = 0; + l.kept = 0; + l.proposed = 0; + l.draft_gpu = 0; + l.verify_gpu = 0; + l.stage_wall = 0; + l.copy_rounds = 0; + } + std.debug.print("warm: lanes over prompt 0, untimed\n", .{}); + continue; + } + std.debug.print("prompt {d}, {d} input tokens: prefill {d:.1} tok/s, decode {d:.3} tok/s ({d:.3} ms wall, {d:.3} ms GPU a token), hash {x:0>16}\n", .{ + pi, prompt.len, @as(f64, @floatFromInt(prompt.len)) / prefill, timed / wall, 1000 * wall / timed, 1000 * gpu / timed, fnv(ids), + }); + std.debug.print(" ids {any}\n", .{ids}); + const text = try tok.decode(a, ids, false); + std.debug.print(" text {s}\n", .{text}); + total_wall += wall; + total_gpu += gpu; + total_tokens += @intFromFloat(timed); + try all_ids.appendSlice(a, ids); + } + if (lanes) |l| std.debug.print("LANES: {d} rounds, {d}/{d} drafts kept, {d:.3} tokens a round, draft {d:.3} ms and verify {d:.3} ms GPU a round, Engram restage {d:.3} ms a round, {d} copy rounds\n", .{ + l.rounds, l.kept, l.proposed, @as(f64, @floatFromInt(l.kept + l.rounds)) / @as(f64, @floatFromInt(l.rounds)), 1000 * l.draft_gpu / @as(f64, @floatFromInt(l.rounds)), 1000 * l.verify_gpu / @as(f64, @floatFromInt(l.rounds)), 1000 * l.stage_wall / @as(f64, @floatFromInt(l.rounds)), l.copy_rounds, + }); + const tt: f64 = @floatFromInt(total_tokens); + std.debug.print("SUMMARY: {d} prompts, decode {d:.3} tok/s, {d:.3} ms wall and {d:.3} ms GPU a token, all-ids hash {x:0>16}\n", .{ lists.items.len - @intFromBool(warm_lanes), tt / total_wall, 1000 * total_wall / tt, 1000 * total_gpu / tt, fnv(all_ids.items) }); + + if (run.profiled > 0) { + const steps: f64 = @floatFromInt(run.profiled); + const items = run.stages.values(); + std.mem.sort(Stage, items, {}, struct { + fn more(_: void, x: Stage, y: Stage) bool { + return x.ns > y.ns; + } + }.more); + var sum: f64 = 0; + for (items) |s| sum += s.ns; + std.debug.print("PROFILE over {d} decode steps: {d:.3} ms a token in {d} timed segments a token\n", .{ run.profiled, sum / steps / 1e6, @divTrunc(blk: { + var c: usize = 0; + for (items) |s| c += s.count; + break :blk c; + }, run.profiled) }); + for (items) |s| { + std.debug.print(" {d:8.3} ms {d:5.1}% x{d:<4} {s}\n", .{ s.ns / steps / 1e6, 100 * s.ns / sum, s.count / run.profiled, s.label }); + } + } +} diff --git a/zig/src/families/hy4_flash/split_metal.zig b/zig/src/families/hy4_flash/split_metal.zig new file mode 100644 index 00000000000..ff33b125bb4 --- /dev/null +++ b/zig/src/families/hy4_flash/split_metal.zig @@ -0,0 +1,172 @@ +//! The engine's Metal module for the Hy4-flash speed probe. Everything is the real module except ComputeEncoder, +//! which forwards to a real encoder and, while a Splitter is splitting, turns each barrier into an encoder boundary +//! whose start and end the GPU timestamps. Without splitting a barrier stays a barrier, so timed runs match the engine. +const std = @import("std"); +const real = @import("real_metal"); + +pub const objc = real.objc; +pub const types = real.types; +pub const Size = real.Size; +pub const ResourceOptions = real.ResourceOptions; +pub const ResourceUsage = real.ResourceUsage; +pub const DispatchType = real.DispatchType; +pub const Device = real.Device; +pub const Buffer = real.Buffer; +pub const MappedFile = real.MappedFile; +pub const Library = real.Library; +pub const CompileOptions = real.CompileOptions; +pub const Pipeline = real.Pipeline; +pub const Queue = real.Queue; +pub const CommandBuffer = real.CommandBuffer; +pub const BlitEncoder = real.BlitEncoder; +pub const SharedEvent = real.SharedEvent; +pub const Event = real.Event; +pub const IndirectCommandBuffer = real.IndirectCommandBuffer; +pub const IndirectCommand = real.IndirectCommand; +pub const ResidencySet = real.ResidencySet; +pub const resident = real.resident; +pub const residency_policy = real.residency_policy; +pub const keepalive = real.keepalive; +pub const clock = real.clock; +pub const pass_metrics = real.pass_metrics; +pub const counters = real.counters; +pub const ane = real.ane; + +pub const max_segments = 2048; // two 8-byte stamps each: Metal caps a sample buffer at 32 KiB + +/// Timing only (TF_HY4_SKIP): dispatches of these pipelines are dropped, so a run's GPU time without them shows +/// what they cost unprofiled. The tokens are then wrong. +pub var skip_ids: []const usize = &.{}; +pub const max_names = 6; + +/// One encoder between two barriers: the pipelines it set (first few) and how many dispatches it made. +pub const Segment = struct { + pipelines: [max_names]usize = @splat(0), + named: u8 = 0, + dispatches: u16 = 0, +}; + +pub const Splitter = struct { + cb: real.CommandBuffer, + cur: real.ComputeEncoder, + split: bool, + pass: ?counters.ComputePass = null, + samples: ?counters.SampleBuffer = null, + count: usize = 0, + segments: []Segment, + current: usize = 0, + + /// A plain concurrent encoder: barriers stay barriers. + pub fn plain(cb: real.CommandBuffer, segments: []Segment) Splitter { + return .{ .cb = cb, .cur = cb.compute(.concurrent), .split = false, .segments = segments }; + } + + /// Timed serial encoders, one per barrier-delimited segment; `samples` holds two stamps a segment. + pub fn timed(cb: real.CommandBuffer, pass: counters.ComputePass, samples: counters.SampleBuffer, segments: []Segment) !Splitter { + var s: Splitter = .{ .cb = cb, .cur = undefined, .split = true, .pass = pass, .samples = samples, .segments = segments }; + try s.open(); + return s; + } + + fn open(self: *Splitter) !void { + if (self.count >= self.segments.len or 2 * self.count + 1 >= self.samples.?.count) return error.TooManyHy4ProbeSegments; + self.segments[self.count] = .{}; + self.cur = try self.pass.?.compute(self.cb, self.samples.?, 2 * self.count, 2 * self.count + 1); + } + + pub fn encoder(self: *Splitter) ComputeEncoder { + return .{ .s = self }; + } + + fn note(self: *Splitter, p: Pipeline) void { + if (!self.split) return; + const seg = &self.segments[self.count]; + if (seg.named < max_names) { + seg.pipelines[seg.named] = @intFromPtr(p.id); + seg.named += 1; + } + } + + fn dispatched(self: *Splitter) void { + if (self.split) self.segments[self.count].dispatches +|= 1; + } + + fn barrier(self: *Splitter) void { + if (!self.split) return self.cur.barrier(); + if (self.segments[self.count].dispatches == 0) return; + self.cur.end(); + self.count += 1; + self.open() catch @panic("hy4 probe: out of timed segments"); + } + + /// End the last encoder. Returns how many timed segments the command buffer holds. + pub fn finish(self: *Splitter) usize { + self.cur.end(); + if (!self.split) return 0; + return self.count + @intFromBool(self.segments[self.count].dispatches != 0); + } +}; + +pub const ComputeEncoder = struct { + s: *Splitter, + + fn skipped(self: ComputeEncoder) bool { + for (skip_ids) |id| if (id == self.s.current) return true; + return false; + } + + pub fn deviceId(self: ComputeEncoder) objc.Id { + return self.s.cur.deviceId(); + } + pub fn setPipeline(self: ComputeEncoder, pipeline: Pipeline) void { + self.s.current = @intFromPtr(pipeline.id); + self.s.note(pipeline); + self.s.cur.setPipeline(pipeline); + } + pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void { + self.s.cur.setBuffer(buffer, offset, index); + } + pub fn setBytes(self: ComputeEncoder, bytes: []const u8, index: usize) void { + self.s.cur.setBytes(bytes, index); + } + pub fn setValue(self: ComputeEncoder, value: anytype, index: usize) void { + self.s.cur.setBytes(std.mem.asBytes(&value), index); + } + pub fn setThreadgroupMemory(self: ComputeEncoder, len: usize, index: usize) void { + self.s.cur.setThreadgroupMemory(len, index); + } + pub fn dispatchGroups(self: ComputeEncoder, groups: Size, threads: Size) void { + if (self.skipped()) return; + self.s.dispatched(); + self.s.cur.dispatchGroups(groups, threads); + } + pub fn dispatchIndirect(self: ComputeEncoder, args: Buffer, offset: usize, threads: Size) void { + if (self.skipped()) return; + self.s.dispatched(); + self.s.cur.dispatchIndirect(args, offset, threads); + } + pub fn dispatchThreads(self: ComputeEncoder, grid: Size, threads: Size) void { + if (self.skipped()) return; + self.s.dispatched(); + self.s.cur.dispatchThreads(grid, threads); + } + pub fn barrier(self: ComputeEncoder) void { + self.s.barrier(); + } + pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void { + self.s.cur.useResource(buffer, usage); + } + pub fn execute(self: ComputeEncoder, icb: IndirectCommandBuffer, first: usize, count: usize) void { + self.s.dispatched(); + self.s.cur.execute(icb, first, count); + } + pub fn end(self: ComputeEncoder) void { + _ = self.s.finish(); + } + pub fn commandBuffer(self: ComputeEncoder) CommandBuffer { + return self.s.cur.commandBuffer(); + } + pub fn dispatchType(self: ComputeEncoder) DispatchType { + return self.s.cur.dispatchType(); + } +}; diff --git a/zig/src/native/hy4_metal.zig b/zig/src/native/hy4_metal.zig new file mode 100644 index 00000000000..bf28b64cff8 --- /dev/null +++ b/zig/src/native/hy4_metal.zig @@ -0,0 +1,82 @@ +//! Hy4-flash served by the lane host on Metal: one stream at a time with DFly2 windows, contexts to 256K tokens +//! (128K by default), and the last stream's caches kept for a following prompt that starts with the same tokens. +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/server/hf_text.zig b/zig/src/server/hf_text.zig index 1a5c73eea3a..403fd2f8c71 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -42,6 +42,9 @@ pub const HfText = struct { eos: []const u32 = &.{}, prefix: []const u32 = &.{}, // the post-processor's tokens before a text (add_special_tokens) suffix: []const u32 = &.{}, + /// Hy4-flash spells its reasoning and tool-call tokens ``, ``, ...: the + /// server reads them as the GLM spellings it parses (decoded text, marker ids, and marker strings it encodes). + hy4: bool = false, /// Loads ``dir``'s tokenizer.json, chat template, special tokens, eos ids; failure reason in `problem` (from `pa`). pub fn load(gpa: Allocator, io: std.Io, dir: []const u8, template_override: ?[]const u8, pa: Allocator, problem: *[]const u8) !*HfText { @@ -135,6 +138,7 @@ pub const HfText = struct { }; } if (t.tool_source.len > 0) t.tool_compiled = template.compile(gpa, t.tool_source, null) catch null; + t.hy4 = t.tok.specialTokenId("") != null and t.tok.specialTokenId("") != null; return t; } @@ -322,8 +326,10 @@ pub const HfText = struct { return @ptrCast(@alignCast(ctx)); } - fn encodeFn(ctx: *anyopaque, a: Allocator, s: []const u8, add_special: bool) model_text.Error![]u32 { + fn encodeFn(ctx: *anyopaque, a: Allocator, s_in: []const u8, add_special: bool) model_text.Error![]u32 { const t = self(ctx); + // a marker the server spells itself (a closing ) encodes as the model's own token + const s = if (t.hy4) hy4Spelling(s_in) orelse s_in else s_in; const ids = t.tok.encode(a, 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 +353,27 @@ 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}"); + const t = self(ctx); + const raw = t.tok.decode(a, ids, false) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else a.dupe(u8, "\u{fffd}"); + if (!t.hy4 or 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 (hy4_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.items; } fn tokenIdFn(ctx: *anyopaque, piece: []const u8) ?u32 { - return self(ctx).tok.specialTokenId(piece); + const t = self(ctx); + if (t.hy4) if (hy4Spelling(piece)) |own| return t.tok.specialTokenId(own); + return t.tok.specialTokenId(piece); } fn tokenStringFn(ctx: *anyopaque, a: Allocator, id: u32) Allocator.Error![]u8 { @@ -598,3 +620,23 @@ test { _ = @import("dory_chat_test.zig"); _ = @import("deepseek_chat_test.zig"); } + +/// Hy4-flash's marker tokens and the GLM spellings the server's reply parsing reads (the call list's wrapper drops). +const hy4_spellings = [_][2][]const u8{ + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, + .{ "", "" }, +}; + +/// The Hy4-flash token a GLM marker spelling stands for, or null. +fn hy4Spelling(piece: []const u8) ?[]const u8 { + for (hy4_spellings) |pair| if (pair[1].len > 0 and std.mem.eql(u8, piece, pair[1])) return pair[0]; + return null; +} 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"); From ee7d298e7bbb487af09f543abaca68e2fe8862e9 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:52:32 +0000 Subject: [PATCH 03/12] hy4_flash: row-invariant decode, so drafted output equals plain decode and a resumed prompt equals a fresh one Every pass takes the kernels a prompt chunk takes, so a row's bits never depend on how many rows share its pass: - dense projections on the tensor units' lane projection at every row count (no 1-2 row GEMVs); - routed experts on the tensor gathers at every row count (no pair GEMVs); - MLA absorb and expand on the BF16 copies at every row count (no 1-row GEMVs over kv_b's codes); - flash attention unsplit (a split count from the pass's widest row changed the other rows' sums); - a pass across 2,048 keys attends its earlier rows over their whole range, as any other pass would, and only its later rows over the recalled lists. Greedy tokens on the probe's prompts: plain, DFly2 (4 rows) and prompt chunks of 1, 37 and 512 rows give the same ids at 4- and 8-bit, at short context, at 3,000 tokens and across the 2,048-key boundary. --- zig/src/families/hy4_flash/metal_dense.zig | 13 +++++----- zig/src/families/hy4_flash/mla_metal.zig | 28 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/zig/src/families/hy4_flash/metal_dense.zig b/zig/src/families/hy4_flash/metal_dense.zig index 1bb82c47cb3..a23a7194a37 100644 --- a/zig/src/families/hy4_flash/metal_dense.zig +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -88,14 +88,14 @@ fn envRows(name: [*:0]const u8, default: u32) u32 { /// Routed-expert passes of at most this many rows (6: the lane verify widths) run every (row, pick) pair as GEMVs /// (TF_HY4_EXPERT_PAIRS); against the tensor gathers 4 rows 24.6 -> 23.1 ms, 5 rows 26.6 -> 24.4, 6 rows 27.8 -> 26.4. pub fn expertPairRows() u32 { - return envRows("TF_HY4_EXPERT_PAIRS", @max(decodeRows(), 6)); + return 0; // row-invariant bits: every pass takes the tensor gathers the prompt chunks take } /// Attention passes of at most this many rows (4 at most) read kv_b's affine codes (TF_HY4_MLA_Q; 0: the BF16 copies). /// One row by default: 15.85 -> 15.29 ms a token; from two rows the fp32 dequant is compute-bound, slower than BF16 /// on tensor units (4 rows: 23.0 -> 24.2 ms). pub fn mlaRows() u32 { - return @min(envRows("TF_HY4_MLA_Q", 1), 4); + return 0; // row-invariant bits: every pass reads the BF16 copies on the tensor units, as prompt chunks do } /// Larger passes up to this many rows (at most one router window, 16) run the grouped GEMVs (TF_HY4_EXPERT_GROUPS). @@ -104,9 +104,7 @@ pub fn expertGroupRows() u32 { } pub fn decodeRows() u32 { - if (decode_rows_override) |v| return v; - const v = std.c.getenv("TF_HY4_DECODE_ROWS") orelse return 2; - return std.fmt.parseInt(u32, std.mem.span(v), 10) catch 2; + return decode_rows_override orelse 0; // row-invariant bits: the lane projection at every row count } pub const Linear = union(enum) { @@ -885,6 +883,8 @@ pub const Kernels = struct { } // 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; const quantized: ?mla_gpu.Quantized = if (self.rows) |r| if (w.kv_q) |q| if (rows <= mlaRows() and (w.bits == 4 or w.bits == 8)) .{ .absorb = r.absorb_q[@intFromBool(w.bits == 8)], .expand = r.expand_q[@intFromBool(w.bits == 8)], @@ -912,7 +912,8 @@ pub const Kernels = struct { .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 or std.c.getenv("TF_HY4_ATTEND_LISTS") != null) null else cache.ranges, + .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, }, diff --git a/zig/src/families/hy4_flash/mla_metal.zig b/zig/src/families/hy4_flash/mla_metal.zig index 814efbc8696..cd22c200968 100644 --- a/zig/src/families/hy4_flash/mla_metal.zig +++ b/zig/src/families/hy4_flash/mla_metal.zig @@ -47,10 +47,8 @@ pub const Nax = struct { /// A split a 32-key tile, up to max_splits (two tiles already run faster split and joined than in one /// threadgroup); with the live key count unknown, a split every 128 keys of the stride. fn splits(shape: attention.Shape, has_parts: bool, live_keys: u32) u32 { - if (!has_parts or shape.rows > 16) return 1; - if (std.c.getenv("TF_HY4_FLASH_SPLIT")) |v| return std.math.clamp(std.fmt.parseInt(u32, std.mem.span(v), 10) catch 1, 1, max_splits); - if (live_keys > 0) return std.math.clamp((live_keys + 31) / 32, 1, max_splits); - return std.math.clamp(shape.key_stride / 128, 1, max_splits); + _ = .{ 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 { @@ -223,6 +221,9 @@ pub const Attention = struct { 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`, as they would in any + /// other pass, and the rest their recalled slot lists. + lists_from: ?u32 = null, }; pub fn load(device: mtl.Device) !Attention { @@ -318,6 +319,10 @@ pub const MlaPass = struct { 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(); @@ -349,7 +354,20 @@ pub fn forward(project: Projections, attend: Attention, e: mtl.ComputeEncoder, b .epsilon = kv.epsilon, }); e.barrier(); - if (project.nax) |n| if (b.attention.ranges) |r| { + 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(); From d2485da3cc767197848b7eaa3512a4d38ec468f6 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:11:13 +0000 Subject: [PATCH 04/12] hy4_flash: lane projections take their group sums in the kernel for passes of 8 rows or fewer, and 8-bit codes reach the tensor units through registers - Small passes skip the sums dispatch and its barrier: each split adds its (group, row) sums up front with the sums pass's own loop, one chain a lane, so the words are the same. - 8-bit layouts take the reg path: the codes in the 4-bit reg order a byte each, unpacked as fp16 integers into the tensor op's right input; the same words as the 8-bit tensor layout. Same greedy tokens as before at 4- and 8-bit (plain, DFly2, 512-row chunks). 4-bit one row 17.19 -> 16.54 ms, four rows 22.97 -> 22.45; 8-bit one row 24.13 -> 22.36 ms, four rows 34.75 -> 33.15, 512 rows 305 ms. --- zig/kernels/metal/core/lane_projection.metal | 71 +++++++++++++++++-- zig/src/core/lane_projection.zig | 33 +++++++-- zig/src/families/hy4_flash/metal_dense.zig | 19 ++++- .../families/hy4_flash/metal_tensor_qkv.zig | 41 +++++++++-- 4 files changed, 147 insertions(+), 17 deletions(-) diff --git a/zig/kernels/metal/core/lane_projection.metal b/zig/kernels/metal/core/lane_projection.metal index 7e65ddb08b6..277071cce7b 100644 --- a/zig/kernels/metal/core/lane_projection.metal +++ b/zig/kernels/metal/core/lane_projection.metal @@ -15,6 +15,15 @@ using namespace mpp::tensor_ops; #ifndef TF_ROW_BLOCKS #define TF_ROW_BLOCKS 0 #endif +// Reg path: each split adds its rows' group sums itself (tf_lane_xsum, the sums pass's own loop), so no sums +// dispatch or barrier comes before the projection; the words are the same. +#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 +233,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 +323,28 @@ 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 (4-bit: two quads; 8-bit: the same codes a byte each, four quads), its two metadata quads and its +// two row sums for one group +#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 +365,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/src/core/lane_projection.zig b/zig/src/core/lane_projection.zig index 2330db0bf4f..124e590f538 100644 --- a/zig/src/core/lane_projection.zig +++ b/zig/src/core/lane_projection.zig @@ -43,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 @@ -125,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); @@ -174,6 +177,26 @@ pub fn regBlock(tiled: *const [256]u32, out: *[256]u32) void { pub const Order = struct { w: Ref, n: usize, k: usize }; +/// Rewrites tile-order 8-bit g64 words (host-visible) in place into the 8-bit reg layout: u32[N/32][K/64][4][32 lanes][4], +/// a lane's codes in the 4-bit reg order a byte each (word 2w: four codes, 2w + 1: the four 16 deeper). +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, @@ -245,6 +268,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, @@ -271,7 +296,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 { @@ -301,7 +326,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); @@ -318,7 +343,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/families/hy4_flash/metal_dense.zig b/zig/src/families/hy4_flash/metal_dense.zig index a23a7194a37..f3ab467a330 100644 --- a/zig/src/families/hy4_flash/metal_dense.zig +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -132,6 +132,8 @@ pub const Linear = union(enum) { 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, const sum_rows = gpu_qkv.prompt_rows; @@ -157,6 +159,7 @@ pub const Linears = struct { 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); @@ -167,6 +170,7 @@ pub const Linears = struct { 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; } @@ -175,6 +179,11 @@ pub const Linears = struct { 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; } + + 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; + } }; pub const Merge = struct { @@ -667,6 +676,12 @@ pub const Kernels = struct { } 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); @@ -859,7 +874,7 @@ pub const Kernels = struct { .tensor => |m| { const kernels = &self.tensors.?; const qkv = s.qkv.?; - try kernels.inputs[m.flavor].encode(e, tref(s.normalized), m.qkv.w, m.qkv.sb, tref(qkv), rows); + 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; @@ -871,7 +886,7 @@ pub const Kernels = struct { } try self.norm(e, q_a, w.q_norm, s.query_norm, rows, w.query_rank, w.epsilon); e.barrier(); - try kernels.queries[m.flavor].encode(e, tref(s.query_norm), m.q_b.w, m.q_b.sb, tref(s.query), rows); + 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(); diff --git a/zig/src/families/hy4_flash/metal_tensor_qkv.zig b/zig/src/families/hy4_flash/metal_tensor_qkv.zig index 58bee4f9e1e..28a6020125b 100644 --- a/zig/src/families/hy4_flash/metal_tensor_qkv.zig +++ b/zig/src/families/hy4_flash/metal_tensor_qkv.zig @@ -38,7 +38,7 @@ pub const Packed = struct { 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) try lane.regOrder(owner.d, &.{.{ .w = .{ .buf = w }, .n = l.n, .k = l.k }}); + 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 } }; } }; @@ -52,11 +52,11 @@ fn layout(bits: u8, n: usize, k: usize, sk: usize) lane.Layout { .k = k, .sk = sk, .format = .{ .bits = bits, .group = 64 }, - .reg = bits == 4, - .precompute_sums = bits == 4, + .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 = bits != 4, + .row_blocks = false, }; } @@ -78,9 +78,24 @@ 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: the same words as the +/// sums pass, without its dispatch and barrier. +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 { @@ -103,6 +118,10 @@ pub const Kernels = struct { 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; } @@ -111,9 +130,23 @@ pub const Kernels = struct { 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); From 503b437d177524ab146c617bf19dab863bdfcf61 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:26:27 +0000 Subject: [PATCH 05/12] hy4_flash: the engine's lane_projection re-export carries regOrder8 --- zig/hy4_engine/lane_projection.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/hy4_engine/lane_projection.zig b/zig/hy4_engine/lane_projection.zig index 4ccced197a0..ff748832bbb 100644 --- a/zig/hy4_engine/lane_projection.zig +++ b/zig/hy4_engine/lane_projection.zig @@ -19,3 +19,4 @@ pub const Projection = m.Projection; pub const reg_rows = m.reg_rows; pub const max_reg_rows = m.max_reg_rows; pub const Sums = m.Sums; +pub const regOrder8 = m.regOrder8; From b7976457f36f8807e5a46ff0bdd08eb1182b6714 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:49:12 +0000 Subject: [PATCH 06/12] hy4_flash: lean pass: one-line comments, settings through platform/environment.zig, no dead decode paths, files under 600 lines - TF_HY4_ENGRAM (nvme, ram or gpu) and TF_HY4_DRAFT_BITS (4, 8 or 16) are read through the environment module. - The 1-2 row dense GEMVs, the expert pair and group GEMVs, the 1-row MLA GEMVs over kv_b's codes and their kernels go, with the diagnostic switches that chose them; every pass already took the prompt chunks' kernels. - The speed probe leaves the tree; Linears, Rows and Scratch move out of metal_dense.zig, residency and drafting out of serve_metal.zig, and the Hy4 marker spellings out of hf_text.zig into hf_hy4.zig (with a test). --- zig/build/hy4_probe.zig | 40 - zig/build/metal_targets.zig | 1 - zig/hy4_engine/lane_projection.zig | 2 +- zig/hy4_engine/row_projection.zig | 2 +- zig/kernels/metal/core/lane_projection.metal | 6 +- zig/kernels/metal/hy4_flash/engram.metal | 4 +- zig/kernels/metal/hy4_flash/ihc.metal | 36 +- zig/kernels/metal/hy4_flash/index_build.metal | 11 +- .../metal/hy4_flash/mla_attention.metal | 12 +- zig/kernels/metal/hy4_flash/mla_nax.metal | 18 +- zig/kernels/metal/hy4_flash/mla_project.metal | 3 +- zig/kernels/metal/hy4_flash/route_rows.metal | 9 +- zig/kernels/metal/hy4_flash/rows.metal | 684 ---------- .../metal/hy4_flash/tensor_dispatch.metal | 6 +- zig/src/core/lane_projection.zig | 3 +- zig/src/cuda/affine_experts.zig | 1 - zig/src/families/hy4_flash/engram_rows.zig | 4 +- zig/src/families/hy4_flash/ihc_metal.zig | 3 +- zig/src/families/hy4_flash/metal_dense.zig | 407 +----- zig/src/families/hy4_flash/metal_draft.zig | 16 +- zig/src/families/hy4_flash/metal_engram.zig | 11 +- zig/src/families/hy4_flash/metal_index.zig | 9 +- zig/src/families/hy4_flash/metal_linears.zig | 123 ++ zig/src/families/hy4_flash/metal_routed.zig | 89 +- zig/src/families/hy4_flash/metal_scratch.zig | 109 ++ .../hy4_flash/metal_tensor_experts.zig | 3 +- .../families/hy4_flash/metal_tensor_qkv.zig | 6 +- zig/src/families/hy4_flash/mla_metal.zig | 38 +- zig/src/families/hy4_flash/mla_weights.zig | 3 +- zig/src/families/hy4_flash/rank_weights.zig | 1 - zig/src/families/hy4_flash/serve_draft.zig | 95 ++ zig/src/families/hy4_flash/serve_metal.zig | 175 +-- zig/src/families/hy4_flash/serve_resident.zig | 78 ++ zig/src/families/hy4_flash/speed_probe.zig | 1151 ----------------- zig/src/families/hy4_flash/split_metal.zig | 172 --- zig/src/native/hy4_metal.zig | 3 +- zig/src/platform/environment.zig | 2 + zig/src/server/hf_hy4.zig | 59 + zig/src/server/hf_text.zig | 50 +- 39 files changed, 555 insertions(+), 2890 deletions(-) delete mode 100644 zig/build/hy4_probe.zig create mode 100644 zig/src/families/hy4_flash/metal_linears.zig create mode 100644 zig/src/families/hy4_flash/metal_scratch.zig create mode 100644 zig/src/families/hy4_flash/serve_draft.zig create mode 100644 zig/src/families/hy4_flash/serve_resident.zig delete mode 100644 zig/src/families/hy4_flash/speed_probe.zig delete mode 100644 zig/src/families/hy4_flash/split_metal.zig create mode 100644 zig/src/server/hf_hy4.zig diff --git a/zig/build/hy4_probe.zig b/zig/build/hy4_probe.zig deleted file mode 100644 index a09ffe54182..00000000000 --- a/zig/build/hy4_probe.zig +++ /dev/null @@ -1,40 +0,0 @@ -//! tf-hy4-speed: the Hy4-flash Metal graph's greedy decode speed and per-stage GPU profile on a real checkpoint. -const std = @import("std"); - -pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, real_metal: *std.Build.Module, sources: *std.Build.Module) void { - const metal = b.createModule(.{ - .root_source_file = b.path("zig/src/families/hy4_flash/split_metal.zig"), - .target = target, - .optimize = optimize, - .imports = &.{.{ .name = "real_metal", .module = real_metal }}, - }); - const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); - const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "tokenizer", .module = tokenizer }} }); - core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, target)); - const with_metal: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources } }; - const row = b.createModule(.{ .root_source_file = b.path("zig/src/core/row_projection.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = with_metal }); - const lane = b.createModule(.{ .root_source_file = b.path("zig/src/core/lane_projection.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = with_metal }); - const route = b.createModule(.{ .root_source_file = b.path("zig/src/core/moe_route.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = with_metal }); - const draft_ops = b.createModule(.{ .root_source_file = b.path("zig/src/core/draft_ops.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ - .{ .name = "metal", .module = metal }, - .{ .name = "draft_ops_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/draft_ops_sources.zig") }) }, - } }); - const hash = b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize }); - const exe = b.addExecutable(.{ .name = "tf-hy4-speed", .root_module = b.createModule(.{ - .root_source_file = b.path("zig/src/families/hy4_flash/speed_probe.zig"), - .target = target, - .optimize = optimize, - .link_libc = true, - .imports = &.{ - .{ .name = "metal", .module = metal }, - .{ .name = "kernel_sources", .module = sources }, - .{ .name = "core", .module = core }, - .{ .name = "row_projection", .module = row }, - .{ .name = "lane_projection", .module = lane }, - .{ .name = "moe_route", .module = route }, - .{ .name = "draft_ops", .module = draft_ops }, - .{ .name = "engram_hash_core", .module = hash }, - }, - }) }); - b.step("tf-hy4-speed", "Hy4-flash Metal greedy decode: IDs, hash, ms a token, per-stage GPU profile").dependOn(&b.addInstallArtifact(exe, .{}).step); -} diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 945604c3101..464b822d4f0 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -420,7 +420,6 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s }) }); b.step("tf-row-check", "The core row projection on synthetic 4-bit matrices: widths bit-equal, a CPU reference, indexed experts").dependOn(&b.addInstallArtifact(row_check, .{}).step); core_checks.rowWidths(b, target, optimize, metal, row_mod); - @import("hy4_probe.zig").steps(b, target, optimize, metal, sources); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = row_mod })).step); core_checks.tileQmm(b, target, optimize, metal, sources, test_step); core_checks.kvPages(b, target, optimize, metal, sources, test_step); diff --git a/zig/hy4_engine/lane_projection.zig b/zig/hy4_engine/lane_projection.zig index ff748832bbb..9a338f95aa5 100644 --- a/zig/hy4_engine/lane_projection.zig +++ b/zig/hy4_engine/lane_projection.zig @@ -1,4 +1,4 @@ -//! The engine's lane_projection for the Hy4-flash family files, which import it by name (the speed probe builds it alone). +//! The engine's lane_projection for the Hy4-flash family files const m = @import("tensorfold").lane_projection; pub const frags = m.frags; pub const affine_mm = m.affine_mm; diff --git a/zig/hy4_engine/row_projection.zig b/zig/hy4_engine/row_projection.zig index 58391df883c..1a7945d8fcb 100644 --- a/zig/hy4_engine/row_projection.zig +++ b/zig/hy4_engine/row_projection.zig @@ -1,4 +1,4 @@ -//! The engine's row_projection for the Hy4-flash family files, which import it by name (the speed probe builds it alone). +//! The engine's row_projection for the Hy4-flash family files const m = @import("tensorfold").row_projection; pub const simd = m.simd; pub const simd_bits = m.simd_bits; diff --git a/zig/kernels/metal/core/lane_projection.metal b/zig/kernels/metal/core/lane_projection.metal index 277071cce7b..f8d2d071a83 100644 --- a/zig/kernels/metal/core/lane_projection.metal +++ b/zig/kernels/metal/core/lane_projection.metal @@ -15,8 +15,7 @@ using namespace mpp::tensor_ops; #ifndef TF_ROW_BLOCKS #define TF_ROW_BLOCKS 0 #endif -// Reg path: each split adds its rows' group sums itself (tf_lane_xsum, the sums pass's own loop), so no sums -// dispatch or barrier comes before the projection; the words are the same. +// 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 @@ -324,8 +323,7 @@ uint group_id [[simdgroup_index_in_threadgroup]],uint lane [[thread_index_in_sim #endif #if (TF_BITS == 4 || TF_BITS == 8) && defined(TF_REG) -// a lane's codes (4-bit: two quads; 8-bit: the same codes a byte each, four quads), its two metadata quads and its -// two row sums for one group +// 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; diff --git a/zig/kernels/metal/hy4_flash/engram.metal b/zig/kernels/metal/hy4_flash/engram.metal index 8a4eb7b2ef0..f0bbad8d76e 100644 --- a/zig/kernels/metal/hy4_flash/engram.metal +++ b/zig/kernels/metal/hy4_flash/engram.metal @@ -117,9 +117,7 @@ kernel void tf_hy4_engram_apply( } } -// Engram tables resident in GPU memory: each cell's affine code times its group's scale, plus the bias (two fp32 -// roundings, as the host's dequant does), rounded to BF16 ties-to-even as the host's gather writes it, so every -// placement stages the same bits. rows[token * 16 + column] = table row; out [token][column][96]; a.x bits, a.y cells. +// 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); diff --git a/zig/kernels/metal/hy4_flash/ihc.metal b/zig/kernels/metal/hy4_flash/ihc.metal index 0fb90dea616..6b982f31cfa 100644 --- a/zig/kernels/metal/hy4_flash/ihc.metal +++ b/zig/kernels/metal/hy4_flash/ihc.metal @@ -60,9 +60,7 @@ kernel void tf_hy4_ihc_collapse( } } -// tf_hy4_ihc_collapse with the gate count fixed at compile time: the same thread partition, fma chains, simd -// butterflies and partial sums in the same order, so the same bits, but the eight gate sums live in registers -// and the loads of an iteration issue together instead of through an indexed stack array. +// 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, @@ -119,10 +117,7 @@ inline void ihc_collapse_fixed( HY4_IHC_FIXED(4) HY4_IHC_FIXED(8) -// The same collapse in two launches. tf_hy4_ihc_partials runs each of the 256-thread version's eight simdgroups as -// its own threadgroup (simdgroup s on core s instead of all eight on one core): thread t = 32 s + lane keeps its -// stride-256 fma chain and butterfly, and lane 0 stores the simdgroup's sums as part[row][gate][s] (gate 8: sum of -// squares). tf_hy4_ihc_finish then adds the eight partials in the same order and writes the collapsed row. +// 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) { @@ -148,8 +143,7 @@ inline void ihc_partials_fixed(const device bfloat *hidden, const device float * } } -// Threadgroup `slice` of a row writes columns [256 slice, 256 slice + 256): every slice derives the same gates from -// the same partials in the same order, and slice 0 alone stores the post gates. +// 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, @@ -230,13 +224,7 @@ kernel void tf_hy4_draft_residual( out[o] = bfloat(float(base[i]) + float(branch[o])); } -// ---- Sub-block seams in two launches instead of five (decode and prompt alike) ---- -// tail: a sub-block's branch (one input, or two added in bfloat as the expert branches are) through its output RMS -// norm (bf16(x * inv) * gain, as the norm kernel rounds), mixed into the four residual streams with the post gates -// (rounded as tf_hy4_ihc_add), and, when the next collapse's weights are given, that collapse's fp32 partial sums -// over the mixed streams. 12 threadgroups of 256 threads a row, each element once; every threadgroup derives the norm -// scale itself from the branch row (6 KB) and stores its 19 sums at part[row][sum][tg] (16 slots a sum). -// mode 0: partials only of the given streams (no branch; after an Engram layer). +// ---- 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; }; @@ -250,8 +238,7 @@ inline float seam_tg_sum(float v, uint lane, uint sg, threadgroup float *scratch return total; } -// The 10 stream products sum_i m[s][i] m[u][i] (s <= u) a row, so the head gets the collapsed row's sum of squares -// as pre^T Gram pre instead of a second pass over the row: part[row][9 + k][tg]. +// 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; @@ -277,8 +264,7 @@ inline void ihc_tail(const device bfloat *branch, const device bfloat *branch2, 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; its stream - // order is the flat order's, so the gate sums keep their bits) + // 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; @@ -335,9 +321,7 @@ inline void ihc_tail(const device bfloat *branch, const device bfloat *branch2, } } -// head: the collapse's gates from the tail's partials (added over the 12 threadgroups in order), the collapsed row -// (as tf_hy4_ihc_finish), then the sub-block's input RMS norm with the row's sum of squares from the tail's stream -// products: 12 threadgroups of 256 a row, a column a thread, no pass over the whole row. +// 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, @@ -376,11 +360,7 @@ inline void ihc_head(const device bfloat *hidden, const device float *part, cons } } -// ---- tail and the next head in one launch (decode passes): the row's 12 threadgroups meet at an in-kernel barrier -// between them (all are resident: at most 16 rows a launch), so the head's gates and Gram sums come from every -// threadgroup's partials without a second launch. A thread owns one column (width 3072 = 12 x 256) and keeps its -// four mixed stream values in registers across the barrier. The partials cross threadgroups as device atomics. -// The same arithmetic as ihc_tail then ihc_head (the same sums in the same orders), so the same bits. +// ---- 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) { diff --git a/zig/kernels/metal/hy4_flash/index_build.metal b/zig/kernels/metal/hy4_flash/index_build.metal index fb63488a218..a54efbaa659 100644 --- a/zig/kernels/metal/hy4_flash/index_build.metal +++ b/zig/kernels/metal/hy4_flash/index_build.metal @@ -1,5 +1,4 @@ -// Hy4-flash's compressed indexer, the parts before scoring: each row's normalized token key into the layer's key -// cache, and each four-slot group's pooled, normalized key (fp32 inside, BF16 out; RoPE runs after, on the cache). +// Hy4-flash's compressed indexer, the parts before scoring #include using namespace metal; #pragma clang fp contract(off) @@ -15,8 +14,7 @@ inline ushort hy4_ix_round(float value) { 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, then -// times the BF16 gain (a BF16 product), written at the row's cache slot. +// 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)]], @@ -40,10 +38,7 @@ kernel void tf_hy4_index_keys( cache[ulong(slot) * 128 + t] = hy4_ix_round(hy4_ix_value(gain[t]) * normed); } -// One threadgroup of 128 a group (thread = output column): the four token keys through the fp32 value and gate -// projections ([out][in]), the slot softmax of the gates plus the intra-group position bias, the weighted sum, and -// the fp32 key norm, rounded to BF16 at the group's cache row. The four slots of a group are its tokens' cache -// slots 4g..4g+3. +// 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)]], diff --git a/zig/kernels/metal/hy4_flash/mla_attention.metal b/zig/kernels/metal/hy4_flash/mla_attention.metal index 4ad6ad5d72e..fef8fc07a54 100644 --- a/zig/kernels/metal/hy4_flash/mla_attention.metal +++ b/zig/kernels/metal/hy4_flash/mla_attention.metal @@ -85,11 +85,7 @@ kernel void tf_hy4_attend_merge( 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. tf_hy4_attend_scores computes every retained key's score with -// tf_hy4_attend_chunks's lane split, fma order and butterfly (so each score's bits are the same), 64 keys a -// simdgroup and four heads a threadgroup, all keys at once. tf_hy4_attend_scored then runs each chunk's online -// softmax over those scores in the original key order, the same recurrence step for step, and writes the same -// partials for tf_hy4_attend_merge. Scores: [row][head][key_stride] floats. +// Chunked attention in two steps. kernel void tf_hy4_attend_scores( const device ushort *query [[buffer(0)]], const device ushort *cache [[buffer(1)]], @@ -135,8 +131,7 @@ kernel void tf_hy4_attend_scored( 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: all 128 threads load 16 keys' latent rows into threadgroup - // memory together (one memory round trip a tile, not one a key), then each head steps through the tile. + // 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; @@ -147,8 +142,7 @@ kernel void tf_hy4_attend_scored( 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): running maxima by a prefix max across lanes (max is exact, so - // the same values as the key-by-key scan), each key's exponentials by the same formula on the same operands. + // 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; diff --git a/zig/kernels/metal/hy4_flash/mla_nax.metal b/zig/kernels/metal/hy4_flash/mla_nax.metal index aec151e524d..c075d70af0c 100644 --- a/zig/kernels/metal/hy4_flash/mla_nax.metal +++ b/zig/kernels/metal/hy4_flash/mla_nax.metal @@ -1,6 +1,4 @@ -// Hy4-flash's absorbed-MLA BF16 products on the tensor units (nax.h's 16x32x16 op): every row count runs the same -// tiles, so prompt chunks and decode rows get the same bits. One head a threadgroup column, 16 rows by 128 outputs a -// threadgroup (4 simdgroups of 16 x 32). +// Hy4-flash's absorbed-MLA BF16 products on the tensor units (nax.h's 16x32x16 op) #include "../nax.h" using namespace tfp; @@ -42,8 +40,7 @@ inline bfloat hy4n_round(float value) { } } -// values[r][h][0, 256) = gate(latent[r][h][0, 512) W_UV[h]^T), W_UV[h] stored [256][512]; the gate as -// tf_hy4_gate_values: the value rounded, times its rounded sigmoid, rounded. +// 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]], @@ -75,17 +72,11 @@ inline bfloat hy4n_round(float value) { } } -// Absorbed MLA attention on the tensor units, flash style: one head and 16 query rows a threadgroup, 32-key tiles at -// absolute key indices (so a row's tiles and their order are its own, whatever rows share its block; tiles outside a -// row's range are exact no-ops for it). S = Q K^T with the 576 key columns split over the 4 simdgroups and their -// partials added in a fixed order; an online softmax a row; O += P V with each simdgroup owning 128 latent columns; -// the learned sink joins at the end. ranges[r] = [lo, hi) key indices; tiles[t] = the slot of key index 32 t (a -// tile's 32 slots are consecutive). +// 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 -// unnormalized O, running max and sum (fp32) for tf_hy4_attend_combine instead of the sink and the division. 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, @@ -255,8 +246,7 @@ inline void hy4_attend_nax(const device bfloat* query, const device bfloat* cach 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: out = sum_z O_z e^(m_z - M) / L, -// L = sum_z l_z e^(m_z - M) + e^(sink - M), M the largest of the maxima and the sink. Grid (heads, rows), 128 threads. +// 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]], diff --git a/zig/kernels/metal/hy4_flash/mla_project.metal b/zig/kernels/metal/hy4_flash/mla_project.metal index c9b471ba25b..f44055f5262 100644 --- a/zig/kernels/metal/hy4_flash/mla_project.metal +++ b/zig/kernels/metal/hy4_flash/mla_project.metal @@ -133,8 +133,7 @@ kernel void tf_hy4_expand_v( expanded[ulong(row_head) * 256 + column] = hy4_mla_round(sum); } -// tf_hy4_expand_v then tf_hy4_gate_values in one launch: the expanded value rounded as before, then gated by the -// rounded sigmoid of its logit exactly as the gate pass does, so the same bits without the second pass. +// 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)]], diff --git a/zig/kernels/metal/hy4_flash/route_rows.metal b/zig/kernels/metal/hy4_flash/route_rows.metal index 77e01bab580..0dffb2a0954 100644 --- a/zig/kernels/metal/hy4_flash/route_rows.metal +++ b/zig/kernels/metal/hy4_flash/route_rows.metal @@ -1,7 +1,5 @@ -// Appended to the core router source (its TF_E, TF_TOPK, PER, RouteArgs and tf_sigmoid_precise). A prompt chunk's -// picks and weights: tf_route_select's per-row top-k (sigmoid + bias, ties to the lower id, weights normalized and -// scaled) step for step, one simdgroup a row and a threadgroup per row, so every row runs at once. +// 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]], @@ -43,10 +41,7 @@ } } -// tf_hy4_route_select_rows as ranks: one thread an expert (TF_E <= 512, threadgroup 512), each expert's rank the -// count of experts ahead of it (larger sigmoid + bias, ties to the lower id), so the top-k write themselves in pick -// order; then the weights normalized in that order as the loop does. The same picks, order and weights (same -// sigmoid, same sums), without the k sequential arg-max rounds. +// 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]], diff --git a/zig/kernels/metal/hy4_flash/rows.metal b/zig/kernels/metal/hy4_flash/rows.metal index c99237e2563..74bc8e330a3 100644 --- a/zig/kernels/metal/hy4_flash/rows.metal +++ b/zig/kernels/metal/hy4_flash/rows.metal @@ -1,8 +1,5 @@ // Hy4-flash lane windows (compiled after the chip's core row projection source, whose helpers it calls). -// Each output column's per-row arithmetic is tf_rp_rows's, as in the plain and wide kernels, so rows give the same -// bits however many share a pass. Here every weight is read once for up to 8 rows, with RPS columns a simdgroup and -// SG simdgroups a threadgroup, and no 64-thread cap, so a 2- to 8-row window costs about what one row does. 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, @@ -15,7 +12,6 @@ inline void tf_hy4_rows_block(const device uint8_t* wr, const device bfloat* sr, } // dims: K, N, GS, rows (as tf_row_projection). X [rows, K]; W [N, K*BITS/32] words; S, B [N, K/GS]. -// SH: 3+ row blocks unpack each code once for all their rows (the core's shared branch) instead of once a pair. 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)]], @@ -58,7 +54,6 @@ template [[host_name("tf_hy4_rows_r1_q4")]] [[kernel]] decltype(tf_hy4_rows<1, 8 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. -// a.x: vocabulary, a.y: where row 0's token goes in OUT. [[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]], @@ -89,682 +84,3 @@ template [[host_name("tf_hy4_rows_r1_q8")]] [[kernel]] decltype(tf_hy4_rows<1, 8 if (lane == 0) out[a.y + row] = id; } } - -// tf_add_bf16 (A + B in bfloat) feeding tf_draft_rms in one launch: the routed and shared expert branches summed as -// each norm thread reads them, with the norm's thread split, sums and roundings, so the same bits and no add pass. -struct Hy4Norm { uint rows, heads, dim, x_stride, y_stride, round_normalized; float eps; }; -[[kernel]] void tf_hy4_add_rms(device const bfloat* A [[buffer(0)]], device const bfloat* B [[buffer(1)]], - device const bfloat* W [[buffer(2)]], constant Hy4Norm& a [[buffer(3)]], - device bfloat* Y [[buffer(4)]], uint2 block [[threadgroup_position_in_grid]], - uint t [[thread_index_in_threadgroup]], uint sg [[simdgroup_index_in_threadgroup]], - uint lane [[thread_index_in_simdgroup]], uint2 threads [[threads_per_threadgroup]]) { - threadgroup float sums[32], inverse[1]; - float value = 0.0f; - const size_t base = size_t(block.y) * a.x_stride + block.x * a.dim; - for (uint first = 4 * t; first < a.dim; first += 4 * threads.x) - for (uint j = 0; j < 4 && first + j < a.dim; j++) { - const bfloat s = A[base + first + j] + B[base + first + j]; - float x = float(s); - value += x * x; - } - value = simd_sum(value); - if (sg == 0) sums[lane] = 0.0f; - threadgroup_barrier(mem_flags::mem_threadgroup); - if (lane == 0) sums[sg] = value; - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg == 0) { - float total = simd_sum(sums[lane]); - if (lane == 0) inverse[0] = precise::rsqrt(total / float(a.dim) + a.eps); - } - threadgroup_barrier(mem_flags::mem_threadgroup); - for (uint first = 4 * t; first < a.dim; first += 4 * threads.x) - for (uint j = 0; j < 4 && first + j < a.dim; j++) { - const uint col = first + j; - const bfloat s = A[base + col] + B[base + col]; - float normalized = float(s) * inverse[0]; - normalized = float(bfloat(normalized)); - Y[size_t(block.y) * a.y_stride + block.x * a.dim + col] = bfloat(normalized * float(W[col])); - } -} - -// Decode-sized passes (1-8 rows) of an MLX-affine 4- or 8-bit [n, k] matrix (groups of 64): fp32 sums, each weight -// read once with 16-byte loads. A simdgroup owns QR output columns; lane l takes 32 consecutive inputs of every -// 1024 (half a group): it holds those columns' weight words, scales and biases, then streams each row's 32 inputs -// through them. y[r][n] = sum over groups of scale * (x . q) + bias * sum(x). dims: K, N, GS (64), rows. -template -[[kernel]] void tf_hy4_qmv(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], rows = min(dims[3], 8); - constexpr int SG = 4, WPL = 32 * BITS / 32; // weight words a lane takes a step (4 at 4 bits, 8 at 8) - const int col0 = (int(tg.x) * SG + int(sg)) * QR; - if (col0 >= N) return; - const int words_row = K * BITS / 32, groups_row = K / 64; - float acc[8][QR]; - for (int r = 0; r < 8; ++r) - for (int j = 0; j < QR; ++j) acc[r][j] = 0.0f; - for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { - uint w[QR][WPL]; - float scale[QR], bias[QR]; - const int g = k0 / 64; - for (int j = 0; j < QR; ++j) { - const int n = col0 + j; - const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); - for (int v = 0; v < WPL / 4; ++v) { - const uint4 w4 = wp[v]; - w[j][4 * v] = w4.x; w[j][4 * v + 1] = w4.y; w[j][4 * v + 2] = w4.z; w[j][4 * v + 3] = w4.w; - } - scale[j] = float(S[size_t(n) * groups_row + g]); - bias[j] = float(B[size_t(n) * groups_row + g]); - } - for (int r = 0; r < rows; ++r) { - const device uint4* xp = (const device uint4*)(X + size_t(r) * K + k0); - float dot[QR]; - for (int j = 0; j < QR; ++j) dot[j] = 0.0f; - float xsum = 0.0f; - for (int v = 0; v < 4; ++v) { - const uint4 x4 = xp[v]; - const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; - for (int u = 0; u < 4; ++u) { - const int i = v * 8 + u * 2; // input index within the lane's 32 - const float x0 = as_type(xw[u] << 16), x1 = as_type(xw[u] & 0xffff0000u); - xsum += x0 + x1; - for (int j = 0; j < QR; ++j) { - float q0, q1; - if (BITS == 4) { - const uint word = w[j][i / 8]; - q0 = float((word >> (4 * (i % 8))) & 0xfu); - q1 = float((word >> (4 * (i % 8 + 1))) & 0xfu); - } else { - const uint word = w[j][i / 4]; - q0 = float((word >> (8 * (i % 4))) & 0xffu); - q1 = float((word >> (8 * (i % 4 + 1))) & 0xffu); - } - dot[j] = fma(x1, q1, fma(x0, q0, dot[j])); - } - } - } - for (int j = 0; j < QR; ++j) acc[r][j] = fma(scale[j], dot[j], fma(bias[j], xsum, acc[r][j])); - } - } - for (int r = 0; r < rows; ++r) { - for (int j = 0; j < QR; ++j) { - const float v = simd_sum(acc[r][j]); - if (lane == 0) OUT[size_t(r) * N + col0 + j] = bfloat(v); - } - } -} - -template [[host_name("tf_hy4_qmv_q4")]] [[kernel]] decltype(tf_hy4_qmv<4, 4>) tf_hy4_qmv<4, 4>; -template [[host_name("tf_hy4_qmv_q8")]] [[kernel]] decltype(tf_hy4_qmv<8, 4>) tf_hy4_qmv<8, 4>; - -// tf_hy4_qmv with the weights unpacked once a step for every row: two output columns a simdgroup, their 64 codes -// as floats in registers, each row's 32 inputs streamed past them (multi-row passes pay one unpack, not one a row). -template -[[kernel]] void tf_hy4_qmv2(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], rows = min(dims[3], 8); - constexpr int SG = 4, QR = 2, WPL = BITS; - const int col0 = (int(tg.x) * SG + int(sg)) * QR; - if (col0 >= N) return; - const int words_row = K * BITS / 32, groups_row = K / 64; - float acc[8][QR]; - for (int r = 0; r < 8; ++r) - for (int j = 0; j < QR; ++j) acc[r][j] = 0.0f; - for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { - float q[QR][32]; - float scale[QR], bias[QR]; - const int g = k0 / 64; - for (int j = 0; j < QR; ++j) { - const int n = col0 + j; - const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); - for (int v = 0; v < WPL / 4; ++v) { - const uint4 w4 = wp[v]; - const uint words[4] = {w4.x, w4.y, w4.z, w4.w}; - for (int u = 0; u < 4; ++u) { - if (BITS == 4) { - for (int b = 0; b < 8; ++b) q[j][(v * 4 + u) * 8 + b] = float((words[u] >> (4 * b)) & 0xfu); - } else { - for (int b = 0; b < 4; ++b) q[j][(v * 4 + u) * 4 + b] = float((words[u] >> (8 * b)) & 0xffu); - } - } - } - scale[j] = float(S[size_t(n) * groups_row + g]); - bias[j] = float(B[size_t(n) * groups_row + g]); - } - for (int r = 0; r < rows; ++r) { - const device uint4* xp = (const device uint4*)(X + size_t(r) * K + k0); - float dot[QR] = {0.0f, 0.0f}; - float xsum = 0.0f; - for (int v = 0; v < 4; ++v) { - const uint4 x4 = xp[v]; - const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; - for (int u = 0; u < 4; ++u) { - const int i = v * 8 + u * 2; - const float x0 = as_type(xw[u] << 16), x1 = as_type(xw[u] & 0xffff0000u); - xsum += x0 + x1; - for (int j = 0; j < QR; ++j) dot[j] = fma(x1, q[j][i + 1], fma(x0, q[j][i], dot[j])); - } - } - for (int j = 0; j < QR; ++j) acc[r][j] = fma(scale[j], dot[j], fma(bias[j], xsum, acc[r][j])); - } - } - for (int r = 0; r < rows; ++r) - for (int j = 0; j < QR; ++j) { - const float v = simd_sum(acc[r][j]); - if (lane == 0) OUT[size_t(r) * N + col0 + j] = bfloat(v); - } -} - -template [[host_name("tf_hy4_qmv2_q4")]] [[kernel]] decltype(tf_hy4_qmv2<4>) tf_hy4_qmv2<4>; -template [[host_name("tf_hy4_qmv2_q8")]] [[kernel]] decltype(tf_hy4_qmv2<8>) tf_hy4_qmv2<8>; - -// tf_hy4_qmv2 for decode passes with the row count fixed at compile time (R = 1 to 4) and QR output columns a -// simdgroup: each lane's 32 inputs are read once for QR columns, and the QR weight loads of a step issue together. -// The same sums per (row, column) as tf_hy4_qmv2 (fma over the 32 codes in order, then scale and bias, then the -// simdgroup sum), so the same bits. -template -[[kernel]] void tf_hy4_qmv3(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]; - constexpr int SG = 4; - const int col0 = (int(tg.x) * SG + int(sg)) * QR; - if (col0 >= N) return; - const int words_row = K * BITS / 32, groups_row = K / 64; - float acc[R][QR]; - for (int r = 0; r < R; ++r) - for (int j = 0; j < QR; ++j) acc[r][j] = 0.0f; - for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { - const int g = k0 / 64; - uint4 wv[QR][BITS / 4]; - float scale[QR], bias[QR]; - for (int j = 0; j < QR; ++j) { - const int n = col0 + j; - const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); - for (int v = 0; v < BITS / 4; ++v) wv[j][v] = wp[v]; - scale[j] = float(S[size_t(n) * groups_row + g]); - bias[j] = float(B[size_t(n) * groups_row + g]); - } - for (int r = 0; r < R; ++r) { - const device uint4* xp = (const device uint4*)(X + size_t(r) * K + k0); - float xs[32]; - float xsum = 0.0f; - for (int v = 0; v < 4; ++v) { - const uint4 x4 = xp[v]; - const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; - for (int u = 0; u < 4; ++u) { - xs[v * 8 + u * 2] = as_type(xw[u] << 16); - xs[v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); - xsum += xs[v * 8 + u * 2] + xs[v * 8 + u * 2 + 1]; - } - } - for (int j = 0; j < QR; ++j) { - float dot = 0.0f; - for (int v = 0; v < BITS / 4; ++v) { - const uint words[4] = {wv[j][v].x, wv[j][v].y, wv[j][v].z, wv[j][v].w}; - for (int u = 0; u < 4; ++u) { - if (BITS == 4) { - for (int b = 0; b < 8; ++b) dot = fma(xs[(v * 4 + u) * 8 + b], float((words[u] >> (4 * b)) & 0xfu), dot); - } else { - for (int b = 0; b < 4; ++b) dot = fma(xs[(v * 4 + u) * 4 + b], float((words[u] >> (8 * b)) & 0xffu), dot); - } - } - } - acc[r][j] = fma(scale[j], dot, fma(bias[j], xsum, acc[r][j])); - } - } - } - for (int r = 0; r < R; ++r) - for (int j = 0; j < QR; ++j) { - const float v = simd_sum(acc[r][j]); - if (lane == 0) OUT[size_t(r) * N + col0 + j] = bfloat(v); - } -} - -template [[host_name("tf_hy4_qmv3_r1_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 1, 4>) tf_hy4_qmv3<4, 1, 4>; -template [[host_name("tf_hy4_qmv3_r2_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 2, 4>) tf_hy4_qmv3<4, 2, 4>; -template [[host_name("tf_hy4_qmv3_r1_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 1, 4>) tf_hy4_qmv3<8, 1, 4>; -template [[host_name("tf_hy4_qmv3_r2_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 2, 4>) tf_hy4_qmv3<8, 2, 4>; -template [[host_name("tf_hy4_qmv3_r3_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 3, 4>) tf_hy4_qmv3<4, 3, 4>; -template [[host_name("tf_hy4_qmv3_r4_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 4, 4>) tf_hy4_qmv3<4, 4, 4>; -template [[host_name("tf_hy4_qmv3_r3_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 3, 4>) tf_hy4_qmv3<8, 3, 4>; -template [[host_name("tf_hy4_qmv3_r4_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 4, 4>) tf_hy4_qmv3<8, 4, 4>; -template [[host_name("tf_hy4_qmv3x8_r1_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 1, 8>) tf_hy4_qmv3<4, 1, 8>; -template [[host_name("tf_hy4_qmv3x8_r2_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 2, 8>) tf_hy4_qmv3<4, 2, 8>; -template [[host_name("tf_hy4_qmv3x8_r1_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 1, 8>) tf_hy4_qmv3<8, 1, 8>; -template [[host_name("tf_hy4_qmv3x8_r2_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 2, 8>) tf_hy4_qmv3<8, 2, 8>; -template [[host_name("tf_hy4_qmv3x8_r3_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 3, 8>) tf_hy4_qmv3<4, 3, 8>; -template [[host_name("tf_hy4_qmv3x8_r4_q4")]] [[kernel]] decltype(tf_hy4_qmv3<4, 4, 8>) tf_hy4_qmv3<4, 4, 8>; -template [[host_name("tf_hy4_qmv3x8_r3_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 3, 8>) tf_hy4_qmv3<8, 3, 8>; -template [[host_name("tf_hy4_qmv3x8_r4_q8")]] [[kernel]] decltype(tf_hy4_qmv3<8, 4, 8>) tf_hy4_qmv3<8, 4, 8>; - -// ---- Routed experts for 1-2 row passes: each (row, pick) pair's gate/up and down as GEMVs over that expert's -// MLX-layout matrices (fp32 sums, each weight read once), the clipped SwiGLU rounded as the tensor gather's epilogue. -struct Hy4ExpertShape { uint pairs, picks, k, n; float limit; }; - -// QR = 2 output columns a simdgroup: their codes unpacked once a step, the row's 32 inputs a lane streamed past. -template -inline void hy4_qmv_cols2(const device bfloat* x, const device uint32_t* W, const device bfloat* S, - const device bfloat* B, int K, int col0, uint lane, thread float (&acc)[2]) { - const int words_row = K * BITS / 32, groups_row = K / 64; - acc[0] = 0.0f; acc[1] = 0.0f; - for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { - const int g = k0 / 64; - const device uint4* xp = (const device uint4*)(x + k0); - float xs[32]; - float xsum = 0.0f; - for (int v = 0; v < 4; ++v) { - const uint4 x4 = xp[v]; - const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; - for (int u = 0; u < 4; ++u) { - xs[v * 8 + u * 2] = as_type(xw[u] << 16); - xs[v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); - xsum += xs[v * 8 + u * 2] + xs[v * 8 + u * 2 + 1]; - } - } - for (int j = 0; j < 2; ++j) { - const int n = col0 + j; - const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); - float dot = 0.0f; - for (int v = 0; v < BITS / 4; ++v) { - const uint4 w4 = wp[v]; - const uint words[4] = {w4.x, w4.y, w4.z, w4.w}; - for (int u = 0; u < 4; ++u) { - if (BITS == 4) { - for (int b = 0; b < 8; ++b) dot = fma(xs[(v * 4 + u) * 8 + b], float((words[u] >> (4 * b)) & 0xfu), dot); - } else { - for (int b = 0; b < 4; ++b) dot = fma(xs[(v * 4 + u) * 4 + b], float((words[u] >> (8 * b)) & 0xffu), dot); - } - } - } - acc[j] = fma(float(S[size_t(n) * groups_row + g]), dot, fma(float(B[size_t(n) * groups_row + g]), xsum, acc[j])); - } - } - acc[0] = simd_sum(acc[0]); - acc[1] = simd_sum(acc[1]); -} - -inline bfloat hy4_expert_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)); - const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); - return sl * up; -} - -// act[pair][n] = swiglu(gate_e x_row, up_e x_row); x = latent [rows][k]; grid (n / 8, pairs), 4 simdgroups. -template -[[kernel]] void tf_hy4_expert_glu(const device bfloat* latent [[buffer(0)]], const device int* pick [[buffer(1)]], - const device uint32_t* GW [[buffer(2)]], const device bfloat* GS [[buffer(3)]], - const device bfloat* GB [[buffer(4)]], const device uint32_t* UW [[buffer(5)]], - const device bfloat* US [[buffer(6)]], const device bfloat* UB [[buffer(7)]], - device bfloat* act [[buffer(8)]], constant Hy4ExpertShape& a [[buffer(9)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint3 tg [[threadgroup_position_in_grid]]) { - const uint p = tg.y; - if (p >= a.pairs) return; - const int col0 = (int(tg.x) * 4 + int(sg)) * 2; - if (col0 >= int(a.n)) return; - const int K = int(a.k), N = int(a.n); - const ulong e = ulong(pick[p]); - const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); - const device bfloat* x = latent + ulong(p / a.picks) * K; - float g[2], u[2]; - hy4_qmv_cols2(x, GW + e * wstride, GS + e * sstride, GB + e * sstride, K, col0, lane, g); - hy4_qmv_cols2(x, UW + e * wstride, US + e * sstride, UB + e * sstride, K, col0, lane, u); - if (lane == 0) - for (int j = 0; j < 2; ++j) act[ulong(p) * N + col0 + j] = hy4_expert_swiglu(g[j], u[j], a.limit); -} - -// out[pair][n] (fp32) = down_e act[pair]; grid (n / 8, pairs). -template -[[kernel]] void tf_hy4_expert_down(const device bfloat* act [[buffer(0)]], const device int* pick [[buffer(1)]], - const device uint32_t* DW [[buffer(2)]], const device bfloat* DS [[buffer(3)]], - const device bfloat* DB [[buffer(4)]], device float* out [[buffer(5)]], - constant Hy4ExpertShape& a [[buffer(6)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint3 tg [[threadgroup_position_in_grid]]) { - const uint p = tg.y; - if (p >= a.pairs) return; - const int col0 = (int(tg.x) * 4 + int(sg)) * 2; - if (col0 >= int(a.n)) return; - const int K = int(a.k), N = int(a.n); - const ulong e = ulong(pick[p]); - const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); - float d[2]; - hy4_qmv_cols2(act + ulong(p) * K, DW + e * wstride, DS + e * sstride, DB + e * sstride, K, col0, lane, d); - if (lane == 0) - for (int j = 0; j < 2; ++j) out[ulong(p) * N + col0 + j] = d[j]; -} - -// tf_hy4_expert_down with tf_hy4_routed_sum folded in: threadgroup (column block, row) takes the row's picks in -// order and adds weight * down(act) as the routed sum does (fma in slot order), writing the bf16 weighted row. -// The same bits as the two launches, without the fp32 pair outputs. -template -[[kernel]] void tf_hy4_expert_down_sum(const device bfloat* act [[buffer(0)]], const device int* pick [[buffer(1)]], - const device uint32_t* DW [[buffer(2)]], const device bfloat* DS [[buffer(3)]], - const device bfloat* DB [[buffer(4)]], device bfloat* weighted [[buffer(5)]], - constant Hy4ExpertShape& a [[buffer(6)]], const device float* wts [[buffer(7)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint3 tg [[threadgroup_position_in_grid]]) { - const uint r = tg.y; - if (r * a.picks >= a.pairs) return; - const int col0 = (int(tg.x) * 4 + int(sg)) * 2; - if (col0 >= int(a.n)) return; - const int K = int(a.k), N = int(a.n); - const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); - float sum[2] = {0.0f, 0.0f}; - for (uint slot = 0; slot < a.picks; ++slot) { - const uint p = r * a.picks + slot; - const ulong e = ulong(pick[p]); - float d[2]; - hy4_qmv_cols2(act + ulong(p) * K, DW + e * wstride, DS + e * sstride, DB + e * sstride, K, col0, lane, d); - const float w = wts[p]; - sum[0] = fma(w, d[0], sum[0]); - sum[1] = fma(w, d[1], sum[1]); - } - if (lane == 0) - for (int j = 0; j < 2; ++j) weighted[ulong(r) * N + col0 + j] = bfloat(sum[j]); -} - -template [[host_name("tf_hy4_expert_down_sum_q4")]] [[kernel]] decltype(tf_hy4_expert_down_sum<4>) tf_hy4_expert_down_sum<4>; -template [[host_name("tf_hy4_expert_down_sum_q8")]] [[kernel]] decltype(tf_hy4_expert_down_sum<8>) tf_hy4_expert_down_sum<8>; - -template [[host_name("tf_hy4_expert_glu_q4")]] [[kernel]] decltype(tf_hy4_expert_glu<4>) tf_hy4_expert_glu<4>; -template [[host_name("tf_hy4_expert_glu_q8")]] [[kernel]] decltype(tf_hy4_expert_glu<8>) tf_hy4_expert_glu<8>; -template [[host_name("tf_hy4_expert_down_q4")]] [[kernel]] decltype(tf_hy4_expert_down<4>) tf_hy4_expert_down<4>; -template [[host_name("tf_hy4_expert_down_q8")]] [[kernel]] decltype(tf_hy4_expert_down<8>) tf_hy4_expert_down<8>; - -// ---- Routed experts for 3-16 row passes, grouped by expert: the router window's jobs (ids[j], member pairs at -// members[j * 16 ..], -1 padded, count[0] jobs), each active expert's codes unpacked once for all its member rows. -// A member row's sums run in hy4_qmv_cols2's order, so every pair's result equals the 1-2 row path's bits. -template -inline void hy4_qmv_cols2_group(const device bfloat* x0, thread const int (&xrow)[M], int count, int ldx, - const device uint32_t* W, const device bfloat* S, const device bfloat* B, int K, - int col0, uint lane, thread float (&acc)[M][2]) { - const int words_row = K * BITS / 32, groups_row = K / 64; - for (int m = 0; m < M; ++m) { acc[m][0] = 0.0f; acc[m][1] = 0.0f; } - for (int k0 = int(lane) * 32; k0 < K; k0 += 1024) { - const int g = k0 / 64; - float q[2][32]; - float sc[2], bi[2]; - for (int j = 0; j < 2; ++j) { - const int n = col0 + j; - const device uint4* wp = (const device uint4*)(W + size_t(n) * words_row + k0 * BITS / 32); - for (int v = 0; v < BITS / 4; ++v) { - const uint4 w4 = wp[v]; - const uint words[4] = {w4.x, w4.y, w4.z, w4.w}; - for (int u = 0; u < 4; ++u) { - if (BITS == 4) { - for (int b = 0; b < 8; ++b) q[j][(v * 4 + u) * 8 + b] = float((words[u] >> (4 * b)) & 0xfu); - } else { - for (int b = 0; b < 4; ++b) q[j][(v * 4 + u) * 4 + b] = float((words[u] >> (8 * b)) & 0xffu); - } - } - } - sc[j] = float(S[size_t(n) * groups_row + g]); - bi[j] = float(B[size_t(n) * groups_row + g]); - } - for (int m = 0; m < M; ++m) { - if (m >= count) break; - const device uint4* xp = (const device uint4*)(x0 + size_t(xrow[m]) * ldx + k0); - float xs[32]; - float xsum = 0.0f; - for (int v = 0; v < 4; ++v) { - const uint4 x4 = xp[v]; - const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; - for (int u = 0; u < 4; ++u) { - xs[v * 8 + u * 2] = as_type(xw[u] << 16); - xs[v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); - xsum += xs[v * 8 + u * 2] + xs[v * 8 + u * 2 + 1]; - } - } - for (int j = 0; j < 2; ++j) { - float dot = 0.0f; - for (int i = 0; i < 32; ++i) dot = fma(xs[i], q[j][i], dot); - acc[m][j] = fma(sc[j], dot, fma(bi[j], xsum, acc[m][j])); - } - } - } - for (int m = 0; m < M; ++m) { - if (m >= count) break; - acc[m][0] = simd_sum(acc[m][0]); - acc[m][1] = simd_sum(acc[m][1]); - } -} - -// act[pair][n] for every member pair of job tg.y; grid (n / 8, job bound), 4 simdgroups. -template -[[kernel]] void tf_hy4_expert_glu_groups(const device bfloat* latent [[buffer(0)]], const device int* ids [[buffer(1)]], - const device int* members [[buffer(2)]], const device int* count [[buffer(3)]], - const device uint32_t* GW [[buffer(4)]], const device bfloat* GS [[buffer(5)]], - const device bfloat* GB [[buffer(6)]], const device uint32_t* UW [[buffer(7)]], - const device bfloat* US [[buffer(8)]], const device bfloat* UB [[buffer(9)]], - device bfloat* act [[buffer(10)]], constant Hy4ExpertShape& a [[buffer(11)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint3 tg [[threadgroup_position_in_grid]]) { - const int job = int(tg.y); - if (job >= count[0]) return; - const int col0 = (int(tg.x) * 4 + int(sg)) * 2; - if (col0 >= int(a.n)) return; - const int K = int(a.k), N = int(a.n); - const ulong e = ulong(ids[job]); - const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); - const device int* mem = members + job * 16; - for (int c0 = 0; c0 < 16; c0 += M) { - int pair[M], xrow[M]; - int n = 0; - for (int m = 0; m < M; ++m) { - const int p = mem[c0 + m]; - pair[m] = p; - xrow[m] = p >= 0 ? p / int(a.picks) : 0; - n += p >= 0 ? 1 : 0; - } - if (n == 0) break; - float g[M][2], u[M][2]; - hy4_qmv_cols2_group(latent, xrow, n, K, GW + e * wstride, GS + e * sstride, GB + e * sstride, K, col0, lane, g); - hy4_qmv_cols2_group(latent, xrow, n, K, UW + e * wstride, US + e * sstride, UB + e * sstride, K, col0, lane, u); - if (lane == 0) - for (int m = 0; m < M; ++m) { - if (m >= n) break; - for (int j = 0; j < 2; ++j) act[ulong(pair[m]) * N + col0 + j] = hy4_expert_swiglu(g[m][j], u[m][j], a.limit); - } - if (n < M) break; - } -} - -// out[pair][n] (fp32) = down_e act[pair] for every member pair of job tg.y; grid (n / 8, job bound). -template -[[kernel]] void tf_hy4_expert_down_groups(const device bfloat* act [[buffer(0)]], const device int* ids [[buffer(1)]], - const device int* members [[buffer(2)]], const device int* count [[buffer(3)]], - const device uint32_t* DW [[buffer(4)]], const device bfloat* DS [[buffer(5)]], - const device bfloat* DB [[buffer(6)]], device float* out [[buffer(7)]], - constant Hy4ExpertShape& a [[buffer(8)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint3 tg [[threadgroup_position_in_grid]]) { - const int job = int(tg.y); - if (job >= count[0]) return; - const int col0 = (int(tg.x) * 4 + int(sg)) * 2; - if (col0 >= int(a.n)) return; - const int K = int(a.k), N = int(a.n); - const ulong e = ulong(ids[job]); - const ulong wstride = ulong(N) * (K * BITS / 32), sstride = ulong(N) * (K / 64); - const device int* mem = members + job * 16; - for (int c0 = 0; c0 < 16; c0 += M) { - int pair[M]; - int n = 0; - for (int m = 0; m < M; ++m) { - const int p = mem[c0 + m]; - pair[m] = p >= 0 ? p : 0; - n += p >= 0 ? 1 : 0; - } - if (n == 0) break; - float d[M][2]; - hy4_qmv_cols2_group(act, pair, n, K, DW + e * wstride, DS + e * sstride, DB + e * sstride, K, col0, lane, d); - if (lane == 0) - for (int m = 0; m < M; ++m) { - if (m >= n) break; - for (int j = 0; j < 2; ++j) out[ulong(pair[m]) * N + col0 + j] = d[m][j]; - } - if (n < M) break; - } -} - -template [[host_name("tf_hy4_expert_glu_groups_q4")]] [[kernel]] decltype(tf_hy4_expert_glu_groups<4, 4>) tf_hy4_expert_glu_groups<4, 4>; -template [[host_name("tf_hy4_expert_glu_groups_q8")]] [[kernel]] decltype(tf_hy4_expert_glu_groups<8, 4>) tf_hy4_expert_glu_groups<8, 4>; -template [[host_name("tf_hy4_expert_down_groups_q4")]] [[kernel]] decltype(tf_hy4_expert_down_groups<4, 4>) tf_hy4_expert_down_groups<4, 4>; -template [[host_name("tf_hy4_expert_down_groups_q8")]] [[kernel]] decltype(tf_hy4_expert_down_groups<8, 4>) tf_hy4_expert_down_groups<8, 4>; - -// ---- MLA absorb and expand-and-gate for 1-4 row passes over kv_b's affine codes: per head 448 rows (192 key, -// then 256 value), each 512 latent values in groups of 64; w = fma(scale, code, bias) in fp32 as read. ---- -struct Hy4MlaQArgs { uint rows, heads; }; - -// absorbed[row][head][c] (c < 512, stride 576) = sum_d query[row][head][d] * key[head][d][c], d < 192. -// Grid (2 halves of 256 columns, heads), 8 simdgroups splitting d (rows d = sg + 8 i, four loads in flight a step); -// a lane holds 8 adjacent columns; the 8 partials meet in two threadgroup steps in a fixed order. -template -[[kernel]] void tf_hy4_absorb_qmv(const device bfloat* query [[buffer(0)]], const device uint32_t* W [[buffer(1)]], - const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], - device bfloat* absorbed [[buffer(4)]], constant Hy4MlaQArgs& a [[buffer(5)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint t [[thread_index_in_threadgroup]], uint3 tg [[threadgroup_position_in_grid]]) { - constexpr int R = 4, SG = 8, D = 192, U = 4, WPR = 512 * BITS / 32; - const int h = int(tg.y), heads = int(a.heads), rows = min(int(a.rows), R); - const int c0 = int(tg.x) * 256 + int(lane) * 8, g = c0 / 64; - threadgroup float qs[R][D]; - threadgroup float part[SG / 2][R][256]; - for (int i = int(t); i < rows * D; i += SG * 32) { - const int r = i / D, d = i % D; - qs[r][d] = float(query[(ulong(r) * heads + h) * 256 + d]); - } - threadgroup_barrier(mem_flags::mem_threadgroup); - float acc[R][8]; - for (int r = 0; r < R; ++r) - for (int k = 0; k < 8; ++k) acc[r][k] = 0.0f; - const ulong base = ulong(h) * 448; - for (int d0 = int(sg); d0 < D; d0 += SG * U) { - uint2 words[U]; - float s[U], b[U]; - for (int u = 0; u < U; ++u) { - const ulong row = base + d0 + SG * u; - if (BITS == 4) words[u] = uint2(W[row * WPR + c0 / 8], 0u); - else words[u] = *(const device uint2*)(W + row * WPR + c0 / 4); - s[u] = float(S[row * 8 + g]); - b[u] = float(B[row * 8 + g]); - } - for (int u = 0; u < U; ++u) { - float w[8]; - if (BITS == 4) { - for (int k = 0; k < 8; ++k) w[k] = fma(s[u], float((words[u].x >> (4 * k)) & 0xfu), b[u]); - } else { - for (int k = 0; k < 4; ++k) { - w[k] = fma(s[u], float((words[u].x >> (8 * k)) & 0xffu), b[u]); - w[4 + k] = fma(s[u], float((words[u].y >> (8 * k)) & 0xffu), b[u]); - } - } - const int d = d0 + SG * u; - for (int r = 0; r < R; ++r) { - if (r >= rows) break; - const float q = qs[r][d]; - for (int k = 0; k < 8; ++k) acc[r][k] = fma(q, w[k], acc[r][k]); - } - } - } - // simdgroups 4-7 hand theirs to 0-3, which then hold the pair sums - if (sg >= SG / 2) - for (int r = 0; r < R; ++r) { - if (r >= rows) break; - for (int k = 0; k < 8; ++k) part[sg - SG / 2][r][lane * 8 + k] = acc[r][k]; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg < SG / 2) - for (int r = 0; r < R; ++r) { - if (r >= rows) break; - for (int k = 0; k < 8; ++k) acc[r][k] += part[sg][r][lane * 8 + k]; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - if (sg < SG / 2) - for (int r = 0; r < R; ++r) { - if (r >= rows) break; - for (int k = 0; k < 8; ++k) part[sg][r][lane * 8 + k] = acc[r][k]; - } - threadgroup_barrier(mem_flags::mem_threadgroup); - for (int i = int(t); i < rows * 256; i += SG * 32) { - const int r = i / 256, c = i % 256; - const float v = ((part[0][r][c] + part[1][r][c]) + part[2][r][c]) + part[3][r][c]; - absorbed[(ulong(r) * heads + h) * 576 + tg.x * 256 + c] = bfloat(v); - } -} - -// values[row][head][e] = bf16(bf16(sum_c latent[row][head][c] * value[head][e][c]) * bf16(sigmoid(logit))), e < 256. -// Grid (256 / 8, heads), 4 simdgroups of two outputs; a lane holds 16 latent columns (one scale group's quarter). -template -[[kernel]] void tf_hy4_expand_gated_qmv(const device bfloat* latent [[buffer(0)]], const device uint32_t* W [[buffer(1)]], - const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], - device bfloat* values [[buffer(4)]], constant Hy4MlaQArgs& a [[buffer(5)]], - const device bfloat* logits [[buffer(6)]], - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], - uint3 tg [[threadgroup_position_in_grid]]) { - constexpr int R = 4, WPR = 512 * BITS / 32; - const int h = int(tg.y), heads = int(a.heads), rows = min(int(a.rows), R); - const int e0 = (int(tg.x) * 4 + int(sg)) * 2; - const int c0 = int(lane) * 16, g = c0 / 64; - float x[R][16], xs[R]; - for (int r = 0; r < R; ++r) { - xs[r] = 0.0f; - if (r >= rows) continue; - const device uint4* xp = (const device uint4*)(latent + (ulong(r) * heads + h) * 512 + c0); - for (int v = 0; v < 2; ++v) { - const uint4 x4 = xp[v]; - const uint xw[4] = {x4.x, x4.y, x4.z, x4.w}; - for (int u = 0; u < 4; ++u) { - x[r][v * 8 + u * 2] = as_type(xw[u] << 16); - x[r][v * 8 + u * 2 + 1] = as_type(xw[u] & 0xffff0000u); - xs[r] += x[r][v * 8 + u * 2] + x[r][v * 8 + u * 2 + 1]; - } - } - } - for (int j = 0; j < 2; ++j) { - const int e = e0 + j; - const ulong row = ulong(h) * 448 + 192 + e; - const float s = float(S[row * 8 + g]), b = float(B[row * 8 + g]); - float q[16]; - if (BITS == 4) { - const uint2 ww = *(const device uint2*)(W + row * WPR + c0 / 8); - for (int k = 0; k < 8; ++k) { - q[k] = float((ww.x >> (4 * k)) & 0xfu); - q[8 + k] = float((ww.y >> (4 * k)) & 0xfu); - } - } else { - const uint4 ww = *(const device uint4*)(W + row * WPR + c0 / 4); - const uint words[4] = {ww.x, ww.y, ww.z, ww.w}; - for (int u = 0; u < 4; ++u) - for (int k = 0; k < 4; ++k) q[u * 4 + k] = float((words[u] >> (8 * k)) & 0xffu); - } - for (int r = 0; r < R; ++r) { - if (r >= rows) break; - float dot = 0.0f; - for (int i = 0; i < 16; ++i) dot = fma(x[r][i], q[i], dot); - const float v = simd_sum(fma(s, dot, b * xs[r])); - if (lane == 0) { - const ulong at = (ulong(r) * heads + h) * 256 + e; - const bfloat value = bfloat(v); - const bfloat gate = bfloat(1.0f / (1.0f + precise::exp(-float(logits[at])))); - values[at] = bfloat(float(value) * float(gate)); - } - } - } -} - -template [[host_name("tf_hy4_absorb_qmv_q4")]] [[kernel]] decltype(tf_hy4_absorb_qmv<4>) tf_hy4_absorb_qmv<4>; -template [[host_name("tf_hy4_absorb_qmv_q8")]] [[kernel]] decltype(tf_hy4_absorb_qmv<8>) tf_hy4_absorb_qmv<8>; -template [[host_name("tf_hy4_expand_gated_qmv_q4")]] [[kernel]] decltype(tf_hy4_expand_gated_qmv<4>) tf_hy4_expand_gated_qmv<4>; -template [[host_name("tf_hy4_expand_gated_qmv_q8")]] [[kernel]] decltype(tf_hy4_expand_gated_qmv<8>) tf_hy4_expand_gated_qmv<8>; diff --git a/zig/kernels/metal/hy4_flash/tensor_dispatch.metal b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal index 98bedb4dba1..8836b29ea61 100644 --- a/zig/kernels/metal/hy4_flash/tensor_dispatch.metal +++ b/zig/kernels/metal/hy4_flash/tensor_dispatch.metal @@ -35,11 +35,7 @@ kernel void tf_hy4_active_experts( 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: job e is expert e (ids the identity), its -// pairs in pair order, as the router's per-window grouping orders them. Every row's picks are distinct experts, so -// a pair's rank in its expert is the earlier rows of the chunk that picked it: whole 64-row blocks by count, then -// the pair's own block by its rows' expert bitmaps. One threadgroup of 1024 threads; a.x pairs (topk a row, rows at -// most 512), a.y experts (at most 512), a.z topk. +// 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]], diff --git a/zig/src/core/lane_projection.zig b/zig/src/core/lane_projection.zig index 124e590f538..b43bf48e4a5 100644 --- a/zig/src/core/lane_projection.zig +++ b/zig/src/core/lane_projection.zig @@ -177,8 +177,7 @@ pub fn regBlock(tiled: *const [256]u32, out: *[256]u32) void { pub const Order = struct { w: Ref, n: usize, k: usize }; -/// Rewrites tile-order 8-bit g64 words (host-visible) in place into the 8-bit reg layout: u32[N/32][K/64][4][32 lanes][4], -/// a lane's codes in the 4-bit reg order a byte each (word 2w: four codes, 2w + 1: the four 16 deeper). +/// 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; diff --git a/zig/src/cuda/affine_experts.zig b/zig/src/cuda/affine_experts.zig index e0ae8d02d81..5bed7b2f121 100644 --- a/zig/src/cuda/affine_experts.zig +++ b/zig/src/cuda/affine_experts.zig @@ -62,7 +62,6 @@ pub const Kernels = struct { } /// Up returns pair rows in BF16. Down reads pair rows and returns FP32 expert contributions. - /// IDs outside this rank's slice write zeros, preserving the global route ordering on each rank. 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; diff --git a/zig/src/families/hy4_flash/engram_rows.zig b/zig/src/families/hy4_flash/engram_rows.zig index efc1d130919..1aa9bf0f31e 100644 --- a/zig/src/families/hy4_flash/engram_rows.zig +++ b/zig/src/families/hy4_flash/engram_rows.zig @@ -65,7 +65,6 @@ pub const Table = struct { } /// Each window is current token first, then older tokens, padded by the caller for a new stream. - /// Output is raw BF16 embedding rows [token][hash head][width], before FP8 simulation or normalization. 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; @@ -79,8 +78,7 @@ pub const Table = struct { } } - // Ask for every row's pages at once (asynchronous read-ahead), so cold rows' faults overlap rather than queue - // one by one in the copies below. + // 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); diff --git a/zig/src/families/hy4_flash/ihc_metal.zig b/zig/src/families/hy4_flash/ihc_metal.zig index dd1fedf4e3d..f9c6a2e3fd7 100644 --- a/zig/src/families/hy4_flash/ihc_metal.zig +++ b/zig/src/families/hy4_flash/ihc_metal.zig @@ -103,8 +103,7 @@ pub const Kernels = struct { 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; with `next` (the next - /// collapse's projection, `gates` of them) also that collapse's partials. + /// 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 }; diff --git a/zig/src/families/hy4_flash/metal_dense.zig b/zig/src/families/hy4_flash/metal_dense.zig index f3ab467a330..3920b6b82a7 100644 --- a/zig/src/families/hy4_flash/metal_dense.zig +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -55,15 +55,13 @@ pub const Buffers = struct { return view; } - /// A dense projection's weights: packed for the tensor units' lane projection when `tensors`, else the row kernels'. + /// 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) and std.c.getenv("TF_HY4_DENSE_ROWS") == null) { + 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)); - // decode-sized passes read the checkpoint layout through the decode kernels - const plain = if (decodeRows() > 0) try self.matrix(w) else null; - return .{ .tensor = .{ .w = packed_.w, .sb = packed_.sb, .n = n, .k = k, .plain = plain } }; + return .{ .tensor = .{ .w = packed_.w, .sb = packed_.sb, .n = n, .k = k } }; } return .{ .portable = try self.matrix(w) }; } @@ -74,50 +72,9 @@ pub const Buffers = struct { }; /// A dense affine projection [n, k]: the core row kernels, or the tensor units' lane projection over packed weights. -/// Passes of at most this many rows (one-row decode, the drafter's columns) take the decode GEMV: fp32 sums, each -/// weight read once, in a different order from the tensor units' (TF_HY4_DECODE_ROWS, default 2, where the GEMV is -/// the faster; 0 keeps the tensor units everywhere). Quality is the same either way (fp32 sums, NLL-checked). -/// A probe's override of decodeRows (kernel checks). -pub var decode_rows_override: ?u32 = null; - -fn envRows(name: [*:0]const u8, default: u32) u32 { - const v = std.c.getenv(name) orelse return default; - return std.fmt.parseInt(u32, std.mem.span(v), 10) catch default; -} - -/// Routed-expert passes of at most this many rows (6: the lane verify widths) run every (row, pick) pair as GEMVs -/// (TF_HY4_EXPERT_PAIRS); against the tensor gathers 4 rows 24.6 -> 23.1 ms, 5 rows 26.6 -> 24.4, 6 rows 27.8 -> 26.4. -pub fn expertPairRows() u32 { - return 0; // row-invariant bits: every pass takes the tensor gathers the prompt chunks take -} - -/// Attention passes of at most this many rows (4 at most) read kv_b's affine codes (TF_HY4_MLA_Q; 0: the BF16 copies). -/// One row by default: 15.85 -> 15.29 ms a token; from two rows the fp32 dequant is compute-bound, slower than BF16 -/// on tensor units (4 rows: 23.0 -> 24.2 ms). -pub fn mlaRows() u32 { - return 0; // row-invariant bits: every pass reads the BF16 copies on the tensor units, as prompt chunks do -} - -/// Larger passes up to this many rows (at most one router window, 16) run the grouped GEMVs (TF_HY4_EXPERT_GROUPS). -pub fn expertGroupRows() u32 { - return @min(envRows("TF_HY4_EXPERT_GROUPS", 0), 16); -} - -pub fn decodeRows() u32 { - return decode_rows_override orelse 0; // row-invariant bits: the lane projection at every row count -} - pub const Linear = union(enum) { portable: affine.Weights, - tensor: struct { w: lane.Ref, sb: lane.Ref, n: u32, k: u32, plain: ?affine.Weights = null }, - - /// The checkpoint-layout weights the decode kernels read, when this projection has them. - fn plainWeights(self: Linear) ?affine.Weights { - return switch (self) { - .portable => |w| w, - .tensor => |t| t.plain, - }; - } + tensor: struct { w: lane.Ref, sb: lane.Ref, n: u32, k: u32 }, pub fn outputs(self: Linear) u32 { return switch (self) { @@ -127,64 +84,7 @@ pub const Linear = union(enum) { } }; -/// The lane projections for every dense shape a model has, made once at load, and one group-sums buffer that the -/// projections reading the same input share (sums once, then every main kernel without a barrier between them). -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, - 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; - } - - 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; - } - - 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; - } -}; +pub const Linears = @import("metal_linears.zig").Linears; pub const Merge = struct { project: mtl.Buffer, @@ -223,8 +123,6 @@ pub const Attention = struct { o_norm: mtl.Buffer, wk: mtl.Buffer, wv: mtl.Buffer, - /// kv_b's affine codes, scales and biases for the decode GEMVs (null under TF_HY4_MLA_BF16). - kv_q: ?[3]mtl.Buffer = null, bits: u8 = 4, sinks: mtl.Buffer, /// A sparse layer's compressed indexer (null on sliding layers). @@ -270,7 +168,6 @@ pub const Attention = struct { .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, - .kv_q = if (w.absorbed.packed_rows) |p| if (std.c.getenv("TF_HY4_MLA_BF16") == null) .{ try b.upload(p.words), try b.upload(p.scales), try b.upload(p.biases) } else null else null, .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, }; @@ -319,235 +216,17 @@ pub const Feed = struct { } }; -fn withAllocation(out: anytype, b: Buffers) @TypeOf(out) { +pub fn withAllocation(out: anytype, b: Buffers) @TypeOf(out) { var owned = out; owned.own = b; return owned; } -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; - } -}; - -/// Lane windows of 2-8 rows through one weight read: tf_hy4_rows, the core row projection's per-row arithmetic -/// (bit-equal to its plain kernel at every row count) with RPS columns a simdgroup and 4 simdgroups a threadgroup. -pub const Rows = struct { - q4: mtl.Pipeline, - q8: mtl.Pipeline, - rps: u32, - /// Greedy tokens on the GPU (first index of the largest logit), so draft columns chain without the host. - argmax: mtl.Pipeline, - /// Decode-sized passes (1-8 rows) of 4- and 8-bit group-64 matrices, each weight read once. - qmv4: mtl.Pipeline, - qmv8: mtl.Pipeline, - /// Output columns a decode GEMV threadgroup covers. - qmv_cols: u32 = 8, - /// 1- to 4-row decode GEMVs with four columns a simdgroup ([bits 4, 8][rows 1-4]; the same bits as qmv2, - /// 14.83 -> 14.23 ms a token); TF_HY4_QMV=2 keeps qmv2, TF_HY4_QMV=8 takes eight columns a simdgroup. - qmv3: ?[2][4]mtl.Pipeline = null, - qmv3_cols: u32 = 16, - /// Routed experts for 1-2 row passes: gate/up into the clipped SwiGLU, then down (q4, q8). - expert_glu: [2]mtl.Pipeline, - expert_down: [2]mtl.Pipeline, - /// Routed experts for 3-16 row passes, grouped by the router window's jobs (each expert's codes unpacked once). - expert_glu_groups: [2]mtl.Pipeline, - expert_down_groups: [2]mtl.Pipeline, - /// The expert down GEMVs with the routed weighted sum folded in (q4, q8; TF_HY4_NO_DOWN_SUM keeps two launches). - expert_down_sum: [2]mtl.Pipeline, - /// MLA absorb and expand-and-gate for 1-4 row passes over kv_b's affine codes (q4, q8). - absorb_q: [2]mtl.Pipeline, - expand_q: [2]mtl.Pipeline, - /// The expert branches' add fused into the norm that reads them (bit-equal to add then norm). - add_norm: mtl.Pipeline, - - pub fn load(a: std.mem.Allocator, device: mtl.Device) !Rows { - const text = try std.mem.concat(a, u8, &.{ affine.source(device.tensorUnits()), @import("kernel_sources").hy4_flash_rows }); - defer a.free(text); - const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); - defer lib.deinit(); - // TF_HY4_ROWS: the variant, r2 (default), r4, r2s, r1s or r1 (columns a simdgroup; s: shared unpack) - const variant: []const u8 = if (std.c.getenv("TF_HY4_ROWS")) |v| std.mem.span(v) else "r2"; - const rps: u32 = if (variant[1] == '1') 1 else if (variant[1] == '4') 4 else 2; - var name4: [32]u8 = undefined; - var name8: [32]u8 = undefined; - var q4 = try mtl.Pipeline.init(device, lib, try std.fmt.bufPrint(&name4, "tf_hy4_rows_{s}_q4", .{variant}), false); - errdefer q4.deinit(); - var q8 = try mtl.Pipeline.init(device, lib, try std.fmt.bufPrint(&name8, "tf_hy4_rows_{s}_q8", .{variant}), false); - errdefer q8.deinit(); - var argmax = try mtl.Pipeline.init(device, lib, "tf_hy4_argmax", false); - errdefer argmax.deinit(); - // TF_HY4_QMV=1 keeps the first decode GEMV (four columns a simdgroup, codes unpacked a row at a time) - const first = if (std.c.getenv("TF_HY4_QMV")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; - var qmv4 = try mtl.Pipeline.init(device, lib, if (first) "tf_hy4_qmv_q4" else "tf_hy4_qmv2_q4", false); - errdefer qmv4.deinit(); - var qmv8 = try mtl.Pipeline.init(device, lib, if (first) "tf_hy4_qmv_q8" else "tf_hy4_qmv2_q8", false); - errdefer qmv8.deinit(); - var qmv3: ?[2][4]mtl.Pipeline = null; - const qmv_mode: []const u8 = if (std.c.getenv("TF_HY4_QMV")) |v| std.mem.span(v) else "3"; - const wide8 = std.mem.eql(u8, qmv_mode, "8"); - if (std.mem.eql(u8, qmv_mode, "3") or wide8) { - var p3: [2][4]mtl.Pipeline = undefined; - const set4 = [_][4][:0]const u8{ .{ "tf_hy4_qmv3_r1_q4", "tf_hy4_qmv3_r2_q4", "tf_hy4_qmv3_r3_q4", "tf_hy4_qmv3_r4_q4" }, .{ "tf_hy4_qmv3_r1_q8", "tf_hy4_qmv3_r2_q8", "tf_hy4_qmv3_r3_q8", "tf_hy4_qmv3_r4_q8" } }; - const set8 = [_][4][:0]const u8{ .{ "tf_hy4_qmv3x8_r1_q4", "tf_hy4_qmv3x8_r2_q4", "tf_hy4_qmv3x8_r3_q4", "tf_hy4_qmv3x8_r4_q4" }, .{ "tf_hy4_qmv3x8_r1_q8", "tf_hy4_qmv3x8_r2_q8", "tf_hy4_qmv3x8_r3_q8", "tf_hy4_qmv3x8_r4_q8" } }; - for (if (wide8) set8 else set4, 0..) |names, bi| { - for (names, 0..) |name, ri| p3[bi][ri] = try mtl.Pipeline.init(device, lib, name, false); - } - qmv3 = p3; - } - errdefer if (qmv3) |p3| for (p3) |row| for (row) |pipe| pipe.deinit(); - var experts: [14]mtl.Pipeline = undefined; - var made: usize = 0; - errdefer for (experts[0..made]) |pipe| pipe.deinit(); - for ([_][:0]const u8{ "tf_hy4_expert_glu_q4", "tf_hy4_expert_glu_q8", "tf_hy4_expert_down_q4", "tf_hy4_expert_down_q8", "tf_hy4_expert_glu_groups_q4", "tf_hy4_expert_glu_groups_q8", "tf_hy4_expert_down_groups_q4", "tf_hy4_expert_down_groups_q8", "tf_hy4_absorb_qmv_q4", "tf_hy4_absorb_qmv_q8", "tf_hy4_expand_gated_qmv_q4", "tf_hy4_expand_gated_qmv_q8", "tf_hy4_expert_down_sum_q4", "tf_hy4_expert_down_sum_q8" }, &experts) |name, *dst| { - dst.* = try mtl.Pipeline.init(device, lib, name, false); - made += 1; - } - return .{ .q4 = q4, .q8 = q8, .rps = rps, .argmax = argmax, .qmv4 = qmv4, .qmv8 = qmv8, .qmv_cols = if (first) 16 else 8, .qmv3 = qmv3, .qmv3_cols = if (wide8) 32 else 16, .expert_glu = .{ experts[0], experts[1] }, .expert_down = .{ experts[2], experts[3] }, .expert_glu_groups = .{ experts[4], experts[5] }, .expert_down_groups = .{ experts[6], experts[7] }, .absorb_q = .{ experts[8], experts[9] }, .expand_q = .{ experts[10], experts[11] }, .expert_down_sum = .{ experts[12], experts[13] }, .add_norm = try mtl.Pipeline.init(device, lib, "tf_hy4_add_rms", false) }; - } - - pub fn deinit(self: Rows) void { - self.q4.deinit(); - self.q8.deinit(); - self.argmax.deinit(); - self.qmv4.deinit(); - self.qmv8.deinit(); - if (self.qmv3) |p3| for (p3) |row| for (row) |pipe| pipe.deinit(); - for (self.expert_glu) |pipe| pipe.deinit(); - for (self.expert_down) |pipe| pipe.deinit(); - for (self.expert_glu_groups) |pipe| pipe.deinit(); - for (self.expert_down_groups) |pipe| pipe.deinit(); - for (self.absorb_q) |pipe| pipe.deinit(); - for (self.expand_q) |pipe| pipe.deinit(); - for (self.expert_down_sum) |pipe| pipe.deinit(); - self.add_norm.deinit(); - } - - /// y = norm(a + b) * gain over `rows` rows of `width`, as dense.Ops.add then dense.Ops.norm. - pub fn addNorm(self: Rows, e: mtl.ComputeEncoder, x: Ref, branch: Ref, gain: mtl.Buffer, y: Ref, rows: u32, width: u32, epsilon: f32) !void { - const p: dense.Norm = .{ .rows = rows, .heads = 1, .dim = width, .x_stride = width, .y_stride = width, .eps = epsilon }; - const threads = try dense.normThreads(p); - e.setPipeline(self.add_norm); - e.setBuffer(x.buffer, x.offset, 0); - e.setBuffer(branch.buffer, branch.offset, 1); - e.setBuffer(gain, 0, 2); - e.setValue(p, 3); - e.setBuffer(y.buffer, y.offset, 4); - e.dispatchGroups(mtl.Size.of(1, rows, 1), mtl.Size.of(threads, 1, 1)); - } - - /// 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)); - } - - fn sg(self: Rows) u32 { - return if (self.rps == 1) 8 else 4; - } +pub const Scratch = @import("metal_scratch.zig").Scratch; - 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, - }; - } -}; +pub const Rows = @import("metal_linears.zig").Rows; fn twoStep(keys: u32) bool { - if (std.c.getenv("TF_HY4_ATTEND")) |v| return std.mem.eql(u8, std.mem.span(v), "two"); return keys >= 1024; } @@ -609,35 +288,13 @@ pub const Kernels = struct { 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() and std.c.getenv("TF_HY4_DENSE_ROWS") == null) out.linears = try Linears.load(a, device, t, bits); - if (std.c.getenv("TF_HY4_ROWS_OFF") == null) out.rows = try Rows.load(a, device); - if (device.tensorUnits() and std.c.getenv("TF_HY4_MLA_FMA") == null) out.projections.nax = try mla_gpu.Nax.load(a, device); + 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 { - if (self.rows) |r| if (r.qmv3) |p3| if (rows <= decodeRows() and rows <= 4 and w.group == 64 and w.sum == .f32 and w.n % r.qmv3_cols == 0 and w.k % 32 == 0 and (w.bits == 4 or w.bits == 8)) { - e.setPipeline(p3[@intFromBool(w.bits == 8)][rows - 1]); - 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([6]i32{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), 1, 1 }, 4); - e.setBuffer(y.buffer, y.offset, 5); - e.dispatchGroups(mtl.Size.of(w.n / r.qmv3_cols, 1, 1), mtl.Size.of(128, 1, 1)); - return; - }; - if (self.rows) |r| if (rows <= decodeRows() and rows <= 8 and w.group == 64 and w.sum == .f32 and w.n % r.qmv_cols == 0 and w.k % 32 == 0 and (w.bits == 4 or w.bits == 8)) { - e.setPipeline(if (w.bits == 4) r.qmv4 else r.qmv8); - 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([6]i32{ @intCast(w.k), @intCast(w.n), @intCast(w.group), @intCast(rows), 1, 1 }, 4); - e.setBuffer(y.buffer, y.offset, 5); - e.dispatchGroups(mtl.Size.of(w.n / r.qmv_cols, 1, 1), mtl.Size.of(128, 1, 1)); - return; - }; var call = try affine.call(&self.affine, w, rows, false); if (self.rows) |r| if (r.choose(w, rows)) |pipe| { call.pipeline = pipe; @@ -661,15 +318,9 @@ pub const Kernels = struct { pub const Out = struct { w: Linear, y: Ref }; - /// Every projection of the same input x: on tensor units one group-sums pass, a barrier, then each projection's - /// main kernel with those sums and no barrier between them (the sums are what each would have made itself). + /// 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 (rows <= decodeRows()) decode: { - for (outs) |o| if (o.w.plainWeights() == null) break :decode; - for (outs) |o| try self.project(e, o.w.plainWeights().?, x, o.y, rows); - return; - } if (outs[0].w == .portable) { for (outs) |o| try self.project(e, o.w.portable, x, o.y, rows); return; @@ -724,21 +375,12 @@ pub const Kernels = struct { }); } - /// Where a sub-block sits between seams: `ready` when the previous tail already wrote this collapse's partials, - /// `next` the collapse after this sub-block (its tail writes that one's partials). - /// ready: the collapse's partials are written; headed: its gates, row and norm too (a fused seam before it). - /// next_gain: the next sub-block's input norm, which lets the tail run that collapse's head in its launch. + /// 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 (TF_HY4_SEAM_FUSE=0 keeps two launches). + /// Decode passes fuse each tail with the next head. pub fn fusedSeams(rows: u32) bool { - if (seamsOff() or rows > ihc_gpu.Kernels.seam_rows) return false; - const v = std.c.getenv("TF_HY4_SEAM_FUSE") orelse return true; - return !std.mem.eql(u8, std.mem.span(v), "0"); - } - - fn seamsOff() bool { - return std.c.getenv("TF_HY4_NO_SEAMS") != null; + 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). @@ -748,7 +390,6 @@ pub const Kernels = struct { 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; - if (seamsOff()) return self.collapse(e, x, w, gain, s); var shape = w.shape; shape.rows = s.shape.rows; if (seam.headed) return shape; @@ -772,8 +413,7 @@ pub const Kernels = struct { return shape; } - /// A sub-block's end: its branch (two added, for the experts) through the output norm, mixed into `out`, and the - /// next collapse's partials when there is one. + /// 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 }); } @@ -801,13 +441,6 @@ pub const Kernels = struct { .barriers = .{ .buffer = s.seam_barriers.buffer, .offset = s.seam_barriers.offset }, }, shape.rows, shape.width, eps); }; - if (seamsOff()) { - if (branch2) |b2| { - if (self.rows) |r| try r.addNorm(e, branch, b2, gain, s.normalized, shape.rows, shape.width, eps) else return error.Hy4SeamsNeedRows; - } else try self.norm(e, branch, gain, s.normalized, shape.rows, shape.width, eps); - e.barrier(); - return self.residual(e, x, s.normalized, s.post, out, shape); - } const r = ihc_gpu.Ref; self.merge.tailPass(e, .{ .branch = r{ .buffer = branch.buffer, .offset = branch.offset }, @@ -900,15 +533,7 @@ pub const Kernels = struct { 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; - const quantized: ?mla_gpu.Quantized = if (self.rows) |r| if (w.kv_q) |q| if (rows <= mlaRows() and (w.bits == 4 or w.bits == 8)) .{ - .absorb = r.absorb_q[@intFromBool(w.bits == 8)], - .expand = r.expand_q[@intFromBool(w.bits == 8)], - .words = .{ .buffer = q[0] }, - .scales = .{ .buffer = q[1] }, - .biases = .{ .buffer = q[2] }, - } else null else null else null; try mla_gpu.forward(self.projections, self.attention, e, .{ - .quantized = quantized, .query = s.query, .key_weights = .{ .buffer = w.wk }, .value_weights = .{ .buffer = w.wv }, diff --git a/zig/src/families/hy4_flash/metal_draft.zig b/zig/src/families/hy4_flash/metal_draft.zig index ac4559adea6..0fdce1fba89 100644 --- a/zig/src/families/hy4_flash/metal_draft.zig +++ b/zig/src/families/hy4_flash/metal_draft.zig @@ -14,13 +14,10 @@ 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, groups of 64) so they run on the -/// target's row kernels, one weight read a block. The draft only proposes: the target verifies every token, so the -/// output is unchanged and only acceptance can move. Unset or 16 keeps BF16. -fn draftBits() ?u8 { - const v = std.c.getenv("TF_HY4_DRAFT_BITS") orelse return null; - const bits = std.fmt.parseInt(u8, std.mem.span(v), 10) catch return null; - return if (bits == 4 or bits == 8) bits else null; +/// 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 { @@ -32,8 +29,7 @@ fn bf16Value(w: u16) f32 { return @bitCast(@as(u32, w) << 16); } -/// MLX affine quantization of a BF16 [n, k] matrix: per group of 64 a bf16 scale and bias (the group's minimum), -/// codes round((w - bias) / scale), packed low bits first into u32 words. +/// 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; @@ -83,7 +79,7 @@ const Linear = struct { 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 (draftBits()) |bits| if (k % 512 == 0 and n % 8 == 0) { + 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 }; diff --git a/zig/src/families/hy4_flash/metal_engram.zig b/zig/src/families/hy4_flash/metal_engram.zig index 720ae4d9bed..8b808aeffa6 100644 --- a/zig/src/families/hy4_flash/metal_engram.zig +++ b/zig/src/families/hy4_flash/metal_engram.zig @@ -13,14 +13,11 @@ const ihc = @import("ihc.zig"); const Ref = common.Ref; const width = 96; -/// Where the n-gram tables live (TF_HY4_ENGRAM): nvme reads the checkpoint's mapping (pages on demand, read -/// ahead a step at a time); ram copies the tables into resident memory for the host's gather; gpu keeps them in GPU -/// memory and gathers there, the host only hashing the windows. All three stage the same bits. +/// Where the n-gram tables live (TF_HY4_ENGRAM) pub const Placement = enum { nvme, ram, gpu }; -pub fn placement() Placement { - const v = std.mem.span(std.c.getenv("TF_HY4_ENGRAM") orelse return .nvme); - return std.meta.stringToEnum(Placement, v) orelse .nvme; +pub fn placement() !Placement { + return @fromBackingInt(@intCast(try @import("sys").environment.read(u32, "TF_HY4_ENGRAM", 0))); } pub const Layer = struct { @@ -63,7 +60,7 @@ pub const Layer = struct { .fp8 = fp8, .hidden = hidden, }; - switch (placement()) { + switch (try placement()) { .nvme => {}, .ram, .gpu => |where| { const t = &out.table.affine; diff --git a/zig/src/families/hy4_flash/metal_index.zig b/zig/src/families/hy4_flash/metal_index.zig index 087a50203b9..620bcee4158 100644 --- a/zig/src/families/hy4_flash/metal_index.zig +++ b/zig/src/families/hy4_flash/metal_index.zig @@ -1,7 +1,4 @@ -//! Hy4-flash's compressed sparse indexer on Metal, after the reference's CompressedIndexer: every pass caches its -//! rows' normalized token keys and re-pools the four-slot groups those rows touch (a group is read only once it -//! closed, so a pass that wrote part of one leaves nothing stale), and from 2,048 keys on each row attends its 511 -//! best-scoring closed groups plus its own group's causal part. Slots are positions here. +//! 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"); @@ -163,9 +160,7 @@ 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), `q_resid` -/// the normalized q_a rows. Leaves the key lists in `c.tokens` and `c.counts` when the scratch selects. Ends -/// without a trailing barrier. +/// 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)}); 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..3ecc917cc96 --- /dev/null +++ b/zig/src/families/hy4_flash/metal_linears.zig @@ -0,0 +1,123 @@ +//! 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("row_projection"); +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("lane_projection"); +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 { + const text = try std.mem.concat(a, u8, &.{ affine.source(device.tensorUnits()), @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_routed.zig b/zig/src/families/hy4_flash/metal_routed.zig index c839d4cac00..c96f2bec6d1 100644 --- a/zig/src/families/hy4_flash/metal_routed.zig +++ b/zig/src/families/hy4_flash/metal_routed.zig @@ -267,15 +267,11 @@ pub const Kernels = struct { }, rows); route.logits(e, self.logits, self.shape, dense.Kernels.dref(d.normalized), w.router, s.logits, rows); e.barrier(); - // the pair GEMVs need only the picks and weights: the per-row select (the same arithmetic) skips the core - // select's expert grouping (TF_HY4_CORE_SELECT keeps it) - const pairs = w.expert_weights == .tensor and rows <= dense.expertPairRows() and rows > dense.expertGroupRows() and - shared.rows != null and std.c.getenv("TF_HY4_EXPERT_GATHER") == null; - if (rows <= max_rows and !(pairs and std.c.getenv("TF_HY4_CORE_SELECT") == null)) { + 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 and std.c.getenv("TF_HY4_SELECT_LOOP") == null; + 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); @@ -295,7 +291,6 @@ pub const Kernels = struct { var shape = w.size; shape.rows = rows; shape.pairs = rows * s.picks; - var summed = false; switch (w.expert_weights) { .portable => |mat| { const ops = self.experts orelse return error.Hy4ExpertKernelsMissing; @@ -316,69 +311,7 @@ pub const Kernels = struct { .output = .{ .buffer = s.pair_outputs }, }, shape); }, - .tensor => |mat| if (rows > dense.expertPairRows() and rows <= dense.expertGroupRows() and rows <= max_rows and shared.rows != null and std.c.getenv("TF_HY4_EXPERT_GATHER") == null) { - // 3-16 rows: the router window's expert jobs as GEMVs, each expert's codes unpacked once for its rows - const r = shared.rows.?; - const which: usize = @intFromBool(w.precision == .q8); - const bound = @min(shape.pairs, shape.experts); - const glu_shape = [5]u32{ shape.pairs, s.picks, shape.width, shape.inner, @bitCast(shape.swiglu_limit) }; - e.setPipeline(r.expert_glu_groups[which]); - e.setBuffer(s.latent.buffer, s.latent.offset, 0); - e.setBuffer(s.select.ids.buf, s.select.ids.off, 1); - e.setBuffer(s.select.members.buf, s.select.members.off, 2); - e.setBuffer(s.select.count.buf, s.select.count.off, 3); - for ([_]@import("lane_projection").Ref{ mat.gate.w, mat.gate.s, mat.gate.b, mat.up.w, mat.up.s, mat.up.b }, 4..) |ref, i| e.setBuffer(ref.buf, ref.off, i); - e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 10); - e.setValue(glu_shape, 11); - e.dispatchGroups(mtl.Size.of(shape.inner / 8, bound, 1), mtl.Size.of(128, 1, 1)); - try shared.linear(e, w.shared_down, d.inner, s.shared, rows); - e.barrier(); - const down_shape = [5]u32{ shape.pairs, s.picks, shape.inner, shape.width, @bitCast(shape.swiglu_limit) }; - e.setPipeline(r.expert_down_groups[which]); - e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 0); - e.setBuffer(s.select.ids.buf, s.select.ids.off, 1); - e.setBuffer(s.select.members.buf, s.select.members.off, 2); - e.setBuffer(s.select.count.buf, s.select.count.off, 3); - for ([_]@import("lane_projection").Ref{ mat.down.w, mat.down.s, mat.down.b }, 4..) |ref, i| e.setBuffer(ref.buf, ref.off, i); - e.setBuffer(s.pair_outputs, 0, 7); - e.setValue(down_shape, 8); - e.dispatchGroups(mtl.Size.of(shape.width / 8, bound, 1), mtl.Size.of(128, 1, 1)); - } else if (rows <= dense.expertPairRows() and shared.rows != null and std.c.getenv("TF_HY4_EXPERT_GATHER") == null) { - // 1-2 rows: every (row, pick) pair's expert as GEMVs (each weight read once), no grouping pass - const r = shared.rows.?; - const which: usize = @intFromBool(w.precision == .q8); - const glu_shape = [5]u32{ shape.pairs, s.picks, shape.width, shape.inner, @bitCast(shape.swiglu_limit) }; - e.setPipeline(r.expert_glu[which]); - e.setBuffer(s.latent.buffer, s.latent.offset, 0); - e.setBuffer(s.select.pick.buf, s.select.pick.off, 1); - for ([_]@import("lane_projection").Ref{ mat.gate.w, mat.gate.s, mat.gate.b, mat.up.w, mat.up.s, mat.up.b }, 2..) |ref, i| e.setBuffer(ref.buf, ref.off, i); - e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 8); - e.setValue(glu_shape, 9); - e.dispatchGroups(mtl.Size.of(shape.inner / 8, shape.pairs, 1), mtl.Size.of(128, 1, 1)); - try shared.linear(e, w.shared_down, d.inner, s.shared, rows); - e.barrier(); - const down_shape = [5]u32{ shape.pairs, s.picks, shape.inner, shape.width, @bitCast(shape.swiglu_limit) }; - if (std.c.getenv("TF_HY4_NO_DOWN_SUM") == null) { - // down and the routed weighted sum in one launch, straight into the weighted rows - e.setPipeline(r.expert_down_sum[which]); - e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 0); - e.setBuffer(s.select.pick.buf, s.select.pick.off, 1); - for ([_]@import("lane_projection").Ref{ mat.down.w, mat.down.s, mat.down.b }, 2..) |ref, i| e.setBuffer(ref.buf, ref.off, i); - e.setBuffer(s.weighted.buffer, s.weighted.offset, 5); - e.setValue(down_shape, 6); - e.setBuffer(s.select.wts.buf, s.select.wts.off, 7); - e.dispatchGroups(mtl.Size.of(shape.width / 8, rows, 1), mtl.Size.of(128, 1, 1)); - summed = true; - } else { - e.setPipeline(r.expert_down[which]); - e.setBuffer(s.pair_activations.buffer, s.pair_activations.offset, 0); - e.setBuffer(s.select.pick.buf, s.select.pick.off, 1); - for ([_]@import("lane_projection").Ref{ mat.down.w, mat.down.s, mat.down.b }, 2..) |ref, i| e.setBuffer(ref.buf, ref.off, i); - e.setBuffer(s.pair_outputs, 0, 5); - e.setValue(down_shape, 6); - e.dispatchGroups(mtl.Size.of(shape.width / 8, shape.pairs, 1), mtl.Size.of(128, 1, 1)); - } - } else { + .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 }; @@ -398,15 +331,13 @@ pub const Kernels = struct { }, } e.barrier(); - if (!summed) { - 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(); - } + 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); 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..6ae9bfdad15 --- /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("row_projection"); +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("lane_projection"); +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 index a9c0458fcd1..b329052689e 100644 --- a/zig/src/families/hy4_flash/metal_tensor_experts.zig +++ b/zig/src/families/hy4_flash/metal_tensor_experts.zig @@ -129,8 +129,7 @@ pub const Kernels = struct { 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): job e = expert e, pairs in pair order, and the - /// latent's row sums. `ids` and `offsets` hold `experts` entries, `order` every pair. + /// 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); diff --git a/zig/src/families/hy4_flash/metal_tensor_qkv.zig b/zig/src/families/hy4_flash/metal_tensor_qkv.zig index 28a6020125b..86ab4132965 100644 --- a/zig/src/families/hy4_flash/metal_tensor_qkv.zig +++ b/zig/src/families/hy4_flash/metal_tensor_qkv.zig @@ -60,8 +60,7 @@ fn layout(bits: u8, n: usize, k: usize, sk: usize) lane.Layout { }; } -/// Any other dense projection [n, k] on tensor units: the QKV layout, with split-K by depth (2 under 2048, 4 to 4096, -/// else 8). Every row's bits are the same however many rows share the encode (independent 16-row blocks). +/// 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); } @@ -78,8 +77,7 @@ 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: the same words as the -/// sums pass, without its dispatch and barrier. +/// 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). diff --git a/zig/src/families/hy4_flash/mla_metal.zig b/zig/src/families/hy4_flash/mla_metal.zig index cd22c200968..ed260237835 100644 --- a/zig/src/families/hy4_flash/mla_metal.zig +++ b/zig/src/families/hy4_flash/mla_metal.zig @@ -42,10 +42,6 @@ pub const Nax = struct { } /// Flash attention over contiguous key ranges: out [rows][heads][512] from the absorbed queries and the cache. - /// Decode passes (one row block) split the keys over up to 8 threadgroups a head (a run of 4+ tiles each) and - /// join them in a second launch (TF_HY4_FLASH_SPLIT=N fixes N, 1 turns it off). - /// A split a 32-key tile, up to max_splits (two tiles already run faster split and joined than in one - /// threadgroup); with the live key count unknown, a split every 128 keys of the stride. 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 @@ -86,8 +82,7 @@ pub const Nax = struct { } }; -/// Each row's keys as one range of key indices [lo, hi) (u32 pairs), and each 32-key tile's first slot: the flash -/// kernel's inputs when every row attends a contiguous run of keys (prompt chunks, sliding windows, short contexts). +/// 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 { @@ -221,8 +216,7 @@ pub const Attention = struct { 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`, as they would in any - /// other pass, and the rest their recalled slot lists. + /// A pass across 2,048 keys: rows before this one take the flash kernel over `ranges` lists_from: ?u32 = null, }; @@ -291,23 +285,7 @@ pub const KvInput = struct { }; /// Decode passes (at most 4 rows): absorb and expand-and-gate as GEMVs over the checkpoint's affine kv_b codes -/// (fp32 dequant on the fly, a quarter of the BF16 copies' bytes at 4 bits). -pub const Quantized = struct { - absorb: mtl.Pipeline, - expand: mtl.Pipeline, - words: Ref, - scales: Ref, - biases: Ref, - - fn bind(q: Quantized, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, input: Ref, output: Ref, rows: u32, heads: u32) void { - e.setPipeline(pipe); - for ([_]Ref{ input, q.words, q.scales, q.biases, output }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); - e.setValue([2]u32{ rows, heads }, 5); - } -}; - pub const MlaPass = struct { - quantized: ?Quantized = null, query: Ref, key_weights: Ref, value_weights: Ref, @@ -328,11 +306,7 @@ pub fn forward(project: Projections, attend: Attention, e: mtl.ComputeEncoder, b 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 (b.quantized) |q| { - if (shape.rows > 4) return error.BadHy4QuantizedMlaRows; - q.bind(e, q.absorb, b.query, b.attention.query, shape.rows, shape.heads); - e.dispatchGroups(mtl.Size.of(weights.latent / 256, shape.heads, 1), mtl.Size.of(256, 1, 1)); - } else if (project.nax) |n| + 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); @@ -372,12 +346,6 @@ pub fn forward(project: Projections, attend: Attention, e: mtl.ComputeEncoder, b } 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 (b.quantized) |q| { - q.bind(e, q.expand, b.attention.output, b.values, shape.rows, shape.heads); - e.setBuffer(b.value_logits.buffer, b.value_logits.offset, 6); - e.dispatchGroups(mtl.Size.of(weights.value_width / 8, shape.heads, 1), mtl.Size.of(128, 1, 1)); - return; - } 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); diff --git a/zig/src/families/hy4_flash/mla_weights.zig b/zig/src/families/hy4_flash/mla_weights.zig index 56e2d8821d0..05be7294949 100644 --- a/zig/src/families/hy4_flash/mla_weights.zig +++ b/zig/src/families/hy4_flash/mla_weights.zig @@ -12,8 +12,7 @@ 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: 192 key rows, then 256 value rows, each -/// 512 latent values in groups of 64), for decode GEMVs that read the codes instead of the BF16 copies. +/// The checkpoint's own affine kv_b rows for the selected heads (per head pub const Packed = struct { bits: u8, words: []u8, diff --git a/zig/src/families/hy4_flash/rank_weights.zig b/zig/src/families/hy4_flash/rank_weights.zig index 82668b630c5..51158881fad 100644 --- a/zig/src/families/hy4_flash/rank_weights.zig +++ b/zig/src/families/hy4_flash/rank_weights.zig @@ -25,7 +25,6 @@ pub const Range = struct { }; /// Q-B and the gate own this rank's output heads. The O projection owns those same input columns. -/// Q-A and KV-A are shared between ranks. The sink and absorbed K/V projection follow the head range. pub const Attention = struct { heads: mla.HeadRange, query: Affine, 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 index 287c98092fe..e5e06d54be6 100644 --- a/zig/src/families/hy4_flash/serve_metal.zig +++ b/zig/src/families/hy4_flash/serve_metal.zig @@ -1,7 +1,4 @@ -//! Hy4-flash behind the lane engine on Metal: one stream at a time with its own caches (every layer's latent KV a -//! slot a position, the sparse layers' indexer keys), 512-row prompt chunks, one-row steps and DFly2 verify windows -//! of up to six rows, each row drawn on the host with the stream's keyed sampler. A released stream's caches stay -//! for the next prompt that starts with the same tokens (an agent's next turn), which then prefills only the rest. +//! Hy4-flash behind the lane engine on Metal const std = @import("std"); const mtl = @import("metal"); const lanes = @import("lanes"); @@ -15,14 +12,14 @@ pub const key_width = 576; // BF16 words in a latent KV slot: 512 latent + 64 ro 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 -const draft_stride: u32 = 2560; // a draft row's keys at most: a recalled list (2,048) and its own rows +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. -const Cache = struct { +pub const Cache = struct { kv: []mtl.Buffer, token_keys: []?mtl.Buffer, group_keys: []?mtl.Buffer, @@ -210,37 +207,7 @@ pub const Metal = struct { /// 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 { - 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; + return @import("serve_resident.zig").buffers(self, list); } /// Bytes one stream's caches take at `capacity` slots. @@ -300,7 +267,7 @@ pub const Metal = struct { } /// Point the layers' caches at `c` for the next pass. - fn bind(self: *Metal, c: *const Cache) void { + 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 .{ @@ -579,91 +546,9 @@ pub const Metal = struct { } } - /// DFly2 from the anchor row's final hidden: `depth` greedy drafts after `bonus` at slot c.len, held for the - /// next verify. The draft writes its blocks' KV into the shared target layers at slots the verify rewrites first. - fn runDraft(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; + /// 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 { @@ -704,54 +589,12 @@ pub const Metal = struct { } }; -fn logit(word: u16) f32 { - return @bitCast(@as(u32, word) << 16); -} - fn argmax(l: []const u16) usize { var best: usize = 0; - for (l, 0..) |w, i| if (logit(w) > logit(l[best])) { + 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; - -/// 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/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/speed_probe.zig b/zig/src/families/hy4_flash/speed_probe.zig deleted file mode 100644 index d4dfb50def4..00000000000 --- a/zig/src/families/hy4_flash/speed_probe.zig +++ /dev/null @@ -1,1151 +0,0 @@ -//! tf-hy4-speed: greedy Hy4-flash decode on the native Metal graph, for speed A/B and per-stage GPU profiles. -//! Contexts stay under 2048 slots, so sparse layers attend every earlier key and no indexer pass is needed. -//! -//! tf-hy4-speed MODEL_DIR GEN [--profile STEPS] [--long TOKENS] [--chunk ROWS] -//! -//! Prints each prompt's generated IDs and their FNV-1a hash (the exactness check between builds), decode ms a token -//! (wall and GPU), and with --profile the GPU time of every barrier-delimited stage, summed per token by its pipelines. -const std = @import("std"); -const mtl = @import("metal"); -const core = @import("core"); -const target = @import("metal_model.zig"); -const ihc = @import("ihc.zig"); -const engram = @import("engram.zig"); -const dfly = @import("metal_draft.zig"); - -/// Cache slots (TF_HY4_CAPACITY, a multiple of 512; past 2,048 sparse layers attend every key unless TF_HY4_INDEX). -var capacity: u32 = 2048; -const index = @import("metal_index.zig"); -const key_width = 576; // BF16 words in a latent KV slot: 512 latent + 64 rope -const window: u32 = 512; -const bos: u32 = 120000; -const max_rows = 512; // a prompt chunk's rows (one router window is 16) - -const prompts = [_][]const u8{ - "The capital of France is", - "Write a short story about a lighthouse keeper who finds a message in a bottle.", - "def merge_sort(values):\n \"\"\"Sort a list of numbers.\"\"\"\n", - "Explain why the sky is blue in three sentences.", -}; - -const long_text = - "The history of the printing press begins long before Gutenberg. Carved wooden blocks were inked and pressed " ++ - "onto paper in East Asia for centuries, and movable type made of clay and later metal appeared well before it " ++ - "reached Europe. What changed in the fifteenth century was the combination of an oil-based ink, a hand mould " ++ - "that cast uniform letters quickly, and a screw press adapted from wine making. Together they made books cheap " ++ - "enough that ideas could travel faster than the authorities who wanted to control them. "; - -const Name = struct { id: usize, name: []const u8 }; - -fn collect(comptime T: type, v: *const T, comptime path: []const u8, list: *std.ArrayList(Name), a: std.mem.Allocator) !void { - if (T == mtl.Pipeline) return list.append(a, .{ .id = @intFromPtr(v.id), .name = path }); - switch (@typeInfo(T)) { - .@"struct" => |s| inline for (s.field_names, s.field_types, s.field_attrs) |f, F, attrs| { - if (!attrs.@"comptime") try collect(F, &@field(v.*, f), path ++ "." ++ f, list, a); - }, - .optional => |o| if (v.*) |*x| try collect(o.child, x, path, list, a), - .array => |ar| for (v) |*x| try collect(ar.child, x, path ++ "[]", list, a), - .@"union" => |u| if (u.tag_type != null) switch (v.*) { - inline else => |*x, tag| try collect(@TypeOf(x.*), x, path ++ "." ++ @tagName(tag), list, a), - }, - else => {}, - } -} - -fn nameOf(names: []const Name, id: usize) []const u8 { - for (names) |n| if (n.id == id) return n.name; - return "?"; -} - -fn bf16(word: u16) f32 { - return @bitCast(@as(u32, word) << 16); -} - -fn argmax(row: []const u16) !u32 { - var best: u32 = 0; - var top: f32 = -std.math.inf(f32); - for (row, 0..) |w, i| { - const v = bf16(w); - if (std.math.isNan(v)) return error.NanLogit; - if (v > top) { - top = v; - best = @intCast(i); - } - } - return best; -} - -const Stage = struct { label: []const u8, ns: f64 = 0, count: usize = 0 }; -const Pass = struct { next: u32, gpu: f64 }; - -/// DFly2 drafting and greedy lane verification. The draft writes its block's KV into the target layers it shares, -/// at positions the verify pass rewrites before any read, so rejection needs no rollback. -const Lanes = struct { - draft: dfly.Draft, - frame: dfly.Frame, - ids: mtl.Buffer, - previous: mtl.Buffer, - tokens: mtl.Buffer, - positions: mtl.Buffer, - writes: mtl.Buffer, - keys: mtl.Buffer, - counts: mtl.Buffer, - caches: []target.LayerCache, - mask: u32, - rounds: usize = 0, - kept: usize = 0, - proposed: usize = 0, - draft_gpu: f64 = 0, - verify_gpu: f64 = 0, - profile_rounds: u32 = 0, - stage_wall: f64 = 0, - copy_rounds: usize = 0, - - fn init(a: std.mem.Allocator, run: *Run) !Lanes { - var draft = try dfly.Draft.open(a, run.device, &run.model.host); - errdefer draft.deinit(); - const frame = try dfly.Frame.init(a, run.device, run.model, &draft, 1, capacity); - const opts = mtl.ResourceOptions.shared; - const w = draft.width; - const out: Lanes = .{ - .draft = draft, - .frame = frame, - .ids = try run.device.buffer(w * 4, opts), - .previous = try run.device.buffer(4, opts), - .tokens = try run.device.buffer(16 * 4, opts), - .positions = try run.device.buffer(w * 3 * 4, opts), - .writes = try run.device.buffer(w * 4, opts), - .keys = try run.device.buffer(@as(usize, w) * capacity * 4, opts), - .counts = try run.device.buffer(w * 4, opts), - .caches = try a.alloc(target.LayerCache, draft.blocks.len), - .mask = run.model.host.config.value.dfly_mask_token_id, - }; - for (out.caches, draft.blocks) |*c, block| c.* = .{ .rows = .{ - .positions = .{ .buffer = out.positions }, - .write_slots = .{ .buffer = out.writes }, - .retained = .{ .buffer = out.keys }, - .counts = .{ .buffer = out.counts }, - .cache = .{ .buffer = run.caches[block.target_kv] }, - .capacity = capacity, - }, .key_stride = capacity }; - return out; - } - - fn submit(run: *Run, cb: mtl.CommandBuffer) !f64 { - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("draft command buffer failed: {s}\n", .{why}); - return error.Hy4ProbeCommandFailed; - } - _ = run; - return cb.gpuSeconds(); - } - - /// Encode and commit the DFly2 chain for `count` tokens after `bonus` at position `p`, from the target's final - /// hidden row `source`: the block pass, then per column the correction, readout and a GPU argmax whose token the - /// next column reads, so one command buffer and no host trips. Read the tokens after `land`. - fn launch(self: *Lanes, run: *Run, p: u32, bonus: u32, source: u32, count: u32) !struct { cb: mtl.CommandBuffer, segs: usize, c0: mtl.counters.ClockSample } { - const w = self.draft.width; - const ids = self.ids.slice(u32, w); - @memset(ids, self.mask); - ids[0] = bonus; - const pos3 = self.positions.slice(i32, w * 3); - const wr = self.writes.slice(i32, w); - const stride: u32 = ((p + w + window - 1) / window) * window; - const keys = self.keys.slice(u32, @as(usize, w) * capacity); - const counts = self.counts.slice(u32, w); - for (0..w) |i| { - const at = p + @as(u32, @intCast(i)); - pos3[i * 3 ..][0..3].* = @splat(@intCast(at)); - wr[i] = @intCast(at); - for (0..at + 1) |j| keys[i * stride + j] = @intCast(j); - counts[i] = at + 1; - } - for (self.caches) |*c| c.key_stride = stride; - const h = self.draft.hidden; - const hidden = run.frame.common.normalized; - const anchor: target.Ref = .{ .buffer = hidden.buffer, .offset = hidden.offset + @as(usize, source) * h * 2 }; - const rows = run.model.common.rows orelse return error.Hy4ProbeNeedsRowKernels; - const cb = run.queue.commandBuffer().retain(); - const profile = self.profile_rounds > 0; - var split = if (profile) try mtl.Splitter.timed(cb, run.pass.?, run.samples.?, run.segments) else mtl.Splitter.plain(cb, run.segments); - const c0 = if (profile) mtl.counters.sampleClocks(run.device) else mtl.counters.ClockSample{}; - const e = split.encoder(); - try self.draft.encode(run.model, e, &self.frame, .{ .buffer = self.ids }, anchor, 1, self.caches); - e.barrier(); - for (0..count) |c| { - const previous: target.Ref = if (c == 0) .{ .buffer = self.ids } else .{ .buffer = self.tokens, .offset = (c - 1) * 4 }; - const logits = try self.draft.next(run.model, e, &self.frame, previous, @intCast(c + 1)); - e.barrier(); - rows.pick(e, logits, .{ .buffer = self.tokens }, @intCast(c), 1, run.vocab); - e.barrier(); - } - const segs = split.finish(); - cb.commit(); - return .{ .cb = cb, .segs = segs, .c0 = c0 }; - } - - fn land(self: *Lanes, run: *Run, l: anytype, count: u32, out: []u32) !void { - l.cb.wait(); - defer l.cb.release(); - if (l.cb.failure()) |why| { - std.debug.print("draft command buffer failed: {s}\n", .{why}); - return error.Hy4ProbeCommandFailed; - } - self.draft_gpu += l.cb.gpuSeconds(); - if (self.profile_rounds > 0) try run.account(l.segs, l.c0, mtl.counters.sampleClocks(run.device)); - @memcpy(out[0..count], self.tokens.slice(u32, count)); - } -}; - -const Run = struct { - a: std.mem.Allocator, - device: mtl.Device, - queue: mtl.Queue, - model: *target.Model, - frame: *target.Frame, - positions: mtl.Buffer, - writes: mtl.Buffer, - slide_keys: mtl.Buffer, - slide_counts: mtl.Buffer, - sparse_keys: mtl.Buffer, - sparse_counts: mtl.Buffer, - /// Each row's key range [lo, hi) for sliding and for sparse layers, and each 32-key tile's first slot (slots - /// are positions here), for the tensor units' flash kernel. - slide_ranges: mtl.Buffer, - sparse_ranges: mtl.Buffer, - tiles: mtl.Buffer, - caches: []mtl.Buffer, - lanes: []target.LayerCache, - sliding: []bool, - /// TF_HY4_INDEX: the compressed indexer's caches (sparse layers), so contexts past 2,048 recall groups. - indexed: bool = false, - picks: mtl.Buffer, - all_logits: bool = false, - pad: u32, - vocab: u32, - // profile - names: []const Name, - pass: ?mtl.counters.ComputePass = null, - samples: ?mtl.counters.SampleBuffer = null, - segments: []mtl.Segment, - stages: std.StringArrayHashMapUnmanaged(Stage) = .empty, - profiled: usize = 0, - - /// One forward over `tokens` at positions start.. with full history `history` (tokens before start). - fn step(self: *Run, history: []const u32, start: u32, tokens: []const u32, profile: bool) !Pass { - return self.stepRows(history, start, tokens, profile, null); - } - - /// Engram windows and the frame's ids for `tokens` at positions start.. (history holds the tokens before). - fn stage(self: *Run, history: []const u32, start: u32, tokens: []const u32) !void { - const n: u32 = @intCast(tokens.len); - var windows: [max_rows][engram.order]u32 = undefined; - var media: [max_rows]u32 = @splat(0); - for (tokens, 0..) |t, r| { - const pos = start + @as(u32, @intCast(r)); - windows[r][0] = t; - for (1..engram.order) |lag| { - windows[r][lag] = if (lag <= r) tokens[r - lag] else if (lag <= pos) history[pos - lag] else self.pad; - } - } - try self.frame.stage(self.model, tokens, windows[0..n], media[0..n]); - } - - /// Positions, write slots and every layer's key list for `n` rows at start.. - fn layout(self: *Run, start: u32, n: u32) void { - const pos3 = self.positions.slice(i32, max_rows * 3); - const wr = self.writes.slice(i32, max_rows); - const last_end = start + n; - const sparse_stride: u32 = ((last_end + window - 1) / window) * window; - const sk = self.slide_keys.slice(u32, max_rows * window); - const sc = self.slide_counts.slice(u32, max_rows); - const pk = self.sparse_keys.slice(u32, max_rows * capacity); - const pc = self.sparse_counts.slice(u32, max_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; - for (0..end) |j| pk[r * sparse_stride + j] = @intCast(j); - pc[r] = end; - self.slide_ranges.slice([2]u32, max_rows)[r] = .{ end - count, end }; - self.sparse_ranges.slice([2]u32, max_rows)[r] = .{ 0, end }; - } - const lists = self.indexed and last_end - 1 >= index.keys_a_row; - if (self.indexed) self.frame.index.stage(start, n) catch unreachable; - for (self.lanes, self.sliding) |*lane, slide| { - lane.key_stride = if (slide) window else if (lists) index.keys_a_row else sparse_stride; - lane.rows.live_keys = if (slide) @min(last_end, window) else last_end; - } - } - - /// The target pass over the staged rows with every row's greedy token into `picks`, encoded, not committed. - fn encodePicks(self: *Run, n: u32) !mtl.CommandBuffer { - const rows = self.model.common.rows orelse return error.Hy4ProbeNeedsRowKernels; - const cb = self.queue.commandBuffer().retain(); - var split = mtl.Splitter.plain(cb, self.segments); - const e = split.encoder(); - const logits = try self.model.encode(e, self.frame, self.lanes); - e.barrier(); - rows.pick(e, logits, .{ .buffer = self.picks }, 0, n, self.vocab); - _ = split.finish(); - return cb; - } - - /// `step`, with every row's greedy token in `each` when given. - fn stepRows(self: *Run, history: []const u32, start: u32, tokens: []const u32, profile: bool, each: ?[]u32) !Pass { - const n: u32 = @intCast(tokens.len); - try self.stage(history, start, tokens); - self.layout(start, n); - // prompt chunks (no per-row picks asked) read out only their last row - self.frame.last_logits = each == null and n > 1 and !self.all_logits; - defer self.frame.last_logits = false; - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - const cb = self.queue.commandBuffer(); - var split = if (profile) - try mtl.Splitter.timed(cb, self.pass.?, self.samples.?, self.segments) - else - mtl.Splitter.plain(cb, self.segments); - const c0 = if (profile) mtl.counters.sampleClocks(self.device) else mtl.counters.ClockSample{}; - const logits = try self.model.encode(split.encoder(), self.frame, self.lanes); - const segs = split.finish(); - cb.commit(); - cb.wait(); - if (cb.failure()) |why| { - std.debug.print("command buffer failed: {s}\n", .{why}); - return error.Hy4ProbeCommandFailed; - } - if (profile) try self.account(segs, c0, mtl.counters.sampleClocks(self.device)); - const out_rows: usize = if (self.frame.last_logits) 1 else n; - const all = logits.buffer.slice(u16, out_rows * self.vocab); - if (each) |out| for (0..n) |r| { - out[r] = try argmax(all[r * self.vocab ..][0..self.vocab]); - }; - return .{ .next = try argmax(all[(out_rows - 1) * self.vocab ..][0..self.vocab]), .gpu = cb.gpuSeconds() }; - } - - fn account(self: *Run, segs: usize, c0: mtl.counters.ClockSample, c1: mtl.counters.ClockSample) !void { - const resolved = try self.samples.?.resolveCompleted(2 * segs); - defer resolved.deinit(); - const v = resolved.values(); - const ratio = @as(f64, @floatFromInt(c1.cpu - c0.cpu)) / @as(f64, @floatFromInt(c1.gpu - c0.gpu)); - for (self.segments[0..segs], 0..) |seg, i| { - const t0 = v[2 * i].timestamp; - const t1 = v[2 * i + 1].timestamp; - if (t0 == mtl.counters.error_value or t1 == mtl.counters.error_value or t1 < t0) continue; - var label: std.ArrayList(u8) = .empty; - for (seg.pipelines[0..seg.named], 0..) |id, k| { - if (k != 0) try label.appendSlice(self.a, " + "); - try label.appendSlice(self.a, nameOf(self.names, id)); - } - if (seg.dispatches > seg.named) try label.print(self.a, " (+{d} dispatches)", .{seg.dispatches - seg.named}); - const key = try label.toOwnedSlice(self.a); - const got = try self.stages.getOrPut(self.a, key); - if (!got.found_existing) got.value_ptr.* = .{ .label = key } else self.a.free(key); - got.value_ptr.ns += @as(f64, @floatFromInt(t1 - t0)) * ratio; - got.value_ptr.count += 1; - } - self.profiled += 1; - } -}; - -/// Copy drafts: the tokens that followed the latest earlier match of the context's last 3 to 8 tokens (the longest -/// match wins), up to `out.len`. Returns how many it found; 0 when nothing earlier matches 3 tokens. -fn copyDraft(context: []const u32, out: []u32) usize { - const n = context.len; - if (n < 4 or out.len == 0) return 0; - var best_len: usize = 0; - var best_end: usize = 0; - var end: usize = n - 1; - while (end > 0) { - end -= 1; - var m: usize = 0; - while (m < 8 and m <= end and context[end - m] == context[n - 1 - m]) m += 1; - if (m > best_len and end + 1 < n) { - best_len = m; - best_end = end; - if (m == 8) break; - } - } - if (best_len < 3) return 0; - const take = @min(out.len, n - 1 - best_end); - @memcpy(out[0..take], context[best_end + 1 ..][0..take]); - return take; -} - -/// TF_HY4_FLASH=slide or sparse limits the flash kernel to one kind of layer (a diagnostic). -fn bf(word: u16) f64 { - return @floatCast(@as(f32, @bitCast(@as(u32, word) << 16))); -} - -/// TF_HY4_ACHECK: one 1-row pass at `at`, then the last layer's attention output against an fp64 reference from the -/// same absorbed query, cache rows and sink (softmax over its key range plus the sink, P V over the 512 latent columns). -fn attentionCheck(run: *Run, hist: []const u32, at: u32) !void { - run.all_logits = false; - _ = try run.step(hist, at, hist[at .. at + 1], false); - const layer = run.model.blocks.len - 1; - const block = &run.model.blocks[layer]; - const heads = block.attention.heads; - const s = &run.frame.common; - const q = s.absorbed.buffer.slice(u16, (s.absorbed.offset / 2) + heads * 576)[s.absorbed.offset / 2 ..]; - const out = s.latent.buffer.slice(u16, (s.latent.offset / 2) + heads * 512)[s.latent.offset / 2 ..]; - const cache = run.caches[layer].slice(u16, capacity * 576); - const sinks = block.attention.sinks.slice(f32, heads); - const range = (if (run.sliding[layer]) run.slide_ranges else run.sparse_ranges).slice([2]u32, max_rows)[0]; - const keys = range[1] - range[0]; - const sc = try run.a.alloc(f64, keys); - defer run.a.free(sc); - var err2: f64 = 0; - var ref2: f64 = 0; - var round2: f64 = 0; - var worst: f64 = 0; - for (0..heads) |h| { - var top: f64 = sinks[h]; - for (0..keys) |j| { - const k = cache[(range[0] + j) * 576 ..][0..576]; - var dot: f64 = 0; - for (0..576) |d| dot += bf(q[h * 576 + d]) * bf(k[d]); - sc[j] = dot * 0.0625; - top = @max(top, sc[j]); - } - var denom: f64 = @exp(@as(f64, sinks[h]) - top); - for (sc) |*v| { - v.* = @exp(v.* - top); - denom += v.*; - } - for (0..512) |c| { - var acc: f64 = 0; - for (0..keys) |j| acc += sc[j] * bf(cache[(range[0] + j) * 576 + c]); - const ref = acc / denom; - const got = bf(out[h * 512 + c]); - const rounded: f64 = @floatCast(@as(f32, @floatCast(ref))); - const r16 = bf(@truncate(@as(u32, @bitCast(@as(f32, @floatCast(rounded)))) >> 16)); - err2 += (got - ref) * (got - ref); - round2 += (r16 - ref) * (r16 - ref); - ref2 += ref * ref; - worst = @max(worst, @abs(got - ref)); - } - } - std.debug.print("ACHECK layer {d} ({s}, {d} heads, keys [{d}, {d})): relative rms error {e:.3} (bf16 truncation of the reference {e:.3}), max |error| {e:.3}\n", .{ layer, if (run.sliding[layer]) "sliding" else "sparse", heads, range[0], range[1], @sqrt(err2 / ref2), @sqrt(round2 / ref2), worst }); -} - -/// TF_HY4_ICHECK (with TF_HY4_INDEX): after a pass, the last sparse layer's indexer against fp64 from the GPU's own -/// inputs: the last row's token-key norm, sampled group keys pooled from the cached token keys (and RoPE'd), and -/// the last row's 511 recalled groups against an fp64 ranking of the GPU's query, group keys and head weights. -fn indexCheck(run: *Run) !void { - var layer: usize = run.model.blocks.len; - while (layer > 0) { - layer -= 1; - if (!run.sliding[layer]) break; - } - const iw = run.model.blocks[layer].attention.index orelse return; - const c = run.lanes[layer].index orelse return; - const sc = &run.frame.index; - const rows = sc.rows; - const pos = sc.first + rows - 1; - const eps: f64 = run.model.host.config.value.text_config.rms_norm_eps; - const tk = c.token_keys.buffer.slice(u16, @as(usize, capacity) * 128); - const gk = c.group_keys.buffer.slice(u16, @as(usize, capacity / 4) * 128); - // the token key norm of the last row - { - const x = sc.keys.buffer.slice(u16, @as(usize, rows) * 128)[(rows - 1) * 128 ..][0..128]; - const gain = iw.token_norm.slice(u16, 128); - var ss: f64 = 0; - for (x) |v| ss += @as(f64, bf(v)) * bf(v); - const inv = 1 / @sqrt(ss / 128 + eps); - var worst: f64 = 0; - var off: usize = 0; - for (0..128) |d| { - const want = bf(gain[d]) * bf(rne(bf(x[d]) * inv)); - const got = bf(tk[pos * 128 + d]); - worst = @max(worst, @abs(got - want)); - if (rne(want) != tk[pos * 128 + d]) off += 1; - } - std.debug.print("ICHECK token key at {d}: {d}/128 off the rounded fp64, worst {e:.3}\n", .{ pos, off, worst }); - } - // group keys: pooled in fp64 from the cached token keys, normalized, rotated at the group's first slot - const vw = iw.values.slice(f32, 128 * 128); - const gw = iw.gates.slice(f32, 128 * 128); - const bias = iw.bias.slice(f32, 4 * 128); - const nw = iw.norm.slice(f32, 128); - const p = run.model.blocks[layer].attention.rope; - const closed = pos / 4; - var worst_g: f64 = 0; - var off_g: usize = 0; - var top_g: f64 = 0; - const samples = [_]u32{ 0, 1, closed / 3, closed / 2, closed -| 2, closed -| 1 }; - for (samples) |g| { - var pooled: [128]f64 = undefined; - var v: [4][128]f64 = undefined; - var z: [4][128]f64 = undefined; - for (0..4) |slot| for (0..128) |o| { - var sv: f64 = 0; - var sg: f64 = 0; - for (0..128) |k| { - const xk: f64 = bf(tk[(@as(usize, g) * 4 + slot) * 128 + k]); - sv += @as(f64, vw[o * 128 + k]) * xk; - sg += @as(f64, gw[o * 128 + k]) * xk; - } - v[slot][o] = sv; - z[slot][o] = sg + bias[slot * 128 + o]; - }; - var ss: f64 = 0; - for (0..128) |o| { - var m: f64 = -std.math.inf(f64); - for (0..4) |slot| m = @max(m, z[slot][o]); - var den: f64 = 0; - for (0..4) |slot| den += @exp(z[slot][o] - m); - var acc: f64 = 0; - for (0..4) |slot| acc += v[slot][o] * @exp(z[slot][o] - m) / den; - pooled[o] = acc; - ss += acc * acc; - } - const inv = 1 / @sqrt(ss / 128 + eps); - var key: [128]f64 = undefined; - for (0..128) |o| key[o] = bf(rne(nw[o] * pooled[o] * inv)); - for (0..32) |i| { - const phase: f64 = @as(f64, @floatFromInt(g * 4)) * p.frequencies[i]; - const cs: f64 = bf(rne(@cos(phase))); - const sn: f64 = bf(rne(@sin(phase))); - const a0 = key[64 + 2 * i]; - const b0 = key[64 + 2 * i + 1]; - key[64 + 2 * i] = a0 * cs - b0 * sn; - key[64 + 2 * i + 1] = b0 * cs + a0 * sn; - } - for (0..128) |o| { - const got: f64 = bf(gk[@as(usize, g) * 128 + o]); - worst_g = @max(worst_g, @abs(got - key[o])); - top_g = @max(top_g, @abs(key[o])); - if (rne(key[o]) != gk[@as(usize, g) * 128 + o]) off_g += 1; - } - } - std.debug.print("ICHECK group keys ({d} groups): {d}/{d} off the rounded fp64, worst {e:.3} of max |k| {d:.3}\n", .{ samples.len, off_g, samples.len * 128, worst_g, top_g }); - if (closed < index.budget_groups) { - std.debug.print("ICHECK recall: row at {d} keeps every group\n", .{pos}); - return; - } - // the last row's ranking - const q = sc.query.buffer.slice(u16, @as(usize, rows) * 2048)[(rows - 1) * 2048 ..][0..2048]; - const hw = sc.head_weights.buffer.slice(u16, @as(usize, rows) * 16)[(rows - 1) * 16 ..][0..16]; - const scores = try run.a.alloc(f64, closed); - defer run.a.free(scores); - for (scores, 0..) |*sco, g| { - var acc: f64 = 0; - for (0..16) |h| { - var dot: f64 = 0; - for (0..128) |d| dot += @as(f64, bf(q[h * 128 + d])) * bf(gk[g * 128 + d]); - acc += @as(f64, bf(hw[h])) * @as(f64, @import("index_recall.zig").head_scale) * @max(dot, 0); - } - sco.* = acc; - } - const order = try run.a.alloc(u32, closed); - defer run.a.free(order); - for (order, 0..) |*o, i| o.* = @intCast(i); - std.mem.sort(u32, order, scores, struct { - fn more(sv: []f64, x: u32, y: u32) bool { - return sv[x] > sv[y]; - } - }.more); - const keep = index.budget_groups - 1; - const want = try run.a.alloc(bool, closed); - defer run.a.free(want); - @memset(want, false); - for (order[0..keep]) |g| want[g] = true; - const threshold = scores[order[keep - 1]]; - const list = c.tokens.buffer.slice(i32, @as(usize, rows) * index.keys_a_row)[(rows - 1) * index.keys_a_row ..][0..index.keys_a_row]; - const count = c.counts.buffer.slice(i32, rows)[rows - 1]; - var missing: usize = 0; - var worst_gap: f64 = 0; - for (0..keep) |i| { - const g: usize = @intCast(@divTrunc(list[i * 4], 4)); - if (g >= closed or !want[g]) { - missing += 1; - if (g < closed) worst_gap = @max(worst_gap, (threshold - scores[g]) / @max(@abs(threshold), 1e-30)); - } - } - var own_ok = true; - for (keep * 4..@as(usize, @intCast(count))) |i| own_ok = own_ok and list[i] == @as(i32, @intCast(closed * 4 + (i - keep * 4))); - std.debug.print("ICHECK recall at {d}: {d} slots, {d}/{d} groups outside the fp64 top {d} (worst relative gap {e:.2} at threshold {d:.4}), own group {s}\n", .{ pos, count, missing, keep, keep, worst_gap, threshold, if (own_ok) "ok" else "WRONG" }); -} - -fn rne(v: f64) u16 { - const f: f32 = @floatCast(v); - const b: u32 = @bitCast(f); - return @truncate((b + 0x7fff + ((b >> 16) & 1)) >> 16); -} - -fn flashFor(slide: bool) bool { - const v = std.mem.span(std.c.getenv("TF_HY4_FLASH") orelse return true); - return if (std.mem.eql(u8, v, "slide")) slide else if (std.mem.eql(u8, v, "sparse")) !slide else true; -} - -fn fnv(ids: []const u32) u64 { - var h: u64 = 0xcbf29ce484222325; - for (ids) |id| for (std.mem.asBytes(&id)) |b| { - h ^= b; - h *%= 0x100000001b3; - }; - return h; -} - -pub fn main(init: std.process.Init) !void { - const a = std.heap.page_allocator; - const io = init.io; - const args = try init.minimal.args.toSlice(init.arena.allocator()); - if (args.len < 3) { - std.debug.print("usage: tf-hy4-speed MODEL_DIR GEN [--profile STEPS] [--long TOKENS] [--chunk ROWS]\n", .{}); - return error.Usage; - } - const dir = args[1]; - const gen = try std.fmt.parseInt(u32, args[2], 10); - if (std.c.getenv("TF_HY4_CAPACITY")) |v| capacity = std.fmt.parseInt(u32, std.mem.span(v), 10) catch 2048; - if (capacity < 2048 or capacity % 512 != 0) return error.BadCapacity; - var profile_steps: u32 = 0; - var long_tokens: u32 = 0; - var chunk: u32 = 16; - var rows_time = false; - var lane_rows: u32 = 0; - var warm_engram = false; - var text_path: ?[]const u8 = null; - var nll = false; - const nll_dump = std.c.getenv("TF_HY4_NLL_DUMP") != null; - var copies = false; - const adapt: ?[2]u32 = if (std.c.getenv("TF_HY4_ADAPT")) |v| blk: { - var it = std.mem.splitScalar(u8, std.mem.span(v), ','); - const lo = std.fmt.parseInt(u32, it.next() orelse "2", 10) catch 2; - const hi = std.fmt.parseInt(u32, it.next() orelse "6", 10) catch 6; - break :blk .{ @max(2, lo), @min(6, hi) }; - } else null; - const profile_prompt: usize = if (std.c.getenv("TF_HY4_PROFILE_PROMPT")) |v| (std.fmt.parseInt(usize, std.mem.span(v), 10) catch 0) else 0; - var i: usize = 3; - if (args.len > 3 and std.mem.eql(u8, args[3], "--rows-time")) { - rows_time = true; - i = 4; - } - while (i + 1 < args.len) : (i += 2) { - if (std.mem.eql(u8, args[i], "--profile")) profile_steps = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--long")) long_tokens = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--chunk")) chunk = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--lanes")) lane_rows = try std.fmt.parseInt(u32, args[i + 1], 10) else if (std.mem.eql(u8, args[i], "--text")) { - text_path = args[i + 1]; - } else if (std.mem.eql(u8, args[i], "--nll")) { - nll = std.mem.eql(u8, args[i + 1], "1"); - } else if (std.mem.eql(u8, args[i], "--copies")) { - copies = std.mem.eql(u8, args[i + 1], "1"); - } else if (std.mem.eql(u8, args[i], "--warm-engram")) { - warm_engram = std.mem.eql(u8, args[i + 1], "1"); - } else return error.Usage; - } - if (chunk == 0 or chunk > max_rows) return error.BadChunk; - - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - const device = try mtl.Device.init(); - defer device.deinit(); - const queue = try device.queue(); - defer queue.deinit(); - std.debug.print("device {s}, tensor units {}\n", .{ device.name(), device.tensorUnits() }); - - const tok_path = try std.fs.path.join(a, &.{ dir, "tokenizer.json" }); - var tok = try core.tokenizer.loadTokenizer(io, a, tok_path); - defer tok.deinit(); - - const t_load = mtl.clock.seconds(); - var model = try target.Model.open(a, io, device, dir); - defer model.deinit(); - const t = model.host.config.value.text_config; - if (warm_engram) { - // Read every Engram table page once, so lookups find their rows in RAM (a resident-table server). - const tw = mtl.clock.seconds(); - var bytes: usize = 0; - var sink: u8 = 0; - for (model.blocks) |*b| if (b.memory) |*m| { - const tab = m.table.affine; - for ([_][]const u8{ tab.words.bytes, tab.scales.bytes, tab.biases.bytes }) |region| { - var at: usize = 0; - while (at < region.len) : (at += 16384) sink +%= @as(*const volatile u8, ®ion[at]).*; - bytes += region.len; - } - }; - std.debug.print("warmed {d:.1} GB of Engram tables in {d:.1}s ({d})\n", .{ @as(f64, @floatFromInt(bytes)) / 1e9, mtl.clock.seconds() - tw, sink }); - } - var frame = try target.Frame.init(a, device, &model, max_rows, capacity); - defer frame.deinit(); - std.debug.print("{d}-bit model loaded in {d:.3}s, device allocations {d:.3} GB\n", .{ model.host.bits, mtl.clock.seconds() - t_load, @as(f64, @floatFromInt(device.allocated())) / 1e9 }); - - const opts = mtl.ResourceOptions.shared; - var run: Run = .{ - .a = a, - .device = device, - .queue = queue, - .model = &model, - .frame = &frame, - .positions = try device.buffer(max_rows * 3 * 4, opts), - .writes = try device.buffer(max_rows * 4, opts), - .slide_keys = try device.buffer(max_rows * window * 4, opts), - .slide_counts = try device.buffer(max_rows * 4, opts), - .sparse_keys = try device.buffer(max_rows * capacity * 4, opts), - .sparse_counts = try device.buffer(max_rows * 4, opts), - .slide_ranges = try device.buffer(max_rows * 8, opts), - .sparse_ranges = try device.buffer(max_rows * 8, opts), - .tiles = try device.buffer(capacity / 32 * 4, opts), - .caches = try a.alloc(mtl.Buffer, model.blocks.len), - .lanes = try a.alloc(target.LayerCache, model.blocks.len), - .sliding = try a.alloc(bool, model.blocks.len), - .picks = try device.buffer(max_rows * 4, opts), - .pad = t.engram_pad_id, - .vocab = t.vocab_size, - .names = &.{}, - .segments = try a.alloc(mtl.Segment, mtl.max_segments), - }; - for (run.caches, run.lanes, run.sliding, 0..) |*c, *lane, *slide, l| { - c.* = try device.buffer(@as(usize, capacity) * key_width * 2, opts); - slide.* = t.layer_types[l] == .sliding_attention; - lane.* = .{ .rows = .{ - .positions = .{ .buffer = run.positions }, - .write_slots = .{ .buffer = run.writes }, - .retained = .{ .buffer = if (slide.*) run.slide_keys else run.sparse_keys }, - .counts = .{ .buffer = if (slide.*) run.slide_counts else run.sparse_counts }, - .cache = .{ .buffer = c.* }, - .capacity = capacity, - .ranges = if (std.c.getenv("TF_HY4_NO_FLASH") == null and flashFor(slide.*)) .{ .ranges = .{ .buffer = if (slide.*) run.slide_ranges else run.sparse_ranges }, .tiles = .{ .buffer = run.tiles } } else null, - }, .key_stride = if (slide.*) window else capacity }; - } - for (run.tiles.slice(u32, capacity / 32), 0..) |*t_, i_| t_.* = @intCast(32 * i_); - if (std.c.getenv("TF_HY4_INDEX") != null) { - // one score row a pass row, shared by the sparse layers; each sparse layer's own token and group keys and lists - const scores = try device.buffer(@as(usize, max_rows) * (capacity / 4) * 4, mtl.ResourceOptions.private); - for (run.lanes, run.sliding) |*lane, slide| { - if (slide) continue; - lane.index = .{ - .token_keys = .{ .buffer = try device.buffer(index.Cache.tokenBytes(capacity), opts) }, - .group_keys = .{ .buffer = try device.buffer(index.Cache.groupBytes(capacity), opts) }, - .capacity = capacity, - .scores = .{ .buffer = scores }, - .score_groups = capacity / 4, - .tokens = .{ .buffer = try device.buffer(@as(usize, max_rows) * index.keys_a_row * 4, opts) }, - .counts = .{ .buffer = try device.buffer(max_rows * 4, opts) }, - }; - } - run.indexed = true; - std.debug.print("indexer on: {d} slots\n", .{capacity}); - } - var skip_list: []const usize = &.{}; - if (std.c.getenv("TF_HY4_SKIP")) |list| { - // timing only (--rows-time): drop dispatches whose pipeline name contains any comma-separated part, from the - // timed passes on (after a real warm-up), always with the router's select dropped too, so the picks stay - // the warm-up's real ones and every variant reads the same experts - var names: std.ArrayList(Name) = .empty; - try collect(@TypeOf(model.common), &model.common, "common", &names, a); - try collect(@TypeOf(model.routed), &model.routed, "routed", &names, a); - try collect(@TypeOf(model.memory), &model.memory, "engram", &names, a); - var ids: std.ArrayList(usize) = .empty; - var it = std.mem.splitScalar(u8, std.mem.span(list), ','); - while (it.next()) |part| for (names.items) |n| if (part.len > 0 and std.mem.indexOf(u8, n.name, part) != null) { - try ids.append(a, n.id); - std.debug.print("skip: {s}\n", .{n.name}); - }; - for (names.items) |n| if (std.mem.indexOf(u8, n.name, "routed.select") != null) try ids.append(a, n.id); - skip_list = ids.items; - } - if (profile_steps > 0) { - var names: std.ArrayList(Name) = .empty; - try collect(@TypeOf(model.common), &model.common, "common", &names, a); - try collect(@TypeOf(model.routed), &model.routed, "routed", &names, a); - try collect(@TypeOf(model.memory), &model.memory, "engram", &names, a); - try collect(mtl.Pipeline, &model.head.lookup, "head.embed", &names, a); - run.names = names.items; - run.pass = try mtl.counters.ComputePass.init(); - run.samples = try mtl.counters.SampleBuffer.init(device, 2 * mtl.max_segments); - std.debug.print("profile: {d} named pipelines, counter mode {s}\n", .{ names.items.len, @tagName(mtl.counters.query(device).mode()) }); - } - - // Build the prompt list: the short set, and optionally a long prompt near `long_tokens` tokens. - var lists: std.ArrayList([]u32) = .empty; - for (prompts) |p| { - const ids = try tok.encode(a, p); - const with = try a.alloc(u32, ids.len + 1); - with[0] = bos; - @memcpy(with[1..], ids); - try lists.append(a, with); - } - if (long_tokens > 0) { - var text: std.ArrayList(u8) = .empty; - var ids = try tok.encode(a, ""); - while (ids.len < long_tokens) { - try text.appendSlice(a, long_text); - ids = try tok.encode(a, text.items); - } - try text.appendSlice(a, "\nSummarize the passage above in one paragraph.\n"); - ids = try tok.encode(a, text.items); - const with = try a.alloc(u32, ids.len + 1); - with[0] = bos; - @memcpy(with[1..], ids); - try lists.append(a, with); - } - - if (text_path) |path| { - // one prompt from a file: its first 1,900 tokens after BOS - const body = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 22)); - const ids = try tok.encode(a, body); - const n = @min(ids.len, if (std.c.getenv("TF_HY4_TEXT_TOKENS")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 1900 else 1900); - const with = try a.alloc(u32, n + 1); - with[0] = bos; - @memcpy(with[1..], ids[0..n]); - lists.items.len = 0; - try lists.append(a, with); - } - // Lanes: a first, untimed copy of prompt 0 warms the draft and multi-row pipelines. - const warm_lanes = lane_rows > 1; - if (warm_lanes) try lists.insert(a, 0, lists.items[0]); - var total_wall: f64 = 0; - var total_gpu: f64 = 0; - var total_tokens: usize = 0; - var all_ids: std.ArrayList(u32) = .empty; - if (std.c.getenv("TF_HY4_KCHECK")) |_| { - // every dense kernel against an fp64 reference on real weights and random rows - const dense = @import("metal_dense.zig"); - const Case = struct { name: []const u8, w: dense.Linear }; - const b1 = &model.blocks[1]; - const b2 = &model.blocks[2]; - var cases: std.ArrayList(Case) = .empty; - try cases.append(a, .{ .name = "o (sparse layer)", .w = b1.attention.o }); - try cases.append(a, .{ .name = "o (sliding layer)", .w = b2.attention.o }); - try cases.append(a, .{ .name = "latent down", .w = b1.feed.routed.down }); - try cases.append(a, .{ .name = "latent up", .w = b1.feed.routed.up }); - try cases.append(a, .{ .name = "shared gate", .w = b1.feed.routed.shared_gate }); - try cases.append(a, .{ .name = "shared down", .w = b1.feed.routed.shared_down }); - try cases.append(a, .{ .name = "lm_head", .w = model.head.vocab }); - var prng = std.Random.DefaultPrng.init(7); - const rnd = prng.random(); - for (cases.items) |c| { - const plain = switch (c.w) { - .portable => |w| w, - .tensor => |tw| tw.plain orelse return error.KcheckNeedsPlain, - }; - const n: usize = plain.n; - const k: usize = plain.k; - for ([_]u32{ 1, 4 }) |rows| { - const xb = try device.buffer(rows * k * 2, opts); - const xs = xb.slice(u16, rows * k); - for (xs) |*v| v.* = @truncate(@as(u32, @bitCast(@as(f32, @floatCast(rnd.floatNorm(f64))))) >> 16); - // fp64 reference - const ref = try a.alloc(f64, rows * n); - const words = plain.w.slice(u32, plain.w.length() / 4); - const scales = plain.scales.slice(u16, plain.scales.length() / 2); - const biases = plain.biases.slice(u16, plain.biases.length() / 2); - const per_row = k * plain.bits / 32; - const groups = k / plain.group; - for (0..rows) |r| for (0..n) |o| { - var acc: f64 = 0; - for (0..k) |col| { - const bitpos = col * plain.bits; - const word = words[o * per_row + bitpos / 32]; - const q: f64 = @floatFromInt((word >> @intCast(bitpos % 32)) & ((@as(u32, 1) << @intCast(plain.bits)) - 1)); - const g = col / plain.group; - const wv = bf16(scales[o * groups + g]) * q + bf16(biases[o * groups + g]); - acc += @as(f64, bf16(xs[r * k + col])) * wv; - } - ref[r * n + o] = acc; - }; - var worst: [3]f64 = @splat(0); - var scale_max: f64 = 0; - for (ref) |v| scale_max = @max(scale_max, @abs(v)); - for ([_]?u32{ 8, 0, 0 }, 0..) |override, kind| { - const yb = try device.buffer(rows * n * 2, opts); - const p2 = mtl.objc.Pool.push(); - defer p2.pop(); - const cb = queue.commandBuffer(); - var split = mtl.Splitter.plain(cb, run.segments); - const e = split.encoder(); - dense.decode_rows_override = override; - switch (kind) { - 0 => try model.common.project(e, plain, .{ .buffer = xb }, .{ .buffer = yb }, rows), - 1 => try model.common.project(e, plain, .{ .buffer = xb }, .{ .buffer = yb }, rows), - else => if (c.w == .tensor) try model.common.linear(e, c.w, .{ .buffer = xb }, .{ .buffer = yb }, rows), - } - dense.decode_rows_override = null; - _ = split.finish(); - cb.commit(); - cb.wait(); - if (kind == 2 and c.w != .tensor) continue; - const ys = yb.slice(u16, rows * n); - for (0..rows * n) |idx| worst[kind] = @max(worst[kind], @abs(@as(f64, bf16(ys[idx])) - ref[idx])); - } - std.debug.print("KCHECK {s:18} n {d:6} k {d:5} bits {d} rows {d}: max |y| {d:.4}; max error: decode GEMV {d:.5}, row kernels {d:.5}, tensor lanes {d:.5}\n", .{ c.name, n, k, plain.bits, rows, scale_max, worst[0], worst[1], worst[2] }); - } - } - return; - } - if (std.c.getenv("TF_HY4_BOS_TOP")) |_| { - // the first token's logits after BOS alone, against the MLX reference's top five - var hist: [1]u32 = .{bos}; - _ = try run.step(&hist, 0, hist[0..1], false); - const row = frame.logits.buffer.slice(u16, run.vocab); - var top: [5]u32 = @splat(0); - var used: [5]bool = @splat(false); - _ = &used; - for (0..5) |k| { - var best: f32 = -std.math.inf(f32); - var id: u32 = 0; - for (row, 0..) |w, t_| { - const v = bf16(w); - var seen = false; - for (top[0..k]) |p_| seen = seen or p_ == t_; - if (!seen and v > best) { - best = v; - id = @intCast(t_); - } - } - top[k] = id; - std.debug.print("BOS TOP {d}: id {d} logit {d:.4}\n", .{ k, id, bf16(row[id]) }); - } - return; - } - if (std.c.getenv("TF_HY4_BARRIER_TEST")) |_| { - // the cost of a dispatch and of a barrier on this GPU: 1400 tiny argmax launches over 64 values - const rows = model.common.rows orelse return error.Hy4ProbeNeedsRowKernels; - for ([_]bool{ false, true }) |barriers| { - var best: f64 = 1e9; - for (0..5) |_| { - const p2 = mtl.objc.Pool.push(); - defer p2.pop(); - const cb = queue.commandBuffer(); - var split = mtl.Splitter.plain(cb, run.segments); - const e = split.encoder(); - for (0..1400) |_| { - rows.pick(e, frame.logits, .{ .buffer = run.picks }, 0, 1, 64); - if (barriers) e.barrier(); - } - _ = split.finish(); - cb.commit(); - cb.wait(); - best = @min(best, cb.gpuSeconds()); - } - std.debug.print("BARRIER TEST: 1400 tiny dispatches {s}: {d:.3} ms GPU ({d:.2} us each)\n", .{ if (barriers) "each followed by a barrier" else "with no barriers", 1000 * best, 1e6 * best / 1400.0 }); - } - return; - } - var lanes: ?Lanes = if (lane_rows > 1) try Lanes.init(a, &run) else null; - if (lanes) |*l| { - if (lane_rows > l.draft.width) return error.Hy4ProbeTooManyLaneRows; - std.debug.print("lanes: DFly2 {d} layers, block {d}, verifying {d} rows a round\n", .{ l.draft.blocks.len, l.draft.width, lane_rows }); - if (run.pass != null) { - var more: std.ArrayList(Name) = .empty; - try more.appendSlice(a, run.names); - try collect(mtl.Pipeline, &l.draft.fuse, "draft.fuse", &more, a); - try collect(mtl.Pipeline, &l.draft.residual, "draft.residual", &more, a); - run.names = more.items; - } - } - // warm the pipelines and caches: a short untimed decode - { - var hist: [64]u32 = undefined; - hist[0] = bos; - var next = (try run.step(&hist, 0, hist[0..1], false)).next; - for (1..8) |p| { - hist[p] = next; - next = (try run.step(&hist, @intCast(p), hist[p .. p + 1], false)).next; - } - } - if (rows_time) { - // One prompt, `gen` plain tokens, then target passes over R real rows at a fixed position (rewritten each time). - // With --long or --text: that long prompt instead of the short set's second, and passes that fit the cache. - const prompt = if (long_tokens > 0 or text_path != null) lists.items[lists.items.len - 1] else lists.items[1]; - const hist = try a.alloc(u32, prompt.len + gen + max_rows); - @memcpy(hist[0..prompt.len], prompt); - var start: u32 = 0; - var next: u32 = 0; - while (start < prompt.len) { - const n: u32 = @min(chunk, @as(u32, @intCast(prompt.len)) - start); - next = (try run.step(hist, start, hist[start .. start + n], false)).next; - start += n; - } - var pos: u32 = @intCast(prompt.len); - const ahead: usize = if (long_tokens > 0 or text_path != null) 16 else max_rows; - for (0..gen + ahead - 1) |_| { - hist[pos] = next; - next = (try run.step(hist, pos, hist[pos .. pos + 1], false)).next; - pos += 1; - } - const at: u32 = @intCast(prompt.len + gen / 2); - var one: f64 = 0; - run.all_logits = true; - if (skip_list.len > 0) { - // one real pass of every timed width first, so each row's picks are its own - _ = try run.step(hist, at, hist[at .. at + 16], false); - mtl.skip_ids = skip_list; - } - for ([_]u32{ 1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 32, 64, 128, 256, 512 }) |rows| { - if (at + rows + 1 > capacity) break; - var times: [7]f64 = undefined; - for (×) |*tm| tm.* = (try run.step(hist, at, hist[at .. at + rows], false)).gpu; - std.mem.sort(f64, ×, {}, std.sort.asc(f64)); - if (rows == 1) one = times[3]; - std.debug.print("ROWS {d:2}: {d:.3} ms GPU a pass (median of 7, min {d:.3}), {d:.2}x one row, {d:.3} ms a row\n", .{ rows, 1000 * times[3], 1000 * times[0], times[3] / one, 1000 * times[3] / @as(f64, @floatFromInt(rows)) }); - } - mtl.skip_ids = &.{}; - if (std.c.getenv("TF_HY4_ACHECK") != null) try attentionCheck(&run, hist, at); - if (profile_steps == 0) return; - // --profile ROWS in this mode: profile three passes of ROWS rows - for (0..3) |_| _ = try run.step(hist, at, hist[at .. at + profile_steps], true); - lists.items.len = 0; - } - for (lists.items, 0..) |prompt, pi| { - if (prompt.len + gen + 1 > capacity) return error.Hy4ProbeContextTooLong; - const hist = try a.alloc(u32, prompt.len + gen + 16); - @memcpy(hist[0..prompt.len], prompt); - const tp = mtl.clock.seconds(); - var start: u32 = 0; - var next: u32 = 0; - var nll_sum: f64 = 0; - var nll_count: usize = 0; - run.all_logits = nll; - while (start < prompt.len) { - const n: u32 = @min(chunk, @as(u32, @intCast(prompt.len)) - start); - next = (try run.step(hist, start, hist[start .. start + n], false)).next; - if (nll) { - // teacher-forced: each row's log-probability of the prompt's next token - const all = run.frame.logits.buffer.slice(u16, @as(usize, n) * run.vocab); - for (0..n) |r| { - const at = start + r + 1; - if (at >= prompt.len) break; - const row = all[r * run.vocab ..][0..run.vocab]; - var top: f64 = -std.math.inf(f64); - for (row) |w| top = @max(top, bf16(w)); - var z: f64 = 0; - for (row) |w| z += @exp(@as(f64, bf16(w)) - top); - const tok_nll = top + @log(z) - bf16(row[hist[at]]); - nll_sum += tok_nll; - nll_count += 1; - if (nll_dump) std.debug.print("TOKNLL {d} {d:.6}\n", .{ at, tok_nll }); - } - } - start += n; - } - run.all_logits = false; - if (std.c.getenv("TF_HY4_ICHECK") != null and run.indexed) try indexCheck(&run); - if (nll and nll_count > 0) std.debug.print("NLL: {d:.5} nats a token over {d} tokens (perplexity {d:.4})\n", .{ nll_sum / @as(f64, @floatFromInt(nll_count)), nll_count, @exp(nll_sum / @as(f64, @floatFromInt(nll_count))) }); - const prefill = mtl.clock.seconds() - tp; - var pos: u32 = @intCast(prompt.len); - var wall: f64 = 0; - var gpu: f64 = 0; - if (lanes) |*l| { - // hist[pos] is the bonus token (not yet in the cache); the last pass's final row is the anchor. - var source: u32 = (@as(u32, @intCast(prompt.len)) - 1) % chunk; - const goal: u32 = @intCast(prompt.len + gen); - const t0 = mtl.clock.seconds(); - const g0 = l.draft_gpu + l.verify_gpu; - var width: u32 = lane_rows; - while (pos < goal) { - const round_pool = mtl.objc.Pool.push(); - defer round_pool.pop(); - const rows: u32 = @min(width, goal - pos); - var drafts: [8]u32 = undefined; - l.profile_rounds = @intFromBool(profile_steps > 0 and pi == 0 and l.rounds >= 2 and l.rounds < 2 + profile_steps); - // the draft runs while the host encodes the verify pass over placeholder rows - hist[pos] = next; - const copied = if (copies and rows > 1) copyDraft(hist[0 .. pos + 1], drafts[0 .. rows - 1]) else 0; - const flight = if (rows > 1 and copied < rows - 1) try l.launch(&run, pos, next, source, rows - 1) else null; - if (copied == rows - 1) l.copy_rounds += 1; - @memset(hist[pos + 1 .. pos + rows], l.mask); - try run.stage(hist, pos, hist[pos .. pos + rows]); - run.layout(pos, rows); - const verify = try run.encodePicks(rows); - defer verify.release(); - if (flight) |f| try l.land(&run, f, rows - 1, drafts[0 .. rows - 1]); - @memcpy(hist[pos + 1 .. pos + rows], drafts[0 .. rows - 1]); - const ts = mtl.clock.seconds(); - try run.stage(hist, pos, hist[pos .. pos + rows]); - l.stage_wall += mtl.clock.seconds() - ts; - verify.commit(); - verify.wait(); - if (verify.failure()) |why| { - std.debug.print("verify command buffer failed: {s}\n", .{why}); - return error.Hy4ProbeCommandFailed; - } - l.verify_gpu += verify.gpuSeconds(); - const picks = run.picks.slice(u32, rows); - var j: u32 = 0; - while (j + 1 < rows and picks[j] == drafts[j]) j += 1; - l.rounds += 1; - l.kept += j; - l.proposed += rows - 1; - source = j; - pos += j + 1; - next = picks[j]; - // TF_HY4_ADAPT=lo,hi: widen after a round that kept every draft, narrow after one that kept none - if (adapt) |range| { - if (j + 1 == rows and width < range[1]) width += 1 else if (j == 0 and width > range[0]) width -= 1; - } - } - wall = mtl.clock.seconds() - t0; - gpu = l.draft_gpu + l.verify_gpu - g0; - } else for (0..gen) |g| { - hist[pos] = next; - const profile = profile_steps > 0 and pi == profile_prompt and g >= 2 and g < 2 + profile_steps; - const t0 = mtl.clock.seconds(); - const r = try run.step(hist, pos, hist[pos .. pos + 1], profile); - if (!profile) { - wall += mtl.clock.seconds() - t0; - gpu += r.gpu; - } - next = r.next; - pos += 1; - } - const timed: f64 = @floatFromInt(gen - @min(gen, if (pi == 0 and lanes == null) profile_steps else 0)); - const ids = hist[prompt.len .. prompt.len + gen]; - if (warm_lanes and pi == 0) { - if (lanes) |*l| { - l.rounds = 0; - l.kept = 0; - l.proposed = 0; - l.draft_gpu = 0; - l.verify_gpu = 0; - l.stage_wall = 0; - l.copy_rounds = 0; - } - std.debug.print("warm: lanes over prompt 0, untimed\n", .{}); - continue; - } - std.debug.print("prompt {d}, {d} input tokens: prefill {d:.1} tok/s, decode {d:.3} tok/s ({d:.3} ms wall, {d:.3} ms GPU a token), hash {x:0>16}\n", .{ - pi, prompt.len, @as(f64, @floatFromInt(prompt.len)) / prefill, timed / wall, 1000 * wall / timed, 1000 * gpu / timed, fnv(ids), - }); - std.debug.print(" ids {any}\n", .{ids}); - const text = try tok.decode(a, ids, false); - std.debug.print(" text {s}\n", .{text}); - total_wall += wall; - total_gpu += gpu; - total_tokens += @intFromFloat(timed); - try all_ids.appendSlice(a, ids); - } - if (lanes) |l| std.debug.print("LANES: {d} rounds, {d}/{d} drafts kept, {d:.3} tokens a round, draft {d:.3} ms and verify {d:.3} ms GPU a round, Engram restage {d:.3} ms a round, {d} copy rounds\n", .{ - l.rounds, l.kept, l.proposed, @as(f64, @floatFromInt(l.kept + l.rounds)) / @as(f64, @floatFromInt(l.rounds)), 1000 * l.draft_gpu / @as(f64, @floatFromInt(l.rounds)), 1000 * l.verify_gpu / @as(f64, @floatFromInt(l.rounds)), 1000 * l.stage_wall / @as(f64, @floatFromInt(l.rounds)), l.copy_rounds, - }); - const tt: f64 = @floatFromInt(total_tokens); - std.debug.print("SUMMARY: {d} prompts, decode {d:.3} tok/s, {d:.3} ms wall and {d:.3} ms GPU a token, all-ids hash {x:0>16}\n", .{ lists.items.len - @intFromBool(warm_lanes), tt / total_wall, 1000 * total_wall / tt, 1000 * total_gpu / tt, fnv(all_ids.items) }); - - if (run.profiled > 0) { - const steps: f64 = @floatFromInt(run.profiled); - const items = run.stages.values(); - std.mem.sort(Stage, items, {}, struct { - fn more(_: void, x: Stage, y: Stage) bool { - return x.ns > y.ns; - } - }.more); - var sum: f64 = 0; - for (items) |s| sum += s.ns; - std.debug.print("PROFILE over {d} decode steps: {d:.3} ms a token in {d} timed segments a token\n", .{ run.profiled, sum / steps / 1e6, @divTrunc(blk: { - var c: usize = 0; - for (items) |s| c += s.count; - break :blk c; - }, run.profiled) }); - for (items) |s| { - std.debug.print(" {d:8.3} ms {d:5.1}% x{d:<4} {s}\n", .{ s.ns / steps / 1e6, 100 * s.ns / sum, s.count / run.profiled, s.label }); - } - } -} diff --git a/zig/src/families/hy4_flash/split_metal.zig b/zig/src/families/hy4_flash/split_metal.zig deleted file mode 100644 index ff33b125bb4..00000000000 --- a/zig/src/families/hy4_flash/split_metal.zig +++ /dev/null @@ -1,172 +0,0 @@ -//! The engine's Metal module for the Hy4-flash speed probe. Everything is the real module except ComputeEncoder, -//! which forwards to a real encoder and, while a Splitter is splitting, turns each barrier into an encoder boundary -//! whose start and end the GPU timestamps. Without splitting a barrier stays a barrier, so timed runs match the engine. -const std = @import("std"); -const real = @import("real_metal"); - -pub const objc = real.objc; -pub const types = real.types; -pub const Size = real.Size; -pub const ResourceOptions = real.ResourceOptions; -pub const ResourceUsage = real.ResourceUsage; -pub const DispatchType = real.DispatchType; -pub const Device = real.Device; -pub const Buffer = real.Buffer; -pub const MappedFile = real.MappedFile; -pub const Library = real.Library; -pub const CompileOptions = real.CompileOptions; -pub const Pipeline = real.Pipeline; -pub const Queue = real.Queue; -pub const CommandBuffer = real.CommandBuffer; -pub const BlitEncoder = real.BlitEncoder; -pub const SharedEvent = real.SharedEvent; -pub const Event = real.Event; -pub const IndirectCommandBuffer = real.IndirectCommandBuffer; -pub const IndirectCommand = real.IndirectCommand; -pub const ResidencySet = real.ResidencySet; -pub const resident = real.resident; -pub const residency_policy = real.residency_policy; -pub const keepalive = real.keepalive; -pub const clock = real.clock; -pub const pass_metrics = real.pass_metrics; -pub const counters = real.counters; -pub const ane = real.ane; - -pub const max_segments = 2048; // two 8-byte stamps each: Metal caps a sample buffer at 32 KiB - -/// Timing only (TF_HY4_SKIP): dispatches of these pipelines are dropped, so a run's GPU time without them shows -/// what they cost unprofiled. The tokens are then wrong. -pub var skip_ids: []const usize = &.{}; -pub const max_names = 6; - -/// One encoder between two barriers: the pipelines it set (first few) and how many dispatches it made. -pub const Segment = struct { - pipelines: [max_names]usize = @splat(0), - named: u8 = 0, - dispatches: u16 = 0, -}; - -pub const Splitter = struct { - cb: real.CommandBuffer, - cur: real.ComputeEncoder, - split: bool, - pass: ?counters.ComputePass = null, - samples: ?counters.SampleBuffer = null, - count: usize = 0, - segments: []Segment, - current: usize = 0, - - /// A plain concurrent encoder: barriers stay barriers. - pub fn plain(cb: real.CommandBuffer, segments: []Segment) Splitter { - return .{ .cb = cb, .cur = cb.compute(.concurrent), .split = false, .segments = segments }; - } - - /// Timed serial encoders, one per barrier-delimited segment; `samples` holds two stamps a segment. - pub fn timed(cb: real.CommandBuffer, pass: counters.ComputePass, samples: counters.SampleBuffer, segments: []Segment) !Splitter { - var s: Splitter = .{ .cb = cb, .cur = undefined, .split = true, .pass = pass, .samples = samples, .segments = segments }; - try s.open(); - return s; - } - - fn open(self: *Splitter) !void { - if (self.count >= self.segments.len or 2 * self.count + 1 >= self.samples.?.count) return error.TooManyHy4ProbeSegments; - self.segments[self.count] = .{}; - self.cur = try self.pass.?.compute(self.cb, self.samples.?, 2 * self.count, 2 * self.count + 1); - } - - pub fn encoder(self: *Splitter) ComputeEncoder { - return .{ .s = self }; - } - - fn note(self: *Splitter, p: Pipeline) void { - if (!self.split) return; - const seg = &self.segments[self.count]; - if (seg.named < max_names) { - seg.pipelines[seg.named] = @intFromPtr(p.id); - seg.named += 1; - } - } - - fn dispatched(self: *Splitter) void { - if (self.split) self.segments[self.count].dispatches +|= 1; - } - - fn barrier(self: *Splitter) void { - if (!self.split) return self.cur.barrier(); - if (self.segments[self.count].dispatches == 0) return; - self.cur.end(); - self.count += 1; - self.open() catch @panic("hy4 probe: out of timed segments"); - } - - /// End the last encoder. Returns how many timed segments the command buffer holds. - pub fn finish(self: *Splitter) usize { - self.cur.end(); - if (!self.split) return 0; - return self.count + @intFromBool(self.segments[self.count].dispatches != 0); - } -}; - -pub const ComputeEncoder = struct { - s: *Splitter, - - fn skipped(self: ComputeEncoder) bool { - for (skip_ids) |id| if (id == self.s.current) return true; - return false; - } - - pub fn deviceId(self: ComputeEncoder) objc.Id { - return self.s.cur.deviceId(); - } - pub fn setPipeline(self: ComputeEncoder, pipeline: Pipeline) void { - self.s.current = @intFromPtr(pipeline.id); - self.s.note(pipeline); - self.s.cur.setPipeline(pipeline); - } - pub fn setBuffer(self: ComputeEncoder, buffer: Buffer, offset: usize, index: usize) void { - self.s.cur.setBuffer(buffer, offset, index); - } - pub fn setBytes(self: ComputeEncoder, bytes: []const u8, index: usize) void { - self.s.cur.setBytes(bytes, index); - } - pub fn setValue(self: ComputeEncoder, value: anytype, index: usize) void { - self.s.cur.setBytes(std.mem.asBytes(&value), index); - } - pub fn setThreadgroupMemory(self: ComputeEncoder, len: usize, index: usize) void { - self.s.cur.setThreadgroupMemory(len, index); - } - pub fn dispatchGroups(self: ComputeEncoder, groups: Size, threads: Size) void { - if (self.skipped()) return; - self.s.dispatched(); - self.s.cur.dispatchGroups(groups, threads); - } - pub fn dispatchIndirect(self: ComputeEncoder, args: Buffer, offset: usize, threads: Size) void { - if (self.skipped()) return; - self.s.dispatched(); - self.s.cur.dispatchIndirect(args, offset, threads); - } - pub fn dispatchThreads(self: ComputeEncoder, grid: Size, threads: Size) void { - if (self.skipped()) return; - self.s.dispatched(); - self.s.cur.dispatchThreads(grid, threads); - } - pub fn barrier(self: ComputeEncoder) void { - self.s.barrier(); - } - pub fn useResource(self: ComputeEncoder, buffer: Buffer, usage: usize) void { - self.s.cur.useResource(buffer, usage); - } - pub fn execute(self: ComputeEncoder, icb: IndirectCommandBuffer, first: usize, count: usize) void { - self.s.dispatched(); - self.s.cur.execute(icb, first, count); - } - pub fn end(self: ComputeEncoder) void { - _ = self.s.finish(); - } - pub fn commandBuffer(self: ComputeEncoder) CommandBuffer { - return self.s.cur.commandBuffer(); - } - pub fn dispatchType(self: ComputeEncoder) DispatchType { - return self.s.cur.dispatchType(); - } -}; diff --git a/zig/src/native/hy4_metal.zig b/zig/src/native/hy4_metal.zig index bf28b64cff8..9c714940ba9 100644 --- a/zig/src/native/hy4_metal.zig +++ b/zig/src/native/hy4_metal.zig @@ -1,5 +1,4 @@ -//! Hy4-flash served by the lane host on Metal: one stream at a time with DFly2 windows, contexts to 256K tokens -//! (128K by default), and the last stream's caches kept for a following prompt that starts with the same tokens. +//! Hy4-flash served by the lane host on Metal const std = @import("std"); const mtl = @import("metal"); const api = @import("engine_api"); 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/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 403fd2f8c71..e1b0022d17a 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -42,9 +42,6 @@ pub const HfText = struct { eos: []const u32 = &.{}, prefix: []const u32 = &.{}, // the post-processor's tokens before a text (add_special_tokens) suffix: []const u32 = &.{}, - /// Hy4-flash spells its reasoning and tool-call tokens ``, ``, ...: the - /// server reads them as the GLM spellings it parses (decoded text, marker ids, and marker strings it encodes). - hy4: bool = false, /// Loads ``dir``'s tokenizer.json, chat template, special tokens, eos ids; failure reason in `problem` (from `pa`). pub fn load(gpa: Allocator, io: std.Io, dir: []const u8, template_override: ?[]const u8, pa: Allocator, problem: *[]const u8) !*HfText { @@ -138,7 +135,6 @@ pub const HfText = struct { }; } if (t.tool_source.len > 0) t.tool_compiled = template.compile(gpa, t.tool_source, null) catch null; - t.hy4 = t.tok.specialTokenId("") != null and t.tok.specialTokenId("") != null; return t; } @@ -326,11 +322,9 @@ pub const HfText = struct { return @ptrCast(@alignCast(ctx)); } - fn encodeFn(ctx: *anyopaque, a: Allocator, s_in: []const u8, add_special: bool) model_text.Error![]u32 { + fn encodeFn(ctx: *anyopaque, a: Allocator, s: []const u8, add_special: bool) model_text.Error![]u32 { const t = self(ctx); - // a marker the server spells itself (a closing ) encodes as the model's own token - const s = if (t.hy4) hy4Spelling(s_in) orelse s_in else s_in; - 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 }); } @@ -353,27 +347,11 @@ pub const HfText = struct { } fn decodeFn(ctx: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { - const t = self(ctx); - const raw = t.tok.decode(a, ids, false) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else a.dupe(u8, "\u{fffd}"); - if (!t.hy4 or 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 (hy4_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.items; + 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 { - const t = self(ctx); - if (t.hy4) if (hy4Spelling(piece)) |own| return t.tok.specialTokenId(own); - return t.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 { @@ -620,23 +598,3 @@ test { _ = @import("dory_chat_test.zig"); _ = @import("deepseek_chat_test.zig"); } - -/// Hy4-flash's marker tokens and the GLM spellings the server's reply parsing reads (the call list's wrapper drops). -const hy4_spellings = [_][2][]const u8{ - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, - .{ "", "" }, -}; - -/// The Hy4-flash token a GLM marker spelling stands for, or null. -fn hy4Spelling(piece: []const u8) ?[]const u8 { - for (hy4_spellings) |pair| if (pair[1].len > 0 and std.mem.eql(u8, piece, pair[1])) return pair[0]; - return null; -} From a9f2d45ab42412e2349074656e4ea37bdac2eb3c Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:04:43 +0000 Subject: [PATCH 07/12] hy4_flash: core imports by path, not through engine re-exports; the CUDA serving pins take the Hy4-flash images - The family files import core/row_projection.zig, lane_projection.zig and moe_route.zig by path; the re-export modules made tensorfold.zig the root of a second module in the Metal runtime source tests. - gradient-serving.tsv: kernels.zig with the Hy4-flash fatbin images registered and root.zig with cuda.affine_experts exported, as earlier families' registrations were recorded. --- zig/build/metal_targets.zig | 4 ---- zig/hy4_engine/lane_projection.zig | 22 ------------------- zig/hy4_engine/moe_route.zig | 10 --------- zig/hy4_engine/row_projection.zig | 18 --------------- zig/src/families/hy4_flash/metal_dense.zig | 4 ++-- zig/src/families/hy4_flash/metal_draft.zig | 2 +- zig/src/families/hy4_flash/metal_engram.zig | 2 +- zig/src/families/hy4_flash/metal_linears.zig | 4 ++-- zig/src/families/hy4_flash/metal_model.zig | 2 +- zig/src/families/hy4_flash/metal_routed.zig | 6 ++--- zig/src/families/hy4_flash/metal_scratch.zig | 4 ++-- .../hy4_flash/metal_tensor_experts.zig | 2 +- .../families/hy4_flash/metal_tensor_qkv.zig | 2 +- zig/src/families/hy4_flash/mla_metal.zig | 2 +- zig/tests/fixtures/gradient-serving.tsv | 4 ++-- 15 files changed, 17 insertions(+), 71 deletions(-) delete mode 100644 zig/hy4_engine/lane_projection.zig delete mode 100644 zig/hy4_engine/moe_route.zig delete mode 100644 zig/hy4_engine/row_projection.zig diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 464b822d4f0..bc32613dff3 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -554,10 +554,6 @@ 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 } }, }); - // Hy4-flash's family files import these by name (the speed probe builds them alone): the engine's own, re-exported - for ([_][]const u8{ "row_projection", "lane_projection", "moe_route" }) |name| { - engine.addImport(name, b.createModule(.{ .root_source_file = b.path(b.fmt("zig/hy4_engine/{s}.zig", .{name})), .target = target, .optimize = optimize, .imports = &.{.{ .name = "tensorfold", .module = engine }} })); - } 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/hy4_engine/lane_projection.zig b/zig/hy4_engine/lane_projection.zig deleted file mode 100644 index 9a338f95aa5..00000000000 --- a/zig/hy4_engine/lane_projection.zig +++ /dev/null @@ -1,22 +0,0 @@ -//! The engine's lane_projection for the Hy4-flash family files -const m = @import("tensorfold").lane_projection; -pub const frags = m.frags; -pub const affine_mm = m.affine_mm; -pub const weight_layout = m.weight_layout; -pub const reg_layout = m.reg_layout; -pub const metadata_layout = m.metadata_layout; -pub const Output = m.Output; -pub const Format = m.Format; -pub const Layout = m.Layout; -pub const source = m.source; -pub const pack = m.pack; -pub const regBlock = m.regBlock; -pub const Order = m.Order; -pub const RegOrder = m.RegOrder; -pub const regOrder = m.regOrder; -pub const Ref = m.Ref; -pub const Projection = m.Projection; -pub const reg_rows = m.reg_rows; -pub const max_reg_rows = m.max_reg_rows; -pub const Sums = m.Sums; -pub const regOrder8 = m.regOrder8; diff --git a/zig/hy4_engine/moe_route.zig b/zig/hy4_engine/moe_route.zig deleted file mode 100644 index 5e9d7803f04..00000000000 --- a/zig/hy4_engine/moe_route.zig +++ /dev/null @@ -1,10 +0,0 @@ -//! The engine's moe_route for the Hy4-flash family files, which import it by name (the speed probe builds it alone). -const m = @import("tensorfold").moe_route; -pub const Shape = m.Shape; -pub const source = m.source; -pub const names = m.names; -pub const logits = m.logits; -pub const Args = m.Args; -pub const Outputs = m.Outputs; -pub const select = m.select; -pub const pack = m.pack; diff --git a/zig/hy4_engine/row_projection.zig b/zig/hy4_engine/row_projection.zig deleted file mode 100644 index 1a7945d8fcb..00000000000 --- a/zig/hy4_engine/row_projection.zig +++ /dev/null @@ -1,18 +0,0 @@ -//! The engine's row_projection for the Hy4-flash family files -const m = @import("tensorfold").row_projection; -pub const simd = m.simd; -pub const simd_bits = m.simd_bits; -pub const batch = m.batch; -pub const columns = m.columns; -pub const groups = m.groups; -pub const bit_widths = m.bit_widths; -pub const Sum = m.Sum; -pub const Weights = m.Weights; -pub const affine = m.affine; -pub const Experts = m.Experts; -pub const Pipelines = m.Pipelines; -pub const source = m.source; -pub const Call = m.Call; -pub const call = m.call; -pub const callStrided = m.callStrided; -pub const callIndexed = m.callIndexed; diff --git a/zig/src/families/hy4_flash/metal_dense.zig b/zig/src/families/hy4_flash/metal_dense.zig index 3920b6b82a7..094b5f7ee0b 100644 --- a/zig/src/families/hy4_flash/metal_dense.zig +++ b/zig/src/families/hy4_flash/metal_dense.zig @@ -1,7 +1,7 @@ //! The native Metal attention and dense feed-forward layer passes for Hy4-flash. const std = @import("std"); const mtl = @import("metal"); -const affine = @import("row_projection"); +const affine = @import("../../core/row_projection.zig"); const dense = @import("draft_ops"); const core = @import("core"); const cfg = @import("config.zig"); @@ -13,7 +13,7 @@ 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("lane_projection"); +const lane = @import("../../core/lane_projection.zig"); const index = @import("metal_index.zig"); pub const Ref = mla_gpu.Ref; diff --git a/zig/src/families/hy4_flash/metal_draft.zig b/zig/src/families/hy4_flash/metal_draft.zig index 0fdce1fba89..741149ba6c8 100644 --- a/zig/src/families/hy4_flash/metal_draft.zig +++ b/zig/src/families/hy4_flash/metal_draft.zig @@ -3,7 +3,7 @@ const std = @import("std"); const mtl = @import("metal"); const source = @import("kernel_sources"); const dense_ops = @import("draft_ops"); -const affine = @import("row_projection"); +const affine = @import("../../core/row_projection.zig"); const ck = @import("loader.zig"); const model = @import("metal_model.zig"); const common = @import("metal_dense.zig"); diff --git a/zig/src/families/hy4_flash/metal_engram.zig b/zig/src/families/hy4_flash/metal_engram.zig index 8b808aeffa6..cebdf742c68 100644 --- a/zig/src/families/hy4_flash/metal_engram.zig +++ b/zig/src/families/hy4_flash/metal_engram.zig @@ -2,7 +2,7 @@ const std = @import("std"); const core = @import("core"); const mtl = @import("metal"); -const affine = @import("row_projection"); +const affine = @import("../../core/row_projection.zig"); const sources = @import("kernel_sources"); const common = @import("metal_dense.zig"); const engram = @import("engram.zig"); diff --git a/zig/src/families/hy4_flash/metal_linears.zig b/zig/src/families/hy4_flash/metal_linears.zig index 3ecc917cc96..eb89517573a 100644 --- a/zig/src/families/hy4_flash/metal_linears.zig +++ b/zig/src/families/hy4_flash/metal_linears.zig @@ -1,7 +1,7 @@ //! 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("row_projection"); +const affine = @import("../../core/row_projection.zig"); const cfg = @import("config.zig"); const ihc = @import("ihc.zig"); const ihc_gpu = @import("ihc_metal.zig"); @@ -9,7 +9,7 @@ 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("lane_projection"); +const lane = @import("../../core/lane_projection.zig"); const dense = @import("metal_dense.zig"); const Buffers = dense.Buffers; const Ref = dense.Ref; diff --git a/zig/src/families/hy4_flash/metal_model.zig b/zig/src/families/hy4_flash/metal_model.zig index f63699c709d..936cbdda962 100644 --- a/zig/src/families/hy4_flash/metal_model.zig +++ b/zig/src/families/hy4_flash/metal_model.zig @@ -2,7 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const source = @import("kernel_sources"); -const aff = @import("row_projection"); +const aff = @import("../../core/row_projection.zig"); const load = @import("loader.zig"); const weights = @import("model_weights.zig"); const dense = @import("metal_dense.zig"); diff --git a/zig/src/families/hy4_flash/metal_routed.zig b/zig/src/families/hy4_flash/metal_routed.zig index c96f2bec6d1..07ad68524b3 100644 --- a/zig/src/families/hy4_flash/metal_routed.zig +++ b/zig/src/families/hy4_flash/metal_routed.zig @@ -2,14 +2,14 @@ const std = @import("std"); const mtl = @import("metal"); const sources = @import("kernel_sources"); -const affine = @import("row_projection"); -const route = @import("moe_route"); +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("lane_projection"); +const lane = @import("../../core/lane_projection.zig"); const Ref = dense.Ref; const RouteRef = @import("draft_ops").Ref; diff --git a/zig/src/families/hy4_flash/metal_scratch.zig b/zig/src/families/hy4_flash/metal_scratch.zig index 6ae9bfdad15..350c784f547 100644 --- a/zig/src/families/hy4_flash/metal_scratch.zig +++ b/zig/src/families/hy4_flash/metal_scratch.zig @@ -1,7 +1,7 @@ //! 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("row_projection"); +const affine = @import("../../core/row_projection.zig"); const cfg = @import("config.zig"); const ihc = @import("ihc.zig"); const ihc_gpu = @import("ihc_metal.zig"); @@ -9,7 +9,7 @@ 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("lane_projection"); +const lane = @import("../../core/lane_projection.zig"); const dense = @import("metal_dense.zig"); const Buffers = dense.Buffers; const Ref = dense.Ref; diff --git a/zig/src/families/hy4_flash/metal_tensor_experts.zig b/zig/src/families/hy4_flash/metal_tensor_experts.zig index b329052689e..ba8a697f4d6 100644 --- a/zig/src/families/hy4_flash/metal_tensor_experts.zig +++ b/zig/src/families/hy4_flash/metal_tensor_experts.zig @@ -2,7 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const core = @import("core"); -const lane = @import("lane_projection"); +const lane = @import("../../core/lane_projection.zig"); const tensor = lane.affine_mm; const source = @import("kernel_sources").hy4_flash_tensor_dispatch; diff --git a/zig/src/families/hy4_flash/metal_tensor_qkv.zig b/zig/src/families/hy4_flash/metal_tensor_qkv.zig index 86ab4132965..d85a33fb6ec 100644 --- a/zig/src/families/hy4_flash/metal_tensor_qkv.zig +++ b/zig/src/families/hy4_flash/metal_tensor_qkv.zig @@ -2,7 +2,7 @@ const std = @import("std"); const mtl = @import("metal"); const core = @import("core"); -const lane = @import("lane_projection"); +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"); diff --git a/zig/src/families/hy4_flash/mla_metal.zig b/zig/src/families/hy4_flash/mla_metal.zig index ed260237835..9aafb9d05af 100644 --- a/zig/src/families/hy4_flash/mla_metal.zig +++ b/zig/src/families/hy4_flash/mla_metal.zig @@ -18,7 +18,7 @@ pub const Nax = struct { attend: mtl.Pipeline, pub fn load(a: std.mem.Allocator, device: mtl.Device) !Nax { - const text = try @import("lane_projection").frags.source(device, a, sources.hy4_flash_mla_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(); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 7c79a04bf67..3b0baf23738 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 9e86f9dd1f3cb11e1494715938271cff70becb57a15dd524b83da90d9c0936c1 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 From 9239bf4f10fea16fe89b4ba9521f0dba55a5322f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:39:30 +0000 Subject: [PATCH 08/12] hy4_flash: pin core affine_mm and lane_projection's new bytes, and cover TF_HY4_ENGRAM and TF_HY4_DRAFT_BITS --- zig/gemma4_shared_affine_test.zig | 8 ++++---- zig/src/platform/environment_test.zig | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) 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/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" { From f9aaf5313031b69c0e0f86ac7f439cd100823314 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:11:14 +0000 Subject: [PATCH 09/12] hy4_flash: the row windows build on the wide row core on every chip rows.metal calls the wide core's tf_rp_rows; before the M5, Rows.load paired it with the legacy core, whose tf_rp_rows takes one template argument fewer, so the library failed to compile there. The wide core is plain Metal (the M5 only prefers it for speed), and on the M5 the compiled text is unchanged. --- zig/src/families/hy4_flash/metal_linears.zig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/zig/src/families/hy4_flash/metal_linears.zig b/zig/src/families/hy4_flash/metal_linears.zig index eb89517573a..e08cc543819 100644 --- a/zig/src/families/hy4_flash/metal_linears.zig +++ b/zig/src/families/hy4_flash/metal_linears.zig @@ -82,7 +82,8 @@ pub const Rows = struct { argmax: mtl.Pipeline, pub fn load(a: std.mem.Allocator, device: mtl.Device) !Rows { - const text = try std.mem.concat(a, u8, &.{ affine.source(device.tensorUnits()), @import("kernel_sources").hy4_flash_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(); From 349a9791b7974d4d7792208cc892eec57e00a03a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:08:13 +0000 Subject: [PATCH 10/12] gradient pins: kernels.zig with both main's and Hy4-flash's image registrations The rebase onto main joins main's newer kernels.zig rows with this branch's Hy4-flash images; the serving pin takes the joined file's bytes. --- zig/tests/fixtures/gradient-serving.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 3b0baf23738..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 9e86f9dd1f3cb11e1494715938271cff70becb57a15dd524b83da90d9c0936c1 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/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 From 2dde483e58b5355adcc3508d0223cac1ef68f71d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:52:29 +0000 Subject: [PATCH 11/12] changelog: #3941's line from lines/3941.txt in place of its own --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f1e25381d7..c8bd9459177 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased + + - 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). From c19a6af85d4711f3c8cb99704f25c13a8f510311 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:28:28 +0000 Subject: [PATCH 12/12] changelog: back under Unreleased --- CHANGELOG.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8bd9459177..cc966d6f462 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +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). @@ -235,8 +234,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML. -- 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). - - Tests: the Zig cache restat tests read `.lib_dir` from `zig env` instead of guessing a `lib` folder beside the executable, so they work with Homebrew Zig (#3786, fixes #3785). Thanks to @AIFlowML. - `tensorfold web`: after a PATH miss, the launcher looks in uv's tool directory for an existing Web executable before offering an install; PATH still wins and installing still needs an explicit yes (#3748, fixes #3747). Thanks to @AIFlowML.