metal: THE ENGINE GENERATES TOKENS ON THE MAC - 17 more kernels, the whole path runs

Official harness completes with no abort: /tmp/r.out = '0,0,0,0,', zero 'no Metal dispatch', zero metal errors.  Prompt 4 tokens in
5112 ms, decode 4 tokens in 18876 ms.  The ids look degenerate and numerical parity is NOT established - the Engram in this pack is
zeros, and a wrong kernel would produce the same output - so what is proven is that the engine walks the entire path and emits ids,
nothing more.

Kernels added (each verified by the engine's next abort naming a later or different launch):
  prompt expert GEMM: gate_up_kernel<T,NE>, down_kernel<T,NE>  (ds4_iq.metal, with IQ3_XXS type 18 joining the decoders - this
  pack mixes gate types 16/17 with down types 18/22)
  mx_combine, engram_dequant (fmt 2), engram_gate, bf16_mv (engram wkv), compress, index_score, topk (radix with simd_ballot),
  finish_kernel<true> (KV pack - the call site had no guard at all), finish rounding branch, gemv_f16_rows, block_max, hc_mean,
  iota_rows, sampler_greedy  (ds4_init.metal, 1521 lines)
  mx_wait skipped under STRATA_METAL, like the pre-existing wait_seq no-op

Also fixed a real pre-existing bug: the 'payload + 65536 from the page base' wrap convention walked off the mapping when a small
buffer sat at an arena chunk's edge (flaky 'mtl: wrap 81920/98304 failed', exit 4, 2 runs in 4).  ds4_finish.cpp now wraps exactly
the pages a buffer spans.

Not ported: sampler_kernel<0> (the sampled path; the harness is greedy), engram fmt 0/1 (this pack is fmt 2), bf16_mv's non-vector
variant.  Expert types beyond 16/17/18/22 make the IQ kernels return false, so the CUDA launch names the line instead of a silent pass.
This commit is contained in:
Niko1221 committed 2026-10-24 01:51:31 +02:00
1 parent 154c2990ed
commit 33bf441cd4
8 files changed
+2940 -65

No files matched your search

+63 -27
View File
@@ -1,8 +1,7 @@
// metal/include/metal_compat/ds4_metal_host.h - the dsv41 kernels that have a Metal dispatch, as the engine calls them.
// metal/include/metal_compat/ds4_metal_host.h - the dsv41 kernels that have a Metal dispatch.
//
// A launch site in the shared dsv41 sources becomes, under STRATA_METAL, a call to one of these instead of the generic
// strata_ds4_launch() stub. Each implementation wraps the engine's own device buffers into the Metal runtime and dispatches
// the MSL kernel of the same name; metal/src/engine/ds4_host.cpp holds them.
// GENERATED from metal/src/engine/ds4_host.cpp and ds4_finish.cpp, which are the source of truth: do not hand-edit the
// declaration block, regenerate it (see RIGS/m1002.md).
#pragma once
#include <cstddef>
@@ -16,11 +15,7 @@ using Stream = StreamImpl*;
namespace strata::dsv41::metal_host {
// ds4_kernels.cu:1477 init_pre_kernel: pre[i] = (i % 8) == 0 ? 1 : 0, i < T*8
bool init_pre(float* pre, int T, void* stream);
// ds4_kernels.cu:130 embed_kernel: h[(t*hc + s)*dim + e] = bf16(rows[t*dim + e])
// ds4_model.cu:2737 cublasSgemm(OP_T, OP_N, ...): C[t][m] = sum_k A[m][k] * B[t][k], F32, alpha 1, beta 0
// ds4_kernels.cu:1894 finish_kernel<false>, the engine's Finish as ds4_kernels.cuh declares it
// ds4_kernels.cu:1894 finish_kernel<false> - the engine's Finish, as ds4_kernels.cuh declares it
struct FinishIn {
const float* w;
float eps;
@@ -32,26 +27,67 @@ struct FinishIn {
uint8_t* pdst;
long long pdst_stride;
};
// ds4_kernels.cu:1938 moe_sort: counts, prefix, fill
bool moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds, int* row_tok, int* pos);
// ds4_kernels.cu:1908 hc_split (the sinkhorn normalisation)
bool hc_split(const float* mixes, const float* scale, const float* base, int hc, int iters, float hc_eps, int T,
float* pre, float* post, float* comb);
// ds4_kernels.cu:1901 hc_mix
bool hc_mix(const float* h, const float* fn, int hcdim, int n_mix, int T, float eps, float* mixes);
// ds4_kernels.cu:1692 hc_mix_scale
bool hc_mix_scale(const float* h, int hcdim, int n_mix, int T, float eps, float* mixes);
// ds4_kernels.cu:1677 hc_post_inplace
bool hc_post(const float* y, float* h, const float* post, const float* comb, int dim, int hc, int T);
bool embed(const uint16_t* rows, int T, float* h, int dim, int hc, void*);
bool engram_dequant_tok(const uint8_t* src, size_t per, int cols, int T, int hd, float* out, int fmt);
bool ext_to_ring(const void* ext, void* ring, long long p0, int n, int T, int d, size_t row_bytes, void* backup);
bool finish(float* x, int n_vec, int len, long long stride, const FinishIn& f);
bool gemv_f32(const float* W, const float* x, int n, int k, int T, float* y, int ldy);
bool hc_mix(const float* h, const float* fn, int hcdim, int n_mix, int T, float eps, float* mixes);
bool hc_mix_scale(const float* h, int hcdim, int n_mix, int T, float eps, float* mixes);
bool hc_post(const float* y, float* h, const float* post, const float* comb, int dim, int hc, int T);
bool hc_post_v(const float* y, const float* res, const float* post, const float* comb, int dim, int hc, int T, float* out);
bool hc_pre_norm(const float* h, const float* mix, const float* w, int dim, int hc, int T, float eps, float* x);
bool hc_split(const float* mixes, const float* scale, const float* base, int hc, int iters, float hc_eps, int T, float* pre, float* post, float* comb);
bool init_pre(float* pre, int T, void*);
bool iq_mv(const void* jobs, int nj);
bool moe_combine(void* acc, const void* y, const int* pos, const float* w_, int T, int k, int r0, int r1, int dim);
bool moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds, int* row_tok, int* pos);
bool moe_win_group_cpu(const void* plan_ptr, void* grp_ptr, void* grp_start, void* grp_ent, void* n_groups, int T, int k);
bool mx_mv(const void* jobs, int nj, int max_n, size_t job_bytes, int fmt);
bool q8_quant_rows(const float* x, size_t ldx, int rows, int k, int8_t* q, float* d);
bool ring_to_ext(const void* ring, void* ext, long long p0, int n, int d, size_t row_bytes);
bool route_publish(const float* logits, const float* bias, int n, int k, int T, float route_scale, const void* vram, int* idx, float* w, void* plan_ptr, const float* bias_vl, unsigned vl);
bool sgemm_tn(const float* A, const float* B, float* C, int m, int nt, int k, int lda, int ldb, int ldc);
bool swiglu(const float* g, const float* u, int n, float lim, float* h);
bool unpack_sel(const void* ckv, const int* sel, int sel_stride, int gen, long long p0, int t0, int R, int kcap, const int* nsel, int cap, void* out, int T, int nsel_count, size_t row_bytes);
bool embed(const uint16_t* rows, int T, float* h, int dim, int hc, void* stream);
// the entry points, as metal/src/engine/ds4_finish.cpp defines them
bool block_max(const float* score, long long stride, int T, const void* rows, int blk, float* bm, long long bm_stride, int nb_max);
bool compress_win(const float* kv, const float* score, float* kv_state, float* score_state, int ratio, int p0, int T, int d, const float* w, float eps, float* latent);
bool embed(const uint16_t* rows, int T, float* h, int dim, int hc, void*);
bool engram_dequant(const uint8_t* rows, const uint8_t* scales, int n, int hd, float* out, int fmt);
bool engram_dequant_tok(const uint8_t* src, size_t per, int cols, int T, int hd, float* out, int fmt);
bool engram_gate(float* h, const float* kv, const float* w, int hc, int dim, int T, float eps);
bool ext_to_ring(const void* ext, void* ring, long long p0, int n, int T, int d, size_t row_bytes, void* backup);
bool finish(float* x, int n_vec, int len, long long stride, const FinishIn& f);
bool gemv_f16_rows(const uint16_t* W, const float* x, size_t ldx, int n, int k, int T, float alpha, float* y, size_t ldy);
bool gemv_f32(const float* W, const float* x, int n, int k, int T, float* y, int ldy);
bool hc_mean(const float* h, int T, int hc, int dim, float* out, long long out_stride);
bool hc_mix(const float* h, const float* fn, int hcdim, int n_mix, int T, float eps, float* mixes);
bool hc_mix_scale(const float* h, int hcdim, int n_mix, int T, float eps, float* mixes);
bool hc_post(const float* y, float* h, const float* post, const float* comb, int dim, int hc, int T);
bool hc_post_v(const float* y, const float* res, const float* post, const float* comb, int dim, int hc, int T, float* out);
bool hc_pre_norm(const float* h, const float* mix, const float* w, int dim, int hc, int T, float eps, float* x);
bool hc_split(const float* mixes, const float* scale, const float* base, int hc, int iters, float hc_eps, int T, float* pre, float* post, float* comb);
bool index_score(const float* q, const float* wq, const void* kc, int heads, int hd, int T, int n, const int* cand, int cand_stride, int blk, const void* rows, float* out, long long out_stride, int kfmt);
bool init_pre(float* pre, int T, void*);
bool iota_rows(int* out, int T, int n, int stride);
bool iq_dn(const unsigned long long* plan_ptr, const unsigned long long* grp_ptr, const int* grp_start, const int* grp_ent, const int* n_groups, const size_t* tr, int n_embd, int n_ff, const int8_t* hq, const float* hd, float* part, int type, int groups);
bool iq_gu(const unsigned long long* plan_ptr, const unsigned long long* grp_ptr, const int* grp_start, const int* grp_ent, const int* n_groups, const size_t* tr, int n_embd, int n_ff, float limit, const int8_t* xq, const float* xd, float* h, int type, int groups);
bool iq_mv(const void* jobs, int nj);
bool moe_combine(void* acc, const void* y, const int* pos, const float* w_, int T, int k, int r0, int r1, int dim);
bool moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds, int* row_tok, int* pos);
bool moe_win_group_cpu(const void* plan_ptr, void* grp_ptr, void* grp_start, void* grp_ent, void* n_groups, int T, int k);
bool mx_combine(const void* plan_ptr, const void* plan_w, const void* part, const void* cpu_part, size_t cpu_stride, const int* cpu_flag, const void* sh_out, void* out, size_t out_stride, int T, int k, int n_embd);
bool mx_mv(const void* jobs, int nj, int max_n, size_t job_bytes, int fmt);
bool q8_quant_rows(const float* x, size_t ldx, int rows, int k, int8_t* q, float* d);
bool ring_to_ext(const void* ring, void* ext, long long p0, int n, int d, size_t row_bytes);
bool route_publish(const float* logits, const float* bias, int n, int k, int T, float route_scale, const void* vram, int* idx, float* w, void* plan_ptr, const float* bias_vl, unsigned vl);
bool sample_greedy(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len, int penalty_last_n, float penalty_repeat, float penalty_freq, float penalty_present, const float* logit_bias, int* out);
bool sgemm_tn(const float* A, const float* B, float* C, int m, int nt, int k, int lda, int ldb, int ldc);
bool swiglu(const float* g, const float* u, int n, float lim, float* h);
bool topk(const float* vals, long long stride, int T, const void* rows, const int* cand, int cand_stride, int blk, int* out, int out_stride);
bool unpack_sel(const void* ckv, const int* sel, int sel_stride, int gen, long long p0, int t0, int R, int kcap, const int* nsel, int cap, void* out, int T, int nsel_count, size_t row_bytes);
} // namespace strata::dsv41::metal_host
} // namespace strata::dsv41::metal_host
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+361
View File
@@ -0,0 +1,361 @@
#include <metal_stdlib>
using namespace metal;
// ds4_iq.cu:809 mv_kernel - the I-quant expert matvec. Same frame as the MXFP4/Q8_0 ones (a warp a row, a lane strides the
// 256-value blocks, eight accumulator columns for the token window), with the block decoder chosen per job by b.type:
// 16 IQ2_XXS (66 B), 17 IQ2_XS (74 B), 22 IQ2_S (82 B). The activations are the quantiser's int8 (xq) with their scales (xd),
// so each sub-group's dot is integer and the two scales fold in at the end - the same arithmetic as the float probes, at a
// quarter of the traffic.
struct Ds4MvJob {
device const uchar* w;
ulong ld;
int type, k, n, ncol;
device const char* xq;
device const float* xd;
device float* y;
ulong ycs;
device const float* bias;
float alpha;
};
kernel void ds4_iq_mv(device const uchar* jobs [[buffer(0)]], uint2 tgp [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
const device Ds4MvJob& b = *(const device Ds4MvJob*) (jobs + (size_t) tgp.y * sizeof(Ds4MvJob));
const uint row = tgp.x * 8u + (tid >> 5);
if (int(row) >= b.n) return;
const uint nsb = uint(b.k) / 32u;
const uint nblk = uint(b.k) / 256u;
const uint bs = b.type == 16 ? 66u : (b.type == 17 ? 74u : 82u);
const device uchar* w = b.w + (size_t) row * b.ld;
float acc[8];
for (uint c = 0; c < 8u; ++c) acc[c] = 0.0f;
for (uint blk = lane; blk < nblk; blk += 32u) {
const device uchar* p = w + (size_t) blk * bs;
const float d = float(as_type<half>(*(const device ushort*) p));
for (uint ib = 0; ib < 8u; ++ib) {
float db0, db1;
uint idx[4];
uint sg[4];
if (b.type == 16) {
const uint aux0 = uint(p[2 + 4 * ib]) | (uint(p[3 + 4 * ib]) << 8) | (uint(p[4 + 4 * ib]) << 16) |
(uint(p[5 + 4 * ib]) << 24);
const uint aux1 = uint(p[6 + 4 * ib]) | (uint(p[7 + 4 * ib]) << 8) | (uint(p[8 + 4 * ib]) << 16) |
(uint(p[9 + 4 * ib]) << 24);
const float db = d * (0.5f + float(aux1 >> 28)) * 0.25f;
db0 = db1 = db;
for (uint l = 0; l < 4u; ++l) {
idx[l] = (aux0 >> (8u * l)) & 0xffu;
sg[l] = uint(ksigns_iq2xs[(aux1 >> (7u * l)) & 127u]);
}
} else if (b.type == 17) {
const device ushort* qs = (const device ushort*) (p + 2);
const device uchar* sc = p + 66;
db0 = d * (0.5f + float(sc[ib] & 0xfu)) * 0.25f;
db1 = d * (0.5f + float(sc[ib] >> 4)) * 0.25f;
for (uint l = 0; l < 4u; ++l) {
const uint q = uint(qs[4u * ib + l]);
idx[l] = q & 511u;
sg[l] = 0xffffffffu ^ ((q >> 9) * 0x00204081u); // the 7 sign bits, expanded (ggml's sign trick)
}
} else {
const device uchar* qs = p + 2;
const device uchar* sgb = qs + 32;
const device uchar* qh = p + 66;
const device uchar* sc = p + 74;
db0 = d * (0.5f + float(sc[ib] & 0xfu)) * 0.25f;
db1 = d * (0.5f + float(sc[ib] >> 4)) * 0.25f;
for (uint l = 0; l < 4u; ++l) {
idx[l] = uint(qs[4u * ib + l]) | ((uint(qh[ib]) << (8u - 2u * l)) & 0x300u);
sg[l] = uint(sgb[4u * ib + l]);
}
}
for (uint l = 0; l < 4u; ++l) {
ulong g;
if (b.type == 16) g = iq2xxs_grid[idx[l]];
else if (b.type == 17) g = iq2xs_grid[idx[l]];
else g = iq2s_grid[idx[l] & 1023u];
const float db = (l < 2u) ? db0 : db1;
const uint off = (size_t) blk * 256u + ib * 32u + l * 8u;
for (uint c = 0; c < 8u; ++c) {
if (int(c) >= b.ncol) break;
const device char* xq = b.xq + (size_t) c * b.k + off;
int sum = 0;
for (uint j = 0; j < 8u; ++j) {
const int code = int((g >> (8u * j)) & 0xffu);
const bool neg = b.type == 16 ? ((sg[l] & uint(kmask_iq2xs[j])) != 0u)
: ((sg[l] & (1u << j)) != 0u);
sum += (neg ? -code : code) * int(xq[j]);
}
acc[c] = fma(b.xd[(size_t) c * nsb + (off / 32u)] * db, float(sum), acc[c]);
}
}
}
}
for (uint c = 0; c < 8u; ++c) {
if (int(c) >= b.ncol) break;
float v = acc[c];
v += simd_shuffle_xor(v, 16);
v += simd_shuffle_xor(v, 8);
v += simd_shuffle_xor(v, 4);
v += simd_shuffle_xor(v, 2);
v += simd_shuffle_xor(v, 1);
if (lane == 0u) b.y[(size_t) c * b.ycs + row] = b.alpha * v + (b.bias != nullptr ? b.bias[row] : 0.0f);
}
}
// ---------------------------------------------------------------- ds4_iq.cu:536 gate_up_kernel / :588 down_kernel
//
// The prompt / window path's expert GEMM (ds4_iq.cu's launch_gu / launch_dn): a threadgroup of 256 = 8 warps, a warp
// RW rows of the gate and of the up (down: RW rows of the down), a lane 32 / RW sub-blocks of the row, and the group's
// entries NE at a pass so that a sub-block the weights decode once serves them all. Grid (rows / (8 RW), groups).
//
// The group's blob and its entries are the CUDA kernel's `group` (ds4_iq.cu:512): a plan group (grp_ptr null) is one
// expert whose entry is the group's own index and whose activation row is 0, a window group's entries come from
// grp_ent[grp_start[g] .. grp_start[g + 1]) and an entry e's activation row is e >> 3.
struct Ds4IqJob {
device const ulong* plan_ptr; // plan_ptr[g]: the expert's blob (0: the group is skipped)
device const ulong* grp_ptr; // grp_ptr[g]: a window set's blob
device const int* grp_start; // a set's first entry (n_groups + 1 of them)
device const int* grp_ent; // the entries (token * 8 + pick)
device const int* n_groups;
device const char* xq; // the int8 activations of a row (n_embd an entry)
device const float* xd; // their scales (n_embd / 32 a row)
device const char* hq; // down's int8 input (n_ff an entry)
device const float* hd;
device float* h; // [entries][n_ff]: the clamped swiglu
device float* part; // [entries][n_embd]: each entry's down output
long tr0, tr1, tr2; // the roles' offsets in a blob
int n_embd, n_ff;
int type; // 16 IQ2_XXS, 17 IQ2_XS, 22 IQ2_S (ds4_iq.cuh's kIQ2_*)
float limit; // swiglu_limit (0: none)
};
// a 32-value sub-block as 32 int8 codes (8 packed ints, values 4 w .. 4 w + 3 in word w) and the two halves' scales
// (ggml's d (2 s + 1) / 8, the .cu's Sub.d * Sub.s0 in one F32: the codes of the second half are scaled by s1)
struct Ds4IqSub {
int q[8];
float s0, s1;
};
// the block bytes of the types these kernels take: 16 IQ2_XXS, 17 IQ2_XS, 18 IQ3_XXS, 22 IQ2_S (ds4_iq.cu's Ty<T>::B)
static inline uint ds4_iq_bs(int type) {
return type == 16 ? 66u : type == 17 ? 74u : type == 18 ? 98u : 82u;
}
// ds4_iq.cu:139 decode<T>: the block's 8 sub-blocks, kb's is the (kb & 7)'th; the grids are ggml-common.h's
static inline Ds4IqSub ds4_iq_sub(device const uchar* row, uint bs, int kb, int type) {
Ds4IqSub s;
const int ib = kb & 7;
const device uchar* p = row + (size_t) (kb >> 3) * bs;
const float d = float(as_type<half>(*(const device ushort*) p));
uint idx[4], sm[4];
float db0, db1;
if (type == 18) { // IQ3_XXS: d, qs[64] grid bytes (4 a sub-block), scales[8] (the top nibble the group's s)
const device uchar* qs = p + 2;
const uint w0 = uint(qs[8 * ib]) | (uint(qs[8 * ib + 1]) << 8) | (uint(qs[8 * ib + 2]) << 16) |
(uint(qs[8 * ib + 3]) << 24);
const uint w1 = uint(qs[8 * ib + 4]) | (uint(qs[8 * ib + 5]) << 8) | (uint(qs[8 * ib + 6]) << 16) |
(uint(qs[8 * ib + 7]) << 24);
const uint aux = uint(qs[64 + 4 * ib]) | (uint(qs[65 + 4 * ib]) << 8) | (uint(qs[66 + 4 * ib]) << 16) |
(uint(qs[67 + 4 * ib]) << 24);
for (uint l = 0; l < 4u; ++l) {
const uint w = l < 2u ? w0 : w1, sh = 16u * (l & 1u);
const uint sg = uint(ksigns_iq2xs[(aux >> (7u * l)) & 127u]);
const uint g0 = iq3xxs_grid[(w >> sh) & 255u], g1 = iq3xxs_grid[(w >> (sh + 8u)) & 255u];
int a0 = 0, a1 = 0;
for (uint j = 0; j < 4u; ++j) {
int v0 = int((g0 >> (8u * j)) & 0xffu), v1 = int((g1 >> (8u * j)) & 0xffu);
if ((sg & (1u << j)) != 0u) v0 = -v0;
if ((sg & (1u << (j + 4u))) != 0u) v1 = -v1;
a0 |= (v0 & 0xff) << int(8u * j);
a1 |= (v1 & 0xff) << int(8u * j);
}
s.q[2u * l] = a0;
s.q[2u * l + 1u] = a1;
}
const float ds = d * (0.5f + float(aux >> 28)) * 0.5f; // ggml's db: d (0.5 + s) 0.5
s.s0 = ds;
s.s1 = ds;
return s;
}
if (type == 16) { // d, qs[8] i16 (4 grid bytes, then 4 sign/scale bytes), scales in the top nibbles
const uint aux0 = uint(p[2 + 8 * ib]) | (uint(p[3 + 8 * ib]) << 8) | (uint(p[4 + 8 * ib]) << 16) |
(uint(p[5 + 8 * ib]) << 24);
const uint aux1 = uint(p[6 + 8 * ib]) | (uint(p[7 + 8 * ib]) << 8) | (uint(p[8 + 8 * ib]) << 16) |
(uint(p[9 + 8 * ib]) << 24);
const float db = d * (0.5f + float(aux1 >> 28)) * 0.25f;
db0 = db1 = db;
for (uint l = 0; l < 4u; ++l) {
idx[l] = (aux0 >> (8u * l)) & 0xffu;
sm[l] = uint(ksigns_iq2xs[(aux1 >> (7u * l)) & 127u]);
}
} else if (type == 17) { // d, qs[16] i16 (9-bit grid, 7 sign bits), scales[8] (two 4-bit)
const device ushort* qs = (const device ushort*) (p + 2);
const device uchar* sc = p + 66;
db0 = d * (0.5f + float(sc[ib] & 0x0fu)) * 0.25f;
db1 = d * (0.5f + float(sc[ib] >> 4)) * 0.25f;
for (uint l = 0; l < 4u; ++l) {
const uint q = uint(qs[4u * uint(ib) + l]);
idx[l] = q & 511u;
sm[l] = uint(ksigns_iq2xs[(q >> 9) & 127u]);
}
} else { // IQ2_S: d, qs[32] (8-bit grid), signs[32], qh[8] (2 bits more), scales[8]
const device uchar* qs = p + 2;
const device uchar* sgb = qs + 32;
const device uchar* qh = p + 66;
const device uchar* sc = p + 74;
db0 = d * (0.5f + float(sc[ib] & 0x0fu)) * 0.25f;
db1 = d * (0.5f + float(sc[ib] >> 4)) * 0.25f;
for (uint l = 0; l < 4u; ++l) {
idx[l] = uint(qs[4u * uint(ib) + l]) | ((uint(qh[ib]) << (8u - 2u * l)) & 0x300u);
sm[l] = uint(sgb[4u * uint(ib) + l]);
}
}
for (uint l = 0; l < 4u; ++l) {
const ulong g = type == 16 ? iq2xxs_grid[idx[l]] : (type == 17 ? iq2xs_grid[idx[l]] : iq2s_grid[idx[l] & 1023u]);
int w0 = 0, w1 = 0;
for (uint j = 0; j < 4u; ++j) {
int v0 = int((g >> (8u * j)) & 0xffu), v1 = int((g >> (8u * (j + 4u))) & 0xffu);
if ((sm[l] & (1u << j)) != 0u) v0 = -v0;
if ((sm[l] & (1u << (j + 4u))) != 0u) v1 = -v1;
w0 |= (v0 & 0xff) << int(8u * j);
w1 |= (v1 & 0xff) << int(8u * j);
}
s.q[2u * l] = w0;
s.q[2u * l + 1u] = w1;
}
s.s0 = db0;
s.s1 = db1;
return s;
}
// 4 int8 codes against the 4 int8 activations packed in x (ds4_iq.cu:350's __dp4a: Metal has no such instruction)
static inline int ds4_iq_dot4(int q, int x) {
const char4 a = as_type<char4>(q), b = as_type<char4>(x);
return int(a.x) * int(b.x) + int(a.y) * int(b.y) + int(a.z) * int(b.z) + int(a.w) * int(b.w);
}
// ds4_iq.cu:349 sub_dot: the sub-block against its 32 int8 activations (8 packed ints), the scales in F32
static inline float ds4_iq_dot(Ds4IqSub s, device const int* xp) {
const int lo = ds4_iq_dot4(s.q[0], xp[0]) + ds4_iq_dot4(s.q[1], xp[1]) + ds4_iq_dot4(s.q[2], xp[2]) +
ds4_iq_dot4(s.q[3], xp[3]);
const int hi = ds4_iq_dot4(s.q[4], xp[4]) + ds4_iq_dot4(s.q[5], xp[5]) + ds4_iq_dot4(s.q[6], xp[6]) +
ds4_iq_dot4(s.q[7], xp[7]);
return s.s0 * float(lo) + s.s1 * float(hi);
}
// ds4_iq.cu:502 lanes_sum: the row's sum over the 32 / RW lanes that share it
template <int RW>
static inline float ds4_iq_lsum(float v) {
for (int o = 16 / RW; o > 0; o >>= 1) v += simd_shuffle_xor(v, ushort(o));
return v;
}
// ds4_iq.cu:497 swiglu: the limit's clamps, then g / (1 + e^-g) * u
static inline float ds4_iq_swiglu(float gv, float uv, float limit) {
if (limit > 0.0f) {
gv = min(gv, limit);
uv = min(max(uv, -limit), limit);
}
return (gv / (1.0f + exp(-gv))) * uv;
}
// the group's blob and its entry range (ds4_iq.cu:512 group); false: the threadgroup has nothing to do
static inline bool ds4_iq_group(constant Ds4IqJob& j, uint g, thread ulong& blob, thread int& m0, thread int& m1) {
if (j.grp_ptr == nullptr) {
const ulong p = j.plan_ptr[g];
if (p == 0ul) return false;
blob = p;
m0 = int(g);
m1 = m0 + 1;
return true;
}
if (int(g) >= *j.n_groups) return false;
blob = j.grp_ptr[g];
m0 = j.grp_start[g];
m1 = j.grp_start[g + 1];
return true;
}
// gate_up_kernel<T, NE> (kGuRW = 1: a warp a row, a lane a sub-block): h = the clamped swiglu of the gate and the up
kernel void ds4_iq_gu(constant Ds4IqJob& j [[buffer(0)]], uint2 tgp [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
ulong blob;
int m0, m1;
if (!ds4_iq_group(j, tgp.y, blob, m0, m1)) return;
const int row = int(tgp.x) * 8 + int(tid >> 5);
if (row >= j.n_ff) return;
const uint bs = ds4_iq_bs(j.type);
const uint nsb = uint(j.n_embd) / 32u;
const size_t rb = (size_t) (j.n_embd / 256) * (size_t) bs;
const device uchar* g = (const device uchar*) blob + (size_t) j.tr0 + (size_t) row * rb;
const device uchar* u = (const device uchar*) blob + (size_t) j.tr1 + (size_t) row * rb;
for (int mm = m0; mm < m1; mm += 4) {
const int ne = min(4, m1 - mm);
int es[4], xr[4];
for (int i = 0; i < 4; ++i) {
if (i < ne) {
const int e = j.grp_ptr == nullptr ? (mm + i) : j.grp_ent[mm + i];
es[i] = e;
xr[i] = j.grp_ptr == nullptr ? 0 : (e >> 3);
}
}
float ag[4] = {0.0f, 0.0f, 0.0f, 0.0f}, au[4] = {0.0f, 0.0f, 0.0f, 0.0f};
for (uint kb = uint(lane); kb < nsb; kb += 32u) {
const Ds4IqSub sg = ds4_iq_sub(g, bs, int(kb), j.type);
const Ds4IqSub su = ds4_iq_sub(u, bs, int(kb), j.type);
for (int i = 0; i < 4; ++i) {
if (i < ne) {
const device int* xp = (const device int*) (j.xq + (size_t) xr[i] * (size_t) j.n_embd +
(size_t) kb * 32u);
const float dx = j.xd[(size_t) xr[i] * nsb + kb];
ag[i] += dx * ds4_iq_dot(sg, xp);
au[i] += dx * ds4_iq_dot(su, xp);
}
}
}
for (int i = 0; i < 4; ++i) {
if (i < ne) {
const float gv = ds4_iq_lsum<1>(ag[i]), uv = ds4_iq_lsum<1>(au[i]);
if (lane == 0u) j.h[(size_t) es[i] * (size_t) j.n_ff + (size_t) row] = ds4_iq_swiglu(gv, uv, j.limit);
}
}
}
}
// down_kernel<T, NE> (kDnRW = 2: a warp two rows, 16 lanes a row): part = the down against the int8 h
kernel void ds4_iq_dn(constant Ds4IqJob& j [[buffer(0)]], uint2 tgp [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
ulong blob;
int m0, m1;
if (!ds4_iq_group(j, tgp.y, blob, m0, m1)) return;
const int row = (int(tgp.x) * 8 + int(tid >> 5)) * 2 + int(lane) / 16;
if (row >= j.n_embd) return;
const uint kl = uint(lane) % 16u;
const uint bs = ds4_iq_bs(j.type);
const uint nsb = uint(j.n_ff) / 32u;
const size_t rb = (size_t) (j.n_ff / 256) * (size_t) bs;
const device uchar* w = (const device uchar*) blob + (size_t) j.tr2 + (size_t) row * rb;
for (int mm = m0; mm < m1; mm += 4) {
const int ne = min(4, m1 - mm);
int es[4];
for (int i = 0; i < 4; ++i)
if (i < ne) es[i] = j.grp_ptr == nullptr ? (mm + i) : j.grp_ent[mm + i];
float ad[4] = {0.0f, 0.0f, 0.0f, 0.0f};
for (uint kb = kl; kb < nsb; kb += 16u) {
const Ds4IqSub sd = ds4_iq_sub(w, bs, int(kb), j.type);
for (int i = 0; i < 4; ++i) {
if (i < ne) {
const device int* hp = (const device int*) (j.hq + (size_t) es[i] * (size_t) j.n_ff +
(size_t) kb * 32u);
ad[i] += j.hd[(size_t) es[i] * nsb + kb] * ds4_iq_dot(sd, hp);
}
}
}
for (int i = 0; i < 4; ++i) {
if (i < ne) {
const float v = ds4_iq_lsum<2>(ad[i]);
if (kl == 0u) j.part[(size_t) es[i] * (size_t) j.n_embd + (size_t) row] = v;
}
}
}
}
+32
View File
@@ -2,6 +2,9 @@
// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
// src/ds4/ds4_gguf.cu - a GGUF's BF16 matrices and MXFP4 experts on the device (see ds4_gguf.cuh).
#include "ds4_gguf.cuh"
#if defined(STRATA_METAL)
#include <ds4_metal_host.h>
#endif
#include "ds4_iq.cuh"
#include "ds4_numerics.cuh"
@@ -198,6 +201,9 @@ __global__ void __launch_bounds__(kThreads) q8_quant_kernel(const float* __restr
}
void q8_quant(const float* x, size_t ldx, int rows, int k, int8_t* q, float* d, cudaStream_t s) {
const dim3 grid((unsigned) ((k / 32 + kWarps - 1) / kWarps), (unsigned) rows);
#if defined(STRATA_METAL)
if (::strata::dsv41::metal_host::q8_quant_rows(x, ldx, rows, k, (int8_t*) q, d)) return;
#endif
strata_ds4_launch(q8_quant_kernel, grid, kThreads, 0, s, x, ldx, k, q, d);
}
@@ -1040,12 +1046,26 @@ template <int NC>
void mv_launch(int f, const BfJobs& J, int nj, int max_n, bool vec, cudaStream_t s) {
const dim3 grid((unsigned) ((max_n + kWarps - 1) / kWarps), (unsigned) nj);
if (f == 1) {
#if defined(STRATA_METAL)
// the MXFP4 matvec: the engine's jobs go across as they are (same layout on both sides)
if (max_n > 0 && nj > 0 &&
::strata::dsv41::metal_host::mx_mv((const void*) &J, nj, max_n, sizeof(BfJob), 1)) return;
#endif
if (vec) strata_ds4_launch(mx_mv_kernel<NC, true, false>, grid, kThreads, 0, s, J);
else strata_ds4_launch(mx_mv_kernel<NC, false, false>, grid, kThreads, 0, s, J);
} else if (f == 2) { // (vec here: every row 4-byte aligned, so staged)
#if defined(STRATA_METAL)
if (max_n > 0 && nj > 0 &&
::strata::dsv41::metal_host::mx_mv((const void*) &J, nj, max_n, sizeof(BfJob), 2)) return;
#endif
if (vec) strata_ds4_launch(q8_mv_kernel<NC, true>, grid, kThreads, 0, s, J);
else strata_ds4_launch(q8_mv_kernel<NC, false>, grid, kThreads, 0, s, J);
} else {
#if defined(STRATA_METAL)
// the BF16 matvec (vec: the rows and activations 16-byte aligned, so the 8-value step is safe)
if (vec && max_n > 0 && nj > 0 &&
::strata::dsv41::metal_host::mx_mv((const void*) &J, nj, max_n, sizeof(BfJob), 0)) return;
#endif
if (vec) strata_ds4_launch(bf16_mv_kernel<NC, true>, grid, kThreads, 0, s, J);
else strata_ds4_launch(bf16_mv_kernel<NC, false>, grid, kThreads, 0, s, J);
}
@@ -1265,6 +1285,10 @@ void moe_down(const x3::MoeArgs& a, const float* h, const float* sh_out, float*
c.out_stride = (size_t) a.n_embd;
c.k = a.k;
c.n_embd = a.n_embd;
#if defined(STRATA_METAL)
if (!::strata::dsv41::metal_host::mx_combine(c.plan_ptr, c.plan_w, c.part, c.cpu_part, c.cpu_stride,
c.cpu_flag, c.sh_out, c.out, c.out_stride, 1, c.k, c.n_embd))
#endif
strata_ds4_launch(mx_combine_kernel, dim3((unsigned) ((a.n_embd + 127) / 128), 1), 128, 0, s, c);
check("moe_down");
}
@@ -1312,7 +1336,10 @@ bool win_experts(const x3::WinArgs& a, cudaStream_t s) {
q8_quant(a.h, (size_t) a.n_ff, a.T * 8, a.n_ff, sc->hq, sc->hd, s); // (rows of picks not on the device: unused)
if (mx) launch_groups<DownK>(m, a.n_embd, groups, a.T, s);
else iq::down(ia, groups, a.T, s);
#if !defined(STRATA_METAL)
// (this port's dispatches are synchronous and nothing is published to wait for: ds4_kernels.cu's wait_seq)
if (a.wait_ptr != nullptr) strata_ds4_launch(mx_wait_kernel, 1, 32, 0, s, a.wait_ptr, a.wait_val);
#endif
CombArgs c{};
c.plan_ptr = a.plan_ptr;
c.plan_w = a.plan_w;
@@ -1325,6 +1352,11 @@ bool win_experts(const x3::WinArgs& a, cudaStream_t s) {
c.out_stride = a.out_stride;
c.k = a.k;
c.n_embd = a.n_embd;
#if defined(STRATA_METAL)
// mx_combine_kernel on the Metal dispatch; the launch below is the fallback
if (!::strata::dsv41::metal_host::mx_combine(c.plan_ptr, c.plan_w, c.part, c.cpu_part, c.cpu_stride,
c.cpu_flag, c.sh_out, c.out, c.out_stride, a.T, c.k, c.n_embd))
#endif
strata_ds4_launch(mx_combine_kernel, dim3((unsigned) ((a.n_embd + 127) / 128), (unsigned) a.T), 128, 0, s, c);
check("win_experts");
return true;
+18
View File
@@ -3,6 +3,9 @@
// src/ds4/ds4_iq.cu - a GGUF's low-bit routed experts on the device (see ds4_iq.cuh). The block layouts and grids are
// ggml's (ggml-common.h, MIT, third_party/ggml/LICENSE); the sign and grid tricks are llama.cpp's vecdotq.cuh.
#include "ds4_iq.cuh"
#if defined(STRATA_METAL)
#include <ds4_metal_host.h>
#endif
#include "ds4_numerics.cuh"
#include <cuda_fp16.h>
@@ -1179,6 +1182,12 @@ const char* name(int t) {
}
bool gate_up(const Args& a, int groups, int ne_max, cudaStream_t s) {
#if defined(STRATA_METAL)
// gate_up_kernel on the Metal dispatch (the prompt / window path's expert GEMM); the launch below is the fallback
if (::strata::dsv41::metal_host::iq_gu(a.plan_ptr, a.grp_ptr, a.grp_start, a.grp_ent, a.n_groups, a.tr, a.n_embd,
a.n_ff, a.limit, a.xq, a.xd, a.h, a.tg, groups))
return true;
#endif
if (is_tq(a.tg)) return tq::gate_up(a, groups, ne_max, s);
if (a.n_embd % 256 != 0 || a.n_ff % (kWarps * kGuRW) != 0) return false;
const dim3 grid((unsigned) (a.n_ff / (kWarps * kGuRW)), (unsigned) groups);
@@ -1189,6 +1198,12 @@ bool gate_up(const Args& a, int groups, int ne_max, cudaStream_t s) {
}
bool down(const Args& a, int groups, int ne_max, cudaStream_t s) {
#if defined(STRATA_METAL)
// down_kernel on the Metal dispatch; the launch below is the fallback
if (::strata::dsv41::metal_host::iq_dn(a.plan_ptr, a.grp_ptr, a.grp_start, a.grp_ent, a.n_groups, a.tr, a.n_embd,
a.n_ff, a.hq, a.hd, a.part, a.td, groups))
return true;
#endif
if (is_tq(a.td)) return tq::down(a, groups, ne_max, s);
if (a.n_ff % 256 != 0 || a.n_embd % (kWarps * kDnRW) != 0) return false;
const dim3 grid((unsigned) (a.n_embd / (kWarps * kDnRW)), (unsigned) groups);
@@ -1240,6 +1255,9 @@ bool set_down(const SetArgs& a, cudaStream_t s) {
}
bool mv(const MvJob* jobs, int n, cudaStream_t s) {
#if defined(STRATA_METAL)
if (n > 0 && n <= 64 && ::strata::dsv41::metal_host::iq_mv((const void*) jobs, n)) return true;
#endif
{ // the trellis jobs go to their kernels, the others on
MvJob tqj[64], oth[64];
int nt = 0, no = 0;
+100 -3
View File
@@ -1826,15 +1826,36 @@ void route_publish(const float* logits, const float* bias, int n, int k, int T,
const unsigned long long* vram, const float* x, int dim, int* idx, float* w,
unsigned long long* plan_ptr, Req* req, unsigned seq, cudaStream_t s, const float* bias_vl,
unsigned vl, int na0, int na1) {
#if defined(STRATA_METAL)
// selection only: the prefetch schedule (req) is published by the CUDA kernel, and is turned on separately here
if (strata::dsv41::metal_host::route_publish(logits, bias, n, k, T, route_scale, vram, idx, w, plan_ptr,
vl != 0 ? bias_vl : nullptr, vl)) {
// no prefetcher on the Mac path, so publish_kernel has no consumer: the selection is the whole job here
(void) req; (void) seq; (void) na0; (void) na1; (void) x; (void) dim;
return;
}
#endif
strata_ds4_launch(route_publish_kernel, T, 512, 0, s, logits, bias, n, k, route_scale, vram, x, dim, idx, w, plan_ptr, req,
vl != 0 ? bias_vl : nullptr, vl);
if (req != nullptr) strata_ds4_launch(publish_kernel, 1, 1, 0, s, req, T, seq, na0, na1);
}
void route_ahead(const float* logits, const float* bias, int n, int m, int T, Req* req, int off, cudaStream_t s) {
#if defined(STRATA_METAL)
// no prefetch schedule on the Mac path yet: the router publishes no requests, so there is nothing to look ahead for
(void) logits; (void) bias; (void) n; (void) m; (void) T; (void) req; (void) off; (void) s;
return;
#endif
if (req != nullptr && m > 0 && T > 0 && n <= 1024 && off + m <= kAhead)
strata_ds4_launch(route_ahead_kernel, T, 512, 0, s, logits, bias, n, m, req, off);
}
void wait_seq(const unsigned* seq_ptr, unsigned seq, cudaStream_t s) { strata_ds4_launch(wait_seq_kernel, 1, 32, 0, s, seq_ptr, seq); }
void wait_seq(const unsigned* seq_ptr, unsigned seq, cudaStream_t s) {
#if defined(STRATA_METAL)
// nothing is published, so nothing is waited for: the CUDA path spins until the host's prefetcher acknowledges
(void) seq_ptr; (void) seq; (void) s;
return;
#endif
strata_ds4_launch(wait_seq_kernel, 1, 32, 0, s, seq_ptr, seq);
}
// the RAM store's experts for the device (a decode token, window of one): a pick the VRAM table left at 0 whose expert the store holds
// (zc_tab[expert] = the slot's device address over PCIe, 0: not) is copied to staging slot i with wide coalesced loads (the PCIe
@@ -1887,6 +1908,10 @@ void finish(float* x, int n_vec, int len, long long stride, const Finish& f, cud
std::fprintf(stderr, "ds4 finish: packed rows of quant %d, %d values not covered\n", f.quant, len);
return;
}
#if defined(STRATA_METAL)
const auto& mp = *reinterpret_cast<const strata::dsv41::metal_host::FinishIn*>(&f);
if (strata::dsv41::metal_host::finish(x, n_vec, len, stride, mp)) return; // finish_kernel<true> (the KV pack)
#endif
strata_ds4_launch(finish_kernel<true>, n_vec, kThreads, 0, s, x, len, stride, f);
} else {
#if defined(STRATA_METAL)
@@ -1912,10 +1937,16 @@ void hc_split(const float* mixes, const float* scale, const float* base, int hc,
}
void hc_pre_norm(const float* h, const float* mix, const float* w, int dim, int hc, int T, float eps, float* x,
cudaStream_t s) {
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::hc_pre_norm(h, mix, w, dim, hc, T, eps, x)) return;
#endif
strata_ds4_launch(hc_pre_norm_kernel, T, 1024, 0, s, h, mix, w, dim, hc, eps, x);
}
void hc_post(const float* y, const float* res, const float* post, const float* comb, int dim, int hc, int T,
float* out, cudaStream_t s) {
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::hc_post_v(y, res, post, comb, dim, hc, T, out)) return;
#endif
strata_ds4_launch(hc_post_kernel, dim3(cdiv(dim * hc, kThreads), T), kThreads, 0, s, y, res, post, comb, dim, hc, out);
}
@@ -1933,6 +1964,9 @@ void hc_mix_scale(const float* h, int hcdim, int n_mix, int T, float eps, float*
strata_ds4_launch(hc_mix_scale_kernel, T, kThreads, 0, s, h, hcdim, n_mix, eps, mixes);
}
void engram_dequant_tok(const uint8_t* src, size_t per, int cols, int T, int hd, float* out, cudaStream_t s, int fmt) {
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::engram_dequant_tok(src, per, cols, T, hd, out, fmt)) return;
#endif
if (T > 0) strata_ds4_launch(engram_dequant_tok_kernel, T * cols, kThreads, 0, s, src, per, cols, hd, out, fmt);
}
void moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds, int* row_tok, int* pos,
@@ -1946,7 +1980,12 @@ void moe_sort(const int* idx, int T, int k, const int* vs, int n_vs, int* bounds
}
void moe_combine(float* acc, const float* y, const int* pos, const float* w, int T, int k, int r0, int r1, int dim,
cudaStream_t s) {
if (r1 > r0 && T > 0) strata_ds4_launch(moe_combine_kernel, dim3(cdiv(dim, kThreads), T), kThreads, 0, s, acc, y, pos, w, k, r0, r1, dim);
if (r1 > r0 && T > 0) {
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::moe_combine(acc, y, pos, w, T, k, r0, r1, dim)) return;
#endif
strata_ds4_launch(moe_combine_kernel, dim3(cdiv(dim, kThreads), T), kThreads, 0, s, acc, y, pos, w, k, r0, r1, dim);
}
}
void gemv_f16(const uint16_t* W, const float* x, int n, int k, int T, float alpha, float* y, cudaStream_t s) {
@@ -1954,12 +1993,19 @@ void gemv_f16(const uint16_t* W, const float* x, int n, int k, int T, float alph
}
void gemv_f16_rows(const uint16_t* W, const float* x, size_t ldx, int n, int k, int T, float alpha, float* y, size_t ldy,
cudaStream_t s) {
#if defined(STRATA_METAL)
// gemv_f16_rows_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::gemv_f16_rows(W, x, ldx, n, k, T, alpha, y, ldy)) return;
#endif
if (T > 0)
strata_ds4_launch(gemv_f16_rows_kernel, dim3(cdiv(n, kThreads / 32), cdiv(T, kRowsT)), kThreads, 0, s, W, x, ldx, n, k, T, alpha,
y, ldy);
}
void gemv_f32(const float* W, const float* x, int n, int k, int T, float* y, int ldy, cudaStream_t s) {
#if defined(STRATA_METAL)
if (T > 0 && ::strata::dsv41::metal_host::gemv_f32(W, x, n, k, T, y, ldy)) return;
#endif
if (T > 0) strata_ds4_launch(gemv_f32_kernel, dim3(cdiv(n, kThreads / 32), T), kThreads, 0, s, W, x, n, k, y, ldy);
}
@@ -1971,11 +2017,20 @@ void route(const float* logits, const float* bias, int n, int k, int T, float ro
}
void swiglu(const float* g, const float* u, int n, float lim, float* h, cudaStream_t s) {
#if defined(STRATA_METAL)
// declared here rather than in the header: the header carries the other entry points, this one is only used here
namespace mh = strata::dsv41::metal_host;
if (n > 0 && mh::swiglu(g, u, n, lim, h)) return;
#endif
if (n > 0) strata_ds4_launch(swiglu_kernel, cdiv(n, kThreads), kThreads, 0, s, g, u, n, lim, h);
}
void compress_win(const float* kv, const float* score, float* kv_state, float* score_state, int ratio, int p0, int T,
int d, const float* w, float eps, float* latent, cudaStream_t s) {
#if defined(STRATA_METAL)
// compress_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::compress_win(kv, score, kv_state, score_state, ratio, p0, T, d, w, eps, latent)) return;
#endif
strata_ds4_launch(compress_kernel, 1, 512, 0, s, kv, score, kv_state, score_state, ratio, p0, T, d, w, eps, latent);
}
@@ -1987,6 +2042,12 @@ void index_score(const float* q, const float* w, const void* k, int heads, int h
return;
}
if (n <= 0) return;
#if defined(STRATA_METAL)
// index_score_kernel<128, kfmt> on the Metal dispatch; the launches below are the fallback
if (strata::dsv41::metal_host::index_score(q, w, (const uint8_t*) k, heads, hd, T, n, cand, cand_stride, blk, &lim,
out, out_stride, kfmt))
return;
#endif
const size_t smem = (size_t) (heads * hd + heads) * sizeof(float);
const dim3 grid(cdiv(n, kThreads), T);
if (kfmt == kKvFp4p)
@@ -1999,6 +2060,10 @@ void index_score(const float* q, const float* w, const void* k, int heads, int h
void topk(const float* vals, long long stride, int T, const Rows& r, const int* cand, int cand_stride, int blk,
int* out, int out_stride, cudaStream_t s) {
#if defined(STRATA_METAL)
// topk_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::topk(vals, stride, T, &r, cand, cand_stride, blk, out, out_stride)) return;
#endif
strata_ds4_launch(topk_kernel, T, 1024, 0, s, vals, stride, r, cand, cand_stride, blk, out, out_stride);
}
@@ -2016,6 +2081,10 @@ void cand_blocks(const float* score, long long stride, int T, const Rows& r, int
rb.k[t] = r.k[t];
nb_max = rb.n[t] > nb_max ? rb.n[t] : nb_max;
}
#if defined(STRATA_METAL)
// block_max_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::block_max(score, stride, T, &r, blk, bm, bm_stride, nb_max)) return;
#endif
strata_ds4_launch(block_max_kernel, dim3(cdiv(nb_max, kThreads), T), kThreads, 0, s, score, stride, r, blk, bm, bm_stride);
topk(bm, bm_stride, T, rb, nullptr, 0, 1, out, out_stride, s);
}
@@ -2064,6 +2133,10 @@ void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int
// the BF16 rows' kernel itself (heads_per_block -1: this way at any T)
const bool few = heads_per_block == -1 || (heads_per_block == 0 && T <= kAttnScratchT);
if (few && scr != nullptr && scr->rows != nullptr && T <= scr->max_t && sel_stride <= scr->cap) {
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::unpack_sel(ckv, sel, sel_stride, a.gen, a.p0, a.t0, a.R, a.kcap, a.nsel,
scr->cap, scr->rows, T, a.gen ? 1 : (T < kWin ? T : kWin), kv_row_bytes(kKvFp4, 512))) return;
#endif
strata_ds4_launch(unpack_sel_kernel, dim3(cdiv(sel_stride, kStage), T), kThreads, 0, s, (const uint8_t*) ckv, sel, sel_stride, a,
scr->cap, scr->rows);
#if !defined(STRATA_USE_HIP)
@@ -2092,6 +2165,9 @@ void sparse_attn(const float* q, const uint16_t* win, const void* ckv, const int
}
void ring_to_ext(const uint8_t* ring, uint16_t* ext, int64_t p0, int n, int d, cudaStream_t s) {
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::ring_to_ext(ring, ext, (long long) p0, n, d, kv_row_bytes(kKvFp8, d))) return;
#endif
strata_ds4_launch(ring_to_ext_kernel, n, kThreads, 0, s, ring, ext, (long long) p0, n, d);
}
void ext_to_ring(const uint16_t* ext, uint8_t* ring, int64_t p0, int n, int T, int d, cudaStream_t s, uint8_t* backup) {
@@ -2099,6 +2175,9 @@ void ext_to_ring(const uint16_t* ext, uint8_t* ring, int64_t p0, int n, int T, i
std::fprintf(stderr, "ds4 ext_to_ring: row of %d not covered\n", d);
return;
}
#if defined(STRATA_METAL)
if (strata::dsv41::metal_host::ext_to_ring(ext, ring, (long long) p0, n, T, d, kv_row_bytes(kKvFp8, d), backup)) return;
#endif
strata_ds4_launch(ext_to_ring_kernel, T, kThreads, 0, s, ext, ring, (long long) p0, n, T, d, backup);
}
void ring_restore(uint8_t* ring, const uint8_t* backup, int64_t p0, int n, int keep, int T, int d, cudaStream_t s) {
@@ -2111,9 +2190,19 @@ void ring_restore_batch(const RingBatch& b, int64_t p0, int n, int keep, int T,
kv_row_bytes(kKvFp8, d));
}
void hc_mean(const float* h, int T, int hc, int dim, float* out, long long out_stride, cudaStream_t s) {
#if defined(STRATA_METAL)
// hc_mean_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::hc_mean(h, T, hc, dim, out, out_stride)) return;
#endif
strata_ds4_launch(hc_mean_kernel, dim3(cdiv(dim, kThreads), T), kThreads, 0, s, h, hc, dim, out, out_stride);
}
void iota_rows(int* out, int T, int n, int stride, cudaStream_t s) { strata_ds4_launch(iota_rows_kernel, T, 64, 0, s, out, n, stride); }
void iota_rows(int* out, int T, int n, int stride, cudaStream_t s) {
#if defined(STRATA_METAL)
// iota_rows_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::iota_rows(out, T, n, stride)) return;
#endif
strata_ds4_launch(iota_rows_kernel, T, 64, 0, s, out, n, stride);
}
void markov_add(float* logits, const uint16_t* E, const uint16_t* H, const int* tok, int V, int R, cudaStream_t s) {
strata_ds4_launch(markov_kernel, cdiv(V, kThreads / 32), kThreads, (size_t) R * sizeof(float), s, logits, E, H, tok, V, R);
}
@@ -2133,10 +2222,18 @@ void confidence(const float* x, const uint16_t* E, const int* tok, const float*
}
void engram_dequant(const uint8_t* rows, const uint8_t* scales, int n, int hd, float* out, cudaStream_t s, int fmt) {
#if defined(STRATA_METAL)
// engram_dequant_kernel on the Metal dispatch (fmt 2, this model's IQ4_NL tables); the launch below is the fallback
if (strata::dsv41::metal_host::engram_dequant(rows, scales, n, hd, out, fmt)) return;
#endif
strata_ds4_launch(engram_dequant_kernel, n, kThreads, 0, s, rows, scales, hd, out, fmt);
}
void engram_gate(float* h, const float* kv, const float* w, int hc, int dim, int T, float eps, cudaStream_t s) {
#if defined(STRATA_METAL)
// engram_gate_kernel on the Metal dispatch; the launch below is the fallback
if (strata::dsv41::metal_host::engram_gate(h, kv, w, hc, dim, T, eps)) return;
#endif
strata_ds4_launch(engram_gate_kernel, dim3(hc, T), 1024, 0, s, h, kv, w, hc, dim, eps);
}
+10
View File
@@ -16,6 +16,9 @@
// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature /
// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics).
#include "strata/dsv41/sampler.hpp"
#if defined(STRATA_METAL)
#include <ds4_metal_host.h>
#endif
#include <cuda_runtime.h>
@@ -525,6 +528,13 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
if (p.greedy || p.temperature <= 0.0f) {
// One block per token, 1,024 threads over the vocabulary. See `sampler_greedy_kernel`.
const int gthreads = 1024;
#if defined(STRATA_METAL)
// sampler_greedy_kernel on the Metal dispatch; the launch below is the fallback
if (::strata::dsv41::metal_host::sample_greedy(logits, n_tokens, n_vocab, history, history_len,
p.penalty_last_n, p.penalty_repeat, p.penalty_freq,
p.penalty_present, p.logit_bias, out))
return;
#endif
strata_ds4_launch(sampler_greedy_kernel, (unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream,
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
} else {