| 1 | // coco turboquant-fast — keep weights COMPRESSED in RAM, matmul reads them packed. |
| 2 | // |
| 3 | // The activation-rotation trick (this is what makes it fast): |
| 4 | // turboquant stores the ROTATED quantized weight Wr (3-bit codes + per-block |
| 5 | // fp16 radius + a seeded ±1 sign + per-d-block FWHT). The real weight is |
| 6 | // W = unrotate(Wr). For a linear y = x @ Wᵀ, because the rotation R is |
| 7 | // orthonormal and block-local: |
| 8 | // ⟨x, unrotate(w)⟩ = ⟨rotate(x), w_rotated⟩ |
| 9 | // So we rotate the ACTIVATION x once per token (sign-flip + per-d-block FWHT, |
| 10 | // O(inn·log d), cheap) → xr, then matmul xr against the COMPRESSED rotated |
| 11 | // codes Wr directly. W is NEVER dequantized to fp16. The matmul reads ~4 |
| 12 | // bits/weight (codes packed two-per-byte) instead of 16 → fewer bytes/token. |
| 13 | // |
| 14 | // Two Metal kernels, both written here as raw MSL and JIT-compiled via candle's |
| 15 | // objc2-metal device handle (candle 0.11 exposes it through MetalDevice): |
| 16 | // 1. tq_rotate_f32 — rotate the activation in place on the GPU (sign-flip + |
| 17 | // block-diagonal FWHT). x never leaves the GPU. |
| 18 | // 2. tq_qmatvec_f32 — quantized mat·vec/mat: for each output o (and token t), |
| 19 | // accumulate xr[t,k] * codebook[code(o,k)] * radius(o,k), reconstructing |
| 20 | // each weight on the fly from the packed nibble codes + fp16 radius. |
| 21 | // |
| 22 | // Activations stay f32 in this path (Qwen's hidden state is tiny; the win is in |
| 23 | // the weight bytes). Only block-Hadamard, outlier-frac 0 weights are supported |
| 24 | // (clean 3-bit codes, inn % d == 0, no sparse outlier side-list) — that is the |
| 25 | // `turboquant-block --outlier-frac 0` recipe, 3.125 bpw, validated coherent. |
| 26 | |
| 27 | use anyhow::{anyhow, Result}; |
| 28 | use candle_core::backend::BackendStorage; |
| 29 | use candle_core::{CpuStorage, CustomOp1, DType, Device, Layout, Shape, Tensor}; |
| 30 | use candle_metal_kernels::metal::{Buffer, ComputeCommandEncoder, ComputePipeline}; |
| 31 | use std::sync::{Arc, Mutex, OnceLock}; |
| 32 | |
| 33 | use crate::turboquant::{self, TqWeight}; |
| 34 | |
| 35 | // ───────────────────────── Metal kernel source (MSL) ───────────────────────── |
| 36 | |
| 37 | const KERNEL_SRC: &str = r#" |
| 38 | #include <metal_stdlib> |
| 39 | using namespace metal; |
| 40 | |
| 41 | // Rotate the activation out-of-place: xr = blockFWHT(x ∘ sgn), per d-wide block. |
| 42 | // Reads x, writes xr — no separate blit copy needed. One threadgroup per |
| 43 | // (block, token); `d` threads cooperate via threadgroup memory. |
| 44 | // grid (threadgroups) = (1, nblocks, tokens) ; tgroup = (d, 1, 1) |
| 45 | kernel void tq_rotate_f32( |
| 46 | device const float* x [[buffer(0)]], // [tokens, inn] |
| 47 | device float* xr [[buffer(1)]], // [tokens, inn] (output) |
| 48 | device const float* sgn [[buffer(2)]], // [inn] (±1), tiled over blocks |
| 49 | constant uint& inn [[buffer(3)]], |
| 50 | constant uint& d [[buffer(4)]], |
| 51 | uint3 tg [[threadgroup_position_in_grid]], |
| 52 | uint3 lt [[thread_position_in_threadgroup]]) |
| 53 | { |
| 54 | threadgroup float buf[1024]; // d <= 1024 |
| 55 | uint blk = tg.y; // which d-block |
| 56 | uint tok = tg.z; // which token row |
| 57 | uint j = lt.x; // coord within the block |
| 58 | if (j >= d) return; |
| 59 | |
| 60 | uint col = blk * d + j; // column within the row |
| 61 | uint idx = tok * inn + col; |
| 62 | // sign-flip on load, keep the working value in a register |
| 63 | float v = x[idx] * sgn[col]; |
| 64 | |
| 65 | // Stages with stride h < 32 live entirely within a SIMD-group: use |
| 66 | // simd_shuffle_xor (no threadgroup barrier). For d=128 that's h=1..16. |
| 67 | for (uint h = 1; h < 32u && h < d; h <<= 1) { |
| 68 | float partner = simd_shuffle_xor(v, h); |
| 69 | v = ((j & h) == 0) ? (v + partner) : (partner - v); |
| 70 | } |
| 71 | // Stages with stride h >= 32 cross SIMD-groups: round-trip via threadgroup |
| 72 | // memory with a barrier. For d=128 that's h=32 and h=64 (2 barriers). |
| 73 | for (uint h = 32u; h < d; h <<= 1) { |
| 74 | buf[j] = v; |
| 75 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 76 | float partner = buf[j ^ h]; |
| 77 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 78 | v = ((j & h) == 0) ? (v + partner) : (partner - v); |
| 79 | } |
| 80 | // orthonormal scale 1/sqrt(d) |
| 81 | xr[idx] = v * rsqrt((float)d); |
| 82 | } |
| 83 | |
| 84 | // BF16-INPUT rotate: identical to tq_rotate_f32 but reads the activation as |
| 85 | // `bfloat` (the model's hidden-state dtype) and converts to f32 on load. This |
| 86 | // lets the model feed the post-norm hidden DIRECTLY into the rotate, eliminating |
| 87 | // candle's separate `to_dtype(F32)` (a full elementwise dispatch) + the |
| 88 | // `contiguous` copy that preceded every rotate. Output stays f32 (xr feeds the |
| 89 | // qmatvec, which wants f32). |
| 90 | kernel void tq_rotate_bf16( |
| 91 | device const bfloat* x [[buffer(0)]], // [tokens, inn] bf16 |
| 92 | device float* xr [[buffer(1)]], // [tokens, inn] f32 (output) |
| 93 | device const float* sgn [[buffer(2)]], // [inn] (±1), tiled over blocks |
| 94 | constant uint& inn [[buffer(3)]], |
| 95 | constant uint& d [[buffer(4)]], |
| 96 | uint3 tg [[threadgroup_position_in_grid]], |
| 97 | uint3 lt [[thread_position_in_threadgroup]]) |
| 98 | { |
| 99 | threadgroup float buf[1024]; |
| 100 | uint blk = tg.y; |
| 101 | uint tok = tg.z; |
| 102 | uint j = lt.x; |
| 103 | if (j >= d) return; |
| 104 | |
| 105 | uint col = blk * d + j; |
| 106 | uint idx = tok * inn + col; |
| 107 | float v = (float)x[idx] * sgn[col]; |
| 108 | |
| 109 | for (uint h = 1; h < 32u && h < d; h <<= 1) { |
| 110 | float partner = simd_shuffle_xor(v, h); |
| 111 | v = ((j & h) == 0) ? (v + partner) : (partner - v); |
| 112 | } |
| 113 | for (uint h = 32u; h < d; h <<= 1) { |
| 114 | buf[j] = v; |
| 115 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 116 | float partner = buf[j ^ h]; |
| 117 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 118 | v = ((j & h) == 0) ? (v + partner) : (partner - v); |
| 119 | } |
| 120 | xr[idx] = v * rsqrt((float)d); |
| 121 | } |
| 122 | |
| 123 | // Fused RoPE (GPT-NeoX "rotate-half" convention, matching candle_nn::rotary_emb::rope). |
| 124 | // Reads q/k DIRECTLY from their transposed [b,h,t,d] VIEW (arbitrary strides) and |
| 125 | // writes a CONTIGUOUS [b,h,t,d] output — folding candle's `.contiguous()` blit copy |
| 126 | // AND the separate rope dispatch into ONE pass. The qkv projection produces |
| 127 | // [b,t,h*d] which is reshaped+transposed to [b,h,t,d] (non-contiguous); candle's |
| 128 | // rope rejects non-contiguous input, so the old path paid a full elementwise copy |
| 129 | // per q and per k every token. Here we index the source via its real strides. |
| 130 | // |
| 131 | // cos/sin are [t, d/2] contiguous (cos[i_t*(d/2)+i_d]). For each (b,h,t,i_d<d/2): |
| 132 | // o1 = src1*cos - src2*sin ; o2 = src1*sin + src2*cos |
| 133 | // where src1 = x[.., i_d], src2 = x[.., i_d + d/2]. Output is dense row-major. |
| 134 | // grid = (d/2, t, b*h) ; tgroup = (d/2,1,1) (d/2 <= 128 here) |
| 135 | kernel void tq_rope_bf16( |
| 136 | device const bfloat* x [[buffer(0)]], // [b,h,t,d] strided view, bf16 |
| 137 | device bfloat* out [[buffer(1)]], // [b,h,t,d] CONTIGUOUS, bf16 (output) |
| 138 | device const bfloat* cos [[buffer(2)]], // [t, d/2] contiguous, bf16 |
| 139 | device const bfloat* sin [[buffer(3)]], // [t, d/2] contiguous, bf16 |
| 140 | constant uint& h [[buffer(4)]], // n heads (this tensor's) |
| 141 | constant uint& t_len [[buffer(5)]], // seq length |
| 142 | constant uint& d [[buffer(6)]], // head_dim |
| 143 | constant int4& strides [[buffer(7)]], // (sb, sh, st, sd) of the input view |
| 144 | uint3 gid [[thread_position_in_grid]]) |
| 145 | { |
| 146 | uint i_d = gid.x; // coord within first half [0, d/2) |
| 147 | uint i_t = gid.y; // position |
| 148 | uint bh = gid.z; // batch*head flattened |
| 149 | if (i_d >= (d >> 1) || i_t >= t_len) return; |
| 150 | uint b_i = bh / h; |
| 151 | uint h_i = bh % h; |
| 152 | |
| 153 | // Source element offsets via the input view's strides (elements, not bytes). |
| 154 | long base = (long)b_i * strides.x + (long)h_i * strides.y + (long)i_t * strides.z; |
| 155 | long o1s = base + (long)i_d * strides.w; |
| 156 | long o2s = base + (long)(i_d + (d >> 1)) * strides.w; |
| 157 | float s1 = (float)x[o1s]; |
| 158 | float s2 = (float)x[o2s]; |
| 159 | |
| 160 | uint i_cs = i_t * (d >> 1) + i_d; |
| 161 | float c = (float)cos[i_cs]; |
| 162 | float s = (float)sin[i_cs]; |
| 163 | |
| 164 | // Contiguous [b,h,t,d] output. |
| 165 | ulong dbase = (((ulong)bh) * t_len + i_t) * d; |
| 166 | out[dbase + i_d] = (bfloat)(s1 * c - s2 * s); |
| 167 | out[dbase + i_d + (d>>1)] = (bfloat)(s1 * s + s2 * c); |
| 168 | } |
| 169 | |
| 170 | // Quantized mat·mat: y[t,o] = sum_k xr[t,k] * codebook[code(o,k)] * radius(o,k). |
| 171 | // One SIMD-group (32 lanes) cooperates on ONE output row: each lane strides over |
| 172 | // k in steps of 32, so the 32 lanes read 32 CONSECUTIVE packed bytes per step |
| 173 | // (coalesced), then a simd_sum reduces the partial dot products. Codes are |
| 174 | // packed two-per-byte (low nibble = even k); each lane consumes one byte = two |
| 175 | // adjacent k. radius is fp16, one per d coords of the row-major (out*inn) grid. |
| 176 | // |
| 177 | // dispatch: grid = (out*32, tokens), threadgroup width = SIMDW * rows_per_tg. |
| 178 | kernel void tq_qmatvec_f32( |
| 179 | device const float* xr [[buffer(0)]], // [tokens, inn] (already rotated) |
| 180 | device const uchar* codes [[buffer(1)]], // packed nibbles, len = out*inn/2 |
| 181 | device const half* radius [[buffer(2)]], // [out*inn/d] |
| 182 | constant float* codebook [[buffer(3)]], // 8 levels |
| 183 | device float* y [[buffer(4)]], // [tokens, out] |
| 184 | constant uint& inn [[buffer(5)]], |
| 185 | constant uint& out_dim [[buffer(6)]], |
| 186 | constant uint& d [[buffer(7)]], |
| 187 | constant uint& tokens [[buffer(8)]], |
| 188 | uint2 gid [[thread_position_in_grid]]) |
| 189 | { |
| 190 | const uint SIMDW = 32; |
| 191 | uint t = gid.y; // token |
| 192 | uint o = gid.x / SIMDW; // output row this simd-group owns |
| 193 | uint lane = gid.x % SIMDW; |
| 194 | if (o >= out_dim || t >= tokens) return; |
| 195 | |
| 196 | float cb[8]; |
| 197 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 198 | |
| 199 | device const float* xrow = xr + (ulong)t * inn; |
| 200 | ulong base_pk = ((ulong)o * inn) >> 1; // packed-byte base (4-aligned) |
| 201 | ulong rbase = ((ulong)o * inn) / d; // radius block base for this row |
| 202 | |
| 203 | // Read 4 packed bytes (8 weights) per load as a uint → wide coalesced loads. |
| 204 | // base_pk is a multiple of 4 for all rows (o*inn/2, inn%8==0), so the uint |
| 205 | // view is aligned. nwords = npk/4 = inn/8 words per row. |
| 206 | device const uint* codes32 = (device const uint*)(codes + base_pk); |
| 207 | uint nwords = inn >> 3; // packed uints per row |
| 208 | |
| 209 | // d (128) is a power of two; one radius block = d coords = d/8 uint-words. |
| 210 | // wshift = log2(d/8). All 8 weights in a uint-word share a d-block when |
| 211 | // d>=8 and inn%d==0 (true here), so ONE radius lookup per word. |
| 212 | uint wshift = (uint)log2((float)(d >> 3)); // words per radius block |
| 213 | |
| 214 | float acc = 0.0f; |
| 215 | for (uint w = lane; w < nwords; w += SIMDW) { |
| 216 | uint packed = codes32[w]; |
| 217 | uint k0 = w << 3; // first weight index of this word |
| 218 | float r = (float)radius[rbase + (w >> wshift)]; |
| 219 | // 8 nibbles, low-to-high = k0..k0+7 |
| 220 | acc += xrow[k0 + 0] * cb[(packed >> 0) & 0xF] * r; |
| 221 | acc += xrow[k0 + 1] * cb[(packed >> 4) & 0xF] * r; |
| 222 | acc += xrow[k0 + 2] * cb[(packed >> 8) & 0xF] * r; |
| 223 | acc += xrow[k0 + 3] * cb[(packed >> 12) & 0xF] * r; |
| 224 | acc += xrow[k0 + 4] * cb[(packed >> 16) & 0xF] * r; |
| 225 | acc += xrow[k0 + 5] * cb[(packed >> 20) & 0xF] * r; |
| 226 | acc += xrow[k0 + 6] * cb[(packed >> 24) & 0xF] * r; |
| 227 | acc += xrow[k0 + 7] * cb[(packed >> 28) & 0xF] * r; |
| 228 | } |
| 229 | // reduce the 32 partial sums across the simd-group |
| 230 | acc = simd_sum(acc); |
| 231 | if (lane == 0) { |
| 232 | y[(ulong)t * out_dim + o] = acc; |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // TRUE 3-bit variant: codes packed 8-per-3-bytes (24-bit little-endian octet, |
| 237 | // code j at bits 3j..3j+3). 3.125 bpw vs the nibble path's 4.125 → 488 MB vs |
| 238 | // 644 MB resident (24% less weight memory). Same SIMD-group-per-row structure as |
| 239 | // the nibble kernel: each lane owns octets at stride 32 (8 consecutive k), so the |
| 240 | // 32 lanes read 32 consecutive 3-byte octets per step. One radius lookup/octet. |
| 241 | // |
| 242 | // NOTE (measured): this variant is correct (≤1e-6 vs the nibble kernel) and |
| 243 | // halves-then-some the weight bytes, but at 1.5B it does NOT raise throughput — |
| 244 | // the qmatvec path is decode/dispatch-bound, not weight-bandwidth-bound, and the |
| 245 | // 3-byte (unaligned) reads + extra unpacking exactly offset the bandwidth saving. |
| 246 | // So 4-bit nibble is the default fast path; pick 3-bit (COCO_PACK_BITS=3) when |
| 247 | // resident RAM matters more than the last ~0 tok/s. |
| 248 | kernel void tq_qmatvec3_f32( |
| 249 | device const float* xr [[buffer(0)]], // [tokens, inn] (already rotated) |
| 250 | device const uchar* codes [[buffer(1)]], // 3-bit stream, len = out*inn/8*3 |
| 251 | device const half* radius [[buffer(2)]], // [out*inn/d] |
| 252 | constant float* codebook [[buffer(3)]], // 8 levels |
| 253 | device float* y [[buffer(4)]], // [tokens, out] |
| 254 | constant uint& inn [[buffer(5)]], |
| 255 | constant uint& out_dim [[buffer(6)]], |
| 256 | constant uint& d [[buffer(7)]], |
| 257 | constant uint& tokens [[buffer(8)]], |
| 258 | uint2 gid [[thread_position_in_grid]]) |
| 259 | { |
| 260 | const uint SIMDW = 32; |
| 261 | uint t = gid.y; // token |
| 262 | uint o = gid.x / SIMDW; // output row this simd-group owns |
| 263 | uint lane = gid.x % SIMDW; |
| 264 | if (o >= out_dim || t >= tokens) return; |
| 265 | |
| 266 | float cb[8]; |
| 267 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 268 | |
| 269 | device const float* xrow = xr + (ulong)t * inn; |
| 270 | ulong base_b = ((ulong)o * inn / 8) * 3; // 3 bytes per 8-code octet |
| 271 | device const uchar* crow = codes + base_b; |
| 272 | ulong rbase = ((ulong)o * inn) / d; |
| 273 | uint noctet = inn >> 3; |
| 274 | uint gshift = (uint)log2((float)(d >> 3)); // octets per radius block |
| 275 | |
| 276 | float acc = 0.0f; |
| 277 | for (uint g = lane; g < noctet; g += SIMDW) { |
| 278 | uint bb = g * 3; |
| 279 | uint v = (uint)crow[bb] | ((uint)crow[bb + 1] << 8) | ((uint)crow[bb + 2] << 16); |
| 280 | uint k0 = g << 3; |
| 281 | float r = (float)radius[rbase + (g >> gshift)]; |
| 282 | acc += xrow[k0 + 0] * cb[(v >> 0) & 0x7] * r; |
| 283 | acc += xrow[k0 + 1] * cb[(v >> 3) & 0x7] * r; |
| 284 | acc += xrow[k0 + 2] * cb[(v >> 6) & 0x7] * r; |
| 285 | acc += xrow[k0 + 3] * cb[(v >> 9) & 0x7] * r; |
| 286 | acc += xrow[k0 + 4] * cb[(v >> 12) & 0x7] * r; |
| 287 | acc += xrow[k0 + 5] * cb[(v >> 15) & 0x7] * r; |
| 288 | acc += xrow[k0 + 6] * cb[(v >> 18) & 0x7] * r; |
| 289 | acc += xrow[k0 + 7] * cb[(v >> 21) & 0x7] * r; |
| 290 | } |
| 291 | acc = simd_sum(acc); |
| 292 | if (lane == 0) { |
| 293 | y[(ulong)t * out_dim + o] = acc; |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | // ───────── FUSED EPILOGUE variants (bf16 out + in-kernel bias) ───────── |
| 298 | // Same dot-product core as the *_f32 kernels above, but the simd-leader writes the |
| 299 | // result DIRECTLY as the model dtype (bf16) and adds the per-row bias IN the |
| 300 | // kernel. This folds candle's separate `to_dtype(bf16)` dispatch + N |
| 301 | // `broadcast_add(bias)` dispatches into the qmatvec epilogue — one fewer full |
| 302 | // elementwise pass over the output per projection group (and the bias add is free, |
| 303 | // piggy-backing on the simd-leader's single store). `bias` is a real per-row |
| 304 | // buffer (length out_dim, zeros where a projection has none); `has_bias` gates it |
| 305 | // so a null/dummy bind is never dereferenced. We accumulate in f32 (full |
| 306 | // precision) and round once at the store. |
| 307 | // |
| 308 | // RESIDUAL epilogue (COCO_FUSE_RESID, default on): buffers 11/12 optionally add a |
| 309 | // per-element residual at the same leader store — y[t,o] = dot + bias + resid[t,o]. |
| 310 | // This is the attention/MLP twin of the SwiGLU fuse: the o_proj and down_proj |
| 311 | // qmatvecs are each followed by a residual add on a hidden-width tensor; folding |
| 312 | // it into the store epilogue kills the standalone candle elementwise add dispatch |
| 313 | // (+ its barrier) after down_proj, and on the o_proj side replaces the two-output |
| 314 | // fused add+norm with (epilogue-add → plain norm). The add is done in f32 before |
| 315 | // the single bf16 rounding (the launch grid is untouched — epilogue-only fuse). |
| 316 | |
| 317 | kernel void tq_qmatvec3_bf16( |
| 318 | device const float* xr [[buffer(0)]], // [tokens, inn] rotated f32 |
| 319 | device const uchar* codes [[buffer(1)]], // 3-bit stream |
| 320 | device const half* radius [[buffer(2)]], // [out*inn/d] |
| 321 | constant float* codebook [[buffer(3)]], // 8 levels |
| 322 | device bfloat* y [[buffer(4)]], // [tokens, out] bf16 (output) |
| 323 | constant uint& inn [[buffer(5)]], |
| 324 | constant uint& out_dim [[buffer(6)]], |
| 325 | constant uint& d [[buffer(7)]], |
| 326 | constant uint& tokens [[buffer(8)]], |
| 327 | device const ushort* bias [[buffer(9)]], // [out_dim] bf16 bits (per-row) |
| 328 | constant uint& has_bias [[buffer(10)]], |
| 329 | device const bfloat* resid [[buffer(11)]], // [tokens, out_dim] residual |
| 330 | constant uint& has_resid [[buffer(12)]], |
| 331 | uint2 gid [[thread_position_in_grid]]) |
| 332 | { |
| 333 | const uint SIMDW = 32; |
| 334 | uint t = gid.y; |
| 335 | uint o = gid.x / SIMDW; |
| 336 | uint lane = gid.x % SIMDW; |
| 337 | if (o >= out_dim || t >= tokens) return; |
| 338 | |
| 339 | float cb[8]; |
| 340 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 341 | |
| 342 | device const float* xrow = xr + (ulong)t * inn; |
| 343 | ulong base_b = ((ulong)o * inn / 8) * 3; |
| 344 | device const uchar* crow = codes + base_b; |
| 345 | ulong rbase = ((ulong)o * inn) / d; |
| 346 | uint noctet = inn >> 3; |
| 347 | uint gshift = (uint)log2((float)(d >> 3)); |
| 348 | |
| 349 | float acc = 0.0f; |
| 350 | for (uint g = lane; g < noctet; g += SIMDW) { |
| 351 | uint bb = g * 3; |
| 352 | uint v = (uint)crow[bb] | ((uint)crow[bb + 1] << 8) | ((uint)crow[bb + 2] << 16); |
| 353 | uint k0 = g << 3; |
| 354 | float r = (float)radius[rbase + (g >> gshift)]; |
| 355 | float part = xrow[k0 + 0] * cb[(v >> 0) & 0x7]; |
| 356 | part += xrow[k0 + 1] * cb[(v >> 3) & 0x7]; |
| 357 | part += xrow[k0 + 2] * cb[(v >> 6) & 0x7]; |
| 358 | part += xrow[k0 + 3] * cb[(v >> 9) & 0x7]; |
| 359 | part += xrow[k0 + 4] * cb[(v >> 12) & 0x7]; |
| 360 | part += xrow[k0 + 5] * cb[(v >> 15) & 0x7]; |
| 361 | part += xrow[k0 + 6] * cb[(v >> 18) & 0x7]; |
| 362 | part += xrow[k0 + 7] * cb[(v >> 21) & 0x7]; |
| 363 | acc += part * r; |
| 364 | } |
| 365 | acc = simd_sum(acc); |
| 366 | if (lane == 0) { |
| 367 | if (has_bias) acc += (float)as_type<bfloat>(bias[o]); |
| 368 | if (has_resid) acc += (float)resid[(ulong)t * out_dim + o]; |
| 369 | y[(ulong)t * out_dim + o] = (bfloat)acc; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | kernel void tq_qmatvec_bf16( |
| 374 | device const float* xr [[buffer(0)]], // [tokens, inn] rotated f32 |
| 375 | device const uchar* codes [[buffer(1)]], // packed nibbles |
| 376 | device const half* radius [[buffer(2)]], // [out*inn/d] |
| 377 | constant float* codebook [[buffer(3)]], // 8 levels |
| 378 | device bfloat* y [[buffer(4)]], // [tokens, out] bf16 (output) |
| 379 | constant uint& inn [[buffer(5)]], |
| 380 | constant uint& out_dim [[buffer(6)]], |
| 381 | constant uint& d [[buffer(7)]], |
| 382 | constant uint& tokens [[buffer(8)]], |
| 383 | device const ushort* bias [[buffer(9)]], // [out_dim] bf16 bits (per-row) |
| 384 | constant uint& has_bias [[buffer(10)]], |
| 385 | device const bfloat* resid [[buffer(11)]], // [tokens, out_dim] residual |
| 386 | constant uint& has_resid [[buffer(12)]], |
| 387 | uint2 gid [[thread_position_in_grid]]) |
| 388 | { |
| 389 | const uint SIMDW = 32; |
| 390 | uint t = gid.y; |
| 391 | uint o = gid.x / SIMDW; |
| 392 | uint lane = gid.x % SIMDW; |
| 393 | if (o >= out_dim || t >= tokens) return; |
| 394 | |
| 395 | float cb[8]; |
| 396 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 397 | |
| 398 | device const float* xrow = xr + (ulong)t * inn; |
| 399 | ulong base_pk = ((ulong)o * inn) >> 1; |
| 400 | ulong rbase = ((ulong)o * inn) / d; |
| 401 | device const uint* codes32 = (device const uint*)(codes + base_pk); |
| 402 | uint nwords = inn >> 3; |
| 403 | uint wshift = (uint)log2((float)(d >> 3)); |
| 404 | |
| 405 | float acc = 0.0f; |
| 406 | for (uint w = lane; w < nwords; w += SIMDW) { |
| 407 | uint packed = codes32[w]; |
| 408 | uint k0 = w << 3; |
| 409 | float r = (float)radius[rbase + (w >> wshift)]; |
| 410 | acc += xrow[k0 + 0] * cb[(packed >> 0) & 0xF] * r; |
| 411 | acc += xrow[k0 + 1] * cb[(packed >> 4) & 0xF] * r; |
| 412 | acc += xrow[k0 + 2] * cb[(packed >> 8) & 0xF] * r; |
| 413 | acc += xrow[k0 + 3] * cb[(packed >> 12) & 0xF] * r; |
| 414 | acc += xrow[k0 + 4] * cb[(packed >> 16) & 0xF] * r; |
| 415 | acc += xrow[k0 + 5] * cb[(packed >> 20) & 0xF] * r; |
| 416 | acc += xrow[k0 + 6] * cb[(packed >> 24) & 0xF] * r; |
| 417 | acc += xrow[k0 + 7] * cb[(packed >> 28) & 0xF] * r; |
| 418 | } |
| 419 | acc = simd_sum(acc); |
| 420 | if (lane == 0) { |
| 421 | if (has_bias) acc += (float)as_type<bfloat>(bias[o]); |
| 422 | if (has_resid) acc += (float)resid[(ulong)t * out_dim + o]; |
| 423 | y[(ulong)t * out_dim + o] = (bfloat)acc; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | // ───────── REGISTER-BLOCKED bf16 variant: QROWS output rows per simd-group ───────── |
| 428 | // The single-row kernel above re-reads the WHOLE activation row (xrow[k]) from |
| 429 | // device memory for every output row, so activation traffic is out*inn floats — |
| 430 | // the activation load dominates arithmetic intensity at decode (tokens=1, the flat |
| 431 | // path). Here ONE simd-group owns QROWS consecutive output rows: each lane loads |
| 432 | // the 8 activation coords of its word ONCE into registers and reuses them across |
| 433 | // all QROWS rows' codes, cutting activation traffic by QROWS* and lifting the |
| 434 | // FMA:load ratio toward ggml mul_mv's. Codes for row (o0+i) are at the same word |
| 435 | // index but row-strided by nwords uints (rows are contiguous out*inn/2 bytes, |
| 436 | // uint-aligned since inn%8==0); radius is row-strided by inn/d. One radius lookup |
| 437 | // per (row, word) — d>=8 so all 8 weights of a word share a d-block. Reductions |
| 438 | // are QROWS independent simd_sums; the simd-leader writes QROWS outputs. |
| 439 | // grid = (ceil(out/QROWS) * 32, tokens) ; tgroup width = multiple of 32. |
| 440 | // |
| 441 | // QROWS is a compile-time template (QR) so the per-row arrays (acc[QR], the |
| 442 | // unrolled inner loop) live entirely in registers and the compiler can fully |
| 443 | // unroll. We instantiate QR=4 (the round-1 default) and QR=8 (wider blocking: |
| 444 | // 8 output rows per activation load → 2x the arithmetic intensity, picked when |
| 445 | // COCO_QROWS=8). The Rust side selects the pipeline + matching grid divisor. |
| 446 | #define DEFINE_QMATVEC_R(NAME, QR) \ |
| 447 | kernel void NAME( \ |
| 448 | device const float* xr [[buffer(0)]], \ |
| 449 | device const uchar* codes [[buffer(1)]], \ |
| 450 | device const half* radius [[buffer(2)]], \ |
| 451 | constant float* codebook [[buffer(3)]], \ |
| 452 | device bfloat* y [[buffer(4)]], \ |
| 453 | constant uint& inn [[buffer(5)]], \ |
| 454 | constant uint& out_dim [[buffer(6)]], \ |
| 455 | constant uint& d [[buffer(7)]], \ |
| 456 | constant uint& tokens [[buffer(8)]], \ |
| 457 | device const ushort* bias [[buffer(9)]], \ |
| 458 | constant uint& has_bias [[buffer(10)]], \ |
| 459 | device const bfloat* resid [[buffer(11)]], \ |
| 460 | constant uint& has_resid [[buffer(12)]], \ |
| 461 | uint2 gid [[thread_position_in_grid]]) \ |
| 462 | { \ |
| 463 | const uint SIMDW = 32; \ |
| 464 | const uint QROWS = (QR); \ |
| 465 | uint t = gid.y; \ |
| 466 | uint grp = gid.x / SIMDW; \ |
| 467 | uint lane = gid.x % SIMDW; \ |
| 468 | uint o0 = grp * QROWS; \ |
| 469 | if (o0 >= out_dim || t >= tokens) return; \ |
| 470 | \ |
| 471 | float cb[8]; \ |
| 472 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; \ |
| 473 | \ |
| 474 | device const float* xrow = xr + (ulong)t * inn; \ |
| 475 | uint nwords = inn >> 3; \ |
| 476 | uint wshift = (uint)log2((float)(d >> 3)); \ |
| 477 | uint rstride = inn / d; \ |
| 478 | \ |
| 479 | /* Row stride in uint-words == nwords (rows back-to-back, uint-aligned). */\ |
| 480 | device const uint* codes32 = \ |
| 481 | (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); \ |
| 482 | /* Per-row code base pointers hoisted out of the word loop: the row index \ |
| 483 | multiply (i*nwords) is loop-invariant, so compute each row's base once. */\ |
| 484 | device const uint* crow[QR]; \ |
| 485 | _Pragma("unroll") \ |
| 486 | for (uint i = 0; i < QROWS; ++i) crow[i] = codes32 + (ulong)i * nwords; \ |
| 487 | \ |
| 488 | float acc[QR]; \ |
| 489 | for (uint i = 0; i < QROWS; ++i) acc[i] = 0.0f; \ |
| 490 | \ |
| 491 | /* Activation viewed as float4: k0 = w<<3 is 8-aligned, so two aligned \ |
| 492 | float4 loads per word (16-byte coalesced) instead of 8 scalar loads. */ \ |
| 493 | device const float4* xrow4 = (device const float4*)xrow; \ |
| 494 | for (uint w = lane; w < nwords; w += SIMDW) { \ |
| 495 | uint q = w << 1; \ |
| 496 | float4 xa = xrow4[q]; \ |
| 497 | float4 xb = xrow4[q + 1]; \ |
| 498 | uint rb = w >> wshift; \ |
| 499 | _Pragma("unroll") \ |
| 500 | for (uint i = 0; i < QROWS; ++i) { \ |
| 501 | uint o = o0 + i; \ |
| 502 | if (o >= out_dim) break; \ |
| 503 | uint packed = crow[i][w]; \ |
| 504 | float r = (float)radius[(ulong)o * rstride + rb]; \ |
| 505 | float4 wa = float4(cb[(packed >> 0) & 0xF], cb[(packed >> 4) & 0xF],\ |
| 506 | cb[(packed >> 8) & 0xF], cb[(packed >> 12) & 0xF]);\ |
| 507 | float4 wb = float4(cb[(packed >> 16) & 0xF], cb[(packed >> 20) & 0xF],\ |
| 508 | cb[(packed >> 24) & 0xF], cb[(packed >> 28) & 0xF]);\ |
| 509 | float part = dot(xa, wa) + dot(xb, wb); \ |
| 510 | acc[i] += part * r; \ |
| 511 | } \ |
| 512 | } \ |
| 513 | _Pragma("unroll") \ |
| 514 | for (uint i = 0; i < QROWS; ++i) { \ |
| 515 | uint o = o0 + i; \ |
| 516 | if (o >= out_dim) break; \ |
| 517 | float s = simd_sum(acc[i]); \ |
| 518 | if (lane == 0) { \ |
| 519 | if (has_bias) s += (float)as_type<bfloat>(bias[o]); \ |
| 520 | if (has_resid) s += (float)resid[(ulong)t * out_dim + o]; \ |
| 521 | y[(ulong)t * out_dim + o] = (bfloat)s; \ |
| 522 | } \ |
| 523 | } \ |
| 524 | } |
| 525 | |
| 526 | DEFINE_QMATVEC_R(tq_qmatvec_bf16_r, 4) |
| 527 | DEFINE_QMATVEC_R(tq_qmatvec_bf16_r8, 8) |
| 528 | |
| 529 | // ───────── FUSED SwiGLU variant: silu(gate)·up computed in the qmatvec epilogue ───────── |
| 530 | // The MLP gate/up projections are stored as ONE QGroup whose concatenated codes are |
| 531 | // [gate(I rows); up(I rows)] back-to-back (out_total = 2*I, I = intermediate dim). |
| 532 | // The old path ran the register-blocked qmatvec over all 2*I rows → [gate; up], then |
| 533 | // candle issued TWO more whole-tensor passes — `silu(gate)` and `* up` — before |
| 534 | // down_proj. Those two elementwise dispatches (+ their GPU barriers + a 2*I→I |
| 535 | // round-trip of the intermediate) are pure dispatch overhead at decode (tokens=1). |
| 536 | // |
| 537 | // Here a simd-group owns QR *gate* rows (o0..o0+QR, o0 strided by QROWS over [0,I)). |
| 538 | // For each gate row `o` it ALSO computes the matching up row `o + I` (same activation |
| 539 | // row, same codebook; the up codes live `half_rows*nwords` uint-words further into the |
| 540 | // SAME codes buffer, the up radius `half_rows*rstride` further into the SAME radius). |
| 541 | // Carrying gate[o] AND up[o] in registers, the simd-leader stores silu(gate)·up |
| 542 | // directly to y[o] (output width I, NOT 2*I). The standalone silu+mul dispatches in |
| 543 | // MLP::forward are then dropped. `half_rows` (= I) is passed in buffer(6) as out_dim |
| 544 | // (the SwiGLU output width); the gate/up split is at row `out_dim`. No bias (gate/up |
| 545 | // never carry one) so the bias buffers are omitted from this variant. |
| 546 | // grid = (ceil(I/QROWS) * 32, tokens) ; same grid math as the register-blocked path |
| 547 | // with out_dim = I. silu(x) = x * sigmoid(x) = x / (1 + exp(-x)), accumulated/applied |
| 548 | // in f32 and rounded once at the bf16 store (matches candle's f32 silu then bf16 mul). |
| 549 | #define DEFINE_QMATVEC_SWIGLU(NAME, QR) \ |
| 550 | kernel void NAME( \ |
| 551 | device const float* xr [[buffer(0)]], \ |
| 552 | device const uchar* codes [[buffer(1)]], \ |
| 553 | device const half* radius [[buffer(2)]], \ |
| 554 | constant float* codebook [[buffer(3)]], \ |
| 555 | device bfloat* y [[buffer(4)]], \ |
| 556 | constant uint& inn [[buffer(5)]], \ |
| 557 | constant uint& out_dim [[buffer(6)]], /* = I (SwiGLU width) */ \ |
| 558 | constant uint& d [[buffer(7)]], \ |
| 559 | constant uint& tokens [[buffer(8)]], \ |
| 560 | uint2 gid [[thread_position_in_grid]]) \ |
| 561 | { \ |
| 562 | const uint SIMDW = 32; \ |
| 563 | const uint QROWS = (QR); \ |
| 564 | uint t = gid.y; \ |
| 565 | uint grp = gid.x / SIMDW; \ |
| 566 | uint lane = gid.x % SIMDW; \ |
| 567 | uint o0 = grp * QROWS; \ |
| 568 | if (o0 >= out_dim || t >= tokens) return; \ |
| 569 | \ |
| 570 | float cb[8]; \ |
| 571 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; \ |
| 572 | \ |
| 573 | device const float* xrow = xr + (ulong)t * inn; \ |
| 574 | uint nwords = inn >> 3; \ |
| 575 | uint wshift = (uint)log2((float)(d >> 3)); \ |
| 576 | uint rstride = inn / d; \ |
| 577 | /* Up row (o) lives `out_dim` rows after gate row (o) in the SAME buffers. */\ |
| 578 | ulong up_word_off = (ulong)out_dim * nwords; /* code words to up codes */\ |
| 579 | ulong up_rad_off = (ulong)out_dim * rstride; /* radius entries to up rad */\ |
| 580 | \ |
| 581 | device const uint* gcodes32 = \ |
| 582 | (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); \ |
| 583 | /* Per-row gate+up code base pointers, hoisted out of the word loop. */ \ |
| 584 | device const uint* gcrow[QR]; \ |
| 585 | device const uint* ucrow[QR]; \ |
| 586 | _Pragma("unroll") \ |
| 587 | for (uint i = 0; i < QROWS; ++i) { \ |
| 588 | gcrow[i] = gcodes32 + (ulong)i * nwords; \ |
| 589 | ucrow[i] = gcrow[i] + up_word_off; \ |
| 590 | } \ |
| 591 | \ |
| 592 | float gacc[QR]; \ |
| 593 | float uacc[QR]; \ |
| 594 | for (uint i = 0; i < QROWS; ++i) { gacc[i] = 0.0f; uacc[i] = 0.0f; } \ |
| 595 | \ |
| 596 | device const float4* xrow4 = (device const float4*)xrow; \ |
| 597 | for (uint w = lane; w < nwords; w += SIMDW) { \ |
| 598 | uint q = w << 1; \ |
| 599 | float4 xa = xrow4[q]; \ |
| 600 | float4 xb = xrow4[q + 1]; \ |
| 601 | uint rb = w >> wshift; \ |
| 602 | _Pragma("unroll") \ |
| 603 | for (uint i = 0; i < QROWS; ++i) { \ |
| 604 | uint o = o0 + i; \ |
| 605 | if (o >= out_dim) break; \ |
| 606 | /* gate row o */ \ |
| 607 | uint gp = gcrow[i][w]; \ |
| 608 | float gr = (float)radius[(ulong)o * rstride + rb]; \ |
| 609 | float4 gwa = float4(cb[(gp >> 0) & 0xF], cb[(gp >> 4) & 0xF], \ |
| 610 | cb[(gp >> 8) & 0xF], cb[(gp >> 12) & 0xF]); \ |
| 611 | float4 gwb = float4(cb[(gp >> 16) & 0xF], cb[(gp >> 20) & 0xF], \ |
| 612 | cb[(gp >> 24) & 0xF], cb[(gp >> 28) & 0xF]); \ |
| 613 | gacc[i] += (dot(xa, gwa) + dot(xb, gwb)) * gr; \ |
| 614 | /* up row o (= concatenated row o+out_dim) */ \ |
| 615 | uint up = ucrow[i][w]; \ |
| 616 | float ur = (float)radius[(ulong)o * rstride + rb + up_rad_off]; \ |
| 617 | float4 uwa = float4(cb[(up >> 0) & 0xF], cb[(up >> 4) & 0xF], \ |
| 618 | cb[(up >> 8) & 0xF], cb[(up >> 12) & 0xF]); \ |
| 619 | float4 uwb = float4(cb[(up >> 16) & 0xF], cb[(up >> 20) & 0xF], \ |
| 620 | cb[(up >> 24) & 0xF], cb[(up >> 28) & 0xF]); \ |
| 621 | uacc[i] += (dot(xa, uwa) + dot(xb, uwb)) * ur; \ |
| 622 | } \ |
| 623 | } \ |
| 624 | _Pragma("unroll") \ |
| 625 | for (uint i = 0; i < QROWS; ++i) { \ |
| 626 | uint o = o0 + i; \ |
| 627 | if (o >= out_dim) break; \ |
| 628 | float g = simd_sum(gacc[i]); \ |
| 629 | float u = simd_sum(uacc[i]); \ |
| 630 | if (lane == 0) { \ |
| 631 | float sg = g / (1.0f + exp(-g)); /* silu(gate) = x·σ(x) */ \ |
| 632 | y[(ulong)t * out_dim + o] = (bfloat)(sg * u); \ |
| 633 | } \ |
| 634 | } \ |
| 635 | } |
| 636 | |
| 637 | DEFINE_QMATVEC_SWIGLU(tq_qmatvec_swiglu_r, 4) |
| 638 | DEFINE_QMATVEC_SWIGLU(tq_qmatvec_swiglu_r8, 8) |
| 639 | |
| 640 | // ───────── FFN MEGAKERNEL (1.5B, no tiling): swiglu → rotate → down, all on-chip ───────── |
| 641 | // ONE dispatch (one threadgroup per token) runs the WHOLE FFN with the I-wide |
| 642 | // SwiGLU intermediate `h` living in threadgroup memory — it never touches device |
| 643 | // memory, and the down-rotate + down-matmul stay fused behind a cheap in-group |
| 644 | // barrier (no device drain, no I→I round-trip dispatch). Engaged only when |
| 645 | // I (intermediate width) fits the 32KB threadgroup budget as bf16: |
| 646 | // I * sizeof(bfloat) = I*2 ; at the 1.5B I=8960 → 17.5KB (FITS). Larger models |
| 647 | // (7B I=18944 → 37KB) DON'T fit one tile and fall back automatically (Rust guard). |
| 648 | // |
| 649 | // Phases (all threads in the group cooperate; one threadgroup owns one token): |
| 650 | // 1. SwiGLU: like tq_qmatvec_swiglu but each simd-group owns a STRIDED set of I |
| 651 | // gate rows. For gate row o it also reads up row (o+I) from the SAME concat |
| 652 | // gate/up buffers, computes silu(gate·xr)·(up·xr), and STORES it as bf16 into |
| 653 | // threadgroup hbuf[o]. (xr = the gate/up-rotated input, buffer 0 — the gate/up |
| 654 | // rotate stays a separate cheap dispatch upstream, identical to the swiglu path.) |
| 655 | // 2. barrier(mem_threadgroup) — all of hbuf is now visible group-wide. |
| 656 | // 3. Rotate h for the down projection: per d-wide (d=128) block, h_rot = |
| 657 | // blockFWHT(h ∘ down_sign)·rsqrt(d) — the SAME transform tq_rotate applies, |
| 658 | // but reading/writing hbuf in place (bf16). Done with a 128-thread FWHT over |
| 659 | // each block; the group processes (tgsize/128) blocks per sweep. Cross-simd |
| 660 | // stages (stride 32,64) round-trip a small per-block threadgroup scratch. |
| 661 | // 4. barrier(mem_threadgroup) — rotated hbuf visible. |
| 662 | // 5. Down matmul: each simd-group owns ONE down output row o (hidden width), |
| 663 | // dot product over the I-wide rotated hbuf with down codes/radius/codebook, |
| 664 | // simd_sum, and the leader stores y[o] (bf16). y is hidden-wide. |
| 665 | // |
| 666 | // Numerics match swiglu(bf16 h) → tq_rotate(h) → down qmatvec exactly except h is |
| 667 | // rounded to bf16 ONCE in threadgroup (the separate path also stored h as bf16), |
| 668 | // and the FWHT/dot accumulate in f32 as before. |
| 669 | // |
| 670 | // Buffers: 0 xr(f32, gate/up-rotated) ; 1 gu_codes ; 2 gu_radius ; 3 codebook(8 f32) |
| 671 | // ; 4 y(bf16 out) ; 5 inn (=hidden, gate/up inn) ; 6 I (intermediate width) |
| 672 | // ; 7 d (=128) ; 8 down_codes ; 9 down_radius ; 10 down_sign(f32 [I]) ; 11 hidden(out) |
| 673 | // grid = (tgsize, tokens=1) threadgroups, threadgroup width = tgsize. |
| 674 | kernel void tq_ffn_mega( |
| 675 | device const float* xr [[buffer(0)]], // [tokens, inn] gate/up-rotated |
| 676 | device const uchar* gu_codes [[buffer(1)]], // concat [gate(I); up(I)] nibbles |
| 677 | device const half* gu_radius [[buffer(2)]], // concat gate/up radii |
| 678 | constant float* codebook [[buffer(3)]], // 8 levels (shared gate/up/down) |
| 679 | device bfloat* y [[buffer(4)]], // [tokens, hidden] (output) |
| 680 | constant uint& inn [[buffer(5)]], // gate/up inn (= hidden) |
| 681 | constant uint& I [[buffer(6)]], // intermediate width |
| 682 | constant uint& d [[buffer(7)]], // block size (128) |
| 683 | device const uchar* dn_codes [[buffer(8)]], // down codes [hidden, I] nibbles |
| 684 | device const half* dn_radius [[buffer(9)]], // down radii [hidden*I/d] |
| 685 | device const float* dn_sign [[buffer(10)]], // down rotation sign [I] (±1) |
| 686 | constant uint& hidden [[buffer(11)]], // down out (= hidden) |
| 687 | uint3 tg [[threadgroup_position_in_grid]], |
| 688 | uint3 lt [[thread_position_in_threadgroup]], |
| 689 | uint3 tgsz3 [[threads_per_threadgroup]]) |
| 690 | { |
| 691 | const uint SIMDW = 32; |
| 692 | // Threadgroup budget (32KB): hbuf 14336*2 = 28KB + scr 512*4 = 2KB = 30KB. |
| 693 | // hbuf holds the whole I-wide SwiGLU intermediate on-chip; the Rust guard only |
| 694 | // engages this kernel when I <= 14336 (the 1.5B I=8960 → 17.5KB used, FITS). |
| 695 | // scr is the per-block FWHT cross-simd scratch (needs `tgsz` floats; tgsz<=512). |
| 696 | threadgroup bfloat hbuf[14336]; |
| 697 | threadgroup float scr[512]; |
| 698 | |
| 699 | uint tgsz = tgsz3.x; // threads per threadgroup |
| 700 | uint tok = tg.y; // one threadgroup per token |
| 701 | uint tid = lt.x; // [0, tgsize) |
| 702 | uint sg = tid / SIMDW; // this simd-group index |
| 703 | uint lane = tid % SIMDW; |
| 704 | uint nsg = tgsz / SIMDW; // simd-groups in the threadgroup |
| 705 | |
| 706 | float cb[8]; |
| 707 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 708 | |
| 709 | device const float* xrow = xr + (ulong)tok * inn; |
| 710 | uint nwords = inn >> 3; // packed uints per gate/up row |
| 711 | uint wshift = (uint)log2((float)(d >> 3)); |
| 712 | uint rstride = inn / d; // radius entries per gate/up row |
| 713 | ulong up_word_off = (ulong)I * nwords; // up codes live I rows after gate |
| 714 | ulong up_rad_off = (ulong)I * rstride; |
| 715 | |
| 716 | // ── Phase 1: SwiGLU → hbuf (each simd-group strides over I gate rows) ── |
| 717 | device const float4* xrow4 = (device const float4*)xrow; |
| 718 | for (uint o = sg; o < I; o += nsg) { |
| 719 | device const uint* gcrow = (device const uint*)(gu_codes + (((ulong)o * inn) >> 1)); |
| 720 | device const uint* ucrow = gcrow + up_word_off; |
| 721 | float gacc = 0.0f, uacc = 0.0f; |
| 722 | for (uint w = lane; w < nwords; w += SIMDW) { |
| 723 | uint q = w << 1; |
| 724 | float4 xa = xrow4[q]; |
| 725 | float4 xb = xrow4[q + 1]; |
| 726 | uint rb = w >> wshift; |
| 727 | uint gp = gcrow[w]; |
| 728 | float gr = (float)gu_radius[(ulong)o * rstride + rb]; |
| 729 | float4 gwa = float4(cb[(gp >> 0) & 0xF], cb[(gp >> 4) & 0xF], |
| 730 | cb[(gp >> 8) & 0xF], cb[(gp >> 12) & 0xF]); |
| 731 | float4 gwb = float4(cb[(gp >> 16) & 0xF], cb[(gp >> 20) & 0xF], |
| 732 | cb[(gp >> 24) & 0xF], cb[(gp >> 28) & 0xF]); |
| 733 | gacc += (dot(xa, gwa) + dot(xb, gwb)) * gr; |
| 734 | uint up = ucrow[w]; |
| 735 | float ur = (float)gu_radius[(ulong)o * rstride + rb + up_rad_off]; |
| 736 | float4 uwa = float4(cb[(up >> 0) & 0xF], cb[(up >> 4) & 0xF], |
| 737 | cb[(up >> 8) & 0xF], cb[(up >> 12) & 0xF]); |
| 738 | float4 uwb = float4(cb[(up >> 16) & 0xF], cb[(up >> 20) & 0xF], |
| 739 | cb[(up >> 24) & 0xF], cb[(up >> 28) & 0xF]); |
| 740 | uacc += (dot(xa, uwa) + dot(xb, uwb)) * ur; |
| 741 | } |
| 742 | float g = simd_sum(gacc); |
| 743 | float u = simd_sum(uacc); |
| 744 | if (lane == 0) { |
| 745 | float sg_act = g / (1.0f + exp(-g)); // silu(gate) = x·σ(x) |
| 746 | hbuf[o] = (bfloat)(sg_act * u); |
| 747 | } |
| 748 | } |
| 749 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 750 | |
| 751 | // ── Phase 3: rotate h per d-block: h_rot = blockFWHT(h ∘ dn_sign)/sqrt(d) ── |
| 752 | // Process `blocks_per_sweep = tgsz/d` blocks at once: thread tid owns coord |
| 753 | // (tid % d) of the (tid / d)-th block in the current sweep. Each block's |
| 754 | // cross-simd FWHT scratch is the `d`-slice of scr it maps to (scr is tgsz wide). |
| 755 | uint nblk = I / d; |
| 756 | uint bps = tgsz / d; // blocks rotated per sweep (>=1; d|tgsz) |
| 757 | if (bps >= 1) { |
| 758 | uint jb = tid % d; // coord within its block |
| 759 | uint slot = tid / d; // which concurrent block this thread serves |
| 760 | for (uint b0 = 0; b0 < nblk; b0 += bps) { |
| 761 | uint blk = b0 + slot; |
| 762 | if (blk < nblk) { |
| 763 | uint col = blk * d + jb; // coord within the I-wide h |
| 764 | float v = (float)hbuf[col] * dn_sign[col]; |
| 765 | // intra-simd stages (stride < 32): simd_shuffle_xor, no barrier |
| 766 | for (uint h = 1; h < 32u && h < d; h <<= 1) { |
| 767 | float partner = simd_shuffle_xor(v, h); |
| 768 | v = ((jb & h) == 0) ? (v + partner) : (partner - v); |
| 769 | } |
| 770 | // cross-simd stages (stride >= 32): per-block scratch slice |
| 771 | threadgroup float* sb = scr + slot * d; |
| 772 | for (uint h = 32u; h < d; h <<= 1) { |
| 773 | sb[jb] = v; |
| 774 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 775 | float partner = sb[jb ^ h]; |
| 776 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 777 | v = ((jb & h) == 0) ? (v + partner) : (partner - v); |
| 778 | } |
| 779 | hbuf[col] = (bfloat)(v * rsqrt((float)d)); |
| 780 | } else { |
| 781 | // threads with no block this sweep must still hit the barriers |
| 782 | for (uint h = 32u; h < d; h <<= 1) { |
| 783 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 784 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | } |
| 789 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 790 | |
| 791 | // ── Phase 5: down matmul y = down · h_rot (one simd-group per output row) ── |
| 792 | uint dn_nwords = I >> 3; // packed uints per down row (inn = I) |
| 793 | uint dn_wshift = (uint)log2((float)(d >> 3)); |
| 794 | uint dn_rstride = I / d; |
| 795 | for (uint o = sg; o < hidden; o += nsg) { |
| 796 | device const uint* drow = (device const uint*)(dn_codes + (((ulong)o * I) >> 1)); |
| 797 | float acc = 0.0f; |
| 798 | for (uint w = lane; w < dn_nwords; w += SIMDW) { |
| 799 | uint packed = drow[w]; |
| 800 | uint k0 = w << 3; |
| 801 | float r = (float)dn_radius[(ulong)o * dn_rstride + (w >> dn_wshift)]; |
| 802 | acc += (float)hbuf[k0 + 0] * cb[(packed >> 0) & 0xF] * r; |
| 803 | acc += (float)hbuf[k0 + 1] * cb[(packed >> 4) & 0xF] * r; |
| 804 | acc += (float)hbuf[k0 + 2] * cb[(packed >> 8) & 0xF] * r; |
| 805 | acc += (float)hbuf[k0 + 3] * cb[(packed >> 12) & 0xF] * r; |
| 806 | acc += (float)hbuf[k0 + 4] * cb[(packed >> 16) & 0xF] * r; |
| 807 | acc += (float)hbuf[k0 + 5] * cb[(packed >> 20) & 0xF] * r; |
| 808 | acc += (float)hbuf[k0 + 6] * cb[(packed >> 24) & 0xF] * r; |
| 809 | acc += (float)hbuf[k0 + 7] * cb[(packed >> 28) & 0xF] * r; |
| 810 | } |
| 811 | acc = simd_sum(acc); |
| 812 | if (lane == 0) { |
| 813 | y[(ulong)tok * hidden + o] = (bfloat)acc; |
| 814 | } |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | // ── uint2 wide-unpack variant ────────────────────────────────────────────── |
| 819 | // Same register-blocking as above but each lane consumes TWO packed words per |
| 820 | // inner iteration: codes are read as a single uint2 (8-byte coalesced) and all |
| 821 | // 16 nibbles are unpacked in registers, and the 16 matching activation coords |
| 822 | // are loaded as four float4. This halves loop trip count + branch overhead and |
| 823 | // raises ILP (two independent dot-product chains per row). Coalescing holds: |
| 824 | // consecutive lanes read consecutive uint2 words across the simd-group. |
| 825 | // Requires nwords (=inn/8) even — true for every weight here (inn is a multiple |
| 826 | // of 16). A scalar tail handles an odd final word defensively. Gated by |
| 827 | // COCO_QW2=1 (with QROWS=4). Numerics match the per-word kernel exactly (same |
| 828 | // FMA grouping per word, only the loop is restructured). |
| 829 | #define DEFINE_QMATVEC_RW2(NAME, QR) \ |
| 830 | kernel void NAME( \ |
| 831 | device const float* xr [[buffer(0)]], \ |
| 832 | device const uchar* codes [[buffer(1)]], \ |
| 833 | device const half* radius [[buffer(2)]], \ |
| 834 | constant float* codebook [[buffer(3)]], \ |
| 835 | device bfloat* y [[buffer(4)]], \ |
| 836 | constant uint& inn [[buffer(5)]], \ |
| 837 | constant uint& out_dim [[buffer(6)]], \ |
| 838 | constant uint& d [[buffer(7)]], \ |
| 839 | constant uint& tokens [[buffer(8)]], \ |
| 840 | device const ushort* bias [[buffer(9)]], \ |
| 841 | constant uint& has_bias [[buffer(10)]], \ |
| 842 | device const bfloat* resid [[buffer(11)]], \ |
| 843 | constant uint& has_resid [[buffer(12)]], \ |
| 844 | uint2 gid [[thread_position_in_grid]]) \ |
| 845 | { \ |
| 846 | const uint SIMDW = 32; \ |
| 847 | const uint QROWS = (QR); \ |
| 848 | uint t = gid.y; \ |
| 849 | uint grp = gid.x / SIMDW; \ |
| 850 | uint lane = gid.x % SIMDW; \ |
| 851 | uint o0 = grp * QROWS; \ |
| 852 | if (o0 >= out_dim || t >= tokens) return; \ |
| 853 | \ |
| 854 | float cb[8]; \ |
| 855 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; \ |
| 856 | \ |
| 857 | device const float* xrow = xr + (ulong)t * inn; \ |
| 858 | uint nwords = inn >> 3; \ |
| 859 | uint nw2 = nwords >> 1; /* number of uint2 pairs */ \ |
| 860 | uint wshift = (uint)log2((float)(d >> 3)); \ |
| 861 | uint rstride = inn / d; \ |
| 862 | \ |
| 863 | device const uint* codes32 = \ |
| 864 | (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); \ |
| 865 | device const uint2* crow2[QR]; \ |
| 866 | _Pragma("unroll") \ |
| 867 | for (uint i = 0; i < QROWS; ++i) \ |
| 868 | crow2[i] = (device const uint2*)(codes32 + (ulong)i * nwords); \ |
| 869 | \ |
| 870 | float acc[QR]; \ |
| 871 | for (uint i = 0; i < QROWS; ++i) acc[i] = 0.0f; \ |
| 872 | \ |
| 873 | device const float4* xrow4 = (device const float4*)xrow; \ |
| 874 | for (uint p = lane; p < nw2; p += SIMDW) { \ |
| 875 | uint w0 = p << 1; /* low word index of this pair */ \ |
| 876 | uint q = w0 << 1; /* float4 index of word w0's low half */ \ |
| 877 | float4 x0 = xrow4[q]; \ |
| 878 | float4 x1 = xrow4[q + 1]; \ |
| 879 | float4 x2 = xrow4[q + 2]; \ |
| 880 | float4 x3 = xrow4[q + 3]; \ |
| 881 | uint rb0 = w0 >> wshift; \ |
| 882 | uint rb1 = (w0 + 1) >> wshift; \ |
| 883 | _Pragma("unroll") \ |
| 884 | for (uint i = 0; i < QROWS; ++i) { \ |
| 885 | uint o = o0 + i; \ |
| 886 | if (o >= out_dim) break; \ |
| 887 | uint2 pk = crow2[i][p]; \ |
| 888 | uint a = pk.x, b = pk.y; \ |
| 889 | float r0 = (float)radius[(ulong)o * rstride + rb0]; \ |
| 890 | float r1 = (float)radius[(ulong)o * rstride + rb1]; \ |
| 891 | float4 a0 = float4(cb[(a >> 0) & 0xF], cb[(a >> 4) & 0xF], \ |
| 892 | cb[(a >> 8) & 0xF], cb[(a >> 12) & 0xF]); \ |
| 893 | float4 a1 = float4(cb[(a >> 16) & 0xF], cb[(a >> 20) & 0xF], \ |
| 894 | cb[(a >> 24) & 0xF], cb[(a >> 28) & 0xF]); \ |
| 895 | float4 b0 = float4(cb[(b >> 0) & 0xF], cb[(b >> 4) & 0xF], \ |
| 896 | cb[(b >> 8) & 0xF], cb[(b >> 12) & 0xF]); \ |
| 897 | float4 b1 = float4(cb[(b >> 16) & 0xF], cb[(b >> 20) & 0xF], \ |
| 898 | cb[(b >> 24) & 0xF], cb[(b >> 28) & 0xF]); \ |
| 899 | acc[i] += (dot(x0, a0) + dot(x1, a1)) * r0; \ |
| 900 | acc[i] += (dot(x2, b0) + dot(x3, b1)) * r1; \ |
| 901 | } \ |
| 902 | } \ |
| 903 | /* Defensive scalar tail for an odd final word (nwords not a multiple of \ |
| 904 | 2). All current weights have even nwords, so this never executes, but \ |
| 905 | it keeps the kernel correct for any inn that is a multiple of 8. */ \ |
| 906 | if ((nwords & 1u) && lane == 0) { \ |
| 907 | uint w = nwords - 1; \ |
| 908 | uint q = w << 1; \ |
| 909 | float4 xa = xrow4[q]; \ |
| 910 | float4 xb = xrow4[q + 1]; \ |
| 911 | uint rb = w >> wshift; \ |
| 912 | _Pragma("unroll") \ |
| 913 | for (uint i = 0; i < QROWS; ++i) { \ |
| 914 | uint o = o0 + i; \ |
| 915 | if (o >= out_dim) break; \ |
| 916 | uint packed = codes32[(ulong)i * nwords + w]; \ |
| 917 | float r = (float)radius[(ulong)o * rstride + rb]; \ |
| 918 | float4 wa = float4(cb[(packed >> 0) & 0xF], cb[(packed >> 4) & 0xF],\ |
| 919 | cb[(packed >> 8) & 0xF], cb[(packed >> 12) & 0xF]);\ |
| 920 | float4 wb = float4(cb[(packed >> 16) & 0xF], cb[(packed >> 20) & 0xF],\ |
| 921 | cb[(packed >> 24) & 0xF], cb[(packed >> 28) & 0xF]);\ |
| 922 | acc[i] += (dot(xa, wa) + dot(xb, wb)) * r; \ |
| 923 | } \ |
| 924 | } \ |
| 925 | _Pragma("unroll") \ |
| 926 | for (uint i = 0; i < QROWS; ++i) { \ |
| 927 | uint o = o0 + i; \ |
| 928 | if (o >= out_dim) break; \ |
| 929 | float s = simd_sum(acc[i]); \ |
| 930 | if (lane == 0) { \ |
| 931 | if (has_bias) s += (float)as_type<bfloat>(bias[o]); \ |
| 932 | if (has_resid) s += (float)resid[(ulong)t * out_dim + o]; \ |
| 933 | y[(ulong)t * out_dim + o] = (bfloat)s; \ |
| 934 | } \ |
| 935 | } \ |
| 936 | } |
| 937 | |
| 938 | DEFINE_QMATVEC_RW2(tq_qmatvec_bf16_rw2, 4) |
| 939 | |
| 940 | // ───────── ROTATE-IN-PROLOGUE variants (COCO_FUSE_ROTATE_IN, default OFF) ───────── |
| 941 | // Fold the standalone activation-rotate dispatch (blockwise FWHT `tq_rotate`) into |
| 942 | // the qmatvec itself: each THREADGROUP cooperatively recomputes the rotation of the |
| 943 | // token's activation row into threadgroup memory (`xbuf`, dynamic, inn f32 + tgsz |
| 944 | // f32 of FWHT scratch), barriers once, then runs the standard register-blocked |
| 945 | // QR=4 dot loop reading xbuf instead of a device xr. This trades REDUNDANT FLOPs |
| 946 | // (every threadgroup re-rotates the row; decode is memory-bound so they are nearly |
| 947 | // free) for one fewer dispatch+barrier per rotate it replaces (qkv, o_proj, |
| 948 | // gate/up — the down rotate stays: its row is I-wide, 8960/18944 f32 > 32KB). |
| 949 | // The launch grid is UNCHANGED vs the separate-rotate path (same threadgroup count |
| 950 | // / simd-group-per-QR-rows layout — parallelism-preserving), but each group now |
| 951 | // reserves (inn+tgsz)*4 B of threadgroup memory, which can trim resident-group |
| 952 | // occupancy — hence flag-OFF, A/B to decide. |
| 953 | // |
| 954 | // Numerics: the FWHT here is the SAME op order as tq_rotate_bf16 (bf16 load → f32 |
| 955 | // sign-flip/butterflies → rsqrt(d) scale) staged as f32, so results match the |
| 956 | // separate-rotate path exactly (verified by the one-shot COCO_QCHECK compare). |
| 957 | // |
| 958 | // Dispatched with dispatch_thread_groups (uniform groups — barrier-safe): grid = |
| 959 | // (ceil(out/(nsg*4)), tokens), tgroup = (tgsz,1,1) with tgsz a multiple of d. |
| 960 | // buffer(0) is the UNROTATED bf16 activation [tokens, inn]. |
| 961 | #define TQ_ROTIN_PROLOGUE \ |
| 962 | uint tgsz = tgsz3.x; \ |
| 963 | uint t = tg.y; \ |
| 964 | uint tid = lt.x; \ |
| 965 | { \ |
| 966 | uint nblk = inn / d; \ |
| 967 | uint jb = tid % d; /* coord within its d-block */ \ |
| 968 | uint slot = tid / d; /* which concurrent block it serves */ \ |
| 969 | uint bps = tgsz / d; /* blocks rotated per sweep (d|tgsz) */ \ |
| 970 | threadgroup float* scr = xbuf + inn; /* cross-simd FWHT scratch */ \ |
| 971 | device const bfloat* xrow_in = x + (ulong)t * inn; \ |
| 972 | for (uint b0 = 0; b0 < nblk; b0 += bps) { \ |
| 973 | uint blk = b0 + slot; \ |
| 974 | if (blk < nblk) { \ |
| 975 | uint col = blk * d + jb; \ |
| 976 | float v = (float)xrow_in[col] * sgn[col]; \ |
| 977 | for (uint h = 1; h < 32u && h < d; h <<= 1) { \ |
| 978 | float partner = simd_shuffle_xor(v, h); \ |
| 979 | v = ((jb & h) == 0) ? (v + partner) : (partner - v); \ |
| 980 | } \ |
| 981 | threadgroup float* sb = scr + slot * d; \ |
| 982 | for (uint h = 32u; h < d; h <<= 1) { \ |
| 983 | sb[jb] = v; \ |
| 984 | threadgroup_barrier(mem_flags::mem_threadgroup); \ |
| 985 | float partner = sb[jb ^ h]; \ |
| 986 | threadgroup_barrier(mem_flags::mem_threadgroup); \ |
| 987 | v = ((jb & h) == 0) ? (v + partner) : (partner - v); \ |
| 988 | } \ |
| 989 | xbuf[col] = v * rsqrt((float)d); \ |
| 990 | } else { \ |
| 991 | /* idle threads must still hit the FWHT barriers */ \ |
| 992 | for (uint h = 32u; h < d; h <<= 1) { \ |
| 993 | threadgroup_barrier(mem_flags::mem_threadgroup); \ |
| 994 | threadgroup_barrier(mem_flags::mem_threadgroup); \ |
| 995 | } \ |
| 996 | } \ |
| 997 | } \ |
| 998 | } \ |
| 999 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 1000 | |
| 1001 | // Rotate-in + register-blocked QR=4 dot + bias/resid epilogue (plain projections). |
| 1002 | kernel void tq_qmatvec_bf16_rot( |
| 1003 | device const bfloat* x [[buffer(0)]], // [tokens, inn] UNROTATED bf16 |
| 1004 | device const uchar* codes [[buffer(1)]], |
| 1005 | device const half* radius [[buffer(2)]], |
| 1006 | constant float* codebook [[buffer(3)]], |
| 1007 | device bfloat* y [[buffer(4)]], |
| 1008 | constant uint& inn [[buffer(5)]], |
| 1009 | constant uint& out_dim [[buffer(6)]], |
| 1010 | constant uint& d [[buffer(7)]], |
| 1011 | constant uint& tokens [[buffer(8)]], |
| 1012 | device const ushort* bias [[buffer(9)]], |
| 1013 | constant uint& has_bias [[buffer(10)]], |
| 1014 | device const bfloat* resid [[buffer(11)]], |
| 1015 | constant uint& has_resid [[buffer(12)]], |
| 1016 | device const float* sgn [[buffer(13)]], // [inn] rotation sign (±1) |
| 1017 | threadgroup float* xbuf [[threadgroup(0)]], // inn + tgsz floats |
| 1018 | uint3 tg [[threadgroup_position_in_grid]], |
| 1019 | uint3 lt [[thread_position_in_threadgroup]], |
| 1020 | uint3 tgsz3 [[threads_per_threadgroup]]) |
| 1021 | { |
| 1022 | const uint SIMDW = 32; |
| 1023 | const uint QROWS = 4; |
| 1024 | TQ_ROTIN_PROLOGUE |
| 1025 | |
| 1026 | uint sg = tid / SIMDW; |
| 1027 | uint lane = tid % SIMDW; |
| 1028 | uint nsg = tgsz / SIMDW; |
| 1029 | uint o0 = (tg.x * nsg + sg) * QROWS; |
| 1030 | if (o0 >= out_dim) return; // AFTER all barriers — safe |
| 1031 | |
| 1032 | float cb[8]; |
| 1033 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 1034 | |
| 1035 | uint nwords = inn >> 3; |
| 1036 | uint wshift = (uint)log2((float)(d >> 3)); |
| 1037 | uint rstride = inn / d; |
| 1038 | |
| 1039 | device const uint* codes32 = |
| 1040 | (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); |
| 1041 | device const uint* crow[4]; |
| 1042 | _Pragma("unroll") |
| 1043 | for (uint i = 0; i < QROWS; ++i) crow[i] = codes32 + (ulong)i * nwords; |
| 1044 | |
| 1045 | float acc[4]; |
| 1046 | for (uint i = 0; i < QROWS; ++i) acc[i] = 0.0f; |
| 1047 | |
| 1048 | threadgroup const float4* xrow4 = (threadgroup const float4*)xbuf; |
| 1049 | for (uint w = lane; w < nwords; w += SIMDW) { |
| 1050 | uint q = w << 1; |
| 1051 | float4 xa = xrow4[q]; |
| 1052 | float4 xb = xrow4[q + 1]; |
| 1053 | uint rb = w >> wshift; |
| 1054 | _Pragma("unroll") |
| 1055 | for (uint i = 0; i < QROWS; ++i) { |
| 1056 | uint o = o0 + i; |
| 1057 | if (o >= out_dim) break; |
| 1058 | uint packed = crow[i][w]; |
| 1059 | float r = (float)radius[(ulong)o * rstride + rb]; |
| 1060 | float4 wa = float4(cb[(packed >> 0) & 0xF], cb[(packed >> 4) & 0xF], |
| 1061 | cb[(packed >> 8) & 0xF], cb[(packed >> 12) & 0xF]); |
| 1062 | float4 wb = float4(cb[(packed >> 16) & 0xF], cb[(packed >> 20) & 0xF], |
| 1063 | cb[(packed >> 24) & 0xF], cb[(packed >> 28) & 0xF]); |
| 1064 | acc[i] += (dot(xa, wa) + dot(xb, wb)) * r; |
| 1065 | } |
| 1066 | } |
| 1067 | _Pragma("unroll") |
| 1068 | for (uint i = 0; i < QROWS; ++i) { |
| 1069 | uint o = o0 + i; |
| 1070 | if (o >= out_dim) break; |
| 1071 | float s = simd_sum(acc[i]); |
| 1072 | if (lane == 0) { |
| 1073 | if (has_bias) s += (float)as_type<bfloat>(bias[o]); |
| 1074 | if (has_resid) s += (float)resid[(ulong)t * out_dim + o]; |
| 1075 | y[(ulong)t * out_dim + o] = (bfloat)s; |
| 1076 | } |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | // Rotate-in + fused SwiGLU (gate/up group): same prologue, then the swiglu QR=4 |
| 1081 | // dot (gate row o + up row o+out_dim from the concatenated codes), silu(g)·u at |
| 1082 | // the leader store. No bias/resid (gate/up never carry either). |
| 1083 | kernel void tq_qmatvec_swiglu_rot( |
| 1084 | device const bfloat* x [[buffer(0)]], // [tokens, inn] UNROTATED bf16 |
| 1085 | device const uchar* codes [[buffer(1)]], |
| 1086 | device const half* radius [[buffer(2)]], |
| 1087 | constant float* codebook [[buffer(3)]], |
| 1088 | device bfloat* y [[buffer(4)]], |
| 1089 | constant uint& inn [[buffer(5)]], |
| 1090 | constant uint& out_dim [[buffer(6)]], // = I (SwiGLU width) |
| 1091 | constant uint& d [[buffer(7)]], |
| 1092 | constant uint& tokens [[buffer(8)]], |
| 1093 | device const float* sgn [[buffer(9)]], // [inn] rotation sign (±1) |
| 1094 | threadgroup float* xbuf [[threadgroup(0)]], // inn + tgsz floats |
| 1095 | uint3 tg [[threadgroup_position_in_grid]], |
| 1096 | uint3 lt [[thread_position_in_threadgroup]], |
| 1097 | uint3 tgsz3 [[threads_per_threadgroup]]) |
| 1098 | { |
| 1099 | const uint SIMDW = 32; |
| 1100 | const uint QROWS = 4; |
| 1101 | TQ_ROTIN_PROLOGUE |
| 1102 | |
| 1103 | uint sg = tid / SIMDW; |
| 1104 | uint lane = tid % SIMDW; |
| 1105 | uint nsg = tgsz / SIMDW; |
| 1106 | uint o0 = (tg.x * nsg + sg) * QROWS; |
| 1107 | if (o0 >= out_dim) return; // AFTER all barriers — safe |
| 1108 | |
| 1109 | float cb[8]; |
| 1110 | for (uint i = 0; i < 8; ++i) cb[i] = codebook[i]; |
| 1111 | |
| 1112 | uint nwords = inn >> 3; |
| 1113 | uint wshift = (uint)log2((float)(d >> 3)); |
| 1114 | uint rstride = inn / d; |
| 1115 | ulong up_word_off = (ulong)out_dim * nwords; |
| 1116 | ulong up_rad_off = (ulong)out_dim * rstride; |
| 1117 | |
| 1118 | device const uint* gcodes32 = |
| 1119 | (device const uint*)(codes + (((ulong)o0 * inn) >> 1)); |
| 1120 | device const uint* gcrow[4]; |
| 1121 | device const uint* ucrow[4]; |
| 1122 | _Pragma("unroll") |
| 1123 | for (uint i = 0; i < QROWS; ++i) { |
| 1124 | gcrow[i] = gcodes32 + (ulong)i * nwords; |
| 1125 | ucrow[i] = gcrow[i] + up_word_off; |
| 1126 | } |
| 1127 | |
| 1128 | float gacc[4]; |
| 1129 | float uacc[4]; |
| 1130 | for (uint i = 0; i < QROWS; ++i) { gacc[i] = 0.0f; uacc[i] = 0.0f; } |
| 1131 | |
| 1132 | threadgroup const float4* xrow4 = (threadgroup const float4*)xbuf; |
| 1133 | for (uint w = lane; w < nwords; w += SIMDW) { |
| 1134 | uint q = w << 1; |
| 1135 | float4 xa = xrow4[q]; |
| 1136 | float4 xb = xrow4[q + 1]; |
| 1137 | uint rb = w >> wshift; |
| 1138 | _Pragma("unroll") |
| 1139 | for (uint i = 0; i < QROWS; ++i) { |
| 1140 | uint o = o0 + i; |
| 1141 | if (o >= out_dim) break; |
| 1142 | uint gp = gcrow[i][w]; |
| 1143 | float gr = (float)radius[(ulong)o * rstride + rb]; |
| 1144 | float4 gwa = float4(cb[(gp >> 0) & 0xF], cb[(gp >> 4) & 0xF], |
| 1145 | cb[(gp >> 8) & 0xF], cb[(gp >> 12) & 0xF]); |
| 1146 | float4 gwb = float4(cb[(gp >> 16) & 0xF], cb[(gp >> 20) & 0xF], |
| 1147 | cb[(gp >> 24) & 0xF], cb[(gp >> 28) & 0xF]); |
| 1148 | gacc[i] += (dot(xa, gwa) + dot(xb, gwb)) * gr; |
| 1149 | uint up = ucrow[i][w]; |
| 1150 | float ur = (float)radius[(ulong)o * rstride + rb + up_rad_off]; |
| 1151 | float4 uwa = float4(cb[(up >> 0) & 0xF], cb[(up >> 4) & 0xF], |
| 1152 | cb[(up >> 8) & 0xF], cb[(up >> 12) & 0xF]); |
| 1153 | float4 uwb = float4(cb[(up >> 16) & 0xF], cb[(up >> 20) & 0xF], |
| 1154 | cb[(up >> 24) & 0xF], cb[(up >> 28) & 0xF]); |
| 1155 | uacc[i] += (dot(xa, uwa) + dot(xb, uwb)) * ur; |
| 1156 | } |
| 1157 | } |
| 1158 | _Pragma("unroll") |
| 1159 | for (uint i = 0; i < QROWS; ++i) { |
| 1160 | uint o = o0 + i; |
| 1161 | if (o >= out_dim) break; |
| 1162 | float g = simd_sum(gacc[i]); |
| 1163 | float u = simd_sum(uacc[i]); |
| 1164 | if (lane == 0) { |
| 1165 | float sg_act = g / (1.0f + exp(-g)); /* silu(gate) = x·σ(x) */ |
| 1166 | y[(ulong)t * out_dim + o] = (bfloat)(sg_act * u); |
| 1167 | } |
| 1168 | } |
| 1169 | } |
| 1170 | |
| 1171 | // ───────── FUSED FLASH-DECODE ATTENTION (one token, GQA, persistent KV) ───────── |
| 1172 | // Replaces candle's per-token cat(kv) + repeat_kv().contiguous() + scores matmul |
| 1173 | // + softmax + AV matmul (each O(ctx), each a separate dispatch + huge copies) |
| 1174 | // with ONE dispatch over the persistent KV cache. This is THE long-context lever: |
| 1175 | // the candle path reallocates & copies the whole cache every token and materializes |
| 1176 | // the GQA-expanded K/V, so decode tok/s collapsed ~35x by 32K. Here the cache lives |
| 1177 | // in a pinned buffer; the new k/v is appended in-kernel; attention is online-softmax |
| 1178 | // (flash style) so nothing of size [heads,1,ctx] is ever materialized. |
| 1179 | // |
| 1180 | // Layout: q [n_heads, head_dim] f32 (RoPE'd). k_new/v_new [n_kv_heads, head_dim] f32 |
| 1181 | // (RoPE'd, in f32). k_cache/v_cache [n_kv_heads, max_ctx, head_dim] f32, persistent. |
| 1182 | // `pos` = index where the new token is written; it then attends over [0..=pos]. |
| 1183 | // GQA: query head h maps to kv head h / (n_heads/n_kv_heads). |
| 1184 | // |
| 1185 | // FLASH-DECODING (split-K) — the parallelism that matters. The naive "1 |
| 1186 | // threadgroup per head, loop all positions" design serializes O(ctx) per head with |
| 1187 | // only n_heads threadgroups (12), leaving the GPU idle and 2 threadgroup-barriers |
| 1188 | // per position. Instead we split the KV range across `n_splits` threadgroups PER |
| 1189 | // head (grid = n_heads × n_splits) so up to n_heads·n_splits groups run in |
| 1190 | // parallel, each over ctx/n_splits positions. Each group is ONE simd-group (32 |
| 1191 | // lanes): the per-position q·k dot is a `simd_sum` (no threadgroup barrier), and |
| 1192 | // each lane owns head_dim/32 value-accumulator coords. A second tiny kernel |
| 1193 | // (tq_attn_combine) merges the per-split partials per head via online-softmax. |
| 1194 | // |
| 1195 | // head_dim must be a multiple of 32 (128 here → 4 coords/lane). q/k/v f32. |
| 1196 | // partial dispatch: grid(threadgroups) = (n_heads, n_splits) ; tgroup = (32,1,1) |
| 1197 | // partial outputs : pacc [n_heads, n_splits, head_dim] f32 |
| 1198 | // pm [n_heads, n_splits] f32 (running max) |
| 1199 | // pl [n_heads, n_splits] f32 (running denom) |
| 1200 | #define COCO_HD_MAX 256 |
| 1201 | // 4-bit KV cache: coords-per-quant-block. Equals the simd width (32) so one block == |
| 1202 | // one simd-group (block absmax = a single simd_max). head_dim must be a multiple of 32. |
| 1203 | #define Q4_BLK 32 |
| 1204 | // k_new/v_new (the decode token's k/v, bf16) are appended IN-KERNEL by the single |
| 1205 | // split whose range includes pos=total-1 (the highest position). Because only that |
| 1206 | // one threadgroup both writes AND reads position `pos`, and every other split reads |
| 1207 | // only OLD positions (< pos, untouched this step), there is NO cross-threadgroup |
| 1208 | // hazard — so we fold the append into this dispatch (no separate kernel, no |
| 1209 | // MTLBarrierScope::Buffers between append→read that serialized the GPU per token). |
| 1210 | kernel void tq_attn_partial( |
| 1211 | device const bfloat* q [[buffer(0)]], // [n_heads, head_dim] bf16, RoPE'd |
| 1212 | device bfloat* k_cache [[buffer(1)]], // [n_kv, max_ctx, head_dim] BF16 |
| 1213 | device bfloat* v_cache [[buffer(2)]], // [n_kv, max_ctx, head_dim] BF16 |
| 1214 | device float* pacc [[buffer(3)]], // [n_heads, n_splits, head_dim] |
| 1215 | device float* pm [[buffer(4)]], // [n_heads, n_splits] |
| 1216 | device float* pl [[buffer(5)]], // [n_heads, n_splits] |
| 1217 | constant uint& n_heads [[buffer(6)]], |
| 1218 | constant uint& n_kv [[buffer(7)]], |
| 1219 | constant uint& head_dim [[buffer(8)]], |
| 1220 | constant uint& max_ctx [[buffer(9)]], |
| 1221 | constant uint& total [[buffer(10)]], // number of valid positions (pos+1) |
| 1222 | constant float& scale [[buffer(11)]], |
| 1223 | constant uint& n_splits [[buffer(12)]], |
| 1224 | device const bfloat* k_new [[buffer(13)]], // [n_kv, head_dim] bf16, RoPE'd |
| 1225 | device const bfloat* v_new [[buffer(14)]], // [n_kv, head_dim] bf16 |
| 1226 | uint3 tg [[threadgroup_position_in_grid]], |
| 1227 | uint3 lt [[thread_position_in_threadgroup]]) |
| 1228 | { |
| 1229 | const uint SIMDW = 32; |
| 1230 | uint lane = lt.x; |
| 1231 | uint h = tg.x; // query head |
| 1232 | uint split = tg.y; // which position-slice |
| 1233 | if (h >= n_heads || split >= n_splits) return; |
| 1234 | uint grp = n_heads / n_kv; |
| 1235 | uint kvh = h / grp; |
| 1236 | |
| 1237 | // This split's position range [p0, p1). |
| 1238 | uint per = (total + n_splits - 1) / n_splits; |
| 1239 | uint p0 = split * per; |
| 1240 | uint p1 = min(p0 + per, total); |
| 1241 | |
| 1242 | uint cpl = head_dim / SIMDW; // coords per lane (4 for head_dim=128) |
| 1243 | |
| 1244 | // In-kernel append: EVERY threadgroup whose range owns pos=total-1 writes the |
| 1245 | // new k/v row for its OWN kv head, then reads it below. No h%grp==0 guard: heads |
| 1246 | // sharing a kvh live in DIFFERENT threadgroups, so if only head 0 wrote, head 1 |
| 1247 | // would read a row written by another group (cross-group race). Letting each |
| 1248 | // group write its own kvh row is redundant (identical data) but RACE-FREE: each |
| 1249 | // group reads exactly what it itself wrote (intra-group, ordered by the barrier). |
| 1250 | uint pos = total - 1; |
| 1251 | bool owns_pos = (p0 <= pos && pos < p1); |
| 1252 | if (owns_pos) { |
| 1253 | for (uint c = 0; c < cpl; ++c) { |
| 1254 | uint j = c * SIMDW + lane; |
| 1255 | ulong dst = ((ulong)kvh * max_ctx + pos) * head_dim + j; |
| 1256 | k_cache[dst] = k_new[kvh * head_dim + j]; // bf16 → bf16 cache |
| 1257 | v_cache[dst] = v_new[kvh * head_dim + j]; |
| 1258 | } |
| 1259 | // Make this group's own writes visible to its own reads below. |
| 1260 | threadgroup_barrier(mem_flags::mem_device); |
| 1261 | } |
| 1262 | |
| 1263 | // Load this lane's q coords into registers (bf16 → f32 on load). |
| 1264 | float qreg[COCO_HD_MAX / 32]; |
| 1265 | for (uint c = 0; c < cpl; ++c) qreg[c] = (float)q[h * head_dim + c * SIMDW + lane]; |
| 1266 | |
| 1267 | float m = -INFINITY, l = 0.0f; |
| 1268 | float acc[COCO_HD_MAX / 32]; |
| 1269 | for (uint c = 0; c < cpl; ++c) acc[c] = 0.0f; |
| 1270 | |
| 1271 | for (uint p = p0; p < p1; ++p) { |
| 1272 | device const bfloat* krow = k_cache + ((ulong)kvh * max_ctx + p) * head_dim; |
| 1273 | // q·k: each lane sums its coords (bf16 cache → f32 math), simd_sum reduces. |
| 1274 | float partial = 0.0f; |
| 1275 | for (uint c = 0; c < cpl; ++c) partial += qreg[c] * (float)krow[c * SIMDW + lane]; |
| 1276 | float score = simd_sum(partial) * scale; // broadcast to all lanes |
| 1277 | float m_new = max(m, score); |
| 1278 | float corr = exp(m - m_new); |
| 1279 | float w = exp(score - m_new); |
| 1280 | l = l * corr + w; |
| 1281 | device const bfloat* vrow = v_cache + ((ulong)kvh * max_ctx + p) * head_dim; |
| 1282 | for (uint c = 0; c < cpl; ++c) acc[c] = acc[c] * corr + w * (float)vrow[c * SIMDW + lane]; |
| 1283 | m = m_new; |
| 1284 | } |
| 1285 | // Write this split's partials. acc is the UN-normalized weighted-V (÷ l done in |
| 1286 | // combine). Empty splits (p0>=p1) write m=-inf, l=0 → ignored in combine. |
| 1287 | ulong pbase = ((ulong)h * n_splits + split) * head_dim; |
| 1288 | for (uint c = 0; c < cpl; ++c) pacc[pbase + c * SIMDW + lane] = acc[c]; |
| 1289 | if (lane == 0) { |
| 1290 | pm[h * n_splits + split] = m; |
| 1291 | pl[h * n_splits + split] = l; |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | // Combine the per-split partials for each head into the final attention output. |
| 1296 | // online-softmax merge across splits: global m = max(m_i); each split contributes |
| 1297 | // exp(m_i - m) * (acc_i, l_i); out = Σ acc / Σ l. |
| 1298 | // dispatch: grid(threadgroups) = (n_heads,1,1) ; tgroup = (32,1,1) |
| 1299 | kernel void tq_attn_combine( |
| 1300 | device const float* pacc [[buffer(0)]], // [n_heads, n_splits, head_dim] |
| 1301 | device const float* pm [[buffer(1)]], // [n_heads, n_splits] |
| 1302 | device const float* pl [[buffer(2)]], // [n_heads, n_splits] |
| 1303 | device float* attn [[buffer(3)]], // [n_heads, head_dim] f32 out |
| 1304 | constant uint& n_heads [[buffer(4)]], |
| 1305 | constant uint& head_dim [[buffer(5)]], |
| 1306 | constant uint& n_splits [[buffer(6)]], |
| 1307 | uint3 tg [[threadgroup_position_in_grid]], |
| 1308 | uint3 lt [[thread_position_in_threadgroup]]) |
| 1309 | { |
| 1310 | const uint SIMDW = 32; |
| 1311 | uint h = tg.x; |
| 1312 | uint lane = lt.x; |
| 1313 | if (h >= n_heads) return; |
| 1314 | uint cpl = head_dim / SIMDW; |
| 1315 | // global max across splits |
| 1316 | float gm = -INFINITY; |
| 1317 | for (uint s = 0; s < n_splits; ++s) gm = max(gm, pm[h * n_splits + s]); |
| 1318 | float gl = 0.0f; |
| 1319 | float out[COCO_HD_MAX / 32]; |
| 1320 | for (uint c = 0; c < cpl; ++c) out[c] = 0.0f; |
| 1321 | for (uint s = 0; s < n_splits; ++s) { |
| 1322 | float m_s = pm[h * n_splits + s]; |
| 1323 | float l_s = pl[h * n_splits + s]; |
| 1324 | if (l_s <= 0.0f) continue; // empty split |
| 1325 | float corr = exp(m_s - gm); |
| 1326 | gl += l_s * corr; |
| 1327 | ulong pbase = ((ulong)h * n_splits + s) * head_dim; |
| 1328 | for (uint c = 0; c < cpl; ++c) out[c] += corr * pacc[pbase + c * SIMDW + lane]; |
| 1329 | } |
| 1330 | float inv = (gl > 0.0f) ? (1.0f / gl) : 0.0f; |
| 1331 | for (uint c = 0; c < cpl; ++c) attn[h * head_dim + c * SIMDW + lane] = out[c] * inv; |
| 1332 | } |
| 1333 | |
| 1334 | // Append a chunk's k/v into the persistent f32 cache, reading BF16 source (the |
| 1335 | // model's hidden dtype) and converting on store — no candle to_dtype(F32) before |
| 1336 | // the append. src contiguous [n_kv, seq, head_dim] (k already RoPE'd); dst cache |
| 1337 | // [n_kv, max_ctx, head_dim] at column offset `pos`. One thread per (kv, s, j). |
| 1338 | // grid = (head_dim, seq, n_kv) ; tgroup = (head_dim,1,1) |
| 1339 | kernel void tq_kv_append( |
| 1340 | device const bfloat* k_src [[buffer(0)]], // [n_kv, seq, head_dim] bf16 |
| 1341 | device const bfloat* v_src [[buffer(1)]], |
| 1342 | device bfloat* k_cache [[buffer(2)]], // [n_kv, max_ctx, head_dim] BF16 |
| 1343 | device bfloat* v_cache [[buffer(3)]], |
| 1344 | constant uint& seq [[buffer(4)]], |
| 1345 | constant uint& head_dim [[buffer(5)]], |
| 1346 | constant uint& max_ctx [[buffer(6)]], |
| 1347 | constant uint& pos [[buffer(7)]], |
| 1348 | uint3 gid [[thread_position_in_grid]]) |
| 1349 | { |
| 1350 | uint j = gid.x; // coord |
| 1351 | uint s = gid.y; // position within the chunk |
| 1352 | uint kv = gid.z; // kv head |
| 1353 | if (j >= head_dim || s >= seq) return; |
| 1354 | ulong src = ((ulong)kv * seq + s) * head_dim + j; |
| 1355 | ulong dst = ((ulong)kv * max_ctx + (pos + s)) * head_dim + j; |
| 1356 | k_cache[dst] = k_src[src]; |
| 1357 | v_cache[dst] = v_src[src]; |
| 1358 | } |
| 1359 | |
| 1360 | // ──────────────── 4-BIT KV-CACHE (q4_0-style, per-32-coord block scale) ─────────── |
| 1361 | // The KV cache stored as 4-bit symmetric-quantized rows instead of bf16 to cut the |
| 1362 | // per-decode KV memory traffic ~4x at long context (the dominant cost there). One |
| 1363 | // row = the `head_dim` (128) coords for a single (kv_head, position). Each row is |
| 1364 | // split into Q4_BLK-coord (=32) BLOCKS, and each block is quantized INDEPENDENTLY: |
| 1365 | // scale = absmax(block)/7, code = round(val/scale) clamped to [-7,7], stored unsigned |
| 1366 | // as (code+8) in 4 bits (nibble), 2 coords per byte. Dequant: val = (nib - 8) * scale. |
| 1367 | // |
| 1368 | // IMPORTANT: a single scale per 128-coord ROW (the original design) was too coarse — |
| 1369 | // one large RoPE'd coordinate inflates the row absmax, quantizing every other coord to |
| 1370 | // near-zero, which collapses the attention scores across positions (the model repeats/ |
| 1371 | // rambles after the first, recency-dominated token). Real llama.cpp `-ctk q4_0` uses a |
| 1372 | // scale PER 32-element block; we match that. With SIMDW==Q4_BLK==32, each block is |
| 1373 | // exactly one simd-group, so the block absmax is a single simd_max (no cross-simd |
| 1374 | // reduction). f32 softmax/accumulation in-kernel after dequant. |
| 1375 | // codes layout: [n_kv, max_ctx, head_dim/2] uchar (nibble-packed, coord j → byte |
| 1376 | // j/2, low nibble for even j, high nibble for odd j) |
| 1377 | // scale layout: [n_kv, max_ctx, head_dim/Q4_BLK] bfloat (one per 32-coord block) |
| 1378 | |
| 1379 | // Quantize + append a prefill chunk's k/v into the 4-bit cache. ONE threadgroup per |
| 1380 | // (kv, s): the head_dim threads find each 32-coord BLOCK's absmax (one simd_max per |
| 1381 | // simd-group, since SIMDW==Q4_BLK), derive that block's bf16 scale, then each thread |
| 1382 | // writes its nibble. Reads bf16 source, writes packed nibbles + per-block bf16 scales. |
| 1383 | // grid = (kv, seq) tgroup = (head_dim). |
| 1384 | kernel void tq_kv_append_q4( |
| 1385 | device const bfloat* k_src [[buffer(0)]], // [n_kv, seq, head_dim] bf16 |
| 1386 | device const bfloat* v_src [[buffer(1)]], |
| 1387 | device uchar* k_codes [[buffer(2)]], // [n_kv, max_ctx, head_dim/2] |
| 1388 | device uchar* v_codes [[buffer(3)]], |
| 1389 | device bfloat* k_scale [[buffer(4)]], // [n_kv, max_ctx, head_dim/Q4_BLK] |
| 1390 | device bfloat* v_scale [[buffer(5)]], |
| 1391 | constant uint& seq [[buffer(6)]], |
| 1392 | constant uint& head_dim [[buffer(7)]], |
| 1393 | constant uint& max_ctx [[buffer(8)]], |
| 1394 | constant uint& pos [[buffer(9)]], |
| 1395 | // NOTE: Metal requires the position stage-in attributes in one kernel to be |
| 1396 | // either ALL scalar or ALL same-width vectors. The previous (uint2 tg, uint lt) |
| 1397 | // pair mixed a width-2 vector with a scalar and failed MSL JIT compilation |
| 1398 | // ("expecting input declarations with either all scalar types or all vector |
| 1399 | // types with the same number of elements"). Use uint3 for both (matching the |
| 1400 | // tq_attn_partial convention) and read the components we need. |
| 1401 | uint3 tg [[threadgroup_position_in_grid]], |
| 1402 | uint3 lt [[thread_position_in_threadgroup]], |
| 1403 | uint sg_id [[simdgroup_index_in_threadgroup]], |
| 1404 | uint n_sg [[simdgroups_per_threadgroup]]) |
| 1405 | { |
| 1406 | (void)n_sg; (void)sg_id; // block index derived from coord (j/Q4_BLK) below |
| 1407 | uint kv = tg.x; // kv head |
| 1408 | uint s = tg.y; // position within the chunk |
| 1409 | uint j = lt.x; // coord |
| 1410 | if (j >= head_dim) return; |
| 1411 | ulong srow = ((ulong)kv * seq + s) * head_dim; |
| 1412 | uint dpos = pos + s; |
| 1413 | float kv_v = (float)k_src[srow + j]; |
| 1414 | float vv_v = (float)v_src[srow + j]; |
| 1415 | |
| 1416 | // ── per-32-coord BLOCK absmax. With SIMDW==Q4_BLK==32, coord j's block is its |
| 1417 | // own simd-group (blk = j/Q4_BLK == sg_id); the block max is one simd_max. ── |
| 1418 | uint blk = j / Q4_BLK; // == sg_id |
| 1419 | uint n_blk = head_dim / Q4_BLK; |
| 1420 | float k_sc = simd_max(fabs(kv_v)) / 7.0f; |
| 1421 | if (k_sc == 0.0f) k_sc = 1.0f; // all-zero block → safe unit scale |
| 1422 | float v_sc = simd_max(fabs(vv_v)) / 7.0f; |
| 1423 | if (v_sc == 0.0f) v_sc = 1.0f; |
| 1424 | |
| 1425 | // lane 0 of each simd-group (== block) writes that block's scale. |
| 1426 | if (simd_is_first()) { |
| 1427 | ulong sbase = ((ulong)kv * max_ctx + dpos) * n_blk + blk; |
| 1428 | k_scale[sbase] = (bfloat)k_sc; |
| 1429 | v_scale[sbase] = (bfloat)v_sc; |
| 1430 | } |
| 1431 | // encode this coord's nibble (signed code in [-7,7], stored as code+8 ∈ [1,15]) |
| 1432 | int kc = (int)round(kv_v / k_sc); kc = clamp(kc, -7, 7); |
| 1433 | int vc = (int)round(vv_v / v_sc); vc = clamp(vc, -7, 7); |
| 1434 | uint nk = (uint)(kc + 8); |
| 1435 | uint nv = (uint)(vc + 8); |
| 1436 | // nibble-pack: the OWNER of each byte is the even-coord thread (j%2==0); it reads |
| 1437 | // its odd neighbour's nibble via threadgroup memory to avoid a read-modify-write |
| 1438 | // race on the shared byte. (Two threads writing the same byte = data race.) |
| 1439 | threadgroup uchar k_nib[256]; // head_dim <= 256 |
| 1440 | threadgroup uchar v_nib[256]; |
| 1441 | k_nib[j] = (uchar)nk; |
| 1442 | v_nib[j] = (uchar)nv; |
| 1443 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 1444 | if ((j & 1u) == 0u) { |
| 1445 | ulong byte = ((ulong)kv * max_ctx + dpos) * (head_dim / 2) + (j >> 1); |
| 1446 | uchar lo_k = k_nib[j], hi_k = (j + 1 < head_dim) ? k_nib[j + 1] : 8; |
| 1447 | uchar lo_v = v_nib[j], hi_v = (j + 1 < head_dim) ? v_nib[j + 1] : 8; |
| 1448 | k_codes[byte] = (uchar)(lo_k | (hi_k << 4)); |
| 1449 | v_codes[byte] = (uchar)(lo_v | (hi_v << 4)); |
| 1450 | } |
| 1451 | } |
| 1452 | |
| 1453 | // Flash-decode split-K partials over the 4-BIT KV cache (q4 variant of |
| 1454 | // tq_attn_partial). Identical online-softmax math; the only difference is K/V are |
| 1455 | // read as packed nibbles + a per-row bf16 scale and DEQUANTIZED on the fly |
| 1456 | // (val = (nib-8)*scale) before the f32 dot / AV accumulation. The decode token's |
| 1457 | // k/v is quantized + appended IN-KERNEL by the split owning pos=total-1 (same |
| 1458 | // race-free design as the bf16 kernel: each group writes its own kv-head row). |
| 1459 | kernel void tq_attn_partial_q4( |
| 1460 | device const bfloat* q [[buffer(0)]], // [n_heads, head_dim] bf16, RoPE'd |
| 1461 | device uchar* k_codes [[buffer(1)]], // [n_kv, max_ctx, head_dim/2] |
| 1462 | device uchar* v_codes [[buffer(2)]], // [n_kv, max_ctx, head_dim/2] |
| 1463 | device float* pacc [[buffer(3)]], // [n_heads, n_splits, head_dim] |
| 1464 | device float* pm [[buffer(4)]], // [n_heads, n_splits] |
| 1465 | device float* pl [[buffer(5)]], // [n_heads, n_splits] |
| 1466 | constant uint& n_heads [[buffer(6)]], |
| 1467 | constant uint& n_kv [[buffer(7)]], |
| 1468 | constant uint& head_dim [[buffer(8)]], |
| 1469 | constant uint& max_ctx [[buffer(9)]], |
| 1470 | constant uint& total [[buffer(10)]], // valid positions (pos+1) |
| 1471 | constant float& scale [[buffer(11)]], |
| 1472 | constant uint& n_splits [[buffer(12)]], |
| 1473 | device const bfloat* k_new [[buffer(13)]], // [n_kv, head_dim] bf16, RoPE'd |
| 1474 | device const bfloat* v_new [[buffer(14)]], // [n_kv, head_dim] bf16 |
| 1475 | device bfloat* k_scale [[buffer(15)]], // [n_kv, max_ctx, head_dim/Q4_BLK] |
| 1476 | device bfloat* v_scale [[buffer(16)]], // [n_kv, max_ctx, head_dim/Q4_BLK] |
| 1477 | constant uint& do_append [[buffer(17)]], // 1 = quantize+append pos in-kernel |
| 1478 | uint3 tg [[threadgroup_position_in_grid]], |
| 1479 | uint3 lt [[thread_position_in_threadgroup]]) |
| 1480 | { |
| 1481 | const uint SIMDW = 32; |
| 1482 | uint lane = lt.x; |
| 1483 | uint h = tg.x; // query head |
| 1484 | uint split = tg.y; // which position-slice |
| 1485 | if (h >= n_heads || split >= n_splits) return; |
| 1486 | uint grp = n_heads / n_kv; |
| 1487 | uint kvh = h / grp; |
| 1488 | uint hd2 = head_dim / 2; // bytes per packed row |
| 1489 | |
| 1490 | uint per = (total + n_splits - 1) / n_splits; |
| 1491 | uint p0 = split * per; |
| 1492 | uint p1 = min(p0 + per, total); |
| 1493 | uint cpl = head_dim / SIMDW; // coords per lane (4 for head_dim=128) |
| 1494 | |
| 1495 | // In-kernel quantize+append of the decode token (only the split owning pos). |
| 1496 | uint pos = total - 1; |
| 1497 | bool owns_pos = (do_append != 0u) && (p0 <= pos && pos < p1); |
| 1498 | if (owns_pos) { |
| 1499 | // Per-32-coord BLOCK absmax. Each lane holds one coord per block (coord |
| 1500 | // c*SIMDW+lane is in block c), so simd_max over the 32 lanes for a fixed c is |
| 1501 | // block c's absmax. ksc_b[c]/vsc_b[c] = that block's scale. (Matches the |
| 1502 | // prefill kernel tq_kv_append_q4's per-block scaling.) |
| 1503 | uint n_blk = head_dim / Q4_BLK; // == cpl here (SIMDW == Q4_BLK) |
| 1504 | float ksc_b[COCO_HD_MAX / 32]; |
| 1505 | float vsc_b[COCO_HD_MAX / 32]; |
| 1506 | for (uint c = 0; c < cpl; ++c) { |
| 1507 | uint j = c * SIMDW + lane; |
| 1508 | float ks = simd_max(fabs((float)k_new[kvh * head_dim + j])) / 7.0f; |
| 1509 | float vs = simd_max(fabs((float)v_new[kvh * head_dim + j])) / 7.0f; |
| 1510 | if (ks == 0.0f) ks = 1.0f; |
| 1511 | if (vs == 0.0f) vs = 1.0f; |
| 1512 | ksc_b[c] = ks; vsc_b[c] = vs; |
| 1513 | if (lane == 0) { |
| 1514 | ulong sbase = ((ulong)kvh * max_ctx + pos) * n_blk + c; |
| 1515 | k_scale[sbase] = (bfloat)ks; |
| 1516 | v_scale[sbase] = (bfloat)vs; |
| 1517 | } |
| 1518 | } |
| 1519 | // Each lane owns cpl coords (j = c*SIMDW + lane). Quantize every coord to a |
| 1520 | // nibble, then nibble-pack via a threadgroup scratch buffer — the SAME race- |
| 1521 | // free pattern as the prefill kernel tq_kv_append_q4 (each lane writes its own |
| 1522 | // nibble to scratch; after a barrier, the even-coord owner assembles the byte |
| 1523 | // from its own + the odd neighbour's scratch nibble). This avoids relying on |
| 1524 | // simd_shuffle_down's cross-lane semantics for the packing (correctness over |
| 1525 | // cleverness). scratch indexed by the absolute coord j (head_dim <= 256). |
| 1526 | threadgroup uchar k_nib[COCO_HD_MAX]; |
| 1527 | threadgroup uchar v_nib[COCO_HD_MAX]; |
| 1528 | for (uint c = 0; c < cpl; ++c) { |
| 1529 | uint j = c * SIMDW + lane; |
| 1530 | int kc = clamp((int)round((float)k_new[kvh * head_dim + j] / ksc_b[c]), -7, 7); |
| 1531 | int vc = clamp((int)round((float)v_new[kvh * head_dim + j] / vsc_b[c]), -7, 7); |
| 1532 | k_nib[j] = (uchar)(kc + 8); |
| 1533 | v_nib[j] = (uchar)(vc + 8); |
| 1534 | } |
| 1535 | simdgroup_barrier(mem_flags::mem_threadgroup); |
| 1536 | for (uint c = 0; c < cpl; ++c) { |
| 1537 | uint j = c * SIMDW + lane; |
| 1538 | if ((j & 1u) == 0u) { |
| 1539 | ulong byte = ((ulong)kvh * max_ctx + pos) * hd2 + (j >> 1); |
| 1540 | uchar lo_k = k_nib[j], hi_k = (j + 1 < head_dim) ? k_nib[j + 1] : 8; |
| 1541 | uchar lo_v = v_nib[j], hi_v = (j + 1 < head_dim) ? v_nib[j + 1] : 8; |
| 1542 | k_codes[byte] = (uchar)(lo_k | (hi_k << 4)); |
| 1543 | v_codes[byte] = (uchar)(lo_v | (hi_v << 4)); |
| 1544 | } |
| 1545 | } |
| 1546 | simdgroup_barrier(mem_flags::mem_device); |
| 1547 | } |
| 1548 | |
| 1549 | // Load this lane's q coords (bf16 → f32). |
| 1550 | float qreg[COCO_HD_MAX / 32]; |
| 1551 | for (uint c = 0; c < cpl; ++c) qreg[c] = (float)q[h * head_dim + c * SIMDW + lane]; |
| 1552 | |
| 1553 | float m = -INFINITY, l = 0.0f; |
| 1554 | float acc[COCO_HD_MAX / 32]; |
| 1555 | for (uint c = 0; c < cpl; ++c) acc[c] = 0.0f; |
| 1556 | |
| 1557 | uint n_blk = head_dim / Q4_BLK; // scale blocks per row |
| 1558 | for (uint p = p0; p < p1; ++p) { |
| 1559 | device const bfloat* krsc = k_scale + ((ulong)kvh * max_ctx + p) * n_blk; |
| 1560 | device const uchar* krow = k_codes + ((ulong)kvh * max_ctx + p) * hd2; |
| 1561 | float partial = 0.0f; |
| 1562 | for (uint c = 0; c < cpl; ++c) { |
| 1563 | uint j = c * SIMDW + lane; |
| 1564 | uchar b = krow[j >> 1]; |
| 1565 | int nib = ((j & 1u) == 0u) ? (b & 0xF) : (b >> 4); |
| 1566 | float kval = (float)(nib - 8) * (float)krsc[j / Q4_BLK]; |
| 1567 | partial += qreg[c] * kval; |
| 1568 | } |
| 1569 | float score = simd_sum(partial) * scale; |
| 1570 | float m_new = max(m, score); |
| 1571 | float corr = exp(m - m_new); |
| 1572 | float w = exp(score - m_new); |
| 1573 | l = l * corr + w; |
| 1574 | device const bfloat* vrsc = v_scale + ((ulong)kvh * max_ctx + p) * n_blk; |
| 1575 | device const uchar* vrow = v_codes + ((ulong)kvh * max_ctx + p) * hd2; |
| 1576 | for (uint c = 0; c < cpl; ++c) { |
| 1577 | uint j = c * SIMDW + lane; |
| 1578 | uchar b = vrow[j >> 1]; |
| 1579 | int nib = ((j & 1u) == 0u) ? (b & 0xF) : (b >> 4); |
| 1580 | float vval = (float)(nib - 8) * (float)vrsc[j / Q4_BLK]; |
| 1581 | acc[c] = acc[c] * corr + w * vval; |
| 1582 | } |
| 1583 | m = m_new; |
| 1584 | } |
| 1585 | ulong pbase = ((ulong)h * n_splits + split) * head_dim; |
| 1586 | for (uint c = 0; c < cpl; ++c) pacc[pbase + c * SIMDW + lane] = acc[c]; |
| 1587 | if (lane == 0) { |
| 1588 | pm[h * n_splits + split] = m; |
| 1589 | pl[h * n_splits + split] = l; |
| 1590 | } |
| 1591 | } |
| 1592 | |
| 1593 | // Fused RMSNorm: out = x * rsqrt(mean(x^2) + eps) * w, reading bf16 x + bf16 w and |
| 1594 | // writing bf16 — ONE dispatch replacing candle's RmsNorm chain (to_dtype(f32) + |
| 1595 | // sqr + mean + add(eps) + rsqrt + broadcast_mul + broadcast_mul + to_dtype(bf16), |
| 1596 | // ~7 elementwise dispatches per norm x ~57 norms/token). One threadgroup per token; |
| 1597 | // the threadgroup width (a multiple of 32, capped) strides over inn coords and |
| 1598 | // reduces the sum-of-squares cooperatively in f32, then each lane writes its |
| 1599 | // normalized coords. Reduction: per-lane partial -> simd_sum within each 32-lane |
| 1600 | // simd-group -> per-simd partials combined via threadgroup memory. Math in f32 |
| 1601 | // (candle's RmsNorm also upcasts); output rounded to bf16. |
| 1602 | kernel void tq_rmsnorm_bf16( |
| 1603 | device const bfloat* x [[buffer(0)]], // [tokens, inn] bf16 |
| 1604 | device bfloat* out [[buffer(1)]], // [tokens, inn] bf16 (output) |
| 1605 | device const bfloat* w [[buffer(2)]], // [inn] bf16 (norm weight) |
| 1606 | constant uint& inn [[buffer(3)]], |
| 1607 | constant float& eps [[buffer(4)]], |
| 1608 | uint tg [[threadgroup_position_in_grid]], |
| 1609 | uint lt [[thread_position_in_threadgroup]], |
| 1610 | uint tgw [[threads_per_threadgroup]], |
| 1611 | uint sg_id [[simdgroup_index_in_threadgroup]], |
| 1612 | uint n_sg [[simdgroups_per_threadgroup]]) |
| 1613 | { |
| 1614 | threadgroup float sg_part[32]; // one partial per simd-group (<=32) |
| 1615 | uint tok = tg; |
| 1616 | uint tid = lt; // thread index within the threadgroup |
| 1617 | uint W = tgw; // threadgroup width (multiple of 32) |
| 1618 | device const bfloat* xrow = x + (ulong)tok * inn; |
| 1619 | device bfloat* orow = out + (ulong)tok * inn; |
| 1620 | |
| 1621 | // Per-thread sum of squares over its strided coords. |
| 1622 | float ss = 0.0f; |
| 1623 | for (uint i = tid; i < inn; i += W) { |
| 1624 | float v = (float)xrow[i]; |
| 1625 | ss += v * v; |
| 1626 | } |
| 1627 | ss = simd_sum(ss); // reduce within the simd-group |
| 1628 | if (simd_is_first()) sg_part[sg_id] = ss; |
| 1629 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 1630 | // simd-group 0 reduces the per-simd partials, broadcasts via sg_part[0]. |
| 1631 | if (sg_id == 0) { |
| 1632 | float p = (lt < n_sg) ? sg_part[lt] : 0.0f; |
| 1633 | p = simd_sum(p); |
| 1634 | if (simd_is_first()) sg_part[0] = p; |
| 1635 | } |
| 1636 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 1637 | float total = sg_part[0]; |
| 1638 | float inv = rsqrt(total / (float)inn + eps); |
| 1639 | for (uint i = tid; i < inn; i += W) { |
| 1640 | orow[i] = (bfloat)(((float)xrow[i]) * inv * (float)w[i]); |
| 1641 | } |
| 1642 | } |
| 1643 | |
| 1644 | // FUSED residual-add + RMSNorm: h = a + b ; out = RMSNorm(h) * w. Writes BOTH the |
| 1645 | // summed residual `h` (needed as the residual for the NEXT add) AND the normalized |
| 1646 | // output, in ONE dispatch. This folds the standalone candle elementwise residual |
| 1647 | // add (`(xs + residual)?` — a full [tokens,inn] pass, one per sublayer ×28 layers) |
| 1648 | // into the RMSNorm that immediately consumes it. The transformer block is |
| 1649 | // h = x + sublayer(...) ; h_norm = RMSNorm(h) |
| 1650 | // so the add result is always read straight by the next norm — we never need a |
| 1651 | // separate add dispatch. Math in f32 (matches candle's upcast); both outputs bf16. |
| 1652 | kernel void tq_add_rmsnorm_bf16( |
| 1653 | device const bfloat* a [[buffer(0)]], // [tokens, inn] bf16 (residual) |
| 1654 | device const bfloat* b [[buffer(1)]], // [tokens, inn] bf16 (sublayer out) |
| 1655 | device bfloat* h [[buffer(2)]], // [tokens, inn] bf16 (a+b, output) |
| 1656 | device bfloat* out [[buffer(3)]], // [tokens, inn] bf16 (RMSNorm(h)*w) |
| 1657 | device const bfloat* w [[buffer(4)]], // [inn] bf16 (norm weight) |
| 1658 | constant uint& inn [[buffer(5)]], |
| 1659 | constant float& eps [[buffer(6)]], |
| 1660 | uint tg [[threadgroup_position_in_grid]], |
| 1661 | uint lt [[thread_position_in_threadgroup]], |
| 1662 | uint tgw [[threads_per_threadgroup]], |
| 1663 | uint sg_id [[simdgroup_index_in_threadgroup]], |
| 1664 | uint n_sg [[simdgroups_per_threadgroup]]) |
| 1665 | { |
| 1666 | threadgroup float sg_part[32]; |
| 1667 | uint tok = tg; |
| 1668 | uint tid = lt; |
| 1669 | uint W = tgw; |
| 1670 | device const bfloat* arow = a + (ulong)tok * inn; |
| 1671 | device const bfloat* brow = b + (ulong)tok * inn; |
| 1672 | device bfloat* hrow = h + (ulong)tok * inn; |
| 1673 | device bfloat* orow = out + (ulong)tok * inn; |
| 1674 | |
| 1675 | // Sum once, store h (rounded bf16 — same precision the standalone add produced), |
| 1676 | // and accumulate the f32 sum-of-squares of the (bf16-rounded) h for the norm. |
| 1677 | float ss = 0.0f; |
| 1678 | for (uint i = tid; i < inn; i += W) { |
| 1679 | bfloat hv = (bfloat)((float)arow[i] + (float)brow[i]); |
| 1680 | hrow[i] = hv; |
| 1681 | float f = (float)hv; |
| 1682 | ss += f * f; |
| 1683 | } |
| 1684 | ss = simd_sum(ss); |
| 1685 | if (simd_is_first()) sg_part[sg_id] = ss; |
| 1686 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 1687 | if (sg_id == 0) { |
| 1688 | float p = (lt < n_sg) ? sg_part[lt] : 0.0f; |
| 1689 | p = simd_sum(p); |
| 1690 | if (simd_is_first()) sg_part[0] = p; |
| 1691 | } |
| 1692 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 1693 | float total = sg_part[0]; |
| 1694 | float inv = rsqrt(total / (float)inn + eps); |
| 1695 | for (uint i = tid; i < inn; i += W) { |
| 1696 | orow[i] = (bfloat)(((float)hrow[i]) * inv * (float)w[i]); |
| 1697 | } |
| 1698 | } |
| 1699 | "#; |
| 1700 | |
| 1701 | // ───────────────────────── compiled-pipeline cache ───────────────────────── |
| 1702 | |
| 1703 | // pub(crate) (fields too) so the enc_proto micro-bench bin (which #[path]-includes |
| 1704 | // this module) can raw-encode the exact same pipelines. No behavior change. |
| 1705 | pub(crate) struct Pipelines { |
| 1706 | pub(crate) rotate: ComputePipeline, // f32-input activation rotate |
| 1707 | pub(crate) rotate_bf16: ComputePipeline, // bf16-input rotate (skips candle to_dtype/contiguous) |
| 1708 | pub(crate) qmatvec: ComputePipeline, // 4-bit nibble codes (legacy) |
| 1709 | pub(crate) qmatvec3: ComputePipeline, // true 3-bit codes (opt-2, default) |
| 1710 | pub(crate) qmatvec_bf16: ComputePipeline, // 4-bit nibble, fused bf16-out + bias epilogue |
| 1711 | pub(crate) qmatvec3_bf16: ComputePipeline, // true 3-bit, fused bf16-out + bias epilogue |
| 1712 | pub(crate) qmatvec_bf16_r: ComputePipeline, // 4-bit nibble, register-blocked (QROWS=4 rows/simd-group) |
| 1713 | pub(crate) qmatvec_bf16_r8: ComputePipeline, // register-blocked QROWS=8 (wider blocking, COCO_QROWS=8) |
| 1714 | pub(crate) qmatvec_bf16_rw2: ComputePipeline, // QROWS=4, uint2 wide-unpack (2 words/iter, COCO_QW2=1) |
| 1715 | pub(crate) qmatvec_swiglu_r: ComputePipeline, // fused gate/up → silu(gate)·up (QROWS=4, COCO_FUSE_SWIGLU) |
| 1716 | pub(crate) qmatvec_swiglu_r8: ComputePipeline, // fused gate/up → silu(gate)·up (QROWS=8) |
| 1717 | pub(crate) qmatvec_bf16_rot: ComputePipeline, // rotate-in prologue + QR=4 dot (COCO_FUSE_ROTATE_IN) |
| 1718 | pub(crate) qmatvec_swiglu_rot: ComputePipeline, // rotate-in prologue + fused SwiGLU (COCO_FUSE_ROTATE_IN) |
| 1719 | pub(crate) ffn_mega: ComputePipeline, // whole FFN in one dispatch (1.5B, h in threadgroup; COCO_FFN_MEGA) |
| 1720 | pub(crate) attn_partial: ComputePipeline, // flash-decoding split-K partials (GQA, persistent KV) |
| 1721 | pub(crate) attn_partial_q4: ComputePipeline, // q4-KV flash-decoding partials (dequant on the fly) |
| 1722 | pub(crate) attn_combine: ComputePipeline, // merge per-split partials per head |
| 1723 | pub(crate) kv_append: ComputePipeline, // append a prefill chunk's k/v into the cache |
| 1724 | pub(crate) kv_append_q4: ComputePipeline, // quantize+append a prefill chunk into the 4-bit cache |
| 1725 | pub(crate) rmsnorm: ComputePipeline, // fused RMSNorm (x * rsqrt(mean(x^2)+eps) * w) |
| 1726 | pub(crate) rope_bf16: ComputePipeline, // fused RoPE reading the transposed view (no .contiguous()) |
| 1727 | pub(crate) add_rmsnorm: ComputePipeline, // fused residual-add + RMSNorm (one dispatch, writes h + normed) |
| 1728 | } |
| 1729 | |
| 1730 | // Keyed by Metal device registry id so we compile the library exactly once. |
| 1731 | static PIPELINES: OnceLock<Mutex<Vec<(u64, Arc<Pipelines>)>>> = OnceLock::new(); |
| 1732 | |
| 1733 | pub(crate) fn get_pipelines(mdev: &candle_metal_kernels::metal::Device) -> Result<Arc<Pipelines>> { |
| 1734 | let cache = PIPELINES.get_or_init(|| Mutex::new(Vec::new())); |
| 1735 | let id = mdev.registry_id(); |
| 1736 | { |
| 1737 | let guard = cache.lock().unwrap(); |
| 1738 | if let Some((_, p)) = guard.iter().find(|(k, _)| *k == id) { |
| 1739 | return Ok(p.clone()); |
| 1740 | } |
| 1741 | } |
| 1742 | let lib = mdev |
| 1743 | .new_library_with_source(KERNEL_SRC, None) |
| 1744 | .map_err(|e| anyhow!("compiling turboquant-fast MSL: {e}"))?; |
| 1745 | let pipe = |name: &str| -> Result<ComputePipeline> { |
| 1746 | let f = lib |
| 1747 | .get_function(name, None) |
| 1748 | .map_err(|e| anyhow!("{name}: {e}"))?; |
| 1749 | mdev.new_compute_pipeline_state_with_function(&f) |
| 1750 | .map_err(|e| anyhow!("pipeline {name}: {e}")) |
| 1751 | }; |
| 1752 | let rotate = pipe("tq_rotate_f32")?; |
| 1753 | let rotate_bf16 = pipe("tq_rotate_bf16")?; |
| 1754 | let qmatvec = pipe("tq_qmatvec_f32")?; |
| 1755 | let qmatvec3 = pipe("tq_qmatvec3_f32")?; |
| 1756 | let qmatvec_bf16 = pipe("tq_qmatvec_bf16")?; |
| 1757 | let qmatvec3_bf16 = pipe("tq_qmatvec3_bf16")?; |
| 1758 | let qmatvec_bf16_r = pipe("tq_qmatvec_bf16_r")?; |
| 1759 | let qmatvec_bf16_r8 = pipe("tq_qmatvec_bf16_r8")?; |
| 1760 | let qmatvec_bf16_rw2 = pipe("tq_qmatvec_bf16_rw2")?; |
| 1761 | let qmatvec_swiglu_r = pipe("tq_qmatvec_swiglu_r")?; |
| 1762 | let qmatvec_swiglu_r8 = pipe("tq_qmatvec_swiglu_r8")?; |
| 1763 | let qmatvec_bf16_rot = pipe("tq_qmatvec_bf16_rot")?; |
| 1764 | let qmatvec_swiglu_rot = pipe("tq_qmatvec_swiglu_rot")?; |
| 1765 | let ffn_mega = pipe("tq_ffn_mega")?; |
| 1766 | let attn_partial = pipe("tq_attn_partial")?; |
| 1767 | let attn_partial_q4 = pipe("tq_attn_partial_q4")?; |
| 1768 | let attn_combine = pipe("tq_attn_combine")?; |
| 1769 | let kv_append = pipe("tq_kv_append")?; |
| 1770 | let kv_append_q4 = pipe("tq_kv_append_q4")?; |
| 1771 | let rmsnorm = pipe("tq_rmsnorm_bf16")?; |
| 1772 | let rope_bf16 = pipe("tq_rope_bf16")?; |
| 1773 | let add_rmsnorm = pipe("tq_add_rmsnorm_bf16")?; |
| 1774 | let p = Arc::new(Pipelines { |
| 1775 | rotate, |
| 1776 | rotate_bf16, |
| 1777 | qmatvec, |
| 1778 | qmatvec3, |
| 1779 | qmatvec_bf16, |
| 1780 | qmatvec3_bf16, |
| 1781 | qmatvec_bf16_r, |
| 1782 | qmatvec_bf16_r8, |
| 1783 | qmatvec_bf16_rw2, |
| 1784 | qmatvec_swiglu_r, |
| 1785 | qmatvec_swiglu_r8, |
| 1786 | qmatvec_bf16_rot, |
| 1787 | qmatvec_swiglu_rot, |
| 1788 | ffn_mega, |
| 1789 | attn_partial, |
| 1790 | attn_partial_q4, |
| 1791 | attn_combine, |
| 1792 | kv_append, |
| 1793 | kv_append_q4, |
| 1794 | rmsnorm, |
| 1795 | rope_bf16, |
| 1796 | add_rmsnorm, |
| 1797 | }); |
| 1798 | cache.lock().unwrap().push((id, p.clone())); |
| 1799 | Ok(p) |
| 1800 | } |
| 1801 | |
| 1802 | // ───────────────────────── GPU-resident compressed weight ───────────────────────── |
| 1803 | |
| 1804 | /// One turboquant weight, kept COMPRESSED on the GPU (packed codes + fp16 radius |
| 1805 | /// + 8-entry codebook + the ±1 sign vector). Plus an optional bias kept on |
| 1806 | /// the device. Nothing here is ever expanded to a dense fp16 weight. |
| 1807 | pub struct QWeight { |
| 1808 | pub(crate) out: usize, |
| 1809 | pub(crate) inn: usize, |
| 1810 | pub(crate) d: usize, |
| 1811 | pub(crate) sign: Tensor, // [inn] f32, on device (±1) |
| 1812 | // codes/radius/bias are held as `Arc<Buffer>` (not bare `Buffer`) so candle's |
| 1813 | // pool allocator never recycles or evicts-from-residency the resident weight |
| 1814 | // memory: the pool reclaims a buffer only when its `Arc<Buffer>` strong count |
| 1815 | // hits 1, and these clones keep it at ≥2 for the model's lifetime. (Storing a |
| 1816 | // bare `Buffer` retains the MTLBuffer but lets the pool's own Arc drop to 1, |
| 1817 | // so a later same-size allocation gets handed the same buffer and overwrites |
| 1818 | // it — the root cause of the garbage we debugged once build-time readbacks |
| 1819 | // started triggering `drop_unused_buffers`.) |
| 1820 | pub(crate) codes: Arc<Buffer>, // packed codes on device (3-bit stream or 4-bit nibble) |
| 1821 | pub(crate) radius: Arc<Buffer>, // f16, len = out*inn/d, on device |
| 1822 | pub(crate) codebook: Vec<f32>, // 8 levels (tiny, passed as constant bytes) |
| 1823 | pub(crate) bias: Option<Tensor>, // [out], on device, in the model dtype |
| 1824 | /// Per-row bias as a raw BF16 device buffer, for the fused bf16 qmatvec |
| 1825 | /// epilogue. Stored as `Arc<Buffer>` (NOT a bare `Buffer`) so candle's pool |
| 1826 | /// allocator — which reclaims/recycles buffers whose `Arc<Buffer>` strong |
| 1827 | /// count drops to 1 — never hands this MTLBuffer to a later same-size |
| 1828 | /// allocation. (A bare `Buffer` retains the MTLBuffer but leaves the pool's |
| 1829 | /// own Arc at count 1, so `find_available_buffer` reuses & overwrites it — |
| 1830 | /// the cause of the fused-bias garbage we debugged.) `None` if no bias. |
| 1831 | pub(crate) bias_bf16: Option<Arc<Buffer>>, |
| 1832 | pub(crate) pack_bits: u8, // 3 = true 3-bit stream (default), 4 = nibble (legacy/A-B) |
| 1833 | pub compressed_bytes: usize, |
| 1834 | } |
| 1835 | |
| 1836 | /// Build a dedicated, pinned BF16 device buffer (length `out`) holding the bias |
| 1837 | /// bits, for the fused qmatvec epilogue. Returns the `Arc<Buffer>` so the caller |
| 1838 | /// can keep candle's pool from recycling it (see `QWeight::bias_bf16`). We read |
| 1839 | /// the bias values to CPU and re-upload via `new_buffer_with_data` rather than |
| 1840 | /// aliasing a transient tensor's storage (whose pool-Arc would drop to 1 and be |
| 1841 | /// reused/overwritten). |
| 1842 | fn bias_to_bf16_buf( |
| 1843 | bias: &Tensor, |
| 1844 | cdev: &candle_core::MetalDevice, |
| 1845 | ) -> Result<Arc<Buffer>> { |
| 1846 | let vals: Vec<half::bf16> = bias.to_dtype(DType::BF16)?.flatten_all()?.to_vec1()?; |
| 1847 | let bits: Vec<u16> = vals.iter().map(|v| v.to_bits()).collect(); |
| 1848 | Ok(cdev.new_buffer_with_data(&bits)?) |
| 1849 | } |
| 1850 | |
| 1851 | /// Code packing for the resident weights / matmul kernel. |
| 1852 | /// 4 = nibble (4.125 bpw, 644 MB) — DEFAULT: validated + fastest (aligned |
| 1853 | /// uint32 reads). The qmatvec path is decode/dispatch-bound at 1.5B, so |
| 1854 | /// this is the throughput choice. |
| 1855 | /// 3 = true 3-bit (3.125 bpw, 488 MB) — 24% less resident RAM at equal speed; |
| 1856 | /// pick it (`COCO_PACK_BITS=3`) when memory matters more than tok/s. |
| 1857 | fn pack_bits_from_env() -> u8 { |
| 1858 | match std::env::var("COCO_PACK_BITS").as_deref() { |
| 1859 | Ok("3") => 3, |
| 1860 | _ => 4, |
| 1861 | } |
| 1862 | } |
| 1863 | |
| 1864 | /// Fused residual epilogue (COCO_FUSE_RESID, default OFF — opt-in): the o_proj / down_proj |
| 1865 | /// qmatvec adds the layer residual at its leader store instead of a standalone |
| 1866 | /// candle elementwise add dispatch. Set COCO_FUSE_RESID=0 to restore the old |
| 1867 | /// add-after path (A/B). |
| 1868 | pub fn fuse_resid_enabled() -> bool { |
| 1869 | // OPT-IN (COCO_FUSE_RESID=1). Measured A/B on the 7B: this fusion is ~2% slower at |
| 1870 | // ctx0 and ~10% slower at 8K than the pre-existing path (whose attn-side add+RMSNorm |
| 1871 | // was already fused via forward_add; the resid qmatvec variant misses the fastest |
| 1872 | // kernel path). Numerically correct (QCHECK 1 ULP) but a measured LOSS — kept only |
| 1873 | // as a documented experiment. Default = the faster separate path. |
| 1874 | matches!(std::env::var("COCO_FUSE_RESID").as_deref(), Ok("1")) |
| 1875 | } |
| 1876 | |
| 1877 | /// Rotate-in-prologue (COCO_FUSE_ROTATE_IN=1, default OFF — experimental A/B): |
| 1878 | /// fold the activation-rotate dispatch into the qmatvec kernel prologue |
| 1879 | /// (threadgroup-memory FWHT recompute per threadgroup). |
| 1880 | fn fuse_rotate_in_enabled() -> bool { |
| 1881 | matches!(std::env::var("COCO_FUSE_ROTATE_IN").as_deref(), Ok("1")) |
| 1882 | } |
| 1883 | |
| 1884 | /// Can the rotate-in kernel take this projection? Mirrors the dispatch-side tgw |
| 1885 | /// computation so the threadgroup-memory budget check ((inn + tgsz) f32 ≤ 32KB) |
| 1886 | /// is decided before choosing the path. Decode-only (tokens==1): at prefill the |
| 1887 | /// separate rotate is amortized over the whole grid, per-threadgroup recompute |
| 1888 | /// is not. The rot kernels are compiled at QROWS=4 without the QW2 restructure, |
| 1889 | /// so any non-default QROWS/QW2 selection falls back to the separate rotate. |
| 1890 | fn rotate_in_eligible(inn: usize, d: usize, pack_bits: u8, in_dtype: DType, tokens: usize) -> bool { |
| 1891 | if !fuse_rotate_in_enabled() || tokens != 1 { |
| 1892 | return false; |
| 1893 | } |
| 1894 | if in_dtype != DType::BF16 || pack_bits == 3 { |
| 1895 | return false; |
| 1896 | } |
| 1897 | if std::env::var("COCO_NO_FUSE").is_ok() || std::env::var("COCO_SKIP_ROTATE").is_ok() { |
| 1898 | return false; |
| 1899 | } |
| 1900 | if matches!(std::env::var("COCO_QROWS").ok().as_deref(), Some("0") | Some("8")) { |
| 1901 | return false; |
| 1902 | } |
| 1903 | if std::env::var("COCO_QW2").as_deref() == Ok("1") { |
| 1904 | return false; |
| 1905 | } |
| 1906 | if inn % d != 0 || inn % 8 != 0 { |
| 1907 | return false; |
| 1908 | } |
| 1909 | // Worst-case threadgroup width the op will pick (qocc simd-groups, rounded to |
| 1910 | // a multiple of d): the dynamic threadgroup buffer is (inn + tgw) f32 and must |
| 1911 | // fit the 32KB budget. o_proj/qkv/gate-up (inn = hidden ≤ 3584) fit; the down |
| 1912 | // rotate does NOT (inn = I = 8960/18944) and keeps its separate dispatch. |
| 1913 | let qocc: usize = std::env::var("COCO_QOCC") |
| 1914 | .ok() |
| 1915 | .and_then(|v| v.parse::<usize>().ok()) |
| 1916 | .filter(|&v| v >= 1) |
| 1917 | .unwrap_or(8); |
| 1918 | let mut tgw = (qocc * 32).min(1024); |
| 1919 | tgw = (tgw / d).max(1) * d; |
| 1920 | (inn + tgw) * 4 <= 32 * 1024 |
| 1921 | } |
| 1922 | |
| 1923 | impl QWeight { |
| 1924 | /// Build a GPU-resident compressed weight from a `TqWeight` (must be |
| 1925 | /// block-Hadamard with no outlier split — the clean 3-bit recipe). |
| 1926 | /// `bias` (if any) is already on `device` in the model dtype. |
| 1927 | pub fn from_tq(q: &TqWeight, bias: Option<Tensor>, device: &Device) -> Result<Self> { |
| 1928 | if !q.block_hadamard { |
| 1929 | return Err(anyhow!( |
| 1930 | "turboquant-fast requires block-Hadamard mode (inn % d == 0)" |
| 1931 | )); |
| 1932 | } |
| 1933 | if !q.outlier_idx.is_empty() { |
| 1934 | return Err(anyhow!( |
| 1935 | "turboquant-fast requires --outlier-frac 0 (no sparse side-list)" |
| 1936 | )); |
| 1937 | } |
| 1938 | if q.bits != 3 { |
| 1939 | return Err(anyhow!("turboquant-fast assumes 3-bit codes (8 levels)")); |
| 1940 | } |
| 1941 | let cdev = match device { |
| 1942 | Device::Metal(m) => m, |
| 1943 | _ => return Err(anyhow!("turboquant-fast requires the Metal device")), |
| 1944 | }; |
| 1945 | |
| 1946 | let sign_v = turboquant::signs(q.p, q.seed); // length p == inn in block mode |
| 1947 | let sign = Tensor::from_vec(sign_v, q.inn, device)?; |
| 1948 | |
| 1949 | // Pack codes: 4-bit nibble (4.125 bpw, default, fastest) or true 3-bit |
| 1950 | // (3.125 bpw, COCO_PACK_BITS=3, less RAM). The matmul kernel is chosen to |
| 1951 | // match. 3-bit packing needs inn % 8 == 0 (true: 1536, 8960). |
| 1952 | let pack_bits = pack_bits_from_env(); |
| 1953 | let packed = if pack_bits == 3 { |
| 1954 | q.codes_packed_3bit() |
| 1955 | } else { |
| 1956 | q.codes_packed_nibble() |
| 1957 | }; |
| 1958 | let codes = cdev.new_buffer_with_data(&packed)?; // Arc<Buffer> |
| 1959 | |
| 1960 | // radius as raw f16 bits -> GPU buffer |
| 1961 | let rad_bits: Vec<u16> = q.radius.iter().map(|r| r.to_bits()).collect(); |
| 1962 | let radius = cdev.new_buffer_with_data(&rad_bits)?; |
| 1963 | |
| 1964 | let compressed_bytes = packed.len() + rad_bits.len() * 2 + q.codebook.len() * 4; |
| 1965 | |
| 1966 | // One-shot self-check: build BOTH the 3-bit and 4-bit code buffers for |
| 1967 | // this weight, run the matmul kernel each way on a fixed random rotated |
| 1968 | // input, and print the max abs diff. They MUST match (same codes, same |
| 1969 | // codebook). Triggered by COCO_QCHECK=1, first weight only. |
| 1970 | if std::env::var("COCO_QCHECK").is_ok() { |
| 1971 | // Check one weight per distinct (out, inn) shape. |
| 1972 | static SEEN: OnceLock<Mutex<Vec<(usize, usize)>>> = OnceLock::new(); |
| 1973 | let seen = SEEN.get_or_init(|| Mutex::new(Vec::new())); |
| 1974 | let key = (q.out, q.inn); |
| 1975 | let do_check = { |
| 1976 | let mut g = seen.lock().unwrap(); |
| 1977 | if g.contains(&key) { |
| 1978 | false |
| 1979 | } else { |
| 1980 | g.push(key); |
| 1981 | true |
| 1982 | } |
| 1983 | }; |
| 1984 | if do_check { |
| 1985 | let nib = q.codes_packed_nibble(); |
| 1986 | let three = q.codes_packed_3bit(); |
| 1987 | let codes_nib = cdev.new_buffer_with_data(&nib)?; |
| 1988 | let codes_3 = cdev.new_buffer_with_data(&three)?; |
| 1989 | // fixed pseudo-random xr [1, inn] |
| 1990 | let xr_v: Vec<f32> = (0..q.inn) |
| 1991 | .map(|i| ((i as f32 * 0.123).sin())) |
| 1992 | .collect(); |
| 1993 | let xr = Tensor::from_vec(xr_v, (1, q.inn), device)?; |
| 1994 | let run = |buf: &Arc<Buffer>, pb: u8| -> Result<Vec<f32>> { |
| 1995 | let y = xr.apply_op1(QMatVecOp { |
| 1996 | qw: QMatVecRef { |
| 1997 | out: q.out, |
| 1998 | inn: q.inn, |
| 1999 | d: q.d, |
| 2000 | codes: buf.clone(), |
| 2001 | radius: radius.clone(), |
| 2002 | codebook: q.codebook.clone(), |
| 2003 | pack_bits: pb, |
| 2004 | bias_bf16: None, |
| 2005 | out_dtype: DType::F32, // f32 path for the kernel A/B check |
| 2006 | swiglu: false, |
| 2007 | resid: None, |
| 2008 | rot_sign: None, |
| 2009 | }, |
| 2010 | tokens: 1, |
| 2011 | })?; |
| 2012 | Ok(y.flatten_all()?.to_vec1()?) |
| 2013 | }; |
| 2014 | let y4 = run(&codes_nib, 4)?; |
| 2015 | let y3 = run(&codes_3, 3)?; |
| 2016 | let mut max_abs = 0f32; |
| 2017 | let mut argmax_diff = 0usize; |
| 2018 | for i in 0..y4.len() { |
| 2019 | let dv = (y4[i] - y3[i]).abs(); |
| 2020 | if dv > max_abs { |
| 2021 | max_abs = dv; |
| 2022 | argmax_diff = i; |
| 2023 | } |
| 2024 | } |
| 2025 | eprintln!( |
| 2026 | "QCHECK out={} inn={} d={} : max|y4-y3|={:.6} at row {} (y4={:.4} y3={:.4})", |
| 2027 | q.out, q.inn, q.d, max_abs, argmax_diff, y4[argmax_diff], y3[argmax_diff] |
| 2028 | ); |
| 2029 | // Also check the FUSED bf16 kernel (no bias) vs the f32 3-bit |
| 2030 | // kernel: rounded to bf16 they should match to ~1e-2. |
| 2031 | let run_bf16 = |buf: &Arc<Buffer>, pb: u8| -> Result<Vec<f32>> { |
| 2032 | let y = xr.apply_op1(QMatVecOp { |
| 2033 | qw: QMatVecRef { |
| 2034 | out: q.out, |
| 2035 | inn: q.inn, |
| 2036 | d: q.d, |
| 2037 | codes: buf.clone(), |
| 2038 | radius: radius.clone(), |
| 2039 | codebook: q.codebook.clone(), |
| 2040 | pack_bits: pb, |
| 2041 | bias_bf16: None, |
| 2042 | out_dtype: DType::BF16, |
| 2043 | swiglu: false, |
| 2044 | resid: None, |
| 2045 | rot_sign: None, |
| 2046 | }, |
| 2047 | tokens: 1, |
| 2048 | })?; |
| 2049 | Ok(y.to_dtype(DType::F32)?.flatten_all()?.to_vec1()?) |
| 2050 | }; |
| 2051 | let yb = run_bf16(&codes_3, 3)?; |
| 2052 | // Bias check: feed a known all-1.0 bias; every output must gain +1.0. |
| 2053 | let onebias: Vec<u16> = (0..q.out).map(|_| half::bf16::from_f32(1.0).to_bits()).collect(); |
| 2054 | let onebias_buf = cdev.new_buffer_with_data(&onebias)?; |
| 2055 | let yb_bias = { |
| 2056 | let y = xr.apply_op1(QMatVecOp { |
| 2057 | qw: QMatVecRef { |
| 2058 | out: q.out, inn: q.inn, d: q.d, |
| 2059 | codes: codes_3.clone(), radius: radius.clone(), |
| 2060 | codebook: q.codebook.clone(), pack_bits: 3, |
| 2061 | bias_bf16: Some(onebias_buf), out_dtype: DType::BF16, |
| 2062 | swiglu: false, resid: None, rot_sign: None, |
| 2063 | }, tokens: 1, |
| 2064 | })?; |
| 2065 | y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()? |
| 2066 | }; |
| 2067 | let mut mbb = 0f32; |
| 2068 | for i in 0..yb.len() { |
| 2069 | let want = yb[i] + 1.0; |
| 2070 | mbb = mbb.max((yb_bias[i] - want).abs()); |
| 2071 | } |
| 2072 | eprintln!("QCHECK-BIAS out={} : max|(ybf16+1)-ybias|={:.6}", q.out, mbb); |
| 2073 | // Residual-epilogue check on the DEFAULT runtime kernel (nibble, |
| 2074 | // register-blocked QR=4): an all-1.0 residual must add exactly |
| 2075 | // +1.0 to every output (the kernel adds resid in f32 before the |
| 2076 | // single bf16 rounding — same structure as the bias check). |
| 2077 | let yb4 = run_bf16(&codes_nib, 4)?; |
| 2078 | let ones_resid = Tensor::ones((1, q.out), DType::BF16, device)?; |
| 2079 | let yb_resid = { |
| 2080 | let y = xr.apply_op1(QMatVecOp { |
| 2081 | qw: QMatVecRef { |
| 2082 | out: q.out, inn: q.inn, d: q.d, |
| 2083 | codes: codes_nib.clone(), radius: radius.clone(), |
| 2084 | codebook: q.codebook.clone(), pack_bits: 4, |
| 2085 | bias_bf16: None, out_dtype: DType::BF16, |
| 2086 | swiglu: false, resid: Some(ones_resid), rot_sign: None, |
| 2087 | }, tokens: 1, |
| 2088 | })?; |
| 2089 | y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()? |
| 2090 | }; |
| 2091 | let mut mrr = 0f32; |
| 2092 | for i in 0..yb4.len() { |
| 2093 | let want = yb4[i] + 1.0; |
| 2094 | mrr = mrr.max((yb_resid[i] - want).abs()); |
| 2095 | } |
| 2096 | eprintln!("QCHECK-RESID out={} : max|(ybf16+1)-yresid|={:.6}", q.out, mrr); |
| 2097 | let mut mb = 0f32; |
| 2098 | let mut ab = 0usize; |
| 2099 | for i in 0..y3.len() { |
| 2100 | let dv = (y3[i] - yb[i]).abs(); |
| 2101 | if dv > mb { mb = dv; ab = i; } |
| 2102 | } |
| 2103 | eprintln!( |
| 2104 | "QCHECK-BF16 out={} inn={} : max|y3-ybf16|={:.6} at row {} (y3={:.4} ybf16={:.4})", |
| 2105 | q.out, q.inn, mb, ab, y3[ab], yb[ab] |
| 2106 | ); |
| 2107 | |
| 2108 | // ── Fused-SwiGLU numerical self-test ────────────────────────────── |
| 2109 | // Treat this weight's rows as a [gate(half); up(half)] pair and verify |
| 2110 | // the fused kernel's silu(gate[i])·up[i] matches the reference computed |
| 2111 | // from the plain nibble bf16 qmatvec (per-row dot products) + a CPU |
| 2112 | // silu*mul. Requires an even row count. |
| 2113 | if q.out % 2 == 0 && q.out >= 2 { |
| 2114 | let half = q.out / 2; |
| 2115 | // Reference: per-row dot products from the plain nibble bf16 kernel. |
| 2116 | let yref = run_bf16(&codes_nib, 4)?; // length q.out |
| 2117 | // Fused: swiglu kernel over the SAME nibble codes, out = half. |
| 2118 | let yswi = { |
| 2119 | let y = xr.apply_op1(QMatVecOp { |
| 2120 | qw: QMatVecRef { |
| 2121 | out: half, |
| 2122 | inn: q.inn, |
| 2123 | d: q.d, |
| 2124 | codes: codes_nib.clone(), |
| 2125 | radius: radius.clone(), |
| 2126 | codebook: q.codebook.clone(), |
| 2127 | pack_bits: 4, |
| 2128 | bias_bf16: None, |
| 2129 | out_dtype: DType::BF16, |
| 2130 | swiglu: true, |
| 2131 | resid: None, |
| 2132 | rot_sign: None, |
| 2133 | }, |
| 2134 | tokens: 1, |
| 2135 | })?; |
| 2136 | y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()? |
| 2137 | }; |
| 2138 | let mut msw = 0f32; |
| 2139 | let mut asw = 0usize; |
| 2140 | for i in 0..half { |
| 2141 | let g = yref[i]; |
| 2142 | let u = yref[i + half]; |
| 2143 | let want = (g / (1.0 + (-g).exp())) * u; // silu(g)*u |
| 2144 | let dv = (yswi[i] - want).abs(); |
| 2145 | if dv > msw { msw = dv; asw = i; } |
| 2146 | } |
| 2147 | eprintln!( |
| 2148 | "QCHECK-SWIGLU out={} (half={}) inn={} : max|yfused-silu(g)*u|={:.6} at row {} (fused={:.4} ref={:.4})", |
| 2149 | q.out, half, q.inn, msw, asw, yswi[asw], |
| 2150 | { let g = yref[asw]; (g/(1.0+(-g).exp()))*yref[asw+half] } |
| 2151 | ); |
| 2152 | } |
| 2153 | } |
| 2154 | } |
| 2155 | |
| 2156 | let bias_bf16 = match &bias { |
| 2157 | Some(b) => Some(bias_to_bf16_buf(b, cdev)?), |
| 2158 | None => None, |
| 2159 | }; |
| 2160 | |
| 2161 | Ok(Self { |
| 2162 | out: q.out, |
| 2163 | inn: q.inn, |
| 2164 | d: q.d, |
| 2165 | sign, |
| 2166 | codes, |
| 2167 | radius, |
| 2168 | codebook: q.codebook.clone(), |
| 2169 | bias, |
| 2170 | bias_bf16, |
| 2171 | pack_bits, |
| 2172 | compressed_bytes, |
| 2173 | }) |
| 2174 | } |
| 2175 | |
| 2176 | /// Rotate an activation once: xr = blockFWHT(x ∘ sgn), per d-wide block. |
| 2177 | /// `x` is [.., inn] on Metal; returns [tokens, inn] f32 (leading dims |
| 2178 | /// flattened, contiguous). This is the launch-bound step we DEDUP: q/k/v all |
| 2179 | /// consume the post-attn-norm hidden, gate/up both consume the post-mlp-norm |
| 2180 | /// input — so the model rotates each shared input ONCE and feeds the result to |
| 2181 | /// several `matmul_rotated` calls instead of re-rotating per projection |
| 2182 | /// (~196 rotate dispatches/token → ~112). |
| 2183 | /// |
| 2184 | /// COCO_SKIP_ROTATE isolates the qmatvec cost (output becomes incoherent). |
| 2185 | pub fn rotate(&self, x: &Tensor) -> Result<Tensor> { |
| 2186 | let dims = x.dims().to_vec(); |
| 2187 | let inn = *dims.last().unwrap(); |
| 2188 | if inn != self.inn { |
| 2189 | return Err(anyhow!( |
| 2190 | "turboquant-fast: rotate input dim {inn} != weight inn {}", |
| 2191 | self.inn |
| 2192 | )); |
| 2193 | } |
| 2194 | let tokens: usize = dims[..dims.len() - 1].iter().product::<usize>().max(1); |
| 2195 | // Feed the (bf16 or f32) hidden straight into the rotate kernel, which |
| 2196 | // reads the input dtype directly — no candle `to_dtype(F32)` per rotate. |
| 2197 | let xc = x.reshape((tokens, inn))?.contiguous()?; |
| 2198 | if std::env::var("COCO_SKIP_ROTATE").is_ok() { |
| 2199 | return Ok(xc.to_dtype(DType::F32)?); // profiling path; qmatvec wants f32 |
| 2200 | } |
| 2201 | Ok(xc.apply_op1(RotateOp { |
| 2202 | sign: self.sign.clone(), |
| 2203 | d: self.d, |
| 2204 | inn, |
| 2205 | tokens, |
| 2206 | })?) |
| 2207 | } |
| 2208 | |
| 2209 | /// Quantized matmul against the compressed codes, taking an ALREADY-ROTATED |
| 2210 | /// input `xr` ([tokens, inn] f32 from `rotate`). Adds bias and restores the |
| 2211 | /// requested leading shape. `lead_dims` are the leading dims of the original |
| 2212 | /// (un-flattened) activation; `out_dtype` is the model dtype. |
| 2213 | pub fn matmul_rotated( |
| 2214 | &self, |
| 2215 | xr: &Tensor, |
| 2216 | lead_dims: &[usize], |
| 2217 | out_dtype: DType, |
| 2218 | ) -> Result<Tensor> { |
| 2219 | self.matmul_rotated_resid(xr, lead_dims, out_dtype, None) |
| 2220 | } |
| 2221 | |
| 2222 | /// `matmul_rotated` + an optional fused residual: when `resid` is `Some` and |
| 2223 | /// the fused bf16 path is active, the kernel's leader store adds |
| 2224 | /// `resid[t,o]` (f32, before the single bf16 rounding) — no standalone candle |
| 2225 | /// elementwise add dispatch. `resid` must be a contiguous bf16 |
| 2226 | /// [tokens, out]-shaped tensor (callers reshape/contiguous first). |
| 2227 | fn matmul_rotated_resid( |
| 2228 | &self, |
| 2229 | xr: &Tensor, |
| 2230 | lead_dims: &[usize], |
| 2231 | out_dtype: DType, |
| 2232 | resid: Option<&Tensor>, |
| 2233 | ) -> Result<Tensor> { |
| 2234 | let tokens: usize = lead_dims.iter().product::<usize>().max(1); |
| 2235 | // BF16 model dtype → fused kernel writes bf16 + adds bias in-kernel; no |
| 2236 | // candle to_dtype / broadcast_add. Other dtypes fall back to the f32 |
| 2237 | // kernel + candle epilogue (kept for completeness). COCO_NO_FUSE forces |
| 2238 | // the f32 fallback (A/B + a safety escape hatch). |
| 2239 | let fused = out_dtype == DType::BF16 && std::env::var("COCO_NO_FUSE").is_err(); |
| 2240 | let resid_t = match resid { |
| 2241 | Some(r) if fused => Some(r.reshape((tokens, self.out))?.contiguous()?), |
| 2242 | _ => None, |
| 2243 | }; |
| 2244 | let mut y = xr.apply_op1(QMatVecOp { |
| 2245 | qw: QMatVecRef { |
| 2246 | out: self.out, |
| 2247 | inn: self.inn, |
| 2248 | d: self.d, |
| 2249 | codes: self.codes.clone(), |
| 2250 | radius: self.radius.clone(), |
| 2251 | codebook: self.codebook.clone(), |
| 2252 | pack_bits: self.pack_bits, |
| 2253 | bias_bf16: if fused { self.bias_bf16.clone() } else { None }, |
| 2254 | out_dtype, |
| 2255 | swiglu: false, |
| 2256 | resid: resid_t, |
| 2257 | rot_sign: None, |
| 2258 | }, |
| 2259 | tokens, |
| 2260 | })?; // [tokens, out] in out_dtype (fused) or f32 (fallback) |
| 2261 | |
| 2262 | if !fused { |
| 2263 | y = y.to_dtype(out_dtype)?; |
| 2264 | if let Some(b) = &self.bias { |
| 2265 | y = y.broadcast_add(b)?; |
| 2266 | } |
| 2267 | if let Some(r) = resid { |
| 2268 | y = (y + r.reshape((tokens, self.out))?)?; |
| 2269 | } |
| 2270 | } |
| 2271 | let mut out_dims = lead_dims.to_vec(); |
| 2272 | out_dims.push(self.out); |
| 2273 | Ok(y.reshape(Shape::from_dims(&out_dims))?) |
| 2274 | } |
| 2275 | |
| 2276 | /// Expose the compressed parts needed by the FFN megakernel to do the |
| 2277 | /// down-projection (its own rotation sign + codes/radius) reading the SwiGLU |
| 2278 | /// intermediate straight from threadgroup memory. Only valid for the clean |
| 2279 | /// nibble path (asserted by the caller's eligibility check). |
| 2280 | pub fn ffn_down_parts(&self) -> (Arc<Buffer>, Arc<Buffer>, Tensor, usize, usize, usize, u8) { |
| 2281 | ( |
| 2282 | self.codes.clone(), |
| 2283 | self.radius.clone(), |
| 2284 | self.sign.clone(), |
| 2285 | self.d, |
| 2286 | self.out, |
| 2287 | self.inn, |
| 2288 | self.pack_bits, |
| 2289 | ) |
| 2290 | } |
| 2291 | |
| 2292 | /// y = x @ Wᵀ (+ bias) with W kept compressed. x: [.., inn] on Metal. |
| 2293 | /// Returns [.., out] in the same dtype as x. Standalone path (rotate + matmul) |
| 2294 | /// kept for the o_proj / down_proj projections whose input is not shared; the |
| 2295 | /// model dedups q/k/v and gate/up via the fused `QGroup` (one rotate + one |
| 2296 | /// qmatvec over concatenated codes). |
| 2297 | pub fn forward(&self, x: &Tensor) -> Result<Tensor> { |
| 2298 | self.forward_opt(x, None) |
| 2299 | } |
| 2300 | |
| 2301 | /// y = x @ Wᵀ (+ bias) + resid — the residual folded into the qmatvec store |
| 2302 | /// epilogue (COCO_FUSE_RESID, default ON). Falls back to `forward` + a candle |
| 2303 | /// elementwise add when the fused epilogue can't engage (non-bf16 dtype, |
| 2304 | /// COCO_NO_FUSE, or COCO_FUSE_RESID=0). `resid` must broadcast-match the |
| 2305 | /// output shape [.., out] (it is the layer residual, same shape). |
| 2306 | pub fn forward_resid(&self, x: &Tensor, resid: &Tensor) -> Result<Tensor> { |
| 2307 | let fused = x.dtype() == DType::BF16 |
| 2308 | && std::env::var("COCO_NO_FUSE").is_err() |
| 2309 | && fuse_resid_enabled(); |
| 2310 | if !fused { |
| 2311 | return Ok((self.forward(x)? + resid)?); |
| 2312 | } |
| 2313 | self.forward_opt(x, Some(resid)) |
| 2314 | } |
| 2315 | |
| 2316 | fn forward_opt(&self, x: &Tensor, resid: Option<&Tensor>) -> Result<Tensor> { |
| 2317 | let dims = x.dims().to_vec(); |
| 2318 | let in_dtype = x.dtype(); |
| 2319 | let lead = dims[..dims.len() - 1].to_vec(); |
| 2320 | let tokens: usize = lead.iter().product::<usize>().max(1); |
| 2321 | |
| 2322 | // ROTATE-IN (COCO_FUSE_ROTATE_IN=1, experimental): skip the standalone |
| 2323 | // rotate dispatch; the qmatvec kernel recomputes the FWHT of the input row |
| 2324 | // in its threadgroup prologue. Engages for o_proj (inn = hidden fits the |
| 2325 | // 32KB threadgroup budget); the down_proj row (inn = I) does NOT fit and |
| 2326 | // keeps the separate rotate. |
| 2327 | if rotate_in_eligible(self.inn, self.d, self.pack_bits, in_dtype, tokens) { |
| 2328 | let xc = x.reshape((tokens, self.inn))?.contiguous()?; |
| 2329 | let resid_t = match resid { |
| 2330 | Some(r) => Some(r.reshape((tokens, self.out))?.contiguous()?), |
| 2331 | None => None, |
| 2332 | }; |
| 2333 | let y = xc.apply_op1(QMatVecOp { |
| 2334 | qw: QMatVecRef { |
| 2335 | out: self.out, |
| 2336 | inn: self.inn, |
| 2337 | d: self.d, |
| 2338 | codes: self.codes.clone(), |
| 2339 | radius: self.radius.clone(), |
| 2340 | codebook: self.codebook.clone(), |
| 2341 | pack_bits: self.pack_bits, |
| 2342 | bias_bf16: self.bias_bf16.clone(), |
| 2343 | out_dtype: in_dtype, |
| 2344 | swiglu: false, |
| 2345 | resid: resid_t, |
| 2346 | rot_sign: Some(self.sign.clone()), |
| 2347 | }, |
| 2348 | tokens, |
| 2349 | })?; |
| 2350 | // One-shot numerical self-test (COCO_QCHECK): rotate-in vs the |
| 2351 | // separate rotate + qmatvec reference on the same live activation. |
| 2352 | if std::env::var("COCO_QCHECK").is_ok() { |
| 2353 | static ROTIN_QCHECK: OnceLock<()> = OnceLock::new(); |
| 2354 | if ROTIN_QCHECK.set(()).is_ok() { |
| 2355 | let xr = self.rotate(x)?; |
| 2356 | let yref = |
| 2357 | self.matmul_rotated_resid(&xr, &[tokens], in_dtype, resid)?; |
| 2358 | let a = y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?; |
| 2359 | let b = yref.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?; |
| 2360 | let mut m = 0f32; |
| 2361 | for i in 0..a.len().min(b.len()) { |
| 2362 | m = m.max((a[i] - b[i]).abs()); |
| 2363 | } |
| 2364 | eprintln!( |
| 2365 | "QCHECK-ROTIN out={} inn={} : max|yrot-yref|={:.6}", |
| 2366 | self.out, self.inn, m |
| 2367 | ); |
| 2368 | } |
| 2369 | } |
| 2370 | let mut out_dims = lead.clone(); |
| 2371 | out_dims.push(self.out); |
| 2372 | return Ok(y.reshape(Shape::from_dims(&out_dims))?); |
| 2373 | } |
| 2374 | |
| 2375 | let xr = self.rotate(x)?; |
| 2376 | self.matmul_rotated_resid(&xr, &lead, in_dtype, resid) |
| 2377 | } |
| 2378 | } |
| 2379 | |
| 2380 | // ───────────────────────── fused group of shared-input projections ───────────────────────── |
| 2381 | |
| 2382 | /// One sub-projection inside a fused `QGroup`: its output width, the row offset |
| 2383 | /// into the concatenated output, and its (already-on-device) bias. |
| 2384 | pub(crate) struct QSub { |
| 2385 | pub(crate) out: usize, |
| 2386 | pub(crate) row_off: usize, |
| 2387 | pub(crate) bias: Option<Tensor>, |
| 2388 | } |
| 2389 | |
| 2390 | /// A set of compressed projections that all consume the SAME input activation and |
| 2391 | /// share the SAME rotation (same `inn`, same sign) — q/k/v (post-attn-norm) and |
| 2392 | /// gate/up (post-mlp-norm). Their codes + radius are CONCATENATED row-wise into a |
| 2393 | /// single GPU buffer, so the whole group runs as ONE rotate + ONE qmatvec |
| 2394 | /// dispatch (out = Σ out_i) instead of N+N. This halves the qmatvec/rotate launch |
| 2395 | /// count for the attention and MLP input projections — the dominant remaining |
| 2396 | /// per-token overhead once activations stay on-GPU. |
| 2397 | pub struct QGroup { |
| 2398 | pub(crate) inn: usize, |
| 2399 | pub(crate) d: usize, |
| 2400 | pub(crate) out_total: usize, |
| 2401 | pub(crate) sign: Tensor, |
| 2402 | // Held as `Arc<Buffer>` to pin against candle's pool recycler (see QWeight). |
| 2403 | pub(crate) codes: Arc<Buffer>, // concatenated packed codes for all sub-projections |
| 2404 | pub(crate) radius: Arc<Buffer>, // concatenated fp16 radii |
| 2405 | pub(crate) codebook: Vec<f32>, |
| 2406 | pub(crate) pack_bits: u8, |
| 2407 | pub(crate) subs: Vec<QSub>, |
| 2408 | /// Concatenated per-row bias (length `out_total`) as a BF16 device buffer for |
| 2409 | /// the fused qmatvec epilogue: the single fused dispatch adds each row's bias |
| 2410 | /// in-kernel. Zero-filled rows where a sub has no bias. `None` if NO sub in the |
| 2411 | /// group has a bias (e.g. gate/up). Held as `Arc<Buffer>` to pin it against |
| 2412 | /// candle's pool recycler (see `QWeight::bias_bf16`). |
| 2413 | pub(crate) bias_bf16: Option<Arc<Buffer>>, |
| 2414 | pub compressed_bytes: usize, |
| 2415 | } |
| 2416 | |
| 2417 | impl QGroup { |
| 2418 | /// Build a fused group from several `TqWeight`s that share `inn`/seed/d (so |
| 2419 | /// the rotation sign is identical). `biases[i]` is the bias for sub i (already |
| 2420 | /// on `device`, model dtype). Concatenates the packed codes + radii into single |
| 2421 | /// device buffers; the qmatvec then grids over the summed output rows. |
| 2422 | pub fn from_tqs( |
| 2423 | qs: &[&TqWeight], |
| 2424 | biases: Vec<Option<Tensor>>, |
| 2425 | device: &Device, |
| 2426 | ) -> Result<Self> { |
| 2427 | let cdev = match device { |
| 2428 | Device::Metal(m) => m, |
| 2429 | _ => return Err(anyhow!("turboquant-fast requires the Metal device")), |
| 2430 | }; |
| 2431 | let first = qs[0]; |
| 2432 | let inn = first.inn; |
| 2433 | let d = first.d; |
| 2434 | let pack_bits = pack_bits_from_env(); |
| 2435 | for q in qs { |
| 2436 | if !q.block_hadamard || !q.outlier_idx.is_empty() || q.bits != 3 { |
| 2437 | return Err(anyhow!("QGroup requires the clean 3-bit block recipe")); |
| 2438 | } |
| 2439 | if q.inn != inn || q.d != d || q.seed != first.seed { |
| 2440 | return Err(anyhow!( |
| 2441 | "QGroup members must share inn/d/seed (same rotation)" |
| 2442 | )); |
| 2443 | } |
| 2444 | } |
| 2445 | |
| 2446 | let sign_v = turboquant::signs(first.p, first.seed); |
| 2447 | let sign = Tensor::from_vec(sign_v, inn, device)?; |
| 2448 | |
| 2449 | // Concatenate packed codes + radii row-wise (row-major [out_i, inn]). |
| 2450 | let mut all_codes: Vec<u8> = Vec::new(); |
| 2451 | let mut all_rad: Vec<u16> = Vec::new(); |
| 2452 | let mut subs = Vec::with_capacity(qs.len()); |
| 2453 | let mut row_off = 0usize; |
| 2454 | for (i, q) in qs.iter().enumerate() { |
| 2455 | let packed = if pack_bits == 3 { |
| 2456 | q.codes_packed_3bit() |
| 2457 | } else { |
| 2458 | q.codes_packed_nibble() |
| 2459 | }; |
| 2460 | all_codes.extend_from_slice(&packed); |
| 2461 | all_rad.extend(q.radius.iter().map(|r| r.to_bits())); |
| 2462 | subs.push(QSub { |
| 2463 | out: q.out, |
| 2464 | row_off, |
| 2465 | bias: biases[i].clone(), |
| 2466 | }); |
| 2467 | row_off += q.out; |
| 2468 | } |
| 2469 | let out_total = row_off; |
| 2470 | let compressed_bytes = all_codes.len() + all_rad.len() * 2 + first.codebook.len() * 4; |
| 2471 | let codes = cdev.new_buffer_with_data(&all_codes)?; |
| 2472 | let radius = cdev.new_buffer_with_data(&all_rad)?; |
| 2473 | |
| 2474 | // Build ONE concatenated BF16 bias buffer (length out_total) so the single |
| 2475 | // fused qmatvec adds every row's bias in its epilogue. Zero where a sub has |
| 2476 | // no bias. Only allocate if at least one sub carries a bias. |
| 2477 | let any_bias = subs.iter().any(|s| s.bias.is_some()); |
| 2478 | let bias_bf16 = if any_bias { |
| 2479 | let mut bits = vec![0u16; out_total]; // bf16 0.0 == bit pattern 0 |
| 2480 | for sub in &subs { |
| 2481 | if let Some(b) = &sub.bias { |
| 2482 | let bb = b.to_dtype(DType::BF16)?.flatten_all()?; |
| 2483 | let vals: Vec<half::bf16> = bb.to_vec1()?; |
| 2484 | for (j, v) in vals.iter().enumerate() { |
| 2485 | bits[sub.row_off + j] = v.to_bits(); |
| 2486 | } |
| 2487 | } |
| 2488 | } |
| 2489 | Some(cdev.new_buffer_with_data(&bits)?) |
| 2490 | } else { |
| 2491 | None |
| 2492 | }; |
| 2493 | |
| 2494 | Ok(Self { |
| 2495 | inn, |
| 2496 | d, |
| 2497 | out_total, |
| 2498 | sign, |
| 2499 | codes, |
| 2500 | radius, |
| 2501 | codebook: first.codebook.clone(), |
| 2502 | pack_bits, |
| 2503 | subs, |
| 2504 | bias_bf16, |
| 2505 | compressed_bytes, |
| 2506 | }) |
| 2507 | } |
| 2508 | |
| 2509 | /// One rotate + one qmatvec over the whole group, then split the concatenated |
| 2510 | /// output into per-projection tensors (+ bias, original leading shape). |
| 2511 | pub fn forward(&self, x: &Tensor) -> Result<Vec<Tensor>> { |
| 2512 | let dims = x.dims().to_vec(); |
| 2513 | let in_dtype = x.dtype(); |
| 2514 | let lead: Vec<usize> = dims[..dims.len() - 1].to_vec(); |
| 2515 | let inn = *dims.last().unwrap(); |
| 2516 | if inn != self.inn { |
| 2517 | return Err(anyhow!("QGroup: input dim {inn} != {}", self.inn)); |
| 2518 | } |
| 2519 | let tokens: usize = lead.iter().product::<usize>().max(1); |
| 2520 | |
| 2521 | // Rotate once (shared sign). The bf16 hidden goes STRAIGHT into the rotate |
| 2522 | // kernel (which converts on load) — no candle `to_dtype(F32)` + `contiguous` |
| 2523 | // before every rotate. We only ensure contiguity (a no-op when already |
| 2524 | // contiguous, e.g. decode's [1, inn]). |
| 2525 | let xc = x.reshape((tokens, inn))?.contiguous()?; |
| 2526 | let fused = in_dtype == DType::BF16 && std::env::var("COCO_NO_FUSE").is_err(); |
| 2527 | // ROTATE-IN (COCO_FUSE_ROTATE_IN=1): the qkv group's shared rotate folds |
| 2528 | // into the qmatvec prologue — one dispatch for the whole group. |
| 2529 | let rot_in = |
| 2530 | fused && rotate_in_eligible(self.inn, self.d, self.pack_bits, in_dtype, tokens); |
| 2531 | // Single fused qmatvec over the concatenated rows. When the model dtype is |
| 2532 | // BF16 (always on Metal), the kernel writes bf16 directly AND adds each |
| 2533 | // row's concatenated bias in its epilogue — so the whole group's dtype |
| 2534 | // conversion + all per-sub bias-adds collapse into the one qmatvec. The |
| 2535 | // f32 fallback (COCO_NO_FUSE) keeps candle's to_dtype + per-sub |
| 2536 | // broadcast_add. |
| 2537 | let y = if rot_in { |
| 2538 | let y = xc.apply_op1(QMatVecOp { |
| 2539 | qw: QMatVecRef { |
| 2540 | out: self.out_total, |
| 2541 | inn: self.inn, |
| 2542 | d: self.d, |
| 2543 | codes: self.codes.clone(), |
| 2544 | radius: self.radius.clone(), |
| 2545 | codebook: self.codebook.clone(), |
| 2546 | pack_bits: self.pack_bits, |
| 2547 | bias_bf16: self.bias_bf16.clone(), |
| 2548 | out_dtype: in_dtype, |
| 2549 | swiglu: false, |
| 2550 | resid: None, |
| 2551 | rot_sign: Some(self.sign.clone()), |
| 2552 | }, |
| 2553 | tokens, |
| 2554 | })?; |
| 2555 | // One-shot self-test (COCO_QCHECK): rotate-in group vs the separate |
| 2556 | // rotate + qmatvec reference on the same live activation. |
| 2557 | if std::env::var("COCO_QCHECK").is_ok() { |
| 2558 | static GROUP_ROTIN_QCHECK: OnceLock<()> = OnceLock::new(); |
| 2559 | if GROUP_ROTIN_QCHECK.set(()).is_ok() { |
| 2560 | let xr = xc.apply_op1(RotateOp { |
| 2561 | sign: self.sign.clone(), |
| 2562 | d: self.d, |
| 2563 | inn, |
| 2564 | tokens, |
| 2565 | })?; |
| 2566 | let yref = xr.apply_op1(QMatVecOp { |
| 2567 | qw: QMatVecRef { |
| 2568 | out: self.out_total, |
| 2569 | inn: self.inn, |
| 2570 | d: self.d, |
| 2571 | codes: self.codes.clone(), |
| 2572 | radius: self.radius.clone(), |
| 2573 | codebook: self.codebook.clone(), |
| 2574 | pack_bits: self.pack_bits, |
| 2575 | bias_bf16: self.bias_bf16.clone(), |
| 2576 | out_dtype: in_dtype, |
| 2577 | swiglu: false, |
| 2578 | resid: None, |
| 2579 | rot_sign: None, |
| 2580 | }, |
| 2581 | tokens, |
| 2582 | })?; |
| 2583 | let a = y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?; |
| 2584 | let b = yref.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?; |
| 2585 | let mut m = 0f32; |
| 2586 | for i in 0..a.len().min(b.len()) { |
| 2587 | m = m.max((a[i] - b[i]).abs()); |
| 2588 | } |
| 2589 | eprintln!( |
| 2590 | "QCHECK-ROTIN-GROUP out={} inn={} : max|yrot-yref|={:.6}", |
| 2591 | self.out_total, self.inn, m |
| 2592 | ); |
| 2593 | } |
| 2594 | } |
| 2595 | y |
| 2596 | } else { |
| 2597 | let xr = if std::env::var("COCO_SKIP_ROTATE").is_ok() { |
| 2598 | // Profiling-only path; qmatvec wants f32 xr, so convert here. |
| 2599 | xc.to_dtype(DType::F32)? |
| 2600 | } else { |
| 2601 | xc.apply_op1(RotateOp { |
| 2602 | sign: self.sign.clone(), |
| 2603 | d: self.d, |
| 2604 | inn, |
| 2605 | tokens, |
| 2606 | })? |
| 2607 | }; |
| 2608 | xr.apply_op1(QMatVecOp { |
| 2609 | qw: QMatVecRef { |
| 2610 | out: self.out_total, |
| 2611 | inn: self.inn, |
| 2612 | d: self.d, |
| 2613 | codes: self.codes.clone(), |
| 2614 | radius: self.radius.clone(), |
| 2615 | codebook: self.codebook.clone(), |
| 2616 | pack_bits: self.pack_bits, |
| 2617 | bias_bf16: if fused { self.bias_bf16.clone() } else { None }, |
| 2618 | out_dtype: in_dtype, |
| 2619 | swiglu: false, |
| 2620 | resid: None, |
| 2621 | rot_sign: None, |
| 2622 | }, |
| 2623 | tokens, |
| 2624 | })? |
| 2625 | }; |
| 2626 | let y = if fused { y } else { y.to_dtype(in_dtype)? }; |
| 2627 | |
| 2628 | // Split into per-projection slices (zero-copy narrow), restore leading |
| 2629 | // shape. In the fused path the bias is already in `y`; only the f32 |
| 2630 | // fallback needs the per-sub broadcast_add here. |
| 2631 | let mut outs = Vec::with_capacity(self.subs.len()); |
| 2632 | for sub in &self.subs { |
| 2633 | let mut yi = y.narrow(1, sub.row_off, sub.out)?; |
| 2634 | if !fused { |
| 2635 | if let Some(b) = &sub.bias { |
| 2636 | yi = yi.broadcast_add(b)?; |
| 2637 | } |
| 2638 | } |
| 2639 | let mut out_dims = lead.clone(); |
| 2640 | out_dims.push(sub.out); |
| 2641 | outs.push(yi.reshape(Shape::from_dims(&out_dims))?); |
| 2642 | } |
| 2643 | Ok(outs) |
| 2644 | } |
| 2645 | |
| 2646 | /// FUSED SwiGLU forward for a 2-sub gate/up group: one rotate + one qmatvec that |
| 2647 | /// emits `silu(gate)·up` DIRECTLY (intermediate width I), collapsing the separate |
| 2648 | /// candle `silu` + `mul` element-wise passes into the qmatvec store epilogue. |
| 2649 | /// Requires exactly two subs of equal width (gate then up), no bias, the bf16 + |
| 2650 | /// 4-bit nibble path. Falls back via `Ok(None)` when those preconditions don't |
| 2651 | /// hold (caller then uses `forward` + candle silu*mul). Gated by COCO_FUSE_SWIGLU |
| 2652 | /// (default ON) at the call site. |
| 2653 | pub fn forward_swiglu(&self, x: &Tensor) -> Result<Option<Tensor>> { |
| 2654 | // Preconditions: exactly [gate; up], equal width, biasless, bf16+nibble. |
| 2655 | let in_dtype = x.dtype(); |
| 2656 | let eligible = self.subs.len() == 2 |
| 2657 | && self.subs[0].out == self.subs[1].out |
| 2658 | && self.subs[0].row_off == 0 |
| 2659 | && self.subs[1].row_off == self.subs[0].out |
| 2660 | && self.subs.iter().all(|s| s.bias.is_none()) |
| 2661 | && self.pack_bits != 3 // swiglu kernel is the 4-bit nibble variant |
| 2662 | && in_dtype == DType::BF16 |
| 2663 | && std::env::var("COCO_NO_FUSE").is_err(); |
| 2664 | if !eligible { |
| 2665 | return Ok(None); |
| 2666 | } |
| 2667 | let half = self.subs[0].out; // I (intermediate / SwiGLU output width) |
| 2668 | |
| 2669 | let dims = x.dims().to_vec(); |
| 2670 | let lead: Vec<usize> = dims[..dims.len() - 1].to_vec(); |
| 2671 | let inn = *dims.last().unwrap(); |
| 2672 | if inn != self.inn { |
| 2673 | return Err(anyhow!("QGroup(swiglu): input dim {inn} != {}", self.inn)); |
| 2674 | } |
| 2675 | let tokens: usize = lead.iter().product::<usize>().max(1); |
| 2676 | |
| 2677 | let xc = x.reshape((tokens, inn))?.contiguous()?; |
| 2678 | |
| 2679 | // ROTATE-IN (COCO_FUSE_ROTATE_IN=1): the gate/up shared rotate folds into |
| 2680 | // the swiglu qmatvec prologue (tq_qmatvec_swiglu_rot) — one dispatch. |
| 2681 | if rotate_in_eligible(self.inn, self.d, self.pack_bits, in_dtype, tokens) { |
| 2682 | let y = xc.apply_op1(QMatVecOp { |
| 2683 | qw: QMatVecRef { |
| 2684 | out: half, |
| 2685 | inn: self.inn, |
| 2686 | d: self.d, |
| 2687 | codes: self.codes.clone(), |
| 2688 | radius: self.radius.clone(), |
| 2689 | codebook: self.codebook.clone(), |
| 2690 | pack_bits: self.pack_bits, |
| 2691 | bias_bf16: None, |
| 2692 | out_dtype: in_dtype, |
| 2693 | swiglu: true, |
| 2694 | resid: None, |
| 2695 | rot_sign: Some(self.sign.clone()), |
| 2696 | }, |
| 2697 | tokens, |
| 2698 | })?; |
| 2699 | // One-shot self-test (COCO_QCHECK): rotate-in swiglu vs the separate |
| 2700 | // rotate + swiglu-qmatvec reference on the same live activation. |
| 2701 | if std::env::var("COCO_QCHECK").is_ok() { |
| 2702 | static SWIGLU_ROTIN_QCHECK: OnceLock<()> = OnceLock::new(); |
| 2703 | if SWIGLU_ROTIN_QCHECK.set(()).is_ok() { |
| 2704 | let xr = xc.apply_op1(RotateOp { |
| 2705 | sign: self.sign.clone(), |
| 2706 | d: self.d, |
| 2707 | inn, |
| 2708 | tokens, |
| 2709 | })?; |
| 2710 | let yref = xr.apply_op1(QMatVecOp { |
| 2711 | qw: QMatVecRef { |
| 2712 | out: half, |
| 2713 | inn: self.inn, |
| 2714 | d: self.d, |
| 2715 | codes: self.codes.clone(), |
| 2716 | radius: self.radius.clone(), |
| 2717 | codebook: self.codebook.clone(), |
| 2718 | pack_bits: self.pack_bits, |
| 2719 | bias_bf16: None, |
| 2720 | out_dtype: in_dtype, |
| 2721 | swiglu: true, |
| 2722 | resid: None, |
| 2723 | rot_sign: None, |
| 2724 | }, |
| 2725 | tokens, |
| 2726 | })?; |
| 2727 | let a = y.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?; |
| 2728 | let b = yref.to_dtype(DType::F32)?.flatten_all()?.to_vec1::<f32>()?; |
| 2729 | let mut m = 0f32; |
| 2730 | for i in 0..a.len().min(b.len()) { |
| 2731 | m = m.max((a[i] - b[i]).abs()); |
| 2732 | } |
| 2733 | eprintln!( |
| 2734 | "QCHECK-ROTIN-SWIGLU I={half} inn={} : max|yrot-yref|={:.6}", |
| 2735 | self.inn, m |
| 2736 | ); |
| 2737 | } |
| 2738 | } |
| 2739 | let mut out_dims = lead.clone(); |
| 2740 | out_dims.push(half); |
| 2741 | return Ok(Some(y.reshape(Shape::from_dims(&out_dims))?)); |
| 2742 | } |
| 2743 | |
| 2744 | // Rotate once (shared sign), straight from the bf16 hidden (no candle |
| 2745 | // to_dtype/contiguous beyond the cheap reshape-contiguous). |
| 2746 | let xr = xc.apply_op1(RotateOp { |
| 2747 | sign: self.sign.clone(), |
| 2748 | d: self.d, |
| 2749 | inn, |
| 2750 | tokens, |
| 2751 | })?; |
| 2752 | |
| 2753 | // One fused SwiGLU qmatvec: codes/radius are the full [gate(I); up(I)] |
| 2754 | // concatenation; `out = half` makes the kernel grid over I gate rows and pair |
| 2755 | // each with up row (o + I), storing silu(gate)·up. Output is [tokens, I]. |
| 2756 | let y = xr.apply_op1(QMatVecOp { |
| 2757 | qw: QMatVecRef { |
| 2758 | out: half, |
| 2759 | inn: self.inn, |
| 2760 | d: self.d, |
| 2761 | codes: self.codes.clone(), |
| 2762 | radius: self.radius.clone(), |
| 2763 | codebook: self.codebook.clone(), |
| 2764 | pack_bits: self.pack_bits, |
| 2765 | bias_bf16: None, |
| 2766 | out_dtype: in_dtype, |
| 2767 | swiglu: true, |
| 2768 | resid: None, |
| 2769 | rot_sign: None, |
| 2770 | }, |
| 2771 | tokens, |
| 2772 | })?; |
| 2773 | |
| 2774 | let mut out_dims = lead.clone(); |
| 2775 | out_dims.push(half); |
| 2776 | Ok(Some(y.reshape(Shape::from_dims(&out_dims))?)) |
| 2777 | } |
| 2778 | |
| 2779 | /// FFN MEGAKERNEL (default-on, COCO_FFN_MEGA != "0"): run the WHOLE FFN |
| 2780 | /// (gate/up SwiGLU → down-rotate → down-matmul) in ONE dispatch, keeping the |
| 2781 | /// I-wide intermediate `h` in threadgroup memory the whole time. This removes |
| 2782 | /// the I→I device round-trip of `h`, the separate down-rotate dispatch, and the |
| 2783 | /// GPU barrier between the swiglu-qmatvec and the down path. `self` must be the |
| 2784 | /// gate/up group; `down` is the down_proj weight. Returns `None` (→ caller uses |
| 2785 | /// the swiglu + separate-down fallback) when ineligible: |
| 2786 | /// * gate/up not swiglu-eligible (same checks as `forward_swiglu`), OR |
| 2787 | /// * I > 14336 (h would not fit the 32KB threadgroup as bf16 — e.g. 7B |
| 2788 | /// I=18944; those fall back automatically — tiling is out of scope), OR |
| 2789 | /// * down is not the matching nibble/d recipe. |
| 2790 | /// The gate/up rotate of the input stays a separate (cheap) dispatch — it is |
| 2791 | /// the swiglu↔down fusion that this kernel buys. |
| 2792 | pub fn forward_ffn_mega(&self, x: &Tensor, down: &QWeight) -> Result<Option<Tensor>> { |
| 2793 | // OPT-IN ONLY (COCO_FFN_MEGA=1). The one-threadgroup-per-token megakernel is |
| 2794 | // numerically correct (QCHECK 1 ULP) but ~20x SLOWER: collapsing the whole FFN |
| 2795 | // onto a single threadgroup serializes it and starves the GPU of parallelism. |
| 2796 | // The h round-trip it saves (~3.8% of traffic) is dwarfed by the lost occupancy. |
| 2797 | // Kept behind a flag as a documented dead-end; the default is the parallel path. |
| 2798 | if std::env::var("COCO_FFN_MEGA").as_deref() != Ok("1") { |
| 2799 | return Ok(None); |
| 2800 | } |
| 2801 | let in_dtype = x.dtype(); |
| 2802 | let eligible = self.subs.len() == 2 |
| 2803 | && self.subs[0].out == self.subs[1].out |
| 2804 | && self.subs[0].row_off == 0 |
| 2805 | && self.subs[1].row_off == self.subs[0].out |
| 2806 | && self.subs.iter().all(|s| s.bias.is_none()) |
| 2807 | && self.pack_bits != 3 |
| 2808 | && in_dtype == DType::BF16 |
| 2809 | && std::env::var("COCO_NO_FUSE").is_err(); |
| 2810 | if !eligible { |
| 2811 | return Ok(None); |
| 2812 | } |
| 2813 | let big_i = self.subs[0].out; // I (intermediate width) |
| 2814 | // Guard: h must fit the 32KB threadgroup as bf16 (hbuf is [14336] bfloat). |
| 2815 | if big_i > 14336 { |
| 2816 | return Ok(None); |
| 2817 | } |
| 2818 | |
| 2819 | let (dn_codes, dn_radius, dn_sign, dn_d, dn_out, dn_inn, dn_pack) = down.ffn_down_parts(); |
| 2820 | // down must be the nibble recipe, consume the I-wide h, share the block size, |
| 2821 | // and emit the hidden width (= gate/up inn here). |
| 2822 | if dn_pack == 3 || dn_inn != big_i || dn_d != self.d || dn_out != self.inn { |
| 2823 | return Ok(None); |
| 2824 | } |
| 2825 | // One-shot activation marker (COCO_FFN_MEGA_DBG=1): proves the megakernel |
| 2826 | // is the path actually taken (vs a silent fallback), once per process. |
| 2827 | if std::env::var("COCO_FFN_MEGA_DBG").is_ok() { |
| 2828 | static MEGA_SEEN: OnceLock<()> = OnceLock::new(); |
| 2829 | if MEGA_SEEN.set(()).is_ok() { |
| 2830 | eprintln!( |
| 2831 | "FFN-MEGA active: I={big_i} hidden={dn_out} d={} (h threadgroup bytes = {})", |
| 2832 | self.d, |
| 2833 | big_i * 2 |
| 2834 | ); |
| 2835 | } |
| 2836 | } |
| 2837 | |
| 2838 | let dims = x.dims().to_vec(); |
| 2839 | let lead: Vec<usize> = dims[..dims.len() - 1].to_vec(); |
| 2840 | let inn = *dims.last().unwrap(); |
| 2841 | if inn != self.inn { |
| 2842 | return Err(anyhow!("QGroup(ffn_mega): input dim {inn} != {}", self.inn)); |
| 2843 | } |
| 2844 | let tokens: usize = lead.iter().product::<usize>().max(1); |
| 2845 | |
| 2846 | // Rotate the post-mlp-norm input ONCE (gate/up sign), exactly as the swiglu |
| 2847 | // path does — that rotate stays a separate, cheap dispatch. |
| 2848 | let xc = x.reshape((tokens, inn))?.contiguous()?; |
| 2849 | let xr = xc.apply_op1(RotateOp { |
| 2850 | sign: self.sign.clone(), |
| 2851 | d: self.d, |
| 2852 | inn, |
| 2853 | tokens, |
| 2854 | })?; |
| 2855 | |
| 2856 | // ONE megakernel dispatch: swiglu → rotate(h) → down, h on-chip. Output is |
| 2857 | // [tokens, hidden] bf16. |
| 2858 | let y = xr.apply_op1(FfnMegaOp { |
| 2859 | inn: self.inn, |
| 2860 | big_i, |
| 2861 | d: self.d, |
| 2862 | hidden: dn_out, |
| 2863 | gu_codes: self.codes.clone(), |
| 2864 | gu_radius: self.radius.clone(), |
| 2865 | codebook: self.codebook.clone(), |
| 2866 | dn_codes, |
| 2867 | dn_radius, |
| 2868 | dn_sign, |
| 2869 | tokens, |
| 2870 | })?; |
| 2871 | |
| 2872 | // ── Megakernel numerical self-test (COCO_QCHECK, once per process) ── |
| 2873 | // Compare the fused-FFN output against the reference path: swiglu (h) → |
| 2874 | // down.forward(h) (separate rotate + qmatvec). They should match to bf16 |
| 2875 | // rounding of h (both round h to bf16 before down). Reports max abs diff. |
| 2876 | if std::env::var("COCO_QCHECK").is_ok() { |
| 2877 | static FFNMEGA_QCHECK: OnceLock<()> = OnceLock::new(); |
| 2878 | if FFNMEGA_QCHECK.set(()).is_ok() { |
| 2879 | if let Some(h) = self.forward_swiglu(x)? { |
| 2880 | let yref = down.forward(&h)?; |
| 2881 | let a = y |
| 2882 | .reshape((tokens, dn_out))? |
| 2883 | .to_dtype(DType::F32)? |
| 2884 | .flatten_all()? |
| 2885 | .to_vec1::<f32>()?; |
| 2886 | let b = yref |
| 2887 | .reshape((tokens, dn_out))? |
| 2888 | .to_dtype(DType::F32)? |
| 2889 | .flatten_all()? |
| 2890 | .to_vec1::<f32>()?; |
| 2891 | let mut m = 0f32; |
| 2892 | let mut ai = 0usize; |
| 2893 | for i in 0..a.len().min(b.len()) { |
| 2894 | let dv = (a[i] - b[i]).abs(); |
| 2895 | if dv > m { |
| 2896 | m = dv; |
| 2897 | ai = i; |
| 2898 | } |
| 2899 | } |
| 2900 | eprintln!( |
| 2901 | "QCHECK-FFNMEGA I={big_i} hidden={dn_out} : max|ymega-yref|={:.6} at {} (mega={:.4} ref={:.4})", |
| 2902 | m, ai, a[ai], b[ai] |
| 2903 | ); |
| 2904 | } |
| 2905 | } |
| 2906 | } |
| 2907 | |
| 2908 | let mut out_dims = lead.clone(); |
| 2909 | out_dims.push(dn_out); |
| 2910 | Ok(Some(y.reshape(Shape::from_dims(&out_dims))?)) |
| 2911 | } |
| 2912 | } |
| 2913 | |
| 2914 | // ───────────────────────── CustomOp1: rotate activation ───────────────────────── |
| 2915 | |
| 2916 | struct RotateOp { |
| 2917 | sign: Tensor, |
| 2918 | d: usize, |
| 2919 | inn: usize, |
| 2920 | tokens: usize, |
| 2921 | } |
| 2922 | |
| 2923 | impl CustomOp1 for RotateOp { |
| 2924 | fn name(&self) -> &'static str { |
| 2925 | "tq_rotate" |
| 2926 | } |
| 2927 | |
| 2928 | fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { |
| 2929 | Err(candle_core::Error::Msg( |
| 2930 | "tq_rotate has no CPU implementation (Metal only)".into(), |
| 2931 | )) |
| 2932 | } |
| 2933 | |
| 2934 | fn metal_fwd( |
| 2935 | &self, |
| 2936 | storage: &candle_core::MetalStorage, |
| 2937 | layout: &Layout, |
| 2938 | ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> { |
| 2939 | use objc2_metal::MTLSize; |
| 2940 | let dev = storage.device().clone(); |
| 2941 | let mdev = dev.metal_device(); |
| 2942 | let pipes = get_pipelines(mdev).map_err(wrap)?; |
| 2943 | |
| 2944 | let inn = self.inn as u32; |
| 2945 | let d = self.d as u32; |
| 2946 | let nblocks = (self.inn / self.d) as u32; |
| 2947 | |
| 2948 | // fresh output buffer; the kernel reads x and writes xr (no blit copy). |
| 2949 | let elem = self.tokens * self.inn; |
| 2950 | let out_buf = dev.new_buffer(elem, DType::F32, "tq_rotate")?; |
| 2951 | let out_ref: &Buffer = &out_buf; |
| 2952 | |
| 2953 | // Pick the kernel by INPUT dtype: bf16 input is read & converted in-kernel |
| 2954 | // (no candle to_dtype/contiguous), f32 input uses the original path. |
| 2955 | let in_dt = storage.dtype(); |
| 2956 | let (rot_pipe, in_off) = match in_dt { |
| 2957 | DType::BF16 => (&pipes.rotate_bf16, layout.start_offset() * DType::BF16.size_in_bytes()), |
| 2958 | DType::F32 => (&pipes.rotate, layout.start_offset() * DType::F32.size_in_bytes()), |
| 2959 | other => { |
| 2960 | return Err(candle_core::Error::Msg(format!( |
| 2961 | "tq_rotate: unsupported input dtype {other:?}" |
| 2962 | ))) |
| 2963 | } |
| 2964 | }; |
| 2965 | |
| 2966 | let sign_storage = self.sign.storage_and_layout().0; |
| 2967 | let sign_buf = match &*sign_storage { |
| 2968 | candle_core::Storage::Metal(s) => s.buffer().clone(), |
| 2969 | _ => return Err(candle_core::Error::Msg("sign not on metal".into())), |
| 2970 | }; |
| 2971 | |
| 2972 | let enc = dev.command_encoder()?; |
| 2973 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 2974 | ce.set_compute_pipeline_state(rot_pipe); |
| 2975 | ce.set_input_buffer(0, Some(storage.buffer()), in_off); |
| 2976 | ce.set_output_buffer(1, Some(out_ref), 0); |
| 2977 | ce.set_input_buffer(2, Some(&sign_buf), 0); |
| 2978 | ce.set_bytes(3, &inn); |
| 2979 | ce.set_bytes(4, &d); |
| 2980 | // grid is in THREADGROUPS: one group per (block, token); kernel reads |
| 2981 | // blk = tg.y, tok = tg.z. Each group has `d` threads (the d-block). |
| 2982 | let grid = MTLSize { |
| 2983 | width: 1, |
| 2984 | height: nblocks as usize, |
| 2985 | depth: self.tokens, |
| 2986 | }; |
| 2987 | let tgroup = MTLSize { width: self.d, height: 1, depth: 1 }; |
| 2988 | ce.dispatch_thread_groups(grid, tgroup); |
| 2989 | drop(enc); |
| 2990 | |
| 2991 | let news = candle_core::MetalStorage::new(out_buf, dev.clone(), elem, DType::F32); |
| 2992 | Ok((news, layout.shape().clone())) |
| 2993 | } |
| 2994 | } |
| 2995 | |
| 2996 | // ───────────────────────── CustomOp1: quantized matmul ───────────────────────── |
| 2997 | |
| 2998 | #[derive(Clone)] |
| 2999 | struct QMatVecRef { |
| 3000 | out: usize, |
| 3001 | inn: usize, |
| 3002 | d: usize, |
| 3003 | codes: Arc<Buffer>, |
| 3004 | radius: Arc<Buffer>, |
| 3005 | codebook: Vec<f32>, |
| 3006 | pack_bits: u8, // 3 = true 3-bit kernel, 4 = nibble kernel |
| 3007 | /// Optional per-row bias kept on-device as BF16 (length `out`). When `Some` |
| 3008 | /// AND the requested output dtype is BF16, the fused kernel writes bf16 and |
| 3009 | /// adds this bias in its epilogue — no candle `to_dtype`/`broadcast_add`. |
| 3010 | /// `Arc<Buffer>` so the pin (vs candle's recycling pool) is carried along. |
| 3011 | bias_bf16: Option<Arc<Buffer>>, |
| 3012 | /// Output dtype. BF16 → fused bf16 epilogue kernel; anything else (e.g. the |
| 3013 | /// f32 QCHECK path) → the legacy f32 kernel (caller does to_dtype/bias). |
| 3014 | out_dtype: DType, |
| 3015 | /// Fused SwiGLU: `codes`/`radius` hold a [gate(I); up(I)] concatenation |
| 3016 | /// (2*`out` rows) and the kernel emits `silu(gate)·up` of width `out` (= I). |
| 3017 | /// Only valid for the bf16 + nibble path (gate/up never carry a bias). |
| 3018 | swiglu: bool, |
| 3019 | /// Optional residual added in the leader-store epilogue (fused bf16 |
| 3020 | /// non-swiglu kernels): y[t,o] = dot + bias + resid[t,o]. Must be a |
| 3021 | /// CONTIGUOUS bf16 [tokens, out] tensor on the device (COCO_FUSE_RESID). |
| 3022 | resid: Option<Tensor>, |
| 3023 | /// When `Some(sign)`, the op INPUT is the UNROTATED bf16 activation and the |
| 3024 | /// rotate-in kernel recomputes the blockwise FWHT in a threadgroup-memory |
| 3025 | /// prologue (COCO_FUSE_ROTATE_IN). `sign` is the [inn] f32 ±1 vector. |
| 3026 | rot_sign: Option<Tensor>, |
| 3027 | } |
| 3028 | |
| 3029 | struct QMatVecOp { |
| 3030 | qw: QMatVecRef, |
| 3031 | tokens: usize, |
| 3032 | } |
| 3033 | |
| 3034 | impl CustomOp1 for QMatVecOp { |
| 3035 | fn name(&self) -> &'static str { |
| 3036 | "tq_qmatvec" |
| 3037 | } |
| 3038 | |
| 3039 | fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { |
| 3040 | Err(candle_core::Error::Msg( |
| 3041 | "tq_qmatvec has no CPU implementation (Metal only)".into(), |
| 3042 | )) |
| 3043 | } |
| 3044 | |
| 3045 | fn metal_fwd( |
| 3046 | &self, |
| 3047 | storage: &candle_core::MetalStorage, |
| 3048 | layout: &Layout, |
| 3049 | ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> { |
| 3050 | use objc2_metal::MTLSize; |
| 3051 | let dev = storage.device().clone(); |
| 3052 | let mdev = dev.metal_device(); |
| 3053 | let pipes = get_pipelines(mdev).map_err(wrap)?; |
| 3054 | |
| 3055 | let inn = self.qw.inn as u32; |
| 3056 | let out_dim = self.qw.out as u32; |
| 3057 | let d = self.qw.d as u32; |
| 3058 | let tokens = self.tokens as u32; |
| 3059 | |
| 3060 | let out_elems = self.tokens * self.qw.out; |
| 3061 | // Input is the rotated f32 xr — or, on the rotate-in path, the UNROTATED |
| 3062 | // bf16 activation (the kernel rotates it in its threadgroup prologue). |
| 3063 | let xr_off = layout.start_offset() * storage.dtype().size_in_bytes(); |
| 3064 | let rot_on = self.qw.rot_sign.is_some(); |
| 3065 | |
| 3066 | // Fused epilogue path: output bf16 directly + add the per-row bias in the |
| 3067 | // kernel (no candle to_dtype/broadcast_add). Used whenever the model dtype |
| 3068 | // is BF16 (always true on Metal). The f32 path stays for the QCHECK self- |
| 3069 | // test, which compares kernels in f32. |
| 3070 | let fused_bf16 = self.qw.out_dtype == DType::BF16; |
| 3071 | let out_dt = if fused_bf16 { DType::BF16 } else { DType::F32 }; |
| 3072 | let out_buf = dev.new_buffer(out_elems, out_dt, "tq_qmatvec")?; |
| 3073 | let out_ref: &Buffer = &out_buf; |
| 3074 | |
| 3075 | // Register-blocked nibble kernel (QROWS output rows per simd-group) is the |
| 3076 | // throughput default for the fused bf16 + 4-bit path: it amortizes the |
| 3077 | // activation load across rows. COCO_QROWS selects the width: |
| 3078 | // "0" → single-row kernel (A/B baseline) |
| 3079 | // "8" → wider register blocking (8 rows/group, tq_qmatvec_bf16_r8) |
| 3080 | // else (default "4") → tq_qmatvec_bf16_r |
| 3081 | let qrows_env = std::env::var("COCO_QROWS").ok(); |
| 3082 | let qrows_sel: usize = match qrows_env.as_deref() { |
| 3083 | Some("0") => 0, |
| 3084 | Some("8") => 8, |
| 3085 | _ => 4, |
| 3086 | }; |
| 3087 | let qrows_on = fused_bf16 && self.qw.pack_bits != 3 && qrows_sel != 0; |
| 3088 | // COCO_QW2=1 swaps the QROWS=4 kernel for its uint2 wide-unpack twin |
| 3089 | // (2 packed words per inner iteration). Only valid at QROWS=4. |
| 3090 | let qw2 = qrows_sel == 4 && std::env::var("COCO_QW2").as_deref() == Ok("1"); |
| 3091 | // Fused SwiGLU is a register-blocked nibble kernel that also folds |
| 3092 | // silu(gate)·up at store; it shares the QROWS width selection. Only set |
| 3093 | // by the gate/up QGroup, only on the bf16 + 4-bit path (asserted at the |
| 3094 | // call site), so qrows_on holds whenever swiglu does. |
| 3095 | let swiglu_on = self.qw.swiglu; |
| 3096 | let pipe = if rot_on { |
| 3097 | // Rotate-in prologue kernels (QR=4; eligibility asserted by the caller |
| 3098 | // via rotate_in_eligible: bf16 + nibble + default QROWS, tokens==1). |
| 3099 | if swiglu_on { |
| 3100 | &pipes.qmatvec_swiglu_rot |
| 3101 | } else { |
| 3102 | &pipes.qmatvec_bf16_rot |
| 3103 | } |
| 3104 | } else if swiglu_on { |
| 3105 | if qrows_sel == 8 { |
| 3106 | &pipes.qmatvec_swiglu_r8 |
| 3107 | } else { |
| 3108 | &pipes.qmatvec_swiglu_r // QROWS=4 (also when COCO_QROWS=0/unset) |
| 3109 | } |
| 3110 | } else if qrows_on { |
| 3111 | if qw2 { |
| 3112 | &pipes.qmatvec_bf16_rw2 |
| 3113 | } else if qrows_sel == 8 { |
| 3114 | &pipes.qmatvec_bf16_r8 |
| 3115 | } else { |
| 3116 | &pipes.qmatvec_bf16_r |
| 3117 | } |
| 3118 | } else { |
| 3119 | match (fused_bf16, self.qw.pack_bits == 3) { |
| 3120 | (true, true) => &pipes.qmatvec3_bf16, |
| 3121 | (true, false) => &pipes.qmatvec_bf16, |
| 3122 | (false, true) => &pipes.qmatvec3, |
| 3123 | (false, false) => &pipes.qmatvec, |
| 3124 | } |
| 3125 | }; |
| 3126 | // SwiGLU's QROWS divisor: the swiglu kernel uses QR=8 only when COCO_QROWS=8, |
| 3127 | // else QR=4 (the swiglu_r kernel is compiled at QR=4 regardless of qrows_sel |
| 3128 | // being 0/unset). Grid math below must match. |
| 3129 | let swiglu_qr: usize = if qrows_sel == 8 { 8 } else { 4 }; |
| 3130 | |
| 3131 | let enc = dev.command_encoder()?; |
| 3132 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3133 | ce.set_compute_pipeline_state(pipe); |
| 3134 | ce.set_input_buffer(0, Some(storage.buffer()), xr_off); |
| 3135 | ce.set_input_buffer(1, Some(self.qw.codes.as_ref()), 0); |
| 3136 | ce.set_input_buffer(2, Some(self.qw.radius.as_ref()), 0); |
| 3137 | // codebook (8 f32) as a constant pointer via set_bytes_directly |
| 3138 | ce.set_bytes_directly( |
| 3139 | 3, |
| 3140 | std::mem::size_of_val(self.qw.codebook.as_slice()), |
| 3141 | self.qw.codebook.as_ptr().cast(), |
| 3142 | ); |
| 3143 | ce.set_output_buffer(4, Some(out_ref), 0); |
| 3144 | ce.set_bytes(5, &inn); |
| 3145 | ce.set_bytes(6, &out_dim); |
| 3146 | ce.set_bytes(7, &d); |
| 3147 | ce.set_bytes(8, &tokens); |
| 3148 | // The SwiGLU kernels have no bias/resid buffers (gate/up never carry |
| 3149 | // either); only the plain fused-bf16 kernels read buffers 9-12. |
| 3150 | if fused_bf16 && !swiglu_on { |
| 3151 | // bias (buffer 9) + has_bias flag (buffer 10). Bind the real bias when |
| 3152 | // present; otherwise bind the codes buffer as a harmless non-null |
| 3153 | // placeholder (has_bias=0 means the kernel never reads it). |
| 3154 | let has_bias: u32 = if self.qw.bias_bf16.is_some() { 1 } else { 0 }; |
| 3155 | // Real bias buffer (Arc deref) when present; else the codes buffer as a |
| 3156 | // harmless non-null placeholder (has_bias=0 ⇒ never read). |
| 3157 | let bias_buf: &Buffer = match &self.qw.bias_bf16 { |
| 3158 | Some(b) => b.as_ref(), |
| 3159 | None => self.qw.codes.as_ref(), |
| 3160 | }; |
| 3161 | ce.set_input_buffer(9, Some(bias_buf), 0); |
| 3162 | ce.set_bytes(10, &has_bias); |
| 3163 | // resid (buffer 11) + has_resid flag (buffer 12): the fused residual |
| 3164 | // epilogue (COCO_FUSE_RESID). Same placeholder trick when absent. |
| 3165 | let has_resid: u32 = if self.qw.resid.is_some() { 1 } else { 0 }; |
| 3166 | match &self.qw.resid { |
| 3167 | Some(r) => { |
| 3168 | if r.dtype() != DType::BF16 { |
| 3169 | return Err(candle_core::Error::Msg( |
| 3170 | "tq_qmatvec: resid must be bf16".into(), |
| 3171 | )); |
| 3172 | } |
| 3173 | let (rst, rl) = r.storage_and_layout(); |
| 3174 | let rbuf = match &*rst { |
| 3175 | candle_core::Storage::Metal(s) => s.buffer().clone(), |
| 3176 | _ => { |
| 3177 | return Err(candle_core::Error::Msg( |
| 3178 | "tq_qmatvec: resid not on metal".into(), |
| 3179 | )) |
| 3180 | } |
| 3181 | }; |
| 3182 | let roff = rl.start_offset() * DType::BF16.size_in_bytes(); |
| 3183 | ce.set_input_buffer(11, Some(&rbuf), roff); |
| 3184 | } |
| 3185 | None => ce.set_input_buffer(11, Some(self.qw.codes.as_ref()), 0), |
| 3186 | } |
| 3187 | ce.set_bytes(12, &has_resid); |
| 3188 | } |
| 3189 | // Rotate-in prologue: bind the ±1 rotation sign vector (buffer 13 for the |
| 3190 | // plain kernel, buffer 9 for the swiglu variant — it has no bias/resid). |
| 3191 | if rot_on { |
| 3192 | let sign_t = self.qw.rot_sign.as_ref().unwrap(); |
| 3193 | let sign_storage = sign_t.storage_and_layout().0; |
| 3194 | let sign_buf = match &*sign_storage { |
| 3195 | candle_core::Storage::Metal(s) => s.buffer().clone(), |
| 3196 | _ => { |
| 3197 | return Err(candle_core::Error::Msg( |
| 3198 | "tq_qmatvec: rot sign not on metal".into(), |
| 3199 | )) |
| 3200 | } |
| 3201 | }; |
| 3202 | let sgn_idx = if swiglu_on { 9 } else { 13 }; |
| 3203 | ce.set_input_buffer(sgn_idx, Some(&sign_buf), 0); |
| 3204 | } |
| 3205 | |
| 3206 | // One SIMD-group (32 lanes) per output row (or per QROWS rows). The |
| 3207 | // threadgroup packs `qocc` simd-groups so reductions stay within a |
| 3208 | // simd-group; capped at the pipeline max. ggml tunes simds-per-threadgroup |
| 3209 | // per quant for occupancy — expose it via COCO_QOCC (simd-groups per |
| 3210 | // threadgroup; default 8) so the fastest config can be picked by A/B. |
| 3211 | const SIMDW: usize = 32; |
| 3212 | let max_w = pipe.max_total_threads_per_threadgroup(); |
| 3213 | let qocc: usize = std::env::var("COCO_QOCC") |
| 3214 | .ok() |
| 3215 | .and_then(|v| v.parse::<usize>().ok()) |
| 3216 | .filter(|&v| v >= 1) |
| 3217 | .unwrap_or(8); |
| 3218 | if rot_on { |
| 3219 | // Rotate-in path: UNIFORM threadgroups (dispatch_thread_groups) — the |
| 3220 | // FWHT prologue barriers require every thread of the group present. |
| 3221 | // tgw must be a multiple of d so each sweep rotates whole d-blocks; |
| 3222 | // the dynamic threadgroup buffer holds the rotated row (inn f32) plus |
| 3223 | // the cross-simd FWHT scratch (tgw f32) — fit pre-checked by |
| 3224 | // rotate_in_eligible. Grid: nsg simd-groups per threadgroup, each |
| 3225 | // owning QR=4 rows → ceil(out / (nsg*4)) groups per token. Same |
| 3226 | // simd-group-per-rows parallelism as the separate-rotate kernel. |
| 3227 | let mut tgw = (qocc * SIMDW).min(max_w); |
| 3228 | tgw = (tgw / self.qw.d).max(1) * self.qw.d; |
| 3229 | tgw = tgw.min(max_w).max(self.qw.d); |
| 3230 | ce.set_threadgroup_memory_length( |
| 3231 | 0, |
| 3232 | (self.qw.inn + tgw) * DType::F32.size_in_bytes(), |
| 3233 | ); |
| 3234 | let rows_per_tg = (tgw / SIMDW) * 4; // QR = 4 (rot kernels) |
| 3235 | let n_tg = (self.qw.out + rows_per_tg - 1) / rows_per_tg; |
| 3236 | let grid = MTLSize { width: n_tg, height: self.tokens, depth: 1 }; |
| 3237 | let tgroup = MTLSize { width: tgw, height: 1, depth: 1 }; |
| 3238 | ce.dispatch_thread_groups(grid, tgroup); |
| 3239 | drop(enc); |
| 3240 | |
| 3241 | let news = |
| 3242 | candle_core::MetalStorage::new(out_buf, dev.clone(), out_elems, out_dt); |
| 3243 | return Ok((news, Shape::from_dims(&[self.tokens, self.qw.out]))); |
| 3244 | } |
| 3245 | let mut tgw = (qocc * SIMDW).min(max_w); |
| 3246 | tgw = (tgw / SIMDW) * SIMDW; // round down to a simd multiple |
| 3247 | tgw = tgw.max(SIMDW); |
| 3248 | // grid.x in THREADS: one simd-group (32 lanes) per output row, or per QROWS |
| 3249 | // rows when the register-blocked kernel is active. The divisor MUST match the |
| 3250 | // kernel's compile-time QROWS (qrows_sel) so each group owns the right rows. |
| 3251 | // SwiGLU grids over `out` (= I) gate rows (each group also does the matching |
| 3252 | // up rows internally); its divisor is swiglu_qr. |
| 3253 | let n_groups = if swiglu_on { |
| 3254 | (self.qw.out + swiglu_qr - 1) / swiglu_qr |
| 3255 | } else if qrows_on { |
| 3256 | (self.qw.out + qrows_sel - 1) / qrows_sel |
| 3257 | } else { |
| 3258 | self.qw.out |
| 3259 | }; |
| 3260 | let grid = MTLSize { |
| 3261 | width: n_groups * SIMDW, |
| 3262 | height: self.tokens, |
| 3263 | depth: 1, |
| 3264 | }; |
| 3265 | let tgroup = MTLSize { width: tgw, height: 1, depth: 1 }; |
| 3266 | ce.dispatch_threads(grid, tgroup); |
| 3267 | drop(enc); |
| 3268 | |
| 3269 | let news = candle_core::MetalStorage::new(out_buf, dev.clone(), out_elems, out_dt); |
| 3270 | Ok((news, Shape::from_dims(&[self.tokens, self.qw.out]))) |
| 3271 | } |
| 3272 | } |
| 3273 | |
| 3274 | // ───────────────────────── CustomOp1: FFN megakernel ───────────────────────── |
| 3275 | // Whole FFN (swiglu → rotate(h) → down) in one dispatch. Input is the |
| 3276 | // gate/up-ROTATED activation `xr` ([tokens, inn] f32). Output is [tokens, hidden] |
| 3277 | // bf16. `h` (I-wide SwiGLU intermediate) lives entirely in threadgroup memory; see |
| 3278 | // the `tq_ffn_mega` kernel. Eligibility (incl. I<=14336) is checked by the caller. |
| 3279 | struct FfnMegaOp { |
| 3280 | inn: usize, // gate/up input width (= hidden) |
| 3281 | big_i: usize, // intermediate width I |
| 3282 | d: usize, // block size (128) |
| 3283 | hidden: usize, // down out width (= hidden) |
| 3284 | gu_codes: Arc<Buffer>, |
| 3285 | gu_radius: Arc<Buffer>, |
| 3286 | codebook: Vec<f32>, |
| 3287 | dn_codes: Arc<Buffer>, |
| 3288 | dn_radius: Arc<Buffer>, |
| 3289 | dn_sign: Tensor, // [I] f32 (±1) on device |
| 3290 | tokens: usize, |
| 3291 | } |
| 3292 | |
| 3293 | impl CustomOp1 for FfnMegaOp { |
| 3294 | fn name(&self) -> &'static str { |
| 3295 | "tq_ffn_mega" |
| 3296 | } |
| 3297 | |
| 3298 | fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { |
| 3299 | Err(candle_core::Error::Msg( |
| 3300 | "tq_ffn_mega has no CPU implementation (Metal only)".into(), |
| 3301 | )) |
| 3302 | } |
| 3303 | |
| 3304 | fn metal_fwd( |
| 3305 | &self, |
| 3306 | storage: &candle_core::MetalStorage, |
| 3307 | layout: &Layout, |
| 3308 | ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> { |
| 3309 | use objc2_metal::MTLSize; |
| 3310 | let dev = storage.device().clone(); |
| 3311 | let mdev = dev.metal_device(); |
| 3312 | let pipes = get_pipelines(mdev).map_err(wrap)?; |
| 3313 | |
| 3314 | let inn = self.inn as u32; |
| 3315 | let big_i = self.big_i as u32; |
| 3316 | let d = self.d as u32; |
| 3317 | let hidden = self.hidden as u32; |
| 3318 | |
| 3319 | let out_elems = self.tokens * self.hidden; |
| 3320 | let xr_off = layout.start_offset() * DType::F32.size_in_bytes(); |
| 3321 | let out_buf = dev.new_buffer(out_elems, DType::BF16, "tq_ffn_mega")?; |
| 3322 | let out_ref: &Buffer = &out_buf; |
| 3323 | |
| 3324 | // down rotation sign buffer (on device). |
| 3325 | let sign_storage = self.dn_sign.storage_and_layout().0; |
| 3326 | let sign_buf = match &*sign_storage { |
| 3327 | candle_core::Storage::Metal(s) => s.buffer().clone(), |
| 3328 | _ => return Err(candle_core::Error::Msg("ffn_mega: down sign not on metal".into())), |
| 3329 | }; |
| 3330 | |
| 3331 | let pipe = &pipes.ffn_mega; |
| 3332 | let enc = dev.command_encoder()?; |
| 3333 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3334 | ce.set_compute_pipeline_state(pipe); |
| 3335 | ce.set_input_buffer(0, Some(storage.buffer()), xr_off); |
| 3336 | ce.set_input_buffer(1, Some(self.gu_codes.as_ref()), 0); |
| 3337 | ce.set_input_buffer(2, Some(self.gu_radius.as_ref()), 0); |
| 3338 | ce.set_bytes_directly( |
| 3339 | 3, |
| 3340 | std::mem::size_of_val(self.codebook.as_slice()), |
| 3341 | self.codebook.as_ptr().cast(), |
| 3342 | ); |
| 3343 | ce.set_output_buffer(4, Some(out_ref), 0); |
| 3344 | ce.set_bytes(5, &inn); |
| 3345 | ce.set_bytes(6, &big_i); |
| 3346 | ce.set_bytes(7, &d); |
| 3347 | ce.set_input_buffer(8, Some(self.dn_codes.as_ref()), 0); |
| 3348 | ce.set_input_buffer(9, Some(self.dn_radius.as_ref()), 0); |
| 3349 | ce.set_input_buffer(10, Some(&sign_buf), 0); |
| 3350 | ce.set_bytes(11, &hidden); |
| 3351 | |
| 3352 | // One threadgroup per token. Threadgroup width = qocc simd-groups, capped at |
| 3353 | // the pipeline max AND at 512 (the FWHT scratch `scr[512]` bound), AND kept a |
| 3354 | // multiple of `d` (=128) so the rotate phase tiles whole blocks per sweep. |
| 3355 | const SIMDW: usize = 32; |
| 3356 | let max_w = pipe.max_total_threads_per_threadgroup(); |
| 3357 | let qocc: usize = std::env::var("COCO_QOCC") |
| 3358 | .ok() |
| 3359 | .and_then(|v| v.parse::<usize>().ok()) |
| 3360 | .filter(|&v| v >= 1) |
| 3361 | .unwrap_or(8); |
| 3362 | let mut tgw = (qocc * SIMDW).min(max_w).min(512); |
| 3363 | tgw = (tgw / SIMDW) * SIMDW; // simd multiple |
| 3364 | // Make tgw a multiple of d (128) so tgsz/d blocks tile evenly each sweep; |
| 3365 | // d=128 is 4 simd-groups, so round down to a multiple of 128 (>= 128). |
| 3366 | tgw = (tgw / self.d).max(1) * self.d; |
| 3367 | tgw = tgw.min(max_w).max(self.d); |
| 3368 | |
| 3369 | // grid in THREADS: one threadgroup (tgw threads) per token along y. |
| 3370 | let grid = MTLSize { width: tgw, height: self.tokens, depth: 1 }; |
| 3371 | let tgroup = MTLSize { width: tgw, height: 1, depth: 1 }; |
| 3372 | ce.dispatch_threads(grid, tgroup); |
| 3373 | drop(enc); |
| 3374 | |
| 3375 | let news = candle_core::MetalStorage::new(out_buf, dev.clone(), out_elems, DType::BF16); |
| 3376 | Ok((news, Shape::from_dims(&[self.tokens, self.hidden]))) |
| 3377 | } |
| 3378 | } |
| 3379 | |
| 3380 | // ───────────────────────── fused flash-decode KV cache ───────────────────────── |
| 3381 | |
| 3382 | /// Persistent per-layer KV cache for the FUSED flash-decode attention path. K and |
| 3383 | /// V live in pinned device buffers `[n_kv, max_ctx, head_dim]` allocated ONCE and |
| 3384 | /// written in-kernel — no per-token `cat` realloc, no `repeat_kv` materialization. |
| 3385 | /// `len` is how many positions are currently stored. |
| 3386 | /// |
| 3387 | /// Precision is selected by `kv_bits` (COCO_KV_BITS): 16 = bf16 cache; 4 = q4_0-style |
| 3388 | /// 4-bit nibble cache (per-(head,position) row scale) — ~4x less KV memory traffic per |
| 3389 | /// decode step at long context, the dominant cost there. The flash-decode kernel |
| 3390 | /// dequantizes K/V on the fly and accumulates the softmax in f32 either way. |
| 3391 | /// |
| 3392 | /// Held buffers are `Arc<Buffer>` so candle's pool never recycles them out from |
| 3393 | /// under us (same pinning rationale as `QWeight`). |
| 3394 | pub struct KvCache { |
| 3395 | pub(crate) n_heads: usize, |
| 3396 | pub(crate) n_kv: usize, |
| 3397 | pub(crate) head_dim: usize, |
| 3398 | pub(crate) max_ctx: usize, |
| 3399 | /// KV precision: 16 = bf16 cache (k_cache/v_cache used), 4 = 4-bit nibble cache |
| 3400 | /// (k_codes/v_codes + k_scale/v_scale used). Default 4 (COCO_KV_BITS). |
| 3401 | pub(crate) kv_bits: u8, |
| 3402 | // ── bf16 path (kv_bits==16) ── |
| 3403 | pub(crate) k_cache: Arc<Buffer>, // [n_kv, max_ctx, head_dim] bf16 |
| 3404 | pub(crate) v_cache: Arc<Buffer>, |
| 3405 | // ── 4-bit path (kv_bits==4) ── |
| 3406 | // Nibble-packed codes [n_kv, max_ctx, head_dim/2] (uchar) + a per-32-coord-block |
| 3407 | // bf16 scale [n_kv, max_ctx, head_dim/32]. ~4x less KV traffic than the bf16 cache. |
| 3408 | pub(crate) k_codes: Arc<Buffer>, |
| 3409 | pub(crate) v_codes: Arc<Buffer>, |
| 3410 | pub(crate) k_scale: Arc<Buffer>, |
| 3411 | pub(crate) v_scale: Arc<Buffer>, |
| 3412 | // Flash-decoding split-K scratch (persistent, sized for MAX_SPLITS). Reused |
| 3413 | // every decode step so we don't allocate per token. |
| 3414 | pub(crate) pacc: Arc<Buffer>, // [n_heads, MAX_SPLITS, head_dim] |
| 3415 | pub(crate) pm: Arc<Buffer>, // [n_heads, MAX_SPLITS] |
| 3416 | pub(crate) pl: Arc<Buffer>, // [n_heads, MAX_SPLITS] |
| 3417 | pub(crate) len: usize, |
| 3418 | } |
| 3419 | |
| 3420 | /// KV-cache element bits. Default 4 (4-bit q4_0-style nibble cache, ~4x less KV |
| 3421 | /// memory traffic at long ctx). Set COCO_KV_BITS=16 for the old bf16 cache (A/B). |
| 3422 | fn kv_bits_from_env() -> u8 { |
| 3423 | // DEFAULT = 16 (bf16, coherent). 4-bit KV DEGENERATES larger models (verified: breaks |
| 3424 | // Qwen2.5-7B into a repetition loop) AND gives no real decode speedup at 8-32K — so it's |
| 3425 | // opt-in only. (It was briefly the default, validated only on the 1.5B → shipped broken 7B.) |
| 3426 | match std::env::var("COCO_KV_BITS").as_deref() { |
| 3427 | Ok("4") => 4, |
| 3428 | _ => 16, |
| 3429 | } |
| 3430 | } |
| 3431 | |
| 3432 | /// Hard cap on position-splits per head for flash-decoding. The actual count per |
| 3433 | /// step targets ~128 splits (n_heads × 128 ≈ GPU simd-group occupancy); beyond |
| 3434 | /// that, finer splits add combine overhead without filling more GPU lanes. |
| 3435 | const MAX_SPLITS: usize = 256; |
| 3436 | |
| 3437 | impl KvCache { |
| 3438 | /// Allocate the persistent K/V buffers for one attention layer. |
| 3439 | pub fn new( |
| 3440 | n_heads: usize, |
| 3441 | n_kv: usize, |
| 3442 | head_dim: usize, |
| 3443 | max_ctx: usize, |
| 3444 | device: &Device, |
| 3445 | ) -> Result<Self> { |
| 3446 | let cdev = match device { |
| 3447 | Device::Metal(m) => m, |
| 3448 | _ => return Err(anyhow!("flash-decode KV cache requires the Metal device")), |
| 3449 | }; |
| 3450 | let elems = n_kv * max_ctx * head_dim; |
| 3451 | let kv_bits = kv_bits_from_env(); |
| 3452 | // PRIVATE (unpooled) buffers: candle's pool never recycles them, and they |
| 3453 | // don't need zeroing — the kernel only ever reads slots [0..=pos] it has |
| 3454 | // itself written. Held as Arc<Buffer> for the model's lifetime. We allocate |
| 3455 | // ONLY the path actually selected by kv_bits at full size; the unused path |
| 3456 | // gets a 1-element placeholder (so the struct stays flat, no Option). |
| 3457 | // |
| 3458 | // bf16 (16-bit): halves attention bandwidth vs f32 — matches llama.cpp f16 KV. |
| 3459 | // 4-bit (q4_0-style): ~4x less than bf16 — nibble codes [.., head_dim/2] + |
| 3460 | // a per-32-coord-block bf16 scale [n_kv, max_ctx, head_dim/32]. The partial |
| 3461 | // kernel dequantizes on the fly (val=(nib-8)*scale) and accumulates in f32. |
| 3462 | let (k_cache, v_cache, k_codes, v_codes, k_scale, v_scale) = if kv_bits == 4 { |
| 3463 | let code_elems = n_kv * max_ctx * (head_dim / 2); // uchar nibble bytes |
| 3464 | // one bf16 scale per 32-coord block (Q4_BLK), not per row — a single |
| 3465 | // per-row scale was too coarse and collapsed attention (see kernel notes). |
| 3466 | let scale_elems = n_kv * max_ctx * (head_dim / 32); |
| 3467 | ( |
| 3468 | cdev.new_private_buffer(1, DType::BF16, "kv_k_unused")?, |
| 3469 | cdev.new_private_buffer(1, DType::BF16, "kv_v_unused")?, |
| 3470 | cdev.new_private_buffer(code_elems, DType::U8, "kv_k_codes")?, |
| 3471 | cdev.new_private_buffer(code_elems, DType::U8, "kv_v_codes")?, |
| 3472 | cdev.new_private_buffer(scale_elems, DType::BF16, "kv_k_scale")?, |
| 3473 | cdev.new_private_buffer(scale_elems, DType::BF16, "kv_v_scale")?, |
| 3474 | ) |
| 3475 | } else { |
| 3476 | ( |
| 3477 | cdev.new_private_buffer(elems, DType::BF16, "kv_k")?, |
| 3478 | cdev.new_private_buffer(elems, DType::BF16, "kv_v")?, |
| 3479 | cdev.new_private_buffer(1, DType::U8, "kv_k_codes_unused")?, |
| 3480 | cdev.new_private_buffer(1, DType::U8, "kv_v_codes_unused")?, |
| 3481 | cdev.new_private_buffer(1, DType::BF16, "kv_k_scale_unused")?, |
| 3482 | cdev.new_private_buffer(1, DType::BF16, "kv_v_scale_unused")?, |
| 3483 | ) |
| 3484 | }; |
| 3485 | let pacc = cdev.new_private_buffer(n_heads * MAX_SPLITS * head_dim, DType::F32, "pacc")?; |
| 3486 | let pm = cdev.new_private_buffer(n_heads * MAX_SPLITS, DType::F32, "pm")?; |
| 3487 | let pl = cdev.new_private_buffer(n_heads * MAX_SPLITS, DType::F32, "pl")?; |
| 3488 | Ok(Self { |
| 3489 | n_heads, |
| 3490 | n_kv, |
| 3491 | head_dim, |
| 3492 | max_ctx, |
| 3493 | kv_bits, |
| 3494 | k_cache, |
| 3495 | v_cache, |
| 3496 | k_codes, |
| 3497 | v_codes, |
| 3498 | k_scale, |
| 3499 | v_scale, |
| 3500 | pacc, |
| 3501 | pm, |
| 3502 | pl, |
| 3503 | len: 0, |
| 3504 | }) |
| 3505 | } |
| 3506 | |
| 3507 | pub fn clear(&mut self) { |
| 3508 | self.len = 0; |
| 3509 | } |
| 3510 | |
| 3511 | pub fn len(&self) -> usize { |
| 3512 | self.len |
| 3513 | } |
| 3514 | |
| 3515 | pub fn max_ctx(&self) -> usize { |
| 3516 | self.max_ctx |
| 3517 | } |
| 3518 | |
| 3519 | /// Append a chunk's k/v into the persistent cache and advance `len`. |
| 3520 | /// `k`/`v` must be contiguous BF16 `[n_kv, seq, head_dim]` (k already RoPE'd) — |
| 3521 | /// the kernel converts to the f32 cache on store. One copy dispatch; no candle |
| 3522 | /// cat/realloc and no candle to_dtype(F32) beforehand. |
| 3523 | pub fn append_prefill(&mut self, k: &Tensor, v: &Tensor) -> Result<()> { |
| 3524 | use objc2_metal::MTLSize; |
| 3525 | let device = k.device().clone(); |
| 3526 | let cdev = match &device { |
| 3527 | Device::Metal(m) => m.clone(), |
| 3528 | _ => return Err(anyhow!("kv append requires the Metal device")), |
| 3529 | }; |
| 3530 | let mdev = cdev.metal_device(); |
| 3531 | let pipes = get_pipelines(mdev)?; |
| 3532 | |
| 3533 | let dims = k.dims().to_vec(); |
| 3534 | // accept [n_kv, seq, head_dim] or [1, n_kv, seq, head_dim] |
| 3535 | let (n_kv, seq, hd) = match dims.len() { |
| 3536 | 3 => (dims[0], dims[1], dims[2]), |
| 3537 | 4 => (dims[1], dims[2], dims[3]), |
| 3538 | _ => return Err(anyhow!("kv append expects 3 or 4 dims, got {dims:?}")), |
| 3539 | }; |
| 3540 | if n_kv != self.n_kv || hd != self.head_dim { |
| 3541 | return Err(anyhow!("kv append shape mismatch")); |
| 3542 | } |
| 3543 | if self.len + seq > self.max_ctx { |
| 3544 | return Err(anyhow!( |
| 3545 | "KV cache overflow on prefill: {} + {} > {}", |
| 3546 | self.len, seq, self.max_ctx |
| 3547 | )); |
| 3548 | } |
| 3549 | |
| 3550 | // bf16 inputs → 2-byte element offset. |
| 3551 | let buf_of = |t: &Tensor| -> Result<(Buffer, usize)> { |
| 3552 | let (s, l) = t.storage_and_layout(); |
| 3553 | match &*s { |
| 3554 | candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)), |
| 3555 | _ => Err(anyhow!("kv append inputs must be on Metal")), |
| 3556 | } |
| 3557 | }; |
| 3558 | let (k_buf, k_off) = buf_of(k)?; |
| 3559 | let (v_buf, v_off) = buf_of(v)?; |
| 3560 | |
| 3561 | let seq_u = seq as u32; |
| 3562 | let hd_u = hd as u32; |
| 3563 | let max_ctx = self.max_ctx as u32; |
| 3564 | let pos = self.len as u32; |
| 3565 | if self.kv_bits == 4 { |
| 3566 | // Quantize + nibble-pack the chunk into the 4-bit cache. ONE threadgroup |
| 3567 | // per (kv, position): head_dim threads cooperatively find each row's |
| 3568 | // absmax → bf16 scale, then pack nibbles + write the scale. |
| 3569 | let enc = cdev.command_encoder()?; |
| 3570 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3571 | ce.set_compute_pipeline_state(&pipes.kv_append_q4); |
| 3572 | ce.set_input_buffer(0, Some(&k_buf), k_off); |
| 3573 | ce.set_input_buffer(1, Some(&v_buf), v_off); |
| 3574 | ce.set_output_buffer(2, Some(self.k_codes.as_ref()), 0); |
| 3575 | ce.set_output_buffer(3, Some(self.v_codes.as_ref()), 0); |
| 3576 | ce.set_output_buffer(4, Some(self.k_scale.as_ref()), 0); |
| 3577 | ce.set_output_buffer(5, Some(self.v_scale.as_ref()), 0); |
| 3578 | ce.set_bytes(6, &seq_u); |
| 3579 | ce.set_bytes(7, &hd_u); |
| 3580 | ce.set_bytes(8, &max_ctx); |
| 3581 | ce.set_bytes(9, &pos); |
| 3582 | let grid = MTLSize { width: n_kv, height: seq, depth: 1 }; |
| 3583 | let tgroup = MTLSize { width: hd, height: 1, depth: 1 }; |
| 3584 | ce.dispatch_thread_groups(grid, tgroup); |
| 3585 | drop(enc); |
| 3586 | self.len += seq; |
| 3587 | return Ok(()); |
| 3588 | } |
| 3589 | { |
| 3590 | let enc = cdev.command_encoder()?; |
| 3591 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3592 | ce.set_compute_pipeline_state(&pipes.kv_append); |
| 3593 | ce.set_input_buffer(0, Some(&k_buf), k_off); |
| 3594 | ce.set_input_buffer(1, Some(&v_buf), v_off); |
| 3595 | ce.set_input_buffer(2, Some(self.k_cache.as_ref()), 0); |
| 3596 | ce.set_input_buffer(3, Some(self.v_cache.as_ref()), 0); |
| 3597 | ce.set_bytes(4, &seq_u); |
| 3598 | ce.set_bytes(5, &hd_u); |
| 3599 | ce.set_bytes(6, &max_ctx); |
| 3600 | ce.set_bytes(7, &pos); |
| 3601 | let grid = MTLSize { width: hd, height: seq, depth: n_kv }; |
| 3602 | let tgroup = MTLSize { width: hd, height: 1, depth: 1 }; |
| 3603 | ce.dispatch_threads(grid, tgroup); |
| 3604 | } |
| 3605 | self.len += seq; |
| 3606 | Ok(()) |
| 3607 | } |
| 3608 | |
| 3609 | /// Append one token's k/v into the cache and run fused flash-decode attention |
| 3610 | /// for the single new query. `q` [n_heads, head_dim] BF16 (RoPE'd), `k_new`/ |
| 3611 | /// `v_new` [n_kv, head_dim] BF16 (k_new RoPE'd) — all contiguous on Metal; the |
| 3612 | /// kernels convert to f32 on load (no candle to_dtype). Returns the attention |
| 3613 | /// output [n_heads*head_dim] f32 as a candle Tensor shaped [1,1,hidden]; the |
| 3614 | /// caller feeds it straight into o_proj (o_proj's rotate handles f32 input). |
| 3615 | /// |
| 3616 | /// TWO Metal dispatches (partial + combine) replace candle's cat + repeat_kv + |
| 3617 | /// scores + softmax + AV (each O(ctx), each a separate dispatch plus huge |
| 3618 | /// copies). The new token's k/v is appended IN the partial kernel (by the split |
| 3619 | /// owning the last position), so there's no separate append dispatch and no |
| 3620 | /// append→read memory barrier serializing the GPU per token. f32 KV cache is |
| 3621 | /// persistent (no per-token realloc). |
| 3622 | pub fn decode(&mut self, q: &Tensor, k_new: &Tensor, v_new: &Tensor) -> Result<Tensor> { |
| 3623 | use objc2_metal::MTLSize; |
| 3624 | let device = q.device().clone(); |
| 3625 | let cdev = match &device { |
| 3626 | Device::Metal(m) => m.clone(), |
| 3627 | _ => return Err(anyhow!("flash-decode requires the Metal device")), |
| 3628 | }; |
| 3629 | let mdev = cdev.metal_device(); |
| 3630 | let pipes = get_pipelines(mdev)?; |
| 3631 | |
| 3632 | if self.len >= self.max_ctx { |
| 3633 | return Err(anyhow!( |
| 3634 | "KV cache overflow: len {} >= max_ctx {}", |
| 3635 | self.len, |
| 3636 | self.max_ctx |
| 3637 | )); |
| 3638 | } |
| 3639 | |
| 3640 | // The new token will occupy slot `len`; after this step the valid range is |
| 3641 | // [0..=len]. The partial kernel appends it (in-kernel) and attends. q/k_new/ |
| 3642 | // v_new are BF16 (read & converted in-kernel) → 2-byte element offsets. |
| 3643 | let pos = self.len as u32; |
| 3644 | let buf_of = |t: &Tensor| -> Result<(Buffer, usize)> { |
| 3645 | let (s, l) = t.storage_and_layout(); |
| 3646 | match &*s { |
| 3647 | candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)), |
| 3648 | _ => Err(anyhow!("flash-decode inputs must be on Metal")), |
| 3649 | } |
| 3650 | }; |
| 3651 | let (q_buf, q_off) = buf_of(q)?; |
| 3652 | let (k_buf, k_off) = buf_of(k_new)?; |
| 3653 | let (v_buf, v_off) = buf_of(v_new)?; |
| 3654 | |
| 3655 | let out_elems = self.n_heads * self.head_dim; |
| 3656 | let out_buf = cdev.new_buffer(out_elems, DType::F32, "tq_attn_out")?; |
| 3657 | |
| 3658 | // For the 4-bit cache, quantize+append the decode token's k/v via the SAME |
| 3659 | // proven prefill kernel (tq_kv_append_q4) BEFORE attending, instead of the |
| 3660 | // in-kernel append inside tq_attn_partial_q4. The in-kernel q4 append path |
| 3661 | // corrupted later positions (token 1 ok, token 2+ garbage); the prefill |
| 3662 | // append is verified-correct, so we reuse it here (correctness over the |
| 3663 | // saved dispatch). After this, self.len == pos+1 and the attention kernel |
| 3664 | // runs read-only (do_append=0). bf16 keeps its single-dispatch in-kernel |
| 3665 | // append (that path is coherent). |
| 3666 | let do_append: u32 = if self.kv_bits == 4 { |
| 3667 | // append_prefill expects [n_kv, seq, head_dim]; k_new/v_new are |
| 3668 | // [n_kv, head_dim] → add the seq=1 axis. This advances self.len by 1. |
| 3669 | let k_app = k_new.unsqueeze(1)?; |
| 3670 | let v_app = v_new.unsqueeze(1)?; |
| 3671 | self.append_prefill(&k_app, &v_app)?; |
| 3672 | 0 |
| 3673 | } else { |
| 3674 | 1 |
| 3675 | }; |
| 3676 | |
| 3677 | let total = (pos + 1) as u32; // valid positions after the append |
| 3678 | // Flash-decoding split count. The attention is PARALLELISM-bound, not |
| 3679 | // bandwidth-bound: with too few splits the GPU sits idle (measured 27 tok/s |
| 3680 | // at 8K with 16 splits → 65 tok/s with 128 splits). The sweet spot is when |
| 3681 | // n_heads × n_splits ≈ GPU simd-group occupancy (~600-1000 on M4 Max), so we |
| 3682 | // TARGET a fixed split count rather than a fixed positions-per-split. Each |
| 3683 | // split still needs enough work, so we also cap at total/MIN_PER_SPLIT. |
| 3684 | // COCO_SPLIT_TARGET overrides the target (profiling). |
| 3685 | let target: usize = std::env::var("COCO_SPLIT_TARGET") |
| 3686 | .ok() |
| 3687 | .and_then(|s| s.parse().ok()) |
| 3688 | .unwrap_or(128); |
| 3689 | const MIN_PER_SPLIT: usize = 16; |
| 3690 | let by_work = ((total as usize) / MIN_PER_SPLIT).max(1); |
| 3691 | // n_splits = min(target, total/MIN_PER_SPLIT), clamped to [1, MAX_SPLITS]. |
| 3692 | let n_splits = target.min(by_work).clamp(1, MAX_SPLITS) as u32; |
| 3693 | |
| 3694 | let n_heads = self.n_heads as u32; |
| 3695 | let n_kv = self.n_kv as u32; |
| 3696 | let head_dim = self.head_dim as u32; |
| 3697 | let max_ctx = self.max_ctx as u32; |
| 3698 | let scale = 1.0f32 / (self.head_dim as f32).sqrt(); |
| 3699 | |
| 3700 | { |
| 3701 | let enc = cdev.command_encoder()?; |
| 3702 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3703 | let grid = MTLSize { width: self.n_heads, height: n_splits as usize, depth: 1 }; |
| 3704 | let tgroup = MTLSize { width: 32, height: 1, depth: 1 }; |
| 3705 | // ── partials (also appends the new token to the cache) ── |
| 3706 | // k/v cache bound as OUTPUTS (the kernel appends the new row): this makes |
| 3707 | // candle's hazard tracker insert the inter-token barrier so token N's |
| 3708 | // write to slot N is visible to token N+1's read. (Binding read-only |
| 3709 | // would skip that barrier → cross-token race.) |
| 3710 | if self.kv_bits == 4 { |
| 3711 | // 4-bit cache: quantize+append the decode token's k/v in-kernel and |
| 3712 | // dequantize the cached K/V on the fly while attending (val=(nib-8)*sc). |
| 3713 | ce.set_compute_pipeline_state(&pipes.attn_partial_q4); |
| 3714 | ce.set_input_buffer(0, Some(&q_buf), q_off); |
| 3715 | ce.set_output_buffer(1, Some(self.k_codes.as_ref()), 0); |
| 3716 | ce.set_output_buffer(2, Some(self.v_codes.as_ref()), 0); |
| 3717 | ce.set_output_buffer(3, Some(self.pacc.as_ref()), 0); |
| 3718 | ce.set_output_buffer(4, Some(self.pm.as_ref()), 0); |
| 3719 | ce.set_output_buffer(5, Some(self.pl.as_ref()), 0); |
| 3720 | ce.set_bytes(6, &n_heads); |
| 3721 | ce.set_bytes(7, &n_kv); |
| 3722 | ce.set_bytes(8, &head_dim); |
| 3723 | ce.set_bytes(9, &max_ctx); |
| 3724 | ce.set_bytes(10, &total); |
| 3725 | ce.set_bytes(11, &scale); |
| 3726 | ce.set_bytes(12, &n_splits); |
| 3727 | ce.set_input_buffer(13, Some(&k_buf), k_off); |
| 3728 | ce.set_input_buffer(14, Some(&v_buf), v_off); |
| 3729 | // scale buffers also bound as OUTPUTS (the owning split writes the new |
| 3730 | // row's scale, all splits read prior rows' scales) → same barrier. |
| 3731 | ce.set_output_buffer(15, Some(self.k_scale.as_ref()), 0); |
| 3732 | ce.set_output_buffer(16, Some(self.v_scale.as_ref()), 0); |
| 3733 | ce.set_bytes(17, &do_append); // 0 → token already appended above |
| 3734 | ce.dispatch_thread_groups(grid, tgroup); |
| 3735 | } else { |
| 3736 | ce.set_compute_pipeline_state(&pipes.attn_partial); |
| 3737 | ce.set_input_buffer(0, Some(&q_buf), q_off); |
| 3738 | ce.set_output_buffer(1, Some(self.k_cache.as_ref()), 0); |
| 3739 | ce.set_output_buffer(2, Some(self.v_cache.as_ref()), 0); |
| 3740 | ce.set_output_buffer(3, Some(self.pacc.as_ref()), 0); |
| 3741 | ce.set_output_buffer(4, Some(self.pm.as_ref()), 0); |
| 3742 | ce.set_output_buffer(5, Some(self.pl.as_ref()), 0); |
| 3743 | ce.set_bytes(6, &n_heads); |
| 3744 | ce.set_bytes(7, &n_kv); |
| 3745 | ce.set_bytes(8, &head_dim); |
| 3746 | ce.set_bytes(9, &max_ctx); |
| 3747 | ce.set_bytes(10, &total); |
| 3748 | ce.set_bytes(11, &scale); |
| 3749 | ce.set_bytes(12, &n_splits); |
| 3750 | ce.set_input_buffer(13, Some(&k_buf), k_off); |
| 3751 | ce.set_input_buffer(14, Some(&v_buf), v_off); |
| 3752 | ce.dispatch_thread_groups(grid, tgroup); |
| 3753 | } |
| 3754 | |
| 3755 | // ── combine (reads pacc/pm/pl which were just written → auto barrier) ── |
| 3756 | ce.set_compute_pipeline_state(&pipes.attn_combine); |
| 3757 | ce.set_input_buffer(0, Some(self.pacc.as_ref()), 0); |
| 3758 | ce.set_input_buffer(1, Some(self.pm.as_ref()), 0); |
| 3759 | ce.set_input_buffer(2, Some(self.pl.as_ref()), 0); |
| 3760 | ce.set_output_buffer(3, Some(out_buf.as_ref()), 0); |
| 3761 | ce.set_bytes(4, &n_heads); |
| 3762 | ce.set_bytes(5, &head_dim); |
| 3763 | ce.set_bytes(6, &n_splits); |
| 3764 | let grid2 = MTLSize { width: self.n_heads, height: 1, depth: 1 }; |
| 3765 | let tgroup2 = MTLSize { width: 32, height: 1, depth: 1 }; |
| 3766 | ce.dispatch_thread_groups(grid2, tgroup2); |
| 3767 | } |
| 3768 | |
| 3769 | // The new token is now in the cache. For kv_bits==4 it was already appended |
| 3770 | // (and self.len advanced) by append_prefill above; only the bf16 in-kernel |
| 3771 | // append path still needs to advance len here. |
| 3772 | if self.kv_bits != 4 { |
| 3773 | self.len += 1; |
| 3774 | } |
| 3775 | |
| 3776 | let storage = |
| 3777 | candle_core::MetalStorage::new(out_buf, cdev.clone(), out_elems, DType::F32); |
| 3778 | let attn = candle_core::Tensor::from_storage( |
| 3779 | candle_core::Storage::Metal(storage), |
| 3780 | Shape::from_dims(&[1, 1, out_elems]), |
| 3781 | candle_core::op::BackpropOp::none(), |
| 3782 | false, |
| 3783 | ); |
| 3784 | Ok(attn) |
| 3785 | } |
| 3786 | } |
| 3787 | |
| 3788 | fn wrap(e: anyhow::Error) -> candle_core::Error { |
| 3789 | candle_core::Error::Msg(e.to_string()) |
| 3790 | } |
| 3791 | |
| 3792 | // ───────────────────────── fused RMSNorm ───────────────────────── |
| 3793 | |
| 3794 | /// A fused RMSNorm that runs `out = x * rsqrt(mean(x^2)+eps) * weight` in ONE Metal |
| 3795 | /// dispatch (bf16 in/out, f32 math). Drop-in for `candle_nn::RmsNorm` on the decode |
| 3796 | /// path: candle's RmsNorm is a chain of ~7 elementwise dispatches (upcast, sqr, |
| 3797 | /// mean, +eps, rsqrt, ×, ×, downcast); there are ~57 norms/token, so collapsing each |
| 3798 | /// to one dispatch removes a big slice of the per-token candle op-tax. |
| 3799 | pub struct RmsNormFused { |
| 3800 | pub(crate) weight: Tensor, // [inn] bf16 on device |
| 3801 | pub(crate) eps: f32, |
| 3802 | pub(crate) inn: usize, |
| 3803 | } |
| 3804 | |
| 3805 | impl RmsNormFused { |
| 3806 | pub fn new(weight: Tensor, eps: f64) -> Result<Self> { |
| 3807 | let inn = weight.dims1()?; |
| 3808 | let weight = weight.to_dtype(DType::BF16)?.contiguous()?; |
| 3809 | Ok(Self { weight, eps: eps as f32, inn }) |
| 3810 | } |
| 3811 | |
| 3812 | /// out has the same shape/dtype as `x` (bf16). Flattens leading dims to tokens. |
| 3813 | pub fn forward(&self, x: &Tensor) -> Result<Tensor> { |
| 3814 | // Fallback to candle when disabled (A/B) or input isn't bf16. |
| 3815 | if std::env::var("COCO_NO_FUSE_NORM").is_ok() || x.dtype() != DType::BF16 { |
| 3816 | let xs = x.to_dtype(DType::F32)?; |
| 3817 | let var = xs.sqr()?.mean_keepdim(D::Minus1)?; |
| 3818 | let xn = xs.broadcast_div(&(var + self.eps as f64)?.sqrt()?)?; |
| 3819 | let w = self.weight.to_dtype(DType::F32)?; |
| 3820 | return Ok(xn.broadcast_mul(&w)?.to_dtype(x.dtype())?); |
| 3821 | } |
| 3822 | let dims = x.dims().to_vec(); |
| 3823 | let inn = *dims.last().unwrap(); |
| 3824 | if inn != self.inn { |
| 3825 | return Err(anyhow!("RmsNormFused: input dim {inn} != weight {}", self.inn)); |
| 3826 | } |
| 3827 | let tokens: usize = dims[..dims.len() - 1].iter().product::<usize>().max(1); |
| 3828 | let xc = x.reshape((tokens, inn))?.contiguous()?; |
| 3829 | let out = xc.apply_op1(RmsNormOp { |
| 3830 | weight: self.weight.clone(), |
| 3831 | eps: self.eps, |
| 3832 | inn, |
| 3833 | tokens, |
| 3834 | })?; |
| 3835 | Ok(out.reshape(Shape::from_dims(&dims))?) |
| 3836 | } |
| 3837 | |
| 3838 | /// FUSED residual-add + RMSNorm: returns `(h, normed)` where `h = a + b` and |
| 3839 | /// `normed = RMSNorm(h) * weight`, computed in ONE Metal dispatch. `h` is the new |
| 3840 | /// residual stream (fed to the next add); `normed` feeds the next sublayer. This |
| 3841 | /// folds the standalone candle elementwise residual add into the norm that |
| 3842 | /// immediately consumes it (one fewer full [tokens,inn] pass per sublayer). Falls |
| 3843 | /// back to candle (`(a+b)` then `forward`) when disabled or off the bf16 path. |
| 3844 | pub fn forward_add(&self, a: &Tensor, b: &Tensor) -> Result<(Tensor, Tensor)> { |
| 3845 | if std::env::var("COCO_NO_FUSE_ADDNORM").is_ok() |
| 3846 | || std::env::var("COCO_NO_FUSE_NORM").is_ok() |
| 3847 | || a.dtype() != DType::BF16 |
| 3848 | || b.dtype() != DType::BF16 |
| 3849 | || !matches!(a.device(), Device::Metal(_)) |
| 3850 | { |
| 3851 | let h = (a + b)?; |
| 3852 | let normed = self.forward(&h)?; |
| 3853 | return Ok((h, normed)); |
| 3854 | } |
| 3855 | let dims = a.dims().to_vec(); |
| 3856 | let inn = *dims.last().unwrap(); |
| 3857 | if inn != self.inn { |
| 3858 | return Err(anyhow!("RmsNormFused::forward_add: dim {inn} != weight {}", self.inn)); |
| 3859 | } |
| 3860 | if b.dims() != a.dims() { |
| 3861 | return Err(anyhow!("forward_add: shape mismatch {:?} vs {:?}", a.dims(), b.dims())); |
| 3862 | } |
| 3863 | let tokens: usize = dims[..dims.len() - 1].iter().product::<usize>().max(1); |
| 3864 | let ac = a.reshape((tokens, inn))?.contiguous()?; |
| 3865 | let bc = b.reshape((tokens, inn))?.contiguous()?; |
| 3866 | let (h, normed) = add_rmsnorm_apply(&ac, &bc, &self.weight, self.eps, tokens, inn)?; |
| 3867 | Ok(( |
| 3868 | h.reshape(Shape::from_dims(&dims))?, |
| 3869 | normed.reshape(Shape::from_dims(&dims))?, |
| 3870 | )) |
| 3871 | } |
| 3872 | } |
| 3873 | |
| 3874 | /// Run the fused add+RMSNorm kernel over contiguous `[tokens, inn]` bf16 `a`/`b` and |
| 3875 | /// bf16 weight `w`, returning `(h=a+b, normed=RMSNorm(h)*w)` as two `[tokens,inn]` |
| 3876 | /// bf16 tensors. Builds the encoder directly (two source reads, two writes) so candle |
| 3877 | /// tracks the hazards; the leader-style one-threadgroup-per-token reduction mirrors |
| 3878 | /// `RmsNormOp`. |
| 3879 | fn add_rmsnorm_apply( |
| 3880 | a: &Tensor, |
| 3881 | b: &Tensor, |
| 3882 | w: &Tensor, |
| 3883 | eps: f32, |
| 3884 | tokens: usize, |
| 3885 | inn: usize, |
| 3886 | ) -> Result<(Tensor, Tensor)> { |
| 3887 | use objc2_metal::MTLSize; |
| 3888 | let device = a.device().clone(); |
| 3889 | let cdev = match &device { |
| 3890 | Device::Metal(m) => m.clone(), |
| 3891 | _ => return Err(anyhow!("add_rmsnorm requires the Metal device")), |
| 3892 | }; |
| 3893 | let mdev = cdev.metal_device(); |
| 3894 | let pipes = get_pipelines(mdev)?; |
| 3895 | |
| 3896 | let buf_of = |t: &Tensor| -> Result<(Buffer, usize)> { |
| 3897 | let (s, l) = t.storage_and_layout(); |
| 3898 | match &*s { |
| 3899 | candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)), |
| 3900 | _ => Err(anyhow!("add_rmsnorm inputs must be on Metal")), |
| 3901 | } |
| 3902 | }; |
| 3903 | let (a_buf, a_off) = buf_of(a)?; |
| 3904 | let (b_buf, b_off) = buf_of(b)?; |
| 3905 | let (w_buf, w_off) = buf_of(w)?; |
| 3906 | |
| 3907 | let elem = tokens * inn; |
| 3908 | let h_buf = cdev.new_buffer(elem, DType::BF16, "tq_addnorm_h")?; |
| 3909 | let out_buf = cdev.new_buffer(elem, DType::BF16, "tq_addnorm_out")?; |
| 3910 | |
| 3911 | let inn_u = inn as u32; |
| 3912 | { |
| 3913 | let enc = cdev.command_encoder()?; |
| 3914 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3915 | ce.set_compute_pipeline_state(&pipes.add_rmsnorm); |
| 3916 | ce.set_input_buffer(0, Some(&a_buf), a_off); |
| 3917 | ce.set_input_buffer(1, Some(&b_buf), b_off); |
| 3918 | ce.set_output_buffer(2, Some(h_buf.as_ref()), 0); |
| 3919 | ce.set_output_buffer(3, Some(out_buf.as_ref()), 0); |
| 3920 | ce.set_input_buffer(4, Some(&w_buf), w_off); |
| 3921 | ce.set_bytes(5, &inn_u); |
| 3922 | ce.set_bytes(6, &eps); |
| 3923 | const SIMDW: usize = 32; |
| 3924 | let max_w = pipes.add_rmsnorm.max_total_threads_per_threadgroup(); |
| 3925 | let mut tgw = (8 * SIMDW).min(max_w).min(inn); |
| 3926 | tgw = (tgw / SIMDW).max(1) * SIMDW; |
| 3927 | let grid = MTLSize { width: tokens * tgw, height: 1, depth: 1 }; |
| 3928 | let tgroup = MTLSize { width: tgw, height: 1, depth: 1 }; |
| 3929 | ce.dispatch_threads(grid, tgroup); |
| 3930 | } |
| 3931 | |
| 3932 | let mk = |buf: Arc<Buffer>| -> Tensor { |
| 3933 | let storage = candle_core::MetalStorage::new(buf, cdev.clone(), elem, DType::BF16); |
| 3934 | candle_core::Tensor::from_storage( |
| 3935 | candle_core::Storage::Metal(storage), |
| 3936 | Shape::from_dims(&[tokens, inn]), |
| 3937 | candle_core::op::BackpropOp::none(), |
| 3938 | false, |
| 3939 | ) |
| 3940 | }; |
| 3941 | Ok((mk(h_buf), mk(out_buf))) |
| 3942 | } |
| 3943 | |
| 3944 | use candle_core::D; |
| 3945 | |
| 3946 | struct RmsNormOp { |
| 3947 | weight: Tensor, |
| 3948 | eps: f32, |
| 3949 | inn: usize, |
| 3950 | tokens: usize, |
| 3951 | } |
| 3952 | |
| 3953 | impl CustomOp1 for RmsNormOp { |
| 3954 | fn name(&self) -> &'static str { |
| 3955 | "tq_rmsnorm" |
| 3956 | } |
| 3957 | fn cpu_fwd(&self, _s: &CpuStorage, _l: &Layout) -> candle_core::Result<(CpuStorage, Shape)> { |
| 3958 | Err(candle_core::Error::Msg("tq_rmsnorm is Metal only".into())) |
| 3959 | } |
| 3960 | fn metal_fwd( |
| 3961 | &self, |
| 3962 | storage: &candle_core::MetalStorage, |
| 3963 | layout: &Layout, |
| 3964 | ) -> candle_core::Result<(candle_core::MetalStorage, Shape)> { |
| 3965 | use objc2_metal::MTLSize; |
| 3966 | let dev = storage.device().clone(); |
| 3967 | let mdev = dev.metal_device(); |
| 3968 | let pipes = get_pipelines(mdev).map_err(wrap)?; |
| 3969 | |
| 3970 | let inn = self.inn as u32; |
| 3971 | let eps = self.eps; |
| 3972 | let elem = self.tokens * self.inn; |
| 3973 | let out_buf = dev.new_buffer(elem, DType::BF16, "tq_rmsnorm")?; |
| 3974 | let out_ref: &Buffer = &out_buf; |
| 3975 | let in_off = layout.start_offset() * DType::BF16.size_in_bytes(); |
| 3976 | |
| 3977 | let w_storage = self.weight.storage_and_layout().0; |
| 3978 | let w_buf = match &*w_storage { |
| 3979 | candle_core::Storage::Metal(s) => s.buffer().clone(), |
| 3980 | _ => return Err(candle_core::Error::Msg("rmsnorm weight not on metal".into())), |
| 3981 | }; |
| 3982 | |
| 3983 | let enc = dev.command_encoder()?; |
| 3984 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 3985 | ce.set_compute_pipeline_state(&pipes.rmsnorm); |
| 3986 | ce.set_input_buffer(0, Some(storage.buffer()), in_off); |
| 3987 | ce.set_output_buffer(1, Some(out_ref), 0); |
| 3988 | ce.set_input_buffer(2, Some(&w_buf), 0); |
| 3989 | ce.set_bytes(3, &inn); |
| 3990 | ce.set_bytes(4, &eps); |
| 3991 | // One threadgroup per token; width = multiple of 32, capped at the pipeline |
| 3992 | // max (we want enough lanes to stride over inn=1536 cheaply). |
| 3993 | const SIMDW: usize = 32; |
| 3994 | let max_w = pipes.rmsnorm.max_total_threads_per_threadgroup(); |
| 3995 | let mut tgw = (8 * SIMDW).min(max_w).min(self.inn); |
| 3996 | tgw = (tgw / SIMDW).max(1) * SIMDW; |
| 3997 | let grid = MTLSize { width: self.tokens * tgw, height: 1, depth: 1 }; |
| 3998 | let tgroup = MTLSize { width: tgw, height: 1, depth: 1 }; |
| 3999 | ce.dispatch_threads(grid, tgroup); |
| 4000 | drop(enc); |
| 4001 | |
| 4002 | let news = candle_core::MetalStorage::new(out_buf, dev.clone(), elem, DType::BF16); |
| 4003 | Ok((news, layout.shape().clone())) |
| 4004 | } |
| 4005 | } |
| 4006 | |
| 4007 | // ───────────────────────── fused RoPE (strided-view input) ───────────────────────── |
| 4008 | |
| 4009 | /// Apply RoPE (rotate-half / GPT-NeoX convention, == candle_nn::rotary_emb::rope) to |
| 4010 | /// a TRANSPOSED q/k view `[b, h, t, d]` WITHOUT first making it contiguous. The |
| 4011 | /// kernel reads the source through its real strides and writes a fresh contiguous |
| 4012 | /// `[b, h, t, d]` bf16 tensor, so candle's separate `.contiguous()` blit copy + the |
| 4013 | /// rope dispatch collapse into ONE pass. `x` must be bf16 on Metal; `cos`/`sin` are |
| 4014 | /// `[t, d/2]` contiguous bf16. Returns a contiguous bf16 tensor of the same shape. |
| 4015 | /// |
| 4016 | /// We build the encoder directly (binding all three source buffers) so candle's |
| 4017 | /// hazard tracker sees the real reads — there is no candle op that consumes a |
| 4018 | /// strided input here, hence a hand-rolled dispatch rather than a CustomOp. |
| 4019 | pub fn rope_apply(x: &Tensor, cos: &Tensor, sin: &Tensor) -> Result<Tensor> { |
| 4020 | use objc2_metal::MTLSize; |
| 4021 | let (b, h, t, d) = x.dims4()?; |
| 4022 | let device = x.device().clone(); |
| 4023 | let cdev = match &device { |
| 4024 | Device::Metal(m) => m.clone(), |
| 4025 | _ => return Err(anyhow!("rope_apply requires the Metal device")), |
| 4026 | }; |
| 4027 | let mdev = cdev.metal_device(); |
| 4028 | let pipes = get_pipelines(mdev)?; |
| 4029 | |
| 4030 | // Source buffer + per-dim strides (in ELEMENTS) of the (possibly transposed) view. |
| 4031 | let (x_s, x_l) = x.storage_and_layout(); |
| 4032 | let x_buf = match &*x_s { |
| 4033 | candle_core::Storage::Metal(ms) => ms.buffer().clone(), |
| 4034 | _ => return Err(anyhow!("rope_apply input must be on Metal")), |
| 4035 | }; |
| 4036 | if x.dtype() != DType::BF16 { |
| 4037 | return Err(anyhow!("rope_apply expects bf16 input, got {:?}", x.dtype())); |
| 4038 | } |
| 4039 | let st = x_l.stride(); // [s_b, s_h, s_t, s_d] |
| 4040 | if st.len() != 4 { |
| 4041 | return Err(anyhow!("rope_apply expects a 4D layout")); |
| 4042 | } |
| 4043 | let x_off = x_l.start_offset() * 2; // bf16 byte offset |
| 4044 | |
| 4045 | // cos/sin are required to ALREADY be contiguous bf16 [t, d/2] (the rope tables |
| 4046 | // are built bf16 at model load and only narrowed — a metadata view — per token). |
| 4047 | // We therefore consume them straight through their strides: NO per-call |
| 4048 | // `.to_dtype(bf16)` / `.contiguous()` prep. Those used to fire 2 throwaway |
| 4049 | // micro-dispatches each here, and rope_apply runs twice per layer (q and k), so |
| 4050 | // ~4×28 ≈ 112 cos/sin prep dispatches/token were pure pipeline-draining overhead |
| 4051 | // on a 64-element slice. (to_dtype/contiguous short-circuit to a clone when |
| 4052 | // already bf16/contiguous, but we drop them outright to keep the path tight and |
| 4053 | // assert the precondition instead.) |
| 4054 | debug_assert_eq!(cos.dtype(), DType::BF16, "rope cos must be bf16"); |
| 4055 | debug_assert_eq!(sin.dtype(), DType::BF16, "rope sin must be bf16"); |
| 4056 | debug_assert!(cos.is_contiguous(), "rope cos must be contiguous"); |
| 4057 | debug_assert!(sin.is_contiguous(), "rope sin must be contiguous"); |
| 4058 | let buf_of = |tns: &Tensor| -> Result<(Buffer, usize)> { |
| 4059 | let (s, l) = tns.storage_and_layout(); |
| 4060 | match &*s { |
| 4061 | candle_core::Storage::Metal(ms) => Ok((ms.buffer().clone(), l.start_offset() * 2)), |
| 4062 | _ => Err(anyhow!("rope_apply cos/sin must be on Metal")), |
| 4063 | } |
| 4064 | }; |
| 4065 | let (cos_buf, cos_off) = buf_of(cos)?; |
| 4066 | let (sin_buf, sin_off) = buf_of(sin)?; |
| 4067 | |
| 4068 | let out_elems = b * h * t * d; |
| 4069 | let out_buf = cdev.new_buffer(out_elems, DType::BF16, "tq_rope")?; |
| 4070 | |
| 4071 | let h_u = h as u32; |
| 4072 | let t_u = t as u32; |
| 4073 | let d_u = d as u32; |
| 4074 | // strides as i32x4 (sb, sh, st, sd). head_dim 128, ctx <= max_position → fits i32. |
| 4075 | let strides: [i32; 4] = [st[0] as i32, st[1] as i32, st[2] as i32, st[3] as i32]; |
| 4076 | { |
| 4077 | let enc = cdev.command_encoder()?; |
| 4078 | let ce: &ComputeCommandEncoder = enc.as_ref(); |
| 4079 | ce.set_compute_pipeline_state(&pipes.rope_bf16); |
| 4080 | ce.set_input_buffer(0, Some(&x_buf), x_off); |
| 4081 | ce.set_output_buffer(1, Some(out_buf.as_ref()), 0); |
| 4082 | ce.set_input_buffer(2, Some(&cos_buf), cos_off); |
| 4083 | ce.set_input_buffer(3, Some(&sin_buf), sin_off); |
| 4084 | ce.set_bytes(4, &h_u); |
| 4085 | ce.set_bytes(5, &t_u); |
| 4086 | ce.set_bytes(6, &d_u); |
| 4087 | ce.set_bytes_directly(7, std::mem::size_of_val(&strides), strides.as_ptr().cast()); |
| 4088 | // grid: (d/2, t, b*h) threads — one per (i_d<d/2, position, batch*head). |
| 4089 | let grid = MTLSize { width: d / 2, height: t, depth: b * h }; |
| 4090 | let tgroup = MTLSize { width: d / 2, height: 1, depth: 1 }; |
| 4091 | ce.dispatch_threads(grid, tgroup); |
| 4092 | } |
| 4093 | |
| 4094 | let storage = candle_core::MetalStorage::new(out_buf, cdev.clone(), out_elems, DType::BF16); |
| 4095 | let out = candle_core::Tensor::from_storage( |
| 4096 | candle_core::Storage::Metal(storage), |
| 4097 | Shape::from_dims(&[b, h, t, d]), |
| 4098 | candle_core::op::BackpropOp::none(), |
| 4099 | false, |
| 4100 | ); |
| 4101 | Ok(out) |
| 4102 | } |