ling32 metal: matrix-unit prefill attention (fp16 hi/lo, 32 heads per token), strata-ling32 CLI (--version, --info --kv, --spec mtp, --spec-block, --spec-adaptive, ERR exits), shared query fragments in the decode attention, build under heavy.lock

This commit is contained in:
Niko1221 committed 2026-12-02 13:11:21 +01:00
1 parent de500bf0d2
commit f9fbc1d186
7 files changed
+261 -31

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
set -e
cd /c/w-ling32-metal
bash engine/src/ling32/metal/sync_mac.sh | tail -1
ssh m1002 'S=~/strata-mac/ling32; cp $S/src/wt/engine/src/ling32/metal/l32wd.sh $S/src/wt/engine/src/ling32/metal/l32run.sh $S/; chmod +x $S/*.sh; bash $S/src/wt/engine/src/ling32/metal/build_mac.sh 2>&1 | grep -E "error|undefined|done" | head -30'
ssh m1002 'S=~/strata-mac/ling32; cp $S/src/wt/engine/src/ling32/metal/l32wd.sh $S/src/wt/engine/src/ling32/metal/l32run.sh $S/; chmod +x $S/*.sh; L=$HOME/strata-mac/locks; until mkdir $L/heavy.lock 2>/dev/null; do sleep 3; done; echo "l32-build $(date)" > $L/heavy.owner; nice bash $S/src/wt/engine/src/ling32/metal/build_mac.sh 2>&1 | grep -E "error|undefined|done" | head -30; rm -f $L/heavy.owner; rmdir $L/heavy.lock'
if [ "$1" = check ]; then
ssh m1002 'S=~/strata-mac/ling32; $S/l32run.sh check $S/bin/ling32-metal --model x --check --kernels $S/src/wt/engine/src/ling32/metal 2>&1 | head -80'
fi
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# exitcodes.sh: exit codes of the CLI error cases of ling32-metal, read right after each command (no pipe). Run on m1002. None of these loads a model or touches the GPU.
S=~/strata-mac/ling32
B=$S/bin/ling32-metal
M=$S/models/Ling-3.2-Air-SQ-96.strata
$B --version > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "--version: rc=$? stdout=$(head -1 /tmp/l32_o.txt)"
$B --info $M --kv > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "--info --kv: rc=$? stdout=$(head -1 /tmp/l32_o.txt)"
$B --info $S/models/does-not-exist.strata --kv > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "--info missing file: rc=$? stderr=$(head -1 /tmp/l32_e.txt)"
$B --model $M --spec mtp > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "--spec mtp without --mtp: rc=$? stderr=$(head -1 /tmp/l32_e.txt)"
$B --model $M --spec dfly > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "--spec dfly: rc=$? stderr=$(head -1 /tmp/l32_e.txt)"
$B --model $M --spec foo > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "--spec foo: rc=$? stderr=$(head -1 /tmp/l32_e.txt)"
$B --model $M --bogus-flag > /tmp/l32_o.txt 2> /tmp/l32_e.txt; echo "unknown flag: rc=$? stderr=$(head -1 /tmp/l32_e.txt)"
rm -f /tmp/l32_o.txt /tmp/l32_e.txt
+23 -11
View File
@@ -380,18 +380,30 @@ kernel void mla_attn_mmah(device const float* qabs [[buffer(0)]], device const f
for (int i = 0; i < 16; ++i) O[i] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int kb = j_lo; kb < j_hi; kb += KB) {
for (int tl = 0; tl < 2; ++tl) {
const int kt = int(sg) * 2 + tl;
simdgroup_float8x8 acc = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
device const float* kbase = cache + cidx_(kb + kt * 8, 0);
for (int k = 0; k < W; k += 8) {
simdgroup_float8x8 qf, kf;
if (k < L32_KVL) simdgroup_load(qf, qb + k, L32_KVL);
else simdgroup_load(qf, qr + (k - L32_KVL), L32_NOPE + L32_ROPE);
simdgroup_load(kf, kbase + (k >> 3) * 64, 8, ulong2(0, 0), true);
simdgroup_multiply_accumulate(acc, qf, kf, acc);
{ // the two key tiles of this simdgroup share every query fragment (two independent chains, unrolled)
simdgroup_float8x8 acc0 = make_filled_simdgroup_matrix<float, 8, 8>(0.0f), acc1 = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);
device const float* kb0 = cache + cidx_(kb + int(sg) * 16, 0);
device const float* kb1 = cache + cidx_(kb + int(sg) * 16 + 8, 0);
#pragma clang loop unroll_count(8)
for (int k = 0; k < L32_KVL; k += 8) {
simdgroup_float8x8 qf, kf0, kf1;
simdgroup_load(qf, qb + k, L32_KVL);
simdgroup_load(kf0, kb0 + (k >> 3) * 64, 8, ulong2(0, 0), true);
simdgroup_load(kf1, kb1 + (k >> 3) * 64, 8, ulong2(0, 0), true);
simdgroup_multiply_accumulate(acc0, qf, kf0, acc0);
simdgroup_multiply_accumulate(acc1, qf, kf1, acc1);
}
simdgroup_store(acc, Ss + kt * 8, KB);
#pragma unroll
for (int k = L32_KVL; k < W; k += 8) {
simdgroup_float8x8 qf, kf0, kf1;
simdgroup_load(qf, qr + (k - L32_KVL), L32_NOPE + L32_ROPE);
simdgroup_load(kf0, kb0 + (k >> 3) * 64, 8, ulong2(0, 0), true);
simdgroup_load(kf1, kb1 + (k >> 3) * 64, 8, ulong2(0, 0), true);
simdgroup_multiply_accumulate(acc0, qf, kf0, acc0);
simdgroup_multiply_accumulate(acc1, qf, kf1, acc1);
}
simdgroup_store(acc0, Ss + int(sg) * 16, KB);
simdgroup_store(acc1, Ss + int(sg) * 16 + 8, KB);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
{
+14 -4
View File
@@ -536,7 +536,7 @@ kernel void kda_chunk_seq(device float* S [[buffer(0)]], device const float* vc
// RoPE table: [pos][L32_ROPE/2] (cos, sin) float2, computed on the CPU in double
// MLA prep, part 1: per token the latent row (RMSNorm(ckv[:kvl]) * ln) and the rotated k_pe go to the cache row pos0 + t. grid N, 256 threads
kernel void mla_prep_cache(device const float* ckv [[buffer(0)]], device const float* ln [[buffer(1)]], device float* cache [[buffer(2)]], device const float2* rope_cs [[buffer(3)]],
device const int* d_pos0 [[buffer(4)]], constant int& cs [[buffer(5)]],
device const int* d_pos0 [[buffer(4)]], constant int& cs [[buffer(5)]], device half* kh [[buffer(6)]], device half* kl [[buffer(7)]],
uint t [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
constexpr int W = L32_KVL + L32_ROPE;
threadgroup float sm[32];
@@ -546,12 +546,22 @@ kernel void mla_prep_cache(device const float* ckv [[buffer(0)]], device const f
for (int i = int(tid); i < L32_KVL; i += 256) ss += cr[i] * cr[i];
ss = tg_sum(ss, sm, tid, 256);
const float r = 1.0f / sqrt(ss / float(L32_KVL) + L32_EPS);
for (int i = int(tid); i < L32_KVL; i += 256) cache[cidx_(pos, i)] = cr[i] * r * ln[i];
for (int i = int(tid); i < L32_KVL; i += 256) {
const float v = cr[i] * r * ln[i];
cache[cidx_(pos, i)] = v;
const half hv = half(v);
kh[(ulong)pos * W + i] = hv;
kl[(ulong)pos * W + i] = half(v - float(hv));
}
for (int j = int(tid); j < L32_ROPE / 2; j += 256) {
const float2 cs_ = rope_cs[(ulong)pos * (L32_ROPE / 2) + j];
const float xe = cr[L32_KVL + 2 * j], xo = cr[L32_KVL + 2 * j + 1];
cache[cidx_(pos, L32_KVL + 2 * j)] = xe * cs_.x - xo * cs_.y;
cache[cidx_(pos, L32_KVL + 2 * j + 1)] = xo * cs_.x + xe * cs_.y;
const float ve = xe * cs_.x - xo * cs_.y, vo = xo * cs_.x + xe * cs_.y;
cache[cidx_(pos, L32_KVL + 2 * j)] = ve;
cache[cidx_(pos, L32_KVL + 2 * j + 1)] = vo;
const half he = half(ve), ho = half(vo);
kh[(ulong)pos * W + L32_KVL + 2 * j] = he; kl[(ulong)pos * W + L32_KVL + 2 * j] = half(ve - float(he));
kh[(ulong)pos * W + L32_KVL + 2 * j + 1] = ho; kl[(ulong)pos * W + L32_KVL + 2 * j + 1] = half(vo - float(ho));
}
}
// part 2: rotate the rope part of every head's query in place. grid (N, H), 32 threads
+63 -12
View File
@@ -326,6 +326,10 @@ struct Engine {
// work buffers
mtl::Buffer ids, pos, rope, dlt, x, h, cur, fa, proj, qn, kn, vc, ko, beta, q, ckv, qabs, ctx, av, gate, g, u, a, rlog, ridx, rw, gu, actp, ye, logits, kscr, layer_out;
std::vector<mtl::Buffer> cache; // per layer (MLA only)
std::vector<mtl::Buffer> cacheh; // the same rows as halves: hi rows then lo rows, row stride 576 (the matrix-unit prefill attention)
mtl::Buffer qhb, qlb; // query halves of a chunk
bool mla_mpp = true; // prefill attention on the matrix unit (hi / lo halves)
size_t cache_rows() const { return size_t((max_ctx + 64 + 7) / 8 * 8); }
std::vector<size_t> s_off, h_off; // per layer state offsets
Ref posr{nullptr, 0}; // MLA position buffer override (the MTP layer uses its own); null: `pos`
bool allow_grouped = true; // false while the MTP layer is built (its experts are S2: no matrix-unit decoder)
@@ -354,6 +358,7 @@ struct Engine {
c.H * c.hd, c.kv_lora, c.nope, c.rope, c.vhead);
s += fmt("#define L32_E %d\n#define L32_TOPK %d\n#define L32_I %d\n#define L32_NGROUP %d\n#define L32_TOPKG %d\n", c.n_exp, c.top_k, c.I_moe, c.n_group, c.topk_group);
s += fmt("#define L32_EPS %.9ef\n#define L32_KDA_LB %.9ef\n#define L32_SCALE %.9ef\n", c.eps, c.kda_lower_bound, c.routed_scale);
if (const char* kb = std::getenv("L32_MPP_KB")) s += fmt("#define MLA_MPP_KB %d\n", std::atoi(kb)); // keys per block of the matrix-unit prefill attention (experiments)
return s;
}
bool init(const std::string& kdir, int max_ctx_, int nmax, std::string& err) {
@@ -413,9 +418,11 @@ struct Engine {
S_ck = cx.alloc(S_sz * nk * 4); hist_ck = cx.alloc(hist_sz * nk * 4);
s_off.assign(c.n_layers, 0); h_off.assign(c.n_layers, 0);
cache.assign(c.n_layers, mtl::Buffer{});
cacheh.assign(c.n_layers, mtl::Buffer{});
if (mla_mpp) { qhb = cx.alloc(size_t(N) * c.H * c.mla_latent_vals() * 2); qlb = cx.alloc(size_t(N) * c.H * c.mla_latent_vals() * 2); }
int k = 0;
for (int il = 0; il < c.n_layers; ++il) {
if (c.is_mla(il)) cache[il] = cx.alloc(size_t((max_ctx + 64 + 7) / 8 * 8) * c.mla_latent_vals() * 4);
if (c.is_mla(il)) { cache[il] = cx.alloc(cache_rows() * c.mla_latent_vals() * 4); cacheh[il] = cx.alloc(cache_rows() * c.mla_latent_vals() * 4); } // halves: 2 x rows x W x 2 bytes
else { s_off[il] = size_t(k) * S_sz * 4; h_off[il] = size_t(k) * hist_sz * 4; ++k; }
}
(void)err;
@@ -425,7 +432,7 @@ struct Engine {
void warm(bool with_mtp) {
std::vector<std::string> names = {"gemv_f32", "rmsnorm", "embed_s8k", "fwht128_rows", "swiglu_k", "kda_step_fused", "kda_prep", "kda_hist", "kda_chunk_pre", "kda_chunk_seq", "mla_prep_cache", "mla_prep_q",
"mla_qabs", "mla_attn_mma", "mla_attn_part2", "mla_attn_part4", "mla_attn_combine", "mla_out2", "alflb_route2", "moe_gu", "moe_act", "moe_dn", "moe_combine_norm", "add_rmsnorm", "copy_u32",
"x_to_half", "moe_plan", "moe_gather", "moe_act_rows", "gemv_f32_nt", "gemv_f32_mm", "alflb_route2x", "mla_attn_mmah", "mla_attn_mma4", "kda_chunk_seq", "kda_chunk_seq_mma"};
"x_to_half", "moe_plan", "moe_gather", "moe_act_rows", "gemv_f32_nt", "gemv_f32_mm", "mla_q_halves", "mla_attn_mpp", "alflb_route2x", "mla_attn_mmah", "mla_attn_mma4", "kda_chunk_seq", "kda_chunk_seq_mma"};
for (int code : {4, 5, 6, 8}) {
for (int nt : {1, 4, 16}) names.push_back(fmt("gemv_sk_%d_%d", code, nt));
names.push_back(fmt("mm_dense_%d_2", code));
@@ -528,14 +535,14 @@ struct Engine {
}
gemv(t, K.o, R(ko), N, R(dlt), D, false);
}
void mla_block(Tape& t, const MlaW& M, const mtl::Buffer& cacheb, int N) {
void mla_block(Tape& t, const MlaW& M, const mtl::Buffer& cacheb, const mtl::Buffer& cachehb, int N) {
const int H = c.H, W = c.mla_latent_vals();
gemv(t, M.q, R(h), N, R(q), c.mla_q_dim(), false);
NB(t, N);
gemv(t, M.kva, R(h), N, R(ckv), W, false);
NB(t, N);
gemv_f32(t, M.g_proj, H, D, R(h), N, R(gate));
t.add("mla_prep_cache", {B(R(ckv)), B(ar(M.kva_ln)), B(R(cacheb)), B(R(rope)), B(posr.b ? posr : R(pos)), I(W)}, N, 1, 1, 256);
t.add("mla_prep_cache", {B(R(ckv)), B(ar(M.kva_ln)), B(R(cacheb)), B(R(rope)), B(posr.b ? posr : R(pos)), I(W), B(R(cachehb, 0)), B(R(cachehb, cache_rows() * W * 2))}, N, 1, 1, 256);
NB(t, N);
t.add("mla_prep_q", {B(R(q)), B(R(rope)), B(posr.b ? posr : R(pos))}, N, H, 1, 32);
NB(t, N);
@@ -555,7 +562,10 @@ struct Engine {
t.add("mla_attn_combine", {B(R(mpart)), B(R(ctx)), I(S2), B(posr.b ? posr : R(pos)), I(mla_thr), I(INF)}, N * H, 1, 1, 256);
}
} else {
if (mla_ht4 && H % 4 == 0) t.add("mla_attn_mma4", {B(R(qabs)), B(R(q)), B(R(cacheb)), B(posr.b ? posr : R(pos)), B(R(ctx)), Fl(1.0f / std::sqrt(float(c.nope + c.rope))), I(N)}, (N + 7) / 8, H / 4, 1, 256);
if (mla_mpp && H == 32 && qhb.handle) { // matrix unit: one threadgroup per token, 32 heads x 64 keys per product, halves hi / lo
t.add("mla_q_halves", {B(R(qabs)), B(R(q)), B(R(qhb)), B(R(qlb))}, N * H, 1, 1, 64);
t.add("mla_attn_mpp", {B(R(qhb)), B(R(qlb)), B(R(cachehb, 0)), B(R(cachehb, cache_rows() * W * 2)), B(posr.b ? posr : R(pos)), B(R(ctx)), Fl(1.0f / std::sqrt(float(c.nope + c.rope)))}, N, 1, 1, 256);
} else if (mla_ht4 && H % 4 == 0) t.add("mla_attn_mma4", {B(R(qabs)), B(R(q)), B(R(cacheb)), B(posr.b ? posr : R(pos)), B(R(ctx)), Fl(1.0f / std::sqrt(float(c.nope + c.rope))), I(N)}, (N + 7) / 8, H / 4, 1, 256);
else t.add("mla_attn_mma", {B(R(qabs)), B(R(q)), B(R(cacheb)), B(posr.b ? posr : R(pos)), B(R(ctx)), Fl(1.0f / std::sqrt(float(c.nope + c.rope))), I(N)}, (N + 7) / 8, H, 1, 128);
}
t.add("mla_out2", {B(R(ctx)), B(ar(M.wv_b)), B(R(gate)), B(R(av))}, N, H, 4, 128);
@@ -634,7 +644,7 @@ struct Engine {
{ auto& lb = lbeg[&v]; lb.resize(size_t(il) + 1, 0); lb[il] = v.size(); }
const LayerW& L = m.L[il];
if (il == 0) t.add("add_rmsnorm", {B(R(x)), B(R(dlt)), B(ar(L.in_ln)), B(R(h)), I(0)}, N, 1, 1, 256); // h = RMSNorm(embedding); later layers get h from the previous layer's last kernel
if (L.is_mla) mla_block(t, L.mla, cache[il], N); else kda_layer(t, il, N);
if (L.is_mla) mla_block(t, L.mla, cache[il], cacheh[il], N); else kda_layer(t, il, N);
t.add("add_rmsnorm", {B(R(x)), B(R(dlt)), B(ar(L.post_ln)), B(R(cur)), I(1)}, N, 1, 1, 256); // x += attention output; cur = post-attention norm
if (L.is_moe) moe_ffn(t, il, N); else dense_ffn(t, il, N);
if (capture_all) {
@@ -801,6 +811,7 @@ struct Opts {
std::string cmp_a, cmp_b, mtp;
bool warm = false;
int spec_k = 0; // 0: adaptive (1..3 per cycle)
bool spec_mtp = false; // --spec mtp: draft with the MTP layer of the sidecar (--mtp FILE)
int cmp_n = 0;
int moe_g = 2;
int mm_min = 32, mm_terms = 2, moe_mm_min = 32, moe_tm = 16, mla_kc = 256, trace_pos = -1;
@@ -812,6 +823,7 @@ struct Opts {
bool f32_mm = true;
bool kda_mma = true;
bool mla_mmah = true;
bool mla_mpp = true;
int mla_kch = 256;
int mla_thr = 8192;
bool mla_ht4 = false;
@@ -969,7 +981,36 @@ static std::string kernels_dir(const std::string& req) {
static std::string kernels_dir(const std::string& req) { return req; }
#endif
#ifndef L32_VERSION
#define L32_VERSION "0.2.25"
#endif
#ifndef L32_BUILD_ID
#define L32_BUILD_ID __DATE__ " " __TIME__
#endif
// --info FILE [--kv]: Section 0 only (no GPU, no model load). --kv: one line key=value for the launcher, the keys of the CUDA / HIP engine (images=0: no vision, tiers=A: Mode A only)
static int cmd_info(const std::string& file, bool kv) {
Ling32File f;
std::string err;
if (!f.open(file, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
const Cfg& c = f.cfg();
if (kv) {
std::printf("arch=ling32 layers=%d vocab=%d drafter=none mtp=1 images=0 tiers=A\n", c.n_layers, c.V);
return 0;
}
int mla = 0;
for (int il = 0; il < c.n_layers; ++il) mla += c.is_mla(il);
std::printf("Ling-3.2-Air %s\n", file.c_str());
std::printf(" layers %d (%d KDA + %d MLA), %d dense + %d MoE, hidden %d, vocab %d, heads %d x %d\n", c.n_layers, c.n_layers - mla, mla, c.first_k_dense, c.n_moe(), c.D, c.V, c.H, c.hd);
std::printf(" MoE: %d experts, top-%d of %d groups x %d, inter %d, shared %d, scale %.2f; MLA: kv_lora %d nope %d rope %d v %d theta %.0f\n", c.n_exp, c.top_k, c.n_group, c.n_exp / c.n_group,
c.I_moe, c.I_shared, c.routed_scale, c.kv_lora, c.nope, c.rope, c.vhead, c.rope_theta);
std::printf(" backend metal, Mode A (experts in one mapped buffer), MTP speculative decoding with --mtp FILE --spec mtp\n");
return 0;
}
int main(int argc, char** argv) {
if (argc >= 2 && !std::strcmp(argv[1], "--version")) { std::printf("strata-ling32 %s (metal, build %s)\n", L32_VERSION, L32_BUILD_ID); return 0; } // no GPU, no model: the engine installer probes this
if (argc >= 3 && !std::strcmp(argv[1], "--info")) return cmd_info(argv[2], argc >= 4 && !std::strcmp(argv[3], "--kv"));
Opts o;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
@@ -993,7 +1034,15 @@ int main(int argc, char** argv) {
else if (a == "--serve") { o.serve = true; o.warm = true; }
else if (a == "--warm") o.warm = true;
else if (a == "--mtp") o.mtp = nx();
else if (a == "--spec-k") o.spec_k = std::atoi(nx().c_str());
else if (a == "--spec-k") o.spec_k = std::atoi(nx().c_str()); // alias of --spec-block (K = drafts per cycle, 1..3)
else if (a == "--spec-block") { const int b = std::atoi(nx().c_str()); o.spec_k = std::min(3, std::max(1, b - 1)); } // CUDA: tokens per verify block (K + 1)
else if (a == "--spec-adaptive") {} // accepted, no-op: the draft count is adaptive by default (spec_k 0)
else if (a == "--spec") {
const std::string v = nx();
if (v == "mtp") o.spec_mtp = true;
else if (v == "dfly") { std::fprintf(stderr, "ERR --spec dfly was removed: the speculative drafter is the MTP layer (--mtp FILE --spec mtp)\n"); return 2; }
else { std::fprintf(stderr, "ERR unknown --spec value %s (expected mtp)\n", v.c_str()); return 2; }
}
else if (a == "--reps") o.reps = std::atoi(nx().c_str());
else if (a == "--cmp") { o.cmp_a = nx(); o.cmp_b = nx(); o.cmp_n = std::atoi(nx().c_str()); }
else if (a == "--mm-min") o.mm_min = std::atoi(nx().c_str());
@@ -1009,6 +1058,7 @@ int main(int argc, char** argv) {
else if (a == "--route-tol") o.route_tol = float(std::atof(nx().c_str()));
else if (a == "--no-kda-mma") o.kda_mma = false;
else if (a == "--no-mla-mmah") o.mla_mmah = false;
else if (a == "--no-mla-mpp") o.mla_mpp = false;
else if (a == "--mla-kch") o.mla_kch = std::atoi(nx().c_str());
else if (a == "--mla-thr") o.mla_thr = std::atoi(nx().c_str());
else if (a == "--mla-ht4") o.mla_ht4 = true;
@@ -1017,7 +1067,7 @@ int main(int argc, char** argv) {
else if (a == "--trace-pos") o.trace_pos = std::atoi(nx().c_str());
else if (a == "--bench-gemv") o.bench_gemv = true;
else if (a == "--bench-prompt") o.bench_prompt = std::atoi(nx().c_str());
else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; }
else { std::fprintf(stderr, "ERR unknown option %s\n", a.c_str()); return 2; }
}
if (!o.cmp_a.empty()) { // two --dump directories: per layer the largest residual difference and the routing agreement (no GPU, no model)
const int N = o.cmp_n, D = 2560, NL = 42;
@@ -1055,6 +1105,7 @@ int main(int argc, char** argv) {
return 0;
}
o.kernels = kernels_dir(o.kernels);
if (o.spec_mtp && o.mtp.empty()) { std::fprintf(stderr, "ERR --spec mtp needs --mtp FILE (the sidecar)\n"); return 2; }
if (o.model.empty() && !o.bench_gemv) { std::fprintf(stderr, "usage: ling32-metal --model F.strata (--jobs J --out DIR | --ids 1,2,3 --gen N) [--kernels DIR] [--ctx N] [--chunk N]\n"); return 2; }
std::string err;
Ling32File f;
@@ -1123,7 +1174,7 @@ int main(int argc, char** argv) {
cx.ggml_common_path.clear();
E0.lib = cx.compile({"ling32_core.metal", "ling32_decode.metal", "ling32_attn.metal", "ling32_mtp.metal", "ling32_mpp.metal"}, Engine::prelude_for(f.cfg()));
std::vector<std::string> names = {"gemv_f32", "rmsnorm", "embed_s8k", "fwht128_rows", "swiglu_k", "kda_step_fused", "kda_prep", "kda_hist", "kda_chunk_pre", "kda_chunk_seq",
"mla_prep_cache", "mla_prep_q", "mla_qabs", "mla_attn_part2", "mla_out2", "alflb_route2", "mla_attn_combine", "mla_out", "alflb_route", "moe_gu", "moe_act", "moe_dn", "moe_combine_norm", "add_rmsnorm", "copy_row_k"};
"mla_prep_cache", "mla_prep_q", "mla_qabs", "mla_attn_part2", "mla_out2", "alflb_route2", "mla_q_halves", "mla_attn_mpp", "mla_attn_combine", "mla_out", "alflb_route", "moe_gu", "moe_act", "moe_dn", "moe_combine_norm", "add_rmsnorm", "copy_row_k"};
for (int code : {4, 5, 6, 8}) for (int nt : {1, 4, 16}) names.push_back(fmt("gemv_sk_%d_%d", code, nt));
for (auto& n : names) {
const mtl::Pipeline& p = E0.P(n);
@@ -1134,16 +1185,16 @@ int main(int argc, char** argv) {
Model m;
if (!load_model(cx, f, m, o.prefault, err)) { std::fprintf(stderr, "load: %s\n", err.c_str()); return 1; }
Engine E(cx, m);
E.mm_min = o.mm_min; E.mm_terms = o.mm_terms; E.moe_mm_min = o.moe_mm_min; E.moe_tm = o.moe_tm; E.moe_g = o.moe_g; E.mla_kc = o.mla_kc; E.trace_pos = o.trace_pos; E.mm_shared = o.mm_shared; E.mm_tm128 = o.mm_tm128; E.mla_mma = o.mla_mma; E.fast_f32 = o.fast_f32; E.f32_mm = o.f32_mm; E.route_tol = o.route_tol; E.kda_mma = o.kda_mma; E.mla_mmah = o.mla_mmah; E.mla_kch = o.mla_kch; E.mla_thr = o.mla_thr; E.mla_ht4 = o.mla_ht4; E.logits_rows = o.logits_rows;
E.mm_min = o.mm_min; E.mm_terms = o.mm_terms; E.moe_mm_min = o.moe_mm_min; E.moe_tm = o.moe_tm; E.moe_g = o.moe_g; E.mla_kc = o.mla_kc; E.trace_pos = o.trace_pos; E.mm_shared = o.mm_shared; E.mm_tm128 = o.mm_tm128; E.mla_mma = o.mla_mma; E.fast_f32 = o.fast_f32; E.f32_mm = o.f32_mm; E.route_tol = o.route_tol; E.kda_mma = o.kda_mma; E.mla_mmah = o.mla_mmah; E.mla_mpp = o.mla_mpp; E.mla_kch = o.mla_kch; E.mla_thr = o.mla_thr; E.mla_ht4 = o.mla_ht4; E.logits_rows = o.logits_rows;
if (o.logits_rows == 0 && o.jobs.empty() && o.dump.empty()) E.logits_rows = 16; // serving and speed runs read the last row(s) only
if (!E.init(o.kernels, o.ctx, o.chunk, err)) { std::fprintf(stderr, "init: %s\n", err.c_str()); return 1; }
std::fprintf(stderr, "ling32-metal: engine ready, rss %.1f GiB\n", rss_gib());
if (!o.mtp.empty()) {
if (o.spec_mtp) {
if (!mtp_init(E, o.mtp, o.spec_k, err)) { std::fprintf(stderr, "mtp: %s\n", err.c_str()); return 1; }
std::fprintf(stderr, "ling32-metal: rss %.1f GiB with the MTP sidecar\n", rss_gib());
}
if (o.warm) {
E.warm(!o.mtp.empty());
E.warm(o.spec_mtp);
const double tw = now_s(); // the first command buffer wires the 77 GiB expert buffer (~9 s): do it before the first request
const int tok0 = 1000;
E.reset();
+4 -3
View File
@@ -117,7 +117,7 @@ struct MtpRt {
float alpha[8] = {0.85f, 0.77f, 0.55f, 0.4f, 0.3f, 0.3f, 0.3f, 0.3f}; // P(slot j accepted | the slots before it were)
double step_ms[8] = {0, 17.2, 21.1, 25.7, 32.5, 40, 48, 56}; // modelled cycle time per K (ms)
int C = 16; // candidates re-scored with the exact head
mtl::Buffer mE, mcat, mout, mrow, mlog, part_v, part_i, cand_id, cand_val, mpos_arr, mnxt, agm, mcache;
mtl::Buffer mE, mcat, mout, mrow, mlog, part_v, part_i, cand_id, cand_val, mpos_arr, mnxt, agm, mcache, mcacheh;
std::map<std::tuple<int, int, int>, std::vector<mtl::Dispatch>> cyc; // (rows of the update pass, rollback index + 1, K)
std::map<std::tuple<int, int, int>, std::vector<mtl::Dispatch>> pre; // prefill chunk: (n, n_logits, rows of the update pass)
// the state between cycles
@@ -142,7 +142,7 @@ static void mtp_pass(Engine& E, Engine::Tape& t, int N, Ref X, int trunk, Ref to
E.allow_grouped = false;
E.posr = posref;
t.add("add_rmsnorm", {Engine::B(E.R(E.x)), Engine::B(E.R(E.dlt)), Engine::B(E.ar(M.L.in_ln)), Engine::B(E.R(E.h)), Engine::I(0)}, N, 1, 1, 256);
E.mla_block(t, M.L.mla, R.mcache, N);
E.mla_block(t, M.L.mla, R.mcache, R.mcacheh, N);
t.add("add_rmsnorm", {Engine::B(E.R(E.x)), Engine::B(E.R(E.dlt)), Engine::B(E.ar(M.L.post_ln)), Engine::B(E.R(E.cur)), Engine::I(1)}, N, 1, 1, 256);
E.moe_block(t, M.L, E.c.n_layers, N, M.sec4, M.desc, 0, 0.0f, 0.0f, 0, false);
E.posr = Ref{nullptr, 0};
@@ -165,7 +165,8 @@ static bool mtp_init(Engine& E, const std::string& path, int K, std::string& err
R->mlog = cx.alloc(size_t(E.c.V) * 4);
R->part_v = cx.alloc(128 * 16 * 4); R->part_i = cx.alloc(128 * 16 * 4); R->cand_id = cx.alloc(64 * 4); R->cand_val = cx.alloc(64 * 4);
R->mpos_arr = cx.alloc(64 * 4); R->mnxt = cx.alloc(N * 4); R->agm = cx.alloc(64 * 4);
R->mcache = cx.alloc(size_t((E.max_ctx + 64 + 7) / 8 * 8) * E.c.mla_latent_vals() * 4);
R->mcache = cx.alloc(E.cache_rows() * E.c.mla_latent_vals() * 4);
R->mcacheh = cx.alloc(E.cache_rows() * E.c.mla_latent_vals() * 4);
// KDA snapshots of a verify of up to K + 1 rows
E.snap_slots = K;
E.ext_len = 3 + K + 1;
+143
View File
@@ -337,3 +337,146 @@ kernel void moe_act_rows(device const uchar* sec4 [[buffer(0)]], device const Ex
al[at] = half(v[i] - float(h));
}
}
// ------------------------------------------------------------------------------------------------ prefill attention on the matrix unit (fp16 hi / lo, 3 products per fp32-like product)
// Q rows (token t, head h) = row t * H + h of [qabs 512 | rope part of q 64] as halves qh (hi) and ql (lo = remainder). grid N * H, 64 threads
kernel void mla_q_halves(device const float* qabs [[buffer(0)]], device const float* q [[buffer(1)]], device half* qh [[buffer(2)]], device half* ql [[buffer(3)]],
uint row [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
constexpr int W = L32_KVL + L32_ROPE;
for (int k = int(tid); k < W; k += 64) {
const float v = k < L32_KVL ? qabs[(ulong)row * L32_KVL + k] : q[(ulong)row * (L32_NOPE + L32_ROPE) + L32_NOPE + (k - L32_KVL)];
const half hv = half(v);
qh[(ulong)row * W + k] = hv;
ql[(ulong)row * W + k] = half(v - float(hv));
}
}
// One threadgroup (8 simdgroups) = ONE token with all its H = 32 heads (32 rows): the keys are shared by the heads, so every key tile is used by 32 rows.
// S = Q K^T over the 576 dims (9 steps of 64, products Qh Kh + Qh Kl + Ql Kh), online softmax in threadgroup memory (P scaled by 4096 so that the halves do not lose the small weights),
// O += P V (V = the first 512 dims of the key rows, 4 column groups of 128 dims, the same 3 products), O stays in the registers of the matrix unit (cooperative tensors).
// kh / kl: the latent cache rows as halves (hi, lo), row stride 576. grid N, 256 threads
#ifndef MLA_MPP_KB
#define MLA_MPP_KB 128
#endif
kernel void mla_attn_mpp(device const half* qh [[buffer(0)]], device const half* ql [[buffer(1)]], device const half* kh [[buffer(2)]], device const half* kl [[buffer(3)]],
device const int* d_pos0 [[buffer(4)]], device float* ctx [[buffer(5)]], constant float& scale [[buffer(6)]],
uint t [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) {
constexpr int W = L32_KVL + L32_ROPE, KB = MLA_MPP_KB, KPT = MLA_MPP_KB / 8, TM = 32, SGN = 8, NTH = SGN * 32, DC = 128, NDS = W / 64;
constexpr float PSC = 4096.0f;
threadgroup float Ss[TM * KB];
threadgroup half* Ph = (threadgroup half*)Ss; // P (hi, lo halves) overwrites S in place (every thread has read its scores into registers before the barrier)
threadgroup half* Pl = Ph + TM * KB;
threadgroup float mrow[TM], lrow[TM], corr[TM];
threadgroup int changed;
const int lim = *d_pos0 + int(t); // the last key this token sees
const int nkb = (lim + KB) / KB; // blocks of 64 keys
tensor<device half, dextents<int32_t, 2>, tensor_inline> tQh((device half*)qh, dextents<int32_t, 2>(W, 1 << 30));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tQl((device half*)ql, dextents<int32_t, 2>(W, 1 << 30));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tKh((device half*)kh, dextents<int32_t, 2>(W, 1 << 30));
tensor<device half, dextents<int32_t, 2>, tensor_inline> tKl((device half*)kl, dextents<int32_t, 2>(W, 1 << 30));
tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline> tS(Ss, dextents<int32_t, 2>(KB, TM));
tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tPh(Ph, dextents<int32_t, 2>(KB, TM));
tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline> tPl(Pl, dextents<int32_t, 2>(KB, TM));
constexpr auto descS = matmul2d_descriptor(TM, KB, 64, false, true, false, matmul2d_descriptor::mode::multiply_accumulate);
constexpr auto descP = matmul2d_descriptor(TM, DC, KB, false, false, false, matmul2d_descriptor::mode::multiply_accumulate);
matmul2d<descS, execution_simdgroups<SGN>> opS;
matmul2d<descP, execution_simdgroups<SGN>> opP;
auto tAq0 = tQh.slice<64, TM>(0, int(t) * TM);
auto tBk0 = tKh.slice<64, KB>(0, 0);
auto tAp0 = tPh.slice<KB, TM>(0, 0);
auto tBv0 = tKh.slice<DC, KB>(0, 0);
auto S = opS.get_destination_cooperative_tensor<decltype(tAq0), decltype(tBk0), float>();
auto O0 = opP.get_destination_cooperative_tensor<decltype(tAp0), decltype(tBv0), float>();
auto O1 = opP.get_destination_cooperative_tensor<decltype(tAp0), decltype(tBv0), float>();
auto O2 = opP.get_destination_cooperative_tensor<decltype(tAp0), decltype(tBv0), float>();
auto O3 = opP.get_destination_cooperative_tensor<decltype(tAp0), decltype(tBv0), float>();
const uint16_t capS = S.get_capacity(), capO = O0.get_capacity();
int rowO[TM * DC / NTH], colO[TM * DC / NTH];
for (uint16_t i = 0; i < capO; ++i) {
O0[i] = 0.0f; O1[i] = 0.0f; O2[i] = 0.0f; O3[i] = 0.0f;
rowO[i] = O0.is_valid_element(i) ? int(O0.get_multidimensional_index(i)[1]) : 0;
colO[i] = O0.is_valid_element(i) ? int(O0.get_multidimensional_index(i)[0]) : 0;
}
if (tid < TM) { mrow[tid] = -FLT_MAX; lrow[tid] = 0.0f; }
threadgroup_barrier(mem_flags::mem_threadgroup);
for (int kb = 0; kb < nkb; ++kb) {
const int k0 = kb * KB;
for (uint16_t i = 0; i < capS; ++i) S[i] = 0.0f;
for (int ds = 0; ds < NDS; ++ds) {
auto aH = tQh.slice<64, TM>(ds * 64, int(t) * TM);
auto aL = tQl.slice<64, TM>(ds * 64, int(t) * TM);
auto bH = tKh.slice<64, KB>(ds * 64, k0);
auto bL = tKl.slice<64, KB>(ds * 64, k0);
opS.run(aH, bH, S);
opS.run(aH, bL, S);
opS.run(aL, bH, S);
}
S.store(tS);
threadgroup_barrier(mem_flags::mem_threadgroup);
{ // online softmax: 8 threads per row, 8 keys each
const int r = int(tid) >> 3, c0 = (int(tid) & 7) * KPT;
float sv[KPT];
float mb = -FLT_MAX;
#pragma unroll
for (int j = 0; j < KPT; ++j) {
sv[j] = (k0 + c0 + j <= lim) ? Ss[r * KB + c0 + j] * scale : -INFINITY;
mb = max(mb, sv[j]);
}
for (ushort o = 4; o >= 1; o >>= 1) mb = max(mb, simd_shuffle_xor(mb, o));
threadgroup_barrier(mem_flags::mem_threadgroup); // all scores are in registers: P may overwrite S
const float mold = mrow[r];
const float mnew = max(mold, mb);
float ps = 0.0f;
#pragma unroll
for (int j = 0; j < KPT; ++j) {
const float p = exp(sv[j] - mnew);
ps += p;
const half hp = half(p * PSC);
Ph[r * KB + c0 + j] = hp;
Pl[r * KB + c0 + j] = half(p * PSC - float(hp));
}
for (ushort o = 4; o >= 1; o >>= 1) ps += simd_shuffle_xor(ps, o);
if ((tid & 7) == 0) {
const float cr = exp(mold - mnew);
corr[r] = cr;
lrow[r] = lrow[r] * cr + ps;
mrow[r] = mnew;
}
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid == 0) {
int ch = 0;
for (int r = 0; r < TM; ++r) ch |= corr[r] != 1.0f;
changed = ch;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (changed) {
for (uint16_t i = 0; i < capO; ++i) {
const float cr = corr[rowO[i]];
O0[i] *= cr; O1[i] *= cr; O2[i] *= cr; O3[i] *= cr;
}
}
{
auto pH = tPh.slice<KB, TM>(0, 0);
auto pL = tPl.slice<KB, TM>(0, 0);
auto v0H = tKh.slice<DC, KB>(0 * DC, k0); auto v0L = tKl.slice<DC, KB>(0 * DC, k0);
opP.run(pH, v0H, O0); opP.run(pH, v0L, O0); opP.run(pL, v0H, O0);
auto v1H = tKh.slice<DC, KB>(1 * DC, k0); auto v1L = tKl.slice<DC, KB>(1 * DC, k0);
opP.run(pH, v1H, O1); opP.run(pH, v1L, O1); opP.run(pL, v1H, O1);
auto v2H = tKh.slice<DC, KB>(2 * DC, k0); auto v2L = tKl.slice<DC, KB>(2 * DC, k0);
opP.run(pH, v2H, O2); opP.run(pH, v2L, O2); opP.run(pL, v2H, O2);
auto v3H = tKh.slice<DC, KB>(3 * DC, k0); auto v3L = tKl.slice<DC, KB>(3 * DC, k0);
opP.run(pH, v3H, O3); opP.run(pH, v3L, O3); opP.run(pL, v3H, O3);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
}
for (uint16_t i = 0; i < capO; ++i) {
if (!O0.is_valid_element(i)) continue;
const float inv = 1.0f / (PSC * lrow[rowO[i]]);
device float* out = ctx + ((ulong)t * TM + rowO[i]) * L32_KVL + colO[i];
out[0 * DC] = O0[i] * inv;
out[1 * DC] = O1[i] * inv;
out[2 * DC] = O2[i] * inv;
out[3 * DC] = O3[i] * inv;
}
}