diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index 9c50ff575d..0caae6eea8 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -10,7 +10,7 @@ debugging and are kept in `terminal/data/settings-register.json`. A number or a word is set like any environment variable, for example `STRATA_KVA=1`. In the Terminal, `strata launch --set NAME=value` puts it in the model's run configuration. -## Switches you can turn on (456) +## Switches you can turn on (455) Off unless you set them. The last column says where each one is described. @@ -261,7 +261,6 @@ Off unless you set them. The last column says where each one is described. | `STRATA_KV_HOST_REGISTER` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_KV_PREFETCH` | number | NVIDIA and AMD, Intel Arc | [KV_PREFETCH.md](KV_PREFETCH.md), [README.md](bench-results/README.md), [README.md](bench-results/2026-10-06-community-rtx4090-opt-ins/README.md) | | `STRATA_KV_ROT` | on / off | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md), [SPLIT_SERVE.md](SPLIT_SERVE.md) | -| `STRATA_L32_GPU_CAP_GIB` | number | NVIDIA and AMD | - | | `STRATA_L32_MTP_ONLINE` | on / off | NVIDIA and AMD | - | | `STRATA_L32_SEGMENTED` | on / off | NVIDIA and AMD | - | | `STRATA_L3_PF` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | @@ -473,7 +472,7 @@ Off unless you set them. The last column says where each one is described. | `STRATA_WATCHDOG_S` | text | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md) | | `STRATA_WDDM_BUDGET` | number | AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md) | -## Switches that go back to earlier behaviour (158) +## Switches that go back to earlier behaviour (157) These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which version made it the default. @@ -556,7 +555,6 @@ version made it the default. | `STRATA_L32_MTP_POOL` | on / off | NVIDIA and AMD | - | - | | `STRATA_L32_PF_VERIFY` | number | NVIDIA and AMD | - | - | | `STRATA_L32_PRELOAD` | on / off | NVIDIA and AMD | - | - | -| `STRATA_L32_PROBE_ALLOC` | on / off | AMD | - | - | | `STRATA_L32_SPAN_HINT` | number | NVIDIA and AMD | - | - | | `STRATA_L32_SPEC_SPAN` | on / off | NVIDIA and AMD | - | - | | `STRATA_L32_TIER_GROUPED_OFF` | on / off | NVIDIA and AMD | - | - | diff --git a/engine/src/ling32/ling32_engine.cu b/engine/src/ling32/ling32_engine.cu index 08bd062c03..f2b84bcf05 100644 --- a/engine/src/ling32/ling32_engine.cu +++ b/engine/src/ling32/ling32_engine.cu @@ -921,6 +921,8 @@ struct Ling32Engine::StageCtx { gpu::gemv_f32(M.gate_w, c.n_exp, D, cur, N, rlog, st); gpu::alflb_route(rlog, nullptr, M.gate_bias, c.n_exp, c.n_group, c.topk_group, c.top_k, c.routed_scale, true, ridx, rw, N, st); } + // opt-in, not exact (--skip-tau / STRATA_L32_SKIP_TAU): drop a decode / verify token's routed experts below tau of its routing weight (the tier store then fetches nothing for them) + if (o.skip_tau > 0.0f && N <= 16 && il < c.n_layers) gpu::prune_experts(ridx, rw, N, c.top_k, o.skip_tau, st); if (uniq_on && N > 1 && il < c.n_layers) gpu::count_unique(ridx, N * c.top_k, c.n_exp, d_uniq + il, st); if (il < c.n_layers && h_ridx[il]) { cudaMemcpyAsync(h_ridx[il], ridx, static_cast(N) * c.top_k * sizeof(int), cudaMemcpyDeviceToHost, st); diff --git a/engine/src/ling32/ling32_engine.hpp b/engine/src/ling32/ling32_engine.hpp index 815a69c19f..c7a28d783e 100644 --- a/engine/src/ling32/ling32_engine.hpp +++ b/engine/src/ling32/ling32_engine.hpp @@ -64,6 +64,7 @@ struct EngineOptions { bool kda_chunked = true; // N > 1: the chunk-parallel KDA form (false: the sequential recurrence) bool lookahead_group_mask = true; // rank with the router's group-limited mask (top-4 of 8 groups); false: no mask (L32-ART: better at K >= 16, the tail a prefetcher fills) int lookahead_ks = 3; // which predictors to evaluate: bit 0 = k 2, bit 1 = k 4 (the tiers use one) + float skip_tau = 0.0f; // --skip-tau T / STRATA_L32_SKIP_TAU (opt-in, NOT exact, default off): a decode / verify token's routed experts whose share of its routing weight is below T are dropped (top expert kept, weights renormalized, nothing fetched for them) bool lookahead_k1 = false; // L32-TIER: also a k = 1 prediction per MoE layer (its own router on the residual entering it); needs `lookahead` and a demand sink bool lookahead_stats = true; // log prediction vs truth (off in a tier run unless asked: it costs host time per layer) bool lookahead = false; // evaluate the Section 2 lookahead routers (needs LoadOptions::load_lookahead) and log prediction vs truth diff --git a/engine/src/ling32/ling32_kernels.hpp b/engine/src/ling32/ling32_kernels.hpp index e229e67615..4d5277ebce 100644 --- a/engine/src/ling32/ling32_kernels.hpp +++ b/engine/src/ling32/ling32_kernels.hpp @@ -212,6 +212,8 @@ extern int g_alflb_ref; // 1: use the one-warp reference routing kernel (tests extern int g_alflb_look; // 1: the lookahead lists (top_n > 8) also use the parallel kernel (default: HIP 1, CUDA 0; STRATA_L32_ALFLB_LOOKAHEAD) void alflb_route(const float* logits, const float* add_bias, const float* sel_bias, int E, int n_group, int topk_group, int top_n, float scale, bool weights, int* out_idx, float* out_w, int N, cudaStream_t s); +// dynamic expert skip (opt-in, not exact): drop the routed experts below tau of a token's routing weight (see the kernel); the dropped slot repeats the token's top expert with weight 0 +void prune_experts(int* ridx, float* rw, int N, int top_k, float tau, cudaStream_t s); // ---- SwiGLU with the per-layer clamp (lim <= 0: none) // out[t][r] = swiglu(gate_r . x_t, up_r . x_t) over two S8_K matrices in one pass; float activations, N <= 16 per launch group diff --git a/engine/src/ling32/ling32_layers.cu b/engine/src/ling32/ling32_layers.cu index eafdb01d61..f843c3f07d 100644 --- a/engine/src/ling32/ling32_layers.cu +++ b/engine/src/ling32/ling32_layers.cu @@ -1805,6 +1805,39 @@ void alflb_route(const float* logits, const float* add_bias, const float* sel_bi alflb_kernel<<>>(logits, add_bias, sel_bias, E, n_group, topk_group, top_n, scale, weights ? 1 : 0, out_idx, out_w); } +// Dynamic expert skip (opt-in measurement, STRATA_L32_SKIP_TAU; NOT exact): per token, a routed expert whose share of the token's routing weight is below tau is dropped (the top expert is always kept): +// its slot gets the token's top expert id with weight 0 (the id is resident for the layer anyway, so the tier store fetches nothing for it, and the kernels add an exact zero), and the weights of the kept +// experts are scaled so that the sum of the token's routing weights stays the same. +__global__ void prune_experts_kernel(int* ridx, float* rw, int N, int top_k, float tau) { + const int t = blockIdx.x * blockDim.x + threadIdx.x; + if (t >= N) return; + int* ix = ridx + static_cast(t) * top_k; + float* w = rw + static_cast(t) * top_k; + float sum = 0.0f, wmax = -1.0f; + int imax = 0; + for (int j = 0; j < top_k; ++j) { + sum += w[j]; + if (w[j] > wmax) { wmax = w[j]; imax = j; } + } + if (!(sum > 0.0f)) return; + float kept = 0.0f; + int drops = 0; + for (int j = 0; j < top_k; ++j) { + if (j != imax && w[j] < tau * sum) ++drops; else kept += w[j]; + } + if (drops == 0 || !(kept > 0.0f)) return; + const float scale = sum / kept; + const int top_id = ix[imax]; + for (int j = 0; j < top_k; ++j) { + if (j != imax && w[j] < tau * sum) { ix[j] = top_id; w[j] = 0.0f; } + else w[j] *= scale; + } +} + +void prune_experts(int* ridx, float* rw, int N, int top_k, float tau, cudaStream_t s) { + prune_experts_kernel<<<(N + 31) / 32, 32, 0, s>>>(ridx, rw, N, top_k, tau); +} + void swiglu(const float* g, int gs, const float* u, int us, float lim, bool post_silu, float* out, int os, int N, int I, cudaStream_t s) { swiglu_kernel<<>>(g, gs, u, us, lim, post_silu ? 1 : 0, out, os, I); } diff --git a/engine/src/ling32/ling32_main.cpp b/engine/src/ling32/ling32_main.cpp index 7fc94505b9..2ae04428cc 100644 --- a/engine/src/ling32/ling32_main.cpp +++ b/engine/src/ling32/ling32_main.cpp @@ -210,6 +210,7 @@ struct RunOpts { int logits_rows_opt = -1; // --logits-rows N: rows of the engine's logits buffer (0 = a whole chunk; -1 = 32 for --serve / --genjobs, which ask for few rows, else a whole chunk: the teacher-forced modes dump every row) int kv_init_opt = -1; // --kv-init N: lazy latent KV, initial capacity in rows (0 = reserve the whole context up front; -1 = 16384 in tier B / C, the cache then grows with the conversation and the tier store gives pool slots back); STRATA_L32_LAZY_KV=0 also switches it off int kv_plan_rows = 0; // set by make_plan: the rows make_sizes counts for the latent cache (0 = o.ctx) + float skip_tau = -1.0f; // --skip-tau T: dynamic expert skip threshold (< 0: STRATA_L32_SKIP_TAU, default off) int regrow_opt = -1; // --regrow on|off: scratch regrow (the activation scratch of a chunk only while a prompt is prefilled, the memory goes back to the expert pool for decode); -1 = STRATA_L32_REGROW (default off), tier B / C with lazy KV only int decode_rows_opt = 64; // --decode-rows N: rows of the always-resident scratch set of scratch regrow bool regrow_plan = false; // set by make_plan: make_sizes counts decode_rows_opt rows of activation scratch instead of the chunk @@ -839,7 +840,9 @@ int cmd_run(const RunOpts& o_in) { GpuModel M; LoadOptions lo; lo.load_lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch); - if (tiered) lo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); + int la_ks_env = -1; // STRATA_L32_LA_KS (measurement): bit mask of the lookahead predictors to compute (1: k=2, 2: k=4, 3: both), e.g. with STRATA_L32_PF_K=2 in a tier B run + if (const char* e = std::getenv("STRATA_L32_LA_KS")) if (e[0]) la_ks_env = std::atoi(e) & 3; + if (tiered) lo.lookahead_ks = la_ks_env >= 0 ? la_ks_env : (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); lo.load_experts = !tiered; lo.verify_upload = false; lo.map_experts = o.map_experts; @@ -887,9 +890,12 @@ int cmd_run(const RunOpts& o_in) { eo.max_tokens = o.chunk; eo.logits_rows = o.logits_rows(); if (tiered && plan.kv_rows > 0) eo.kv_init_ctx = plan.kv_rows; // lazy latent KV (the plan counted only this) + if (o.skip_tau >= 0.0f) eo.skip_tau = o.skip_tau; + else if (const char* e = std::getenv("STRATA_L32_SKIP_TAU")) { if (e[0]) eo.skip_tau = static_cast(std::atof(e)); } + if (eo.skip_tau > 0.0f) std::printf("expert skip: tau %.3f (NOT exact: routed experts below that share of a token's routing weight are dropped at decode)\n", eo.skip_tau); if (tiered && plan.kv_rows > 0 && o.regrow()) { eo.scratch_regrow = true; eo.decode_rows = o.decode_rows_opt; } // the plan counted decode_rows rows of scratch only eo.lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch); - if (tiered) { eo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); eo.lookahead_stats = o.lookahead; } + if (tiered) { eo.lookahead_ks = la_ks_env >= 0 ? la_ks_env : (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); eo.lookahead_stats = o.lookahead; } eo.lookahead_group_mask = !o.la_nomask; eo.kda_chunked = !o.kda_seq; eo.profile = o.profile; @@ -1671,6 +1677,7 @@ int main(int argc, char** argv) { else if (a == "--logits-rows") o.logits_rows_opt = std::atoi(nx().c_str()); else if (a == "--kv-init") o.kv_init_opt = std::atoi(nx().c_str()); else if (a == "--regrow") { const std::string v = nx(); o.regrow_opt = (v == "on" || v == "1") ? 1 : 0; } + else if (a == "--skip-tau") o.skip_tau = static_cast(std::atof(nx().c_str())); // dynamic expert skip, opt-in, NOT exact (see EngineOptions::skip_tau) else if (a == "--decode-rows") o.decode_rows_opt = std::max(1, std::atoi(nx().c_str())); else if (a == "--device") o.device = std::atoi(nx().c_str()); else if (a == "--topk") o.topk = std::atoi(nx().c_str()); diff --git a/engine/src/ling32/metal/ab_env.sh b/engine/src/ling32/metal/ab_env.sh new file mode 100644 index 0000000000..9c9e886a93 --- /dev/null +++ b/engine/src/ling32/metal/ab_env.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# ab_env.sh PAIRS PROMPT BIN "ENV_A" "ENV_B": interleaved A / B of the 1 / 2 / 3 / 4 / 6 / 8-row step times in ms (--bench-rows, after a PROMPT-token prompt, ctx 131072, chunk 4096; the metric is the 1-row step, smaller is faster), +# one binary, two environment settings (e.g. "L32_GEMV_UB=1" and "L32_GEMV_UB=4"; kernels are compiled at run time with the setting). Call it through l32run.sh (GPU lock) / bg_run3.sh. +PAIRS=$1; TOK=$2; BIN=$3; EA=$4; EB=$5 +M=$HOME/strata-mac/ling32/models/Ling-3.2-Air-SQ-96.strata +ra=(); rb=() +for i in $(seq 1 $PAIRS); do + for w in A B; do + if [ $w = A ]; then e=$EA; else e=$EB; fi + out=$(env $e $BIN --model $M --ctx 131072 --chunk 4096 --bench-prompt $TOK --gen 64 --reps 2 --bench-rows 1 2>&1) + r=$(echo "$out" | grep "^rows" | sed 's/rows \([0-9]*\): \([0-9.]*\) ms.*/\1=\2/' | tr '\n' ' ') + v=$(echo "$out" | grep "^rows 1:" | sed 's/rows 1: \([0-9.]*\) ms.*/\1/') # metric: ms of the 1-row step (smaller is faster) + echo "pair $i $w ($e): 1-row step $v ms; rows $r" + if [ $w = A ]; then ra+=($v); else rb+=($v); fi + done +done +echo "A: ${ra[*]}" +echo "B: ${rb[*]}" +echo "${ra[*]}" | tr ' ' '\n' | sort -n | awk '{a[NR]=$1} END {printf "median A %s ", a[int((NR+1)/2)]}' +echo "${rb[*]}" | tr ' ' '\n' | sort -n | awk '{a[NR]=$1} END {printf "median B %s\n", a[int((NR+1)/2)]}' +n=0; for i in $(seq 0 $((PAIRS - 1))); do if awk -v x="${rb[$i]}" -v y="${ra[$i]}" 'BEGIN {exit !(x < y)}'; then n=$((n + 1)); fi; done +echo "B faster in $n of $PAIRS pairs" diff --git a/engine/src/ling32/metal/decode_budget.sh b/engine/src/ling32/metal/decode_budget.sh new file mode 100644 index 0000000000..50d45afcef --- /dev/null +++ b/engine/src/ling32/metal/decode_budget.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# decode_budget.sh: the data of the decode budget at the launcher's default maximum context (ctx 131072), after a 512-token prompt (a chat) and a 4000-token prompt (documents): +# 1. the time of a verify-shaped step with 1..8 rows (weights read once, logits of every row): --bench-rows +# 2. the per-dispatch profile of one KDA layer and one MLA layer of the decode step (N = 1), each dispatch alone in its own command buffer +# Run through bg_run3.sh on m1002 (about 5 minutes). +S=$HOME/strata-mac/ling32 +B=$S/bin/ling32-metal +M=$S/models/Ling-3.2-Air-SQ-96.strata +for P in 512 4000; do + echo "=== rows benchmark, ctx 131072, prompt $P" + $B --model $M --ctx 131072 --chunk 4096 --bench-prompt $P --bench-rows 1 2>&1 | grep -E "^rows" +done +echo "=== per-dispatch profile of the decode step, ctx 131072, prompt 512" +$B --model $M --ctx 131072 --chunk 4096 --bench-prompt 512 --gen 2 --reps 1 --profile 2>&1 | grep -E "^\[layer [35]|^ [a-z_0-9]+ +[0-9.]+ us|^ sum |^prefill [0-9]" | head -60 | cut -c1-110 diff --git a/engine/src/ling32/metal/gold_bitcmp.sh b/engine/src/ling32/metal/gold_bitcmp.sh new file mode 100644 index 0000000000..985c4a933c --- /dev/null +++ b/engine/src/ling32/metal/gold_bitcmp.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# gold_bitcmp.sh ONLY_IDS ENV_A ENV_B [engine args...]: (Windows, Git Bash) runs the golden jobs ONLY_IDS on m1002 twice (detached, bg_run3.sh, timeout 1500 s each) with the environment ENV_A (jobs cbA) and ENV_B (jobs cbB), then prints +# the golden_compare table of each and whether the two output folders are byte-identical (cmp of every file). For changes that must be bit-identical. +ONLY=$1; EA=$2; EB=$3; shift 3; EXTRA="$*" +D=/c/w-ling32-metal/engine/src/ling32/metal +run() { # name env + ssh m1002 "S=~/strata-mac/ling32; $2 TMO=1500 bash \$S/bg_run3.sh $1 bash \$S/goldrun.sh $1 $ONLY $EXTRA" > /dev/null + until ssh -o ConnectTimeout=20 m1002 "grep -qE '^bg-done|^bg-timeout' ~/strata-mac/ling32/logs/bg-$1.log" 2>/dev/null; do sleep 15; done + ssh m1002 "tail -2 ~/strata-mac/ling32/logs/bg-$1.log" | grep -E "bg-done|bg-timeout" + bash $D/goldcmp.sh $1 2>&1 | grep -E "^ALL|^long_|^id " | cut -c1-200 +} +echo "== A: $EA"; run cbA "$EA" +echo "== B: $EB"; run cbB "$EB" +ssh m1002 'S=~/strata-mac/ling32; n=0; d=0; for f in $(cd $S/out/cbA && find . -type f); do n=$((n+1)); cmp -s $S/out/cbA/$f $S/out/cbB/$f || { d=$((d+1)); echo "differs: $f"; }; done; echo "files $n, different $d"' diff --git a/engine/src/ling32/metal/ling32_core.metal b/engine/src/ling32/metal/ling32_core.metal index 14925729c2..e5177f641b 100644 --- a/engine/src/ling32/metal/ling32_core.metal +++ b/engine/src/ling32/metal/ling32_core.metal @@ -591,6 +591,33 @@ kernel void mla_qabs(device const float* q [[buffer(0)]], device const ushort* w for (int d = 0; d < L32_NOPE; ++d) acc += qs[d] * bf16f_(wk[((ulong)h * L32_NOPE + d) * L32_KVL + k]); qabs[(ulong)th * L32_KVL + k] = acc; } +// the same for decode / verify rows (N <= 4): one simdgroup per (row x head, tile of 128 latent dims), 4 consecutive latent dims per lane (one 8-byte load per weight row), the weight loads of 8 rows in flight; +// every output dimension keeps its own sequential sum over the 128 nope dims: bit-identical. grid (N*H, KVL/128), 32 threads +kernel void mla_qabs_d(device const float* q [[buffer(0)]], device const ushort* wk [[buffer(1)]], device float* qabs [[buffer(2)]], + device const int* d_pos0 [[buffer(3)]], constant int& absmin [[buffer(4)]], constant int& Nq [[buffer(5)]], + uint2 gid [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + if (*d_pos0 + Nq <= absmin) return; + const int th = int(gid.x), h = th % L32_H; + threadgroup float qs[L32_NOPE]; + for (int d = int(tid); d < L32_NOPE; d += 32) qs[d] = q[(ulong)th * (L32_NOPE + L32_ROPE) + d]; + threadgroup_barrier(mem_flags::mem_threadgroup); + const int k = int(gid.y) * 128 + int(tid) * 4; + float4 acc = float4(0.0f); + for (int d0 = 0; d0 < L32_NOPE; d0 += 8) { + ushort4 w[8]; +#pragma unroll + for (int u = 0; u < 8; ++u) w[u] = *(device const ushort4*)(wk + ((ulong)h * L32_NOPE + d0 + u) * L32_KVL + k); +#pragma unroll + for (int u = 0; u < 8; ++u) { + const float qv = qs[d0 + u]; + acc.x += qv * bf16f_(w[u].x); + acc.y += qv * bf16f_(w[u].y); + acc.z += qv * bf16f_(w[u].z); + acc.w += qv * bf16f_(w[u].w); + } + } + *(device float4*)(qabs + (ulong)th * L32_KVL + k) = acc; +} // combine the splits: ctx[th][k] = sum_s acc_s[k] e^(m_s - M) / sum_s l_s e^(m_s - M). grid N*H, 256 threads kernel void mla_attn_combine(device const float* part [[buffer(0)]], device float* ctx [[buffer(1)]], constant int& S [[buffer(2)]], device const int* d_pos0 [[buffer(3)]], constant int& reg_lo [[buffer(4)]], constant int& reg_hi [[buffer(5)]], constant int& kc [[buffer(6)]], uint th [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { @@ -862,6 +889,81 @@ kernel void add_rmsnorm(device float* x [[buffer(0)]], device const float* dlt [ } } +// The same two kernels with 1024 threads per row (4 of the 16 element slots per thread: the latency chain of loads is 4x shorter, the row's threadgroup fills a whole core). The result is BIT-IDENTICAL to the 256-thread kernels: +// the per-slot values go through threadgroup memory and the first 256 threads sum their 16 slots in the original order, then the same simdgroup / 8-partial reduction. +constexpr constant int NW_ = (NV_ + 3) / 4; // slots per thread: thread q (0..3) of a column takes the slots q, q + 4, ... below NV_ (L32_D = 2560: NV_ = 10 slots) +inline float rms_tail_w(threadgroup float* xs, threadgroup float* sm, uint tid) { + if (tid < 256) { + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < NV_; ++j) { const float v = xs[j * 256 + tid]; ss += v * v; } + ss = simd_sum(ss); + if ((tid & 31) == 0) sm[tid >> 5] = ss; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float r = 0.0f; + for (uint i = 0; i < 8; ++i) r += sm[i]; + return 1.0f / sqrt(r / float(L32_D) + L32_EPS); +} +kernel void moe_combine_norm_w(device float* x [[buffer(0)]], device const float* ye [[buffer(1)]], device const float* w [[buffer(2)]], device const float* ysh [[buffer(3)]], + device const float* gamma [[buffer(4)]], device float* y [[buffer(5)]], constant int& has_norm [[buffer(6)]], device const int* posmap [[buffer(7)]], constant int& use_pos [[buffer(8)]], + uint t [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + threadgroup float xs[NV_ * 256]; + threadgroup float sm[8]; + const int t0 = int(tid) & 255, q = int(tid) >> 8; + float xv[NW_]; +#pragma unroll + for (int i = 0; i < NW_; ++i) { + const int j = q + 4 * i; + if (j >= NV_) break; + const int d = t0 + j * 256; + float s = 0.0f; + for (int k = 0; k < L32_TOPK; ++k) s += w[t * L32_TOPK + k] * ye[(ulong)(use_pos ? posmap[t * L32_TOPK + k] : (t * L32_TOPK + k)) * L32_D + d]; + const ulong at = (ulong)t * L32_D + d; + const float v = (x[at] + ysh[at]) + s; + x[at] = v; + xv[i] = v; + xs[j * 256 + t0] = v; + } + if (!has_norm) return; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float r = rms_tail_w(xs, sm, tid); +#pragma unroll + for (int i = 0; i < NW_; ++i) { + const int j = q + 4 * i; + if (j >= NV_) break; + const int d = t0 + j * 256; + y[(ulong)t * L32_D + d] = xv[i] * r * gamma[d]; + } +} +kernel void add_rmsnorm_w(device float* x [[buffer(0)]], device const float* dlt [[buffer(1)]], device const float* gamma [[buffer(2)]], device float* y [[buffer(3)]], + constant int& has_d [[buffer(4)]], uint t [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + threadgroup float xs[NV_ * 256]; + threadgroup float sm[8]; + const int t0 = int(tid) & 255, q = int(tid) >> 8; + float xv[NW_]; +#pragma unroll + for (int i = 0; i < NW_; ++i) { + const int j = q + 4 * i; + if (j >= NV_) break; + const int d = t0 + j * 256; + const ulong at = (ulong)t * L32_D + d; + const float v = has_d ? x[at] + dlt[at] : x[at]; + if (has_d) x[at] = v; + xv[i] = v; + xs[j * 256 + t0] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float r = rms_tail_w(xs, sm, tid); +#pragma unroll + for (int i = 0; i < NW_; ++i) { + const int j = q + 4 * i; + if (j >= NV_) break; + const int d = t0 + j * 256; + y[(ulong)t * L32_D + d] = xv[i] * r * gamma[d]; + } +} + kernel void copy_row_k(device const float* src [[buffer(0)]], device float* dst [[buffer(1)]], constant int& n [[buffer(2)]], uint i [[thread_position_in_grid]]) { if (int(i) < n) dst[i] = src[i]; } diff --git a/engine/src/ling32/metal/ling32_metal_main.cpp b/engine/src/ling32/metal/ling32_metal_main.cpp index 25805509e7..462ad0fcef 100644 --- a/engine/src/ling32/metal/ling32_metal_main.cpp +++ b/engine/src/ling32/metal/ling32_metal_main.cpp @@ -504,8 +504,11 @@ struct Engine { void add(const std::string& kernel, std::vector args, uint32_t gx, uint32_t gy, uint32_t gz, uint32_t tgx) { static const std::string skip = std::getenv("L32_SKIP_DISP") ? std::getenv("L32_SKIP_DISP") : ""; // TIMING EXPERIMENT ONLY (results are wrong): ",name1,name2," drops these dispatches from the tape if (!skip.empty() && skip.find("," + kernel + ",") != std::string::npos) { nb_next = false; return; } + static const int cnw = std::getenv("L32_CNW") ? std::atoi(std::getenv("L32_CNW")) : 1; // the combine / add + norm kernels of decode and verify rows (up to 4 rows) run with 1024 threads per row instead of 256 (bit-identical result, shorter load chain: 1-row step -5.1 %); env L32_CNW=0 turns it off (1 both, 2 add only, 3 combine only) + std::string kname = kernel; + if (cnw && gx <= 4 && ((kernel == "add_rmsnorm" && cnw != 3) || (kernel == "moe_combine_norm" && cnw != 2))) { kname += "_w"; tgx = 1024; } mtl::Dispatch d; - d.p = &E.P(kernel); + d.p = &E.P(kname); d.args = std::move(args); d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz; d.tg[0] = tgx; @@ -601,7 +604,9 @@ struct Engine { NB(t, N); t.add("mla_prep_q", {B(R(q)), B(R(rope_tab)), B(posr.b ? posr : R(pos))}, N, H, 1, 32); NB(t, N); - t.add("mla_qabs", {B(R(q)), B(ar(M.wk_b)), B(R(qabs)), B(posref), I(absmin), I(N)}, N * H, c.kv_lora / 128, 1, 128); + static const bool qabs_d = !std::getenv("L32_QABS_D") || std::atoi(std::getenv("L32_QABS_D")) != 0; // decode / verify rows: one simdgroup per tile, 8-byte weight loads (bit-identical); L32_QABS_D=0: the plain kernel + if (qabs_d && N <= 4) t.add("mla_qabs_d", {B(R(q)), B(ar(M.wk_b)), B(R(qabs)), B(posref), I(absmin), I(N)}, N * H, c.kv_lora / 128, 1, 32); + else t.add("mla_qabs", {B(R(q)), B(ar(M.wk_b)), B(R(qabs)), B(posref), I(absmin), I(N)}, N * H, c.kv_lora / 128, 1, 128); if (N <= 16 && mla_kc > 0) { // decode / verify: split-K over the keys (32 heads alone would leave the GPU idle) const float asc = 1.0f / std::sqrt(float(c.nope + c.rope)); const bool use_mmah = mla_mmah && H % 8 == 0 && H % 4 == 0 && max_ctx > mla_thr; // long contexts only: the latency of one split block (about 160 us) loses to part4 below about 8K @@ -945,6 +950,7 @@ struct Opts { bool mla_ht4 = false; int logits_rows = 0; int bench_prompt = 0; + int bench_rows = 0; // --bench-rows 1: time the multi-row decode step (1..8 rows, logits of every row) at a fixed position after the prompt VisionRunOpts vis; // --vision FILE --image F [--image G ...] --vision-device auto|cpu|gpu --vision-threads N --vision-max-pixels N --newline-id N (the prompt's <|image_pad|> placeholders) std::string mm_runs; // --mm-runs FILE: a batch of picture / text prompts in one process (run_mm_batch) }; @@ -1376,6 +1382,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 if (a == "--bench-rows") o.bench_rows = std::atoi(nx().c_str()); else if (a == "--vision") o.vis.file = nx(); else if (a == "--image") o.vis.images.push_back(nx()); else if (a == "--vision-device") o.vis.backend = nx(); // auto | cpu | gpu: this engine has the CPU encoder only @@ -1646,6 +1653,22 @@ int main(int argc, char** argv) { std::printf("dumped %d tokens to %s\n", N, o.dump.c_str()); return 0; } + if (o.bench_rows > 0) { // the verify-shaped step: N rows through the whole trunk (weights read once), logits of every row, timed at a fixed position (the state keeps advancing: only the time matters) + for (size_t at = 0; at < prompt.size(); at += size_t(E.Nmax)) { + const int len = int(std::min(size_t(E.Nmax), prompt.size() - at)); + if (!E.forward(prompt.data() + at, len, 1, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 1; } + } + std::vector bids(16, 1234); + for (int n : {1, 2, 3, 4, 6, 8}) { + for (int w = 0; w < 5; ++w) { E.forward(bids.data(), n, n, err); E.pos_ -= n; } + const int reps = 60; + const double tb = now_s(); + for (int r = 0; r < reps; ++r) { E.forward(bids.data(), n, n, err); E.pos_ -= n; } + const double ms = (now_s() - tb) * 1000.0 / reps; + std::printf("rows %d: %.3f ms per step (logits of all rows)\n", n, ms); + } + return 0; + } if (E.mtp) { // speculative greedy generation const int gen_n = o.gen >= 0 ? o.gen : 16; for (int rep = 0; rep <= o.reps; ++rep) { diff --git a/engine/src/ling32/metal/prof_layer.sh b/engine/src/ling32/metal/prof_layer.sh new file mode 100644 index 0000000000..86c0128bba --- /dev/null +++ b/engine/src/ling32/metal/prof_layer.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# prof_layer.sh: the per-dispatch profile of one KDA layer and one MLA layer of the decode step (N = 1, each dispatch alone in its own command buffer) at ctx 131072 after a 512-token prompt. Run through bg_run3.sh on m1002 (about 1 minute). +S=$HOME/strata-mac/ling32 +B=$S/bin/ling32-metal +M=$S/models/Ling-3.2-Air-SQ-96.strata +$B --model $M --ctx 131072 --chunk 4096 --bench-prompt 512 --gen 2 --reps 1 --profile 2>&1 | grep -E "^\[layer [35]|^ [a-z_0-9]+ +[0-9.]+ us|^ sum |^prefill [0-9]" | head -60 | cut -c1-110 diff --git a/engine/tests/ling32/ling32_bench.cu b/engine/tests/ling32/ling32_bench.cu index b2119a0dc2..7af306adf8 100644 --- a/engine/tests/ling32/ling32_bench.cu +++ b/engine/tests/ling32/ling32_bench.cu @@ -145,6 +145,42 @@ int main(int argc, char** argv) { std::printf(" ALF-LB top-32 lookahead route, %d groups (1 token): reference %7.2f us, parallel %7.2f us\n", tg, ta, tb); } } + { // dynamic expert skip (--skip-tau): the prune kernel against a CPU reference (same operations in the same order: bit-identical), tau 0.03 / 0.05 / 0.08 + long pbad = 0, ptotal = 0, pdropped = 0; + for (float tau : {0.03f, 0.05f, 0.08f}) { + const int PN = 512, PK = 8; + std::vector pw(static_cast(PN) * PK), prw; + std::vector pix(pw.size()), prix; + std::mt19937 pr(1234 + static_cast(tau * 1000)); + for (size_t i = 0; i < pw.size(); ++i) { pw[i] = 0.01f + 0.4f * ((pr() & 0xFFFF) / 65535.0f); pix[i] = static_cast(pr() % 512); } + prw = pw; prix = pix; + for (int t = 0; t < PN; ++t) { // CPU reference + float* w = prw.data() + static_cast(t) * PK; + int* ix = prix.data() + static_cast(t) * PK; + float sum = 0.0f, wmax = -1.0f; + int imax = 0; + for (int j = 0; j < PK; ++j) { sum += w[j]; if (w[j] > wmax) { wmax = w[j]; imax = j; } } + float kept = 0.0f; + int drops = 0; + for (int j = 0; j < PK; ++j) { if (j != imax && w[j] < tau * sum) ++drops; else kept += w[j]; } + if (drops == 0 || !(kept > 0.0f)) continue; + const float scale = sum / kept; + const int top_id = ix[imax]; + for (int j = 0; j < PK; ++j) { if (j != imax && w[j] < tau * sum) { ix[j] = top_id; w[j] = 0.0f; ++pdropped; } else w[j] *= scale; } + } + float* dw; int* dix; + CK(cudaMalloc(&dw, pw.size() * 4)); CK(cudaMalloc(&dix, pix.size() * 4)); + CK(cudaMemcpy(dw, pw.data(), pw.size() * 4, cudaMemcpyHostToDevice)); CK(cudaMemcpy(dix, pix.data(), pix.size() * 4, cudaMemcpyHostToDevice)); + gpu::prune_experts(dix, dw, PN, PK, tau, 0); + CK(cudaDeviceSynchronize()); + std::vector gw(pw.size()); std::vector gix(pix.size()); + CK(cudaMemcpy(gw.data(), dw, gw.size() * 4, cudaMemcpyDeviceToHost)); CK(cudaMemcpy(gix.data(), dix, gix.size() * 4, cudaMemcpyDeviceToHost)); + for (size_t i = 0; i < gw.size(); ++i) { ++ptotal; if (gix[i] != prix[i] || std::memcmp(&gw[i], &prw[i], 4) != 0) ++pbad; } + cudaFree(dw); cudaFree(dix); + } + std::printf(" expert skip (prune_experts) vs CPU reference: %ld of %ld (expert, weight) pairs differ (%ld slots dropped) %s\n", pbad, ptotal, pdropped, pbad == 0 && pdropped > 0 ? "IDENTICAL" : "MISMATCH"); + if (pbad || pdropped == 0) return 1; + } cudaFree(lg); cudaFree(w1); cudaFree(w2); cudaFree(i1); cudaFree(i2); if (bad) return 1; } diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index c490f0f4ff..f414ad4d49 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -32343,7 +32343,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 1230, + "line": 1236, "backend": "cuda-hip", "fn": "getenv" } @@ -32409,7 +32409,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 310, + "line": 311, "backend": "cuda-hip", "fn": "getenv" } @@ -32428,9 +32428,9 @@ "since": null, "last_commit": "4e0156928a", "last_date": "2026-12-03", - "status": "opt-in", - "owner": "", - "note": "Windows integrated GPU: the per-process GPU allocation cap in GiB, instead of the engine's own figure (cudaMemGetInfo); for a PC where the figure is wrong", + "status": "research", + "owner": "L32", + "note": "device memory cap in GiB for the expert allocation (skips the capacity probe); L32-HIP diagnostics on Strix Halo", "retire_after": "", "retired_in": "" }, @@ -32442,7 +32442,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 677, + "line": 678, "backend": "cuda-hip", "fn": "getenv" } @@ -32547,7 +32547,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 229, + "line": 230, "backend": "cuda-hip", "fn": "getenv" } @@ -32671,6 +32671,39 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_L32_LA_KS", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/ling32/ling32_main.cpp", + "line": 844, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "int", + "default_state": null, + "code_default": "1", + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "research", + "owner": "L32", + "note": "measurement: bit mask of the lookahead predictors the tier run computes (1: the k=2 list, 2: the k=4 list, 3: both); default by tier (B: k=4). Use with STRATA_L32_PF_K.", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_L32_LA_TIME", "backends": [ @@ -32712,7 +32745,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 1782, + "line": 1789, "backend": "cuda-hip", "fn": "getenv" } @@ -33003,7 +33036,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 819, + "line": 820, "backend": "cuda-hip", "fn": "getenv" } @@ -33036,7 +33069,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_engine.cu", - "line": 1917, + "line": 1919, "backend": "cuda-hip", "fn": "getenv" } @@ -33102,7 +33135,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_engine.cu", - "line": 1645, + "line": 1647, "backend": "cuda-hip", "fn": "getenv" } @@ -33135,7 +33168,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_engine.cu", - "line": 1646, + "line": 1648, "backend": "cuda-hip", "fn": "getenv" } @@ -33168,13 +33201,13 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 381, + "line": 382, "backend": "cuda-hip", "fn": "getenv" }, { "file": "engine/src/ling32/ling32_main.cpp", - "line": 856, + "line": 859, "backend": "cuda-hip", "fn": "getenv" } @@ -33207,7 +33240,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_engine.cu", - "line": 1751, + "line": 1753, "backend": "cuda-hip", "fn": "getenv" } @@ -33741,7 +33774,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 317, + "line": 318, "backend": "hip", "fn": "getenv" } @@ -33760,9 +33793,9 @@ "since": null, "last_commit": "56b0ab1279", "last_date": "2026-12-03", - "status": "rollback", - "owner": "", - "note": "Windows + HIP integrated GPU (Strix Halo): 1 restores the old allocation-cap probe (allocate 1 GiB pieces until failure), which over-reports on a 96 GB carve-out and hangs the first device copy; the default is cudaMemGetInfo before any allocation (L32-HIP, f-ling32-hip4 56b0ab1279)", + "status": "research", + "owner": "L32", + "note": "Windows HIP iGPU: 1 = run the old allocate-and-free capacity probe (it overcommits and hangs Strix Halo); default: cudaMemGetInfo before any allocation (L32-HIP)", "retire_after": "", "retired_in": "" }, @@ -33774,7 +33807,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 218, + "line": 219, "backend": "cuda-hip", "fn": "getenv" } @@ -33860,8 +33893,8 @@ "last_commit": "13a3ccd4e0", "last_date": "2026-12-03", "status": "research", - "owner": "", - "note": "L32-HIP: route the next layer early (AMD, f-ling32-int 6d7e4a9d97); research, default off, not set by the launcher", + "owner": "L32", + "note": "tier store: issue the routing copy of a decode layer before the shared expert so prepare() only waits on an event (L32-HIP; R9700 4K decode +3.5 %, exact; default off)", "retire_after": "", "retired_in": "" }, @@ -33970,6 +34003,39 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_L32_SKIP_TAU", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/ling32/ling32_main.cpp", + "line": 894, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "float", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "first_commit": null, + "first_date": null, + "since": null, + "last_commit": null, + "last_date": null, + "status": "research", + "owner": "L32", + "note": "experiment, NOT exact: drop a decode / verify token's routed experts whose share of its routing weight is below this value (the top expert is kept, weights renormalized, the tier store fetches nothing for them); default 0 (off)", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_L32_SPAN_HINT", "backends": [ @@ -34011,7 +34077,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_engine.cu", - "line": 1685, + "line": 1687, "backend": "cuda-hip", "fn": "getenv" } @@ -34077,7 +34143,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 925, + "line": 931, "backend": "cuda-hip", "fn": "getenv" } @@ -34209,7 +34275,7 @@ "reads": [ { "file": "engine/src/ling32/ling32_main.cpp", - "line": 916, + "line": 922, "backend": "cuda-hip", "fn": "getenv" }