diff --git a/README.md b/README.md index 4402f59..17529ff 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ compiled at run time with NVRTC, and the same kernels run on Vulkan: no C++ buil fit in VRAM run on the CPU at the same time as the GPU work, and the expert placement adapts to the routing it sees. Supported models: Qwen3, Qwen3-Next, Qwen3.5/3.6, Qwen3.8-Flash-Next, Recursive Flint, Gemma 4, DeepSeek-V4.1-Flash, -GLM-5.3-Flash, Hy4-flash and Inkling 2 Mini. The architectures, the GGUF types and the notes for each model are in +GLM-5.3-Flash, Hy4-flash, Inkling 2 Mini and Kolibri 1.1. The architectures, the GGUF types and the notes for each model are in [docs/MODELS.md](docs/MODELS.md). Version 1.3.1. diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index 194604e..d6a5671 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -275,6 +275,45 @@ used part of the GPU during that run. Alternating runs of the old and new build CUDA 25.4 to 33.5 tok/s, Vulkan 16.6 to 25.4 tok/s, prefill unchanged (within 1-4%). Most of the Vulkan gain is the IQ4_NL expert matvec (105 to 270 GB/s on 8 experts of 2304x2304). +## Kolibri 1.1 Q4_K_M (43.4 GB) + +`Kolibri-1.1-Q4_K_M.gguf` (architecture `kolibri1`), measured 2026-11-25 on the reference machine (RTX 3060 12 GB, +30 GB RAM, NVMe). The file does not fit in RAM plus VRAM. Both engines run as servers and answer the same streamed +`/v1/chat/completions` request with 128 reply tokens, greedy: prefill is the prompt tokens over the time to the first +token, decode is the other 127 tokens over the rest. Each server first answers a 0.5k-token request that is not +counted. RustingStrata: `serve --model ` with default flags (9.7 GB of VRAM). llama.cpp: the Kolibri fork at +5f4d22289, CUDA build, `llama-server -c 40000` with `-ngl 4` (its best prefill here) and with `-ngl 99 -cmoe` (its +best decode here). Mean, the range of the runs in brackets, the number of runs after it. + +| Prompt | | Prefill (tok/s) | Decode (tok/s) | Runs | +|---|---|---|---|---| +| 0.5k (561 tokens) | RustingStrata | 181.0 (156.9-199.6) | 33.4 (32.0-35.8) | 5 | +| | llama.cpp `-ngl 4` | 145.4 (93.8-165.5) | 15.5 (14.6-16.8) | 5 | +| | llama.cpp `-ngl 99 -cmoe` | 98.5 (10.7-173.7) | 27.0 (9.7-34.8) | 5 | +| 3.8k (3860) | RustingStrata | 148.7 (141.9-152.9) | 23.0 (22.4-23.4) | 3 | +| | llama.cpp `-ngl 4` | 41.3 | 5.9 | 1 | +| | llama.cpp `-ngl 99 -cmoe` | 27.9 | 10.6 | 1 | +| 16k (16163) | RustingStrata | 139.1 (130.8-147.4) | 21.0 (20.9-21.1) | 2 | +| | llama.cpp `-ngl 4` | 48.4 | 3.8 | 1 | +| | llama.cpp `-ngl 99 -cmoe` | 30.0 | 8.7 | 1 | +| 32k (31443) | RustingStrata | 158.8 (146.8-170.9) | 21.1 (20.1-22.0) | 2 | +| | llama.cpp `-ngl 4` | 34.0 | 3.3 | 1 | +| | llama.cpp `-ngl 99 -cmoe` | 32.9 | 9.3 | 1 | + +Quality vs llama.cpp, same GGUF, teacher-forced: the fork's greedy tokens (`-ngl 4`, 48 tokens) go through +`rustingstrata score` and the top token is compared at every step: 45, 46, 44 and 46 of 48 after prompts of 2k, 3.8k, +16k and 32k tokens. The fork against itself (CPU against GPU layers, or `-ngl 2` against `-ngl 4`) gives 45, 45, 40 +and 44 of 48. Every miss is at a step where the reference's two best tokens are close. + +Caveats: the llama.cpp rows at 3.8k and above are one run each, and the llama.cpp runs were made before the last +RustingStrata prefill change, in the same night and not interleaved with it (the 0.5k RustingStrata row before that +change, run between the two llama.cpp rows, was 132.4 (110.0-148.0) / 33.2). The low ends of the llama.cpp ranges at +0.5k are its first runs, with the experts not yet in the page cache; its later runs reach 148-166 (`-ngl 4`) and +129-174 (`-cmoe`) tok/s of prefill. llama.cpp counts 564 tokens for the 0.5k prompt. +`--moe-cache-mib 5000` and `--moe-cache-mib 8000 --moe-cache-cpu-share 0.5` were also tried for llama.cpp at 3.8k +and were slower in decode than `-cmoe` alone (34.9 / 3.8 and 37.6 / 6.6). Speed on this file depends on the drive +and on how much of the file the page cache holds. + ## Not yet measured - Qwen3-Next against llama.cpp in one table. diff --git a/docs/MODELS.md b/docs/MODELS.md index 7fd1100..6f369b0 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -19,6 +19,7 @@ The engine picks the code path from `general.architecture` in the file. | [DeepSeek-V4.1-Flash](#deepseek-v41-flash-iq2_xxs-249-gb) | `deepseek41` | own forward, matvecs and expert cache on the CUDA card, greedy only | | [GLM-5.3-Flash](#glm-53-flash-ud-q2_k_xl-119-gb) | `glm5-next` | own forward, matvecs and expert cache on the CUDA card, greedy only | | [Hy4-flash](#hy4-flash-iq2_siq2_xxs-85-gb) | `hy_v4_flash` | own forward, matvecs and expert cache on CUDA or Vulkan, greedy only | +| [Kolibri 1.1](#kolibri-11-q4_k_m-434-gb) | `kolibri1` | own forward, matvecs, expert cache and attention on the CUDA card, greedy only | | [Inkling 2 Mini](#inkling-2-mini-iq4_nl-176-gb) | `inkling2_loop`, `inkling2` | own forward, matvecs and expert cache on CUDA or Vulkan | The models with their own forward open the GPU by themselves (no `--gpu` flag), have nothing to calibrate and load @@ -70,6 +71,42 @@ The 1.3.0 prefill is the wall time less the load and the decode; it had no timer host round trip for each group of matrix products of each layer, and no llama.cpp run was made on this machine; the report in issue #81 has llama.cpp well ahead on an RTX 4070 SUPER. +## Kolibri 1.1 (Q4_K_M, 43.4 GB) + +`chat`, `generate`, `serve`, `score` and `bench` detect the `kolibri1` architecture +([Aleph-Alpha/Kolibri-1.1-GGUF](https://huggingface.co/Aleph-Alpha/Kolibri-1.1-GGUF)) and run its own forward: 50 +layers, 384 experts a layer with 6 routed and one shared, a sliding window of 513 positions on four layers of every +five, and on every fifth layer an attention over the 2048 keys that an indexer picks (K and V rounded to NVFP4). + +```bash +rustingstrata chat --model Kolibri-1.1-Q4_K_M.gguf +rustingstrata serve --model Kolibri-1.1-Q4_K_M.gguf --port 8080 +``` + +The matrix products, both kinds of attention and the routed experts that fit run on the CUDA card; the other experts +run on the CPU at the same time. A prompt goes through the layers in chunks of 1024 tokens (`STRATA_DS_CHUNK`), and a +layer's experts on the card take one round trip for the whole chunk. `STRATA_KOL_CPU_ATTN=1` keeps the attention of a +chunk on the CPU. The chat template is ChatML with the model's "Reasoning effort" system section (`--think`). + +Reference machine (RTX 3060 12 GB, 30 GB RAM), server to server, a streamed chat request with 128 reply tokens, +prefill / decode in tok/s (the table with ranges is in [BENCHMARKS.md](BENCHMARKS.md#kolibri-11-q4_k_m-434-gb)): + +| Prompt | RustingStrata | llama.cpp `-ngl 4` | llama.cpp `-ngl 99 -cmoe` | +|---|---|---|---| +| 0.5k tokens | 181 / 33.4 | 145 / 15.5 | 99 / 27.0 | +| 3.8k | 149 / 23.0 | 41 / 5.9 | 28 / 10.6 | +| 16k | 139 / 21.0 | 48 / 3.8 | 30 / 8.7 | +| 32k | 159 / 21.1 | 34 / 3.3 | 33 / 9.3 | + +Quality: llama.cpp's greedy tokens fed through RustingStrata's forward give the same top token at 45, 46, 44 and 46 +of 48 steps after prompts of 2k, 3.8k, 16k and 32k tokens. Two llama.cpp runs of the same file (CPU against GPU +layers) agree with each other at 40-45 of 48; the misses are near ties. + +Caveats: the file is larger than the RAM and VRAM of the reference machine together, so the experts that are not on +the card are read from the drive through the page cache, and the first request after a start is slower. CUDA only +(no Vulkan kernel for the attention over picked keys; without a card it runs on the CPU). Decoding is greedy, there +are no stop strings, and the model's thinking arrives inside `content`. + ## DeepSeek-V4.1-Flash (IQ2_XXS, 249 GB) `chat`, `generate` and `serve` detect the `deepseek41` architecture and run it on the CPU reference forward, with the diff --git a/docs/USAGE.md b/docs/USAGE.md index 32e0375..009ed30 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -72,7 +72,7 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def ## Flags - `--backend NAME` GPU backend: `cuda`, `vulkan` or `hip` (AMD cards through ROCm, one device per run, see [HIP.md](HIP.md)). Without it CUDA is used when it loads, else Vulkan. -- `--ctx` KV cache size in tokens (default 4096). For Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 it is the prompt plus reply limit instead, and the default is the context the model was trained on; their caches grow with the text. +- `--ctx` KV cache size in tokens (default 4096). For Inkling 2, Hy4, GLM, DeepSeek, Kolibri and Gemma 4 it is the prompt plus reply limit instead, and the default is the context the model was trained on; their caches grow with the text. - `--mtp [N]` speculative decoding with the model's draft head. Greedy tokens stay the same; sampling keeps its distribution. Needs a GGUF with an MTP head (for example the Qwen3.6-35B-A3B MTP files). Qwen3.8-Flash-Next (`qwen4exp`) takes its head from a companion file: `--mtp-model mtp-...-shared-Q8_0.gguf`. @@ -156,7 +156,7 @@ other MCP clients use, and pass it with `--mcp ` (or `STRATA_MCP`; the def - `--alias prism` (`serve`) is the model name in `/v1/models` and in the replies, whatever file is loaded (default: the file name), so clients set up for `prism` keep working when another model is loaded. Calibration and the expert profile stay per file. -- Inkling 2, Hy4, GLM, DeepSeek and Gemma 4 run on their own code path. The server loads them like any other model +- Inkling 2, Hy4, GLM, DeepSeek, Kolibri and Gemma 4 run on their own code path. The server loads them like any other model (`serve --model `, or from the chat page of a running server, in either direction), with these limits: one request at a time, greedy (Inkling 2 also samples: `temperature`, `top_k`, `top_p`, `seed`; a seed repeats its text only with `STRATA_FIXED_EXPERTS=1`, because the adaptive expert split moves the logits a little), diff --git a/src/backend.rs b/src/backend.rs index 12489b2..8240578 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -389,6 +389,10 @@ pub trait Backend: Send { /// Inkling 2 sigmoid top-k router for `rows` tokens: picks top `k` from `logits` (`[rows, n_expert]`) using /// `sigmoid(logit) + bias`, writes indices `[rows, k]` to `ids`, normalized unbiased probs * `exp_scale` (* `dn_sc[id]` /// if non-null) to `wts`, and optional `gu_sc[id]` (or `1.0`) to `gsc_out`. + /// Attention of `nt` queries, each over its own key list: row t of `idx` (`ns` u32 positions, the first `cnt[t]` + /// valid) names the rows of the f16 caches `kc`/`vc` (`[(pos * nkv + g) * hd]`) that query t attends. `q` and + /// `out` are f32 `[t][head][hd]`. Kolibri's sparse layers. + fn attn_sel(&self, _q: u64, _kc: u64, _vc: u64, _idx: u64, _cnt: u64, _out: u64, _nt: usize, _nh: usize, _nkv: usize, _hd: usize, _ns: usize, _scale: f32) -> anyhow::Result<()> { anyhow::bail!("{}: attention over key lists not implemented", self.name()) } fn ink_route(&self, _logits: u64, _bias: u64, _ids: u64, _wts: u64, _gu_sc: u64, _dn_sc: u64, _gsc_out: u64, _n_expert: usize, _k: usize, _exp_scale: f32, _rows: usize) -> anyhow::Result<()> { anyhow::bail!("{}: Inkling 2 router not implemented", self.name()) } /// Gyro files (`config::Hadamard`): each of `rows` rows of n floats at `x` (times silu(x) * u first when `u` is /// not 0) becomes H (s x) per `block` values, written to `out`, which may be `x`. `s`: the row's n signs as floats. diff --git a/src/config.rs b/src/config.rs index c5b3bde..1ec2b8d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -262,7 +262,7 @@ pub struct ModelConfig { } /// Architectures with their own forward and server outside `ModelConfig` (`src/main.rs` dispatches on them). -pub const OWN_ARCHS: [&str; 6] = ["gemma4", "glm5-next", "deepseek41", crate::hy4::ARCH, crate::inkling2::ARCH, crate::inkling2::ARCH_RUNS]; +pub const OWN_ARCHS: [&str; 7] = ["gemma4", "glm5-next", "deepseek41", crate::hy4::ARCH, crate::kolibri::ARCH, crate::inkling2::ARCH, crate::inkling2::ARCH_RUNS]; impl ModelConfig { pub fn from_gguf(g: &Gguf) -> anyhow::Result { diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 21f37af..51ef225 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2147,6 +2147,71 @@ extern "C" __global__ void ink_ffn_sum(float* acc, const float* d, const float* acc[(size_t)tok * n + c] = o; } +// Attention of each query over its own list of keys (Kolibri sparse layers). Block = (query t, K/V head g); the +// `per` = nh / nkv query heads of g are one warp each, so a tile of 32 keys is read once for all of them. +// q: f32 [t][head][hd]; kc, vc: f16 rows [(pos * nkv + g) * hd]; idx: ns key positions per query, the first cnt[t] +// valid. Online softmax: each head keeps its running maximum m, sum l and weighted V sum (hd / 32 values a thread). +// A key row of the tile takes hd + 1 floats, so the 32 lanes that read one dimension of 32 keys hit 32 banks. +// Shared memory: (per + 64) * hd + per * 32 + 32 floats. +extern "C" __global__ void attn_sel(const float* q, const u16* kc, const u16* vc, const unsigned* idx, const int* cnt, + float* out, int nh, int nkv, int hd, int ns, float scale) { + extern __shared__ float sm[]; + int t = blockIdx.x, g = blockIdx.y, per = nh / nkv; + int tid = threadIdx.x, h = tid >> 5, c = tid & 31, nthr = per * 32, n = cnt[t], nd = hd / 32; + float* qs = sm; + float* kt = qs + per * hd; + float* vt = kt + 32 * (hd + 1); + float* ps = vt + 32 * hd; + const float* qg = q + ((size_t)t * nh + (size_t)g * per) * hd; + for (int i = tid; i < per * hd; i += nthr) qs[i] = qg[i]; + const unsigned* sel = idx + (size_t)t * ns; + float acc[8]; + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + float m = __int_as_float(0xff800000), l = 0.0f; + for (int j0 = 0; j0 < n; j0 += 32) { + __syncthreads(); + for (int i = tid; i < 32 * hd; i += nthr) { + int j = j0 + i / hd; + if (j < n) { + size_t row = ((size_t)sel[j] * nkv + g) * hd + i % hd; + kt[i + i / hd] = h2f(kc[row]); + vt[i] = h2f(vc[row]); + } else { + kt[i + i / hd] = 0.0f; + vt[i] = 0.0f; + } + } + __syncthreads(); + float s = __int_as_float(0xff800000); + if (j0 + c < n) { + const float* qh = qs + h * hd; + const float* kr = kt + c * (hd + 1); + float d = 0.0f; + for (int i = 0; i < hd; i++) d = fmaf(qh[i], kr[i], d); + s = d * scale; + } + float mx = s; + for (int o = 16; o > 0; o >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, o)); + float mn = fmaxf(m, mx); + float a = expf(m - mn); + float p = expf(s - mn); + float sum = p; + for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffff, sum, o); + l = l * a + sum; + m = mn; + ps[tid] = p; + __syncwarp(); + const float* ph = ps + h * 32; + for (int r = 0; r < nd; r++) { + float v = 0.0f; + for (int k = 0; k < 32; k++) v = fmaf(ph[k], vt[k * hd + c + 32 * r], v); + acc[r] = acc[r] * a + v; + } + } + float* o = out + ((size_t)t * nh + (size_t)g * per + h) * hd; + for (int r = 0; r < nd; r++) o[c + 32 * r] = acc[r] / l; +} + __device__ __forceinline__ unsigned ink_f2key(float x) { unsigned u = __float_as_uint(x == 0.0f ? 0.0f : x); return (u & 0x80000000u) ? ~u : (u ^ 0x80000000u); @@ -2874,11 +2939,14 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* float sink_val = sink[(size_t)t * nh + h]; float r_reg = (nr <= 32 && lane < nr) ? r[((size_t)t * nh + h) * nr + lane] : 0.f; float m = 0.f, l = 1.f; + // Row of the key in the old rows: a ring of `ring` rows on a sliding layer, counted (no division a key). + int old_row = win > 0 ? start % ring : start; for (int kp = start; kp <= q_pos; kp++) { bool use_new = kc_new && kp >= pos; const u16* kbuf = use_new ? kc_new : kc; const u16* vbuf = use_new ? vc_new : vc; - size_t row = use_new ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + size_t row = use_new ? (size_t)(kp - pos) : (size_t)old_row; + if (++old_row == ring) old_row = 0; size_t kbase = row * kw + (size_t)kh * HD; float s = 0.f; for (int j = 0; j < PER; j++) s += qv[j] * ldkv1(kbuf, kbase + lane + 32 * j, HD); @@ -2915,6 +2983,89 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ } DEF_INK_PREFILL(32) DEF_INK_PREFILL(64) DEF_INK_PREFILL(128) +// The same attention for a layer that sees every key, where the K/V rows of a long prompt do not stay in the cache. +// The arithmetic of a (query, key) pair and the order of the keys are those of ink_attn_prefill_t: same bits. +template +__device__ void ink_attn_prefill_sh_t(const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + // A block is one K/V head and a group of tokens: one warp for each (token, query head of the K/V head). The + // block reads the K and V rows of 32 keys once, into shared memory, and every warp takes them from there + // (each warp read them from the cache itself: the same rows, once a warp). + constexpr int HD = 32 * PER, TK = 32; + extern __shared__ float skv[]; // TK * HD values of K, then TK * HD values of V + float* sk = skv; float* sv = skv + TK * HD; + int g = nh / nkv, kh = blockIdx.y, w = threadIdx.x >> 5, lane = threadIdx.x & 31, tb = (blockDim.x >> 5) / g; + int t0 = blockIdx.x * tb, t = t0 + w / g, h = kh * g + w % g, kw = nkv * HD; + bool live = t < nt; + if (!live) t = nt - 1; + int q_pos = pos + t; + int start = (win > 0 && q_pos + 1 > win) ? (q_pos + 1 - win) : 0; + int kbeg = (win > 0 && pos + t0 + 1 > win) ? (pos + t0 + 1 - win) : 0, kend = pos + min(nt, t0 + tb) - 1; + float scale = 1.f / sqrtf((float)HD); + float qv[PER], acc[PER]; + for (int j = 0; j < PER; j++) { + qv[j] = q[((size_t)t * nh + h) * HD + lane + 32 * j] * scale; + acc[j] = 0.f; + } + float sink_val = sink[(size_t)t * nh + h]; + float r_reg = (nr <= 32 && lane < nr) ? r[((size_t)t * nh + h) * nr + lane] : 0.f; + float m = 0.f, l = 1.f; + for (int k0 = kbeg; k0 <= kend; k0 += TK) { + int n = min(TK, kend + 1 - k0); + // Row of key k0 in the old rows: a ring of `ring` rows on a sliding layer. + int r0 = win > 0 ? k0 % ring : k0; + for (int i = threadIdx.x; i < n * HD; i += blockDim.x) { + int key = i / HD, kp = k0 + key; + bool use_new = kc_new && kp >= pos; + size_t row = use_new ? (size_t)(kp - pos) : (size_t)(r0 + key >= ring ? r0 + key - ring : r0 + key); + size_t off = row * kw + (size_t)kh * HD + i % HD; + sk[i] = ldkv1(use_new ? kc_new : kc, off, HD); + sv[i] = ldkv1(use_new ? vc_new : vc, off, HD); + } + __syncthreads(); + if (live) for (int i = max(start - k0, 0); i < n && k0 + i <= q_pos; i++) { + const float* kr = sk + i * HD + lane; + const float* vr = sv + i * HD + lane; + float s = 0.f; + for (int j = 0; j < PER; j++) s += qv[j] * kr[32 * j]; + s = warp_sum(s); + int dist = q_pos - k0 - i; + float b = 0.f; + if (dist < ext) { + if (nr <= 32) { + b = lane < nr ? r_reg * bias[dist * nr + lane] : 0.f; + } else { + for (int c = lane; c < nr; c += 32) b += r[((size_t)t * nh + h) * nr + c] * bias[dist * nr + c]; + } + b = warp_sum(b); + } + float logit = s + b - sink_val; + float mn = fmaxf(m, logit), c = expf(m - mn), e = expf(logit - mn); + l = l * c + e; + for (int j = 0; j < PER; j++) acc[j] = e * vr[32 * j] + acc[j] * c; + m = mn; + } + __syncthreads(); + } + if (!live) return; + float inv = 1.f / l; + for (int j = 0; j < PER; j++) { + int col = lane + 32 * j; + size_t idx = ((size_t)t * nh + h) * HD + col; + outp[idx] = acc[j] * inv * sigmoid(gate[idx]); + } +} +#define DEF_INK_PREFILL_SH(HD) \ + extern "C" __global__ void __launch_bounds__(1024) ink_attn_prefill_sh_##HD( \ + const float* q, const float* r, const float* sink, const float* gate, \ + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, \ + const float* bias, float* outp, \ + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { \ + ink_attn_prefill_sh_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ + } +DEF_INK_PREFILL_SH(32) DEF_INK_PREFILL_SH(64) DEF_INK_PREFILL_SH(128) template __device__ void attn_decode_llama(const float* q, const u16* kc, const u16* vc, float* part, const int* step, const int* sel, int nh, int nkv, float scale, int bx, int win) { diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index e909a56..bf9d411 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,13 +17,13 @@ pub(crate) const QTYPES: [GgmlType; 29] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -pub(crate) const KERNELS: [&str; 54] = [ +pub(crate) const KERNELS: [&str; 58] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_ffn_sum", "ink_route", + "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_route", "attn_sel", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; @@ -1167,15 +1167,20 @@ impl Backend for Gpu { &self, q: u64, r: u64, sink: u64, gate: u64, kc: u64, vc: u64, kc_new: u64, vc_new: u64, bias: u64, out: u64, pos: usize, nt: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize, ring: usize, win: usize, ) -> anyhow::Result<()> { - let kn = match hd { - 32 => "ink_attn_prefill_32", - 64 => "ink_attn_prefill_64", - 128 => "ink_attn_prefill_128", - _ => anyhow::bail!("ink_attn_prefill: unsupported hd={hd}"), - }; - launch!(self, kn, cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), - q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, - pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + anyhow::ensure!(matches!(hd, 32 | 64 | 128), "ink_attn_prefill: unsupported hd={hd}"); + let g = nh / nkv.max(1); + if win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 { + // Every key: a block is one K/V head and `tb` tokens, with 32 keys of K and V in shared memory. + let tb = (32 / g).min(8); + launch!(self, &format!("ink_attn_prefill_sh_{hd}"), cfg((nt.div_ceil(tb) as u32, nkv as u32), (32 * tb * g) as u32, (2 * 32 * hd * 4) as u32), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, i32::MAX, win as i32); + } else { + // `ring` is the count of old rows that the kernel wraps at: only a sliding layer wraps. + launch!(self, &format!("ink_attn_prefill_{hd}"), cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, if win > 0 { ring.max(1) } else { i32::MAX as usize } as i32, win as i32); + } Ok(()) } fn ink_ffn_sum_n(&self, acc: u64, d: u64, wts: u64, ne: usize, n: usize, nt: usize, cpu: u64) -> anyhow::Result<()> { @@ -1238,6 +1243,14 @@ impl Backend for Gpu { Ok(()) } + fn attn_sel(&self, q: u64, kc: u64, vc: u64, idx: u64, cnt: u64, out: u64, nt: usize, nh: usize, nkv: usize, hd: usize, ns: usize, scale: f32) -> anyhow::Result<()> { + let per = nh / nkv.max(1); + anyhow::ensure!(hd % 32 == 0 && hd <= 256 && nkv > 0 && nh % nkv == 0 && per <= 32, "attn_sel: unsupported shape nh={nh} nkv={nkv} hd={hd}"); + launch!(self, "attn_sel", cfg((nt as u32, nkv as u32), (per * 32) as u32, (((per + 64) * hd + per * 32 + 32) * 4) as u32), + q, kc, vc, idx, cnt, out, nh as i32, nkv as i32, hd as i32, ns as i32, scale); + Ok(()) + } + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); Ok(()) diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index 660d3fa..0e216dd 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -20,7 +20,7 @@ pub(crate) mod dev { /// A tensor id holds its GPU in the top 8 bits (so STAGED, GPU 255, is never a real id) and its index there below. const SHIFT: u32 = 24; pub fn gpu_of(id: u32) -> usize { (id >> SHIFT) as usize } - pub(crate) struct Part { pub(crate) be: Box, ts: Vec, x: Buf, y: Buf, stage: Buf, bytes: usize, budget: usize, room: usize } + pub(crate) struct Part { pub(crate) be: Box, ts: Vec, x: Buf, y: Buf, stage: Buf, bytes: usize, pub(crate) budget: usize, room: usize } pub struct SlabBuf { buf: Buf, bytes: usize, freed: std::sync::Arc } impl SlabBuf { pub fn addr(&self) -> u64 { self.buf.addr() } @@ -419,6 +419,56 @@ pub(crate) mod dev { drop(owned); Some(y) } + /// SwiGLU experts of a chunk of tokens, all on the device, in four launches whatever the number of experts. + /// `x`: one row of activations a token. Expert i (`gates[i]`, `ups[i]`, `downs[i]`) runs on `pairs[i]`, a list + /// of (token, slot of the expert among the `k` of that token, router weight). Returns per token the weighted + /// sum of these experts' outputs. None when a matrix is on another GPU or the chunk does not fit. + pub fn swiglu_chunk(&self, gates: &[Mat], ups: &[Mat], downs: &[Mat], pairs: &[Vec<(usize, usize, f32)>], x: &[f32], k: usize) -> Option> { + use crate::backend::GEMM_BM; + let d = self.part_of(gates.first()?)?; + if gates.iter().chain(ups).chain(downs).any(|m| self.part_of(m) != Some(d) || m.scale != 1.0) { return None; } + let (p, nf, nl) = (&self.parts[d], downs[0].cols, downs[0].rows); + let (nt, np) = (x.len() / gates[0].cols, pairs.iter().map(|v| v.len()).sum::()); + // GEMM tiles [weights, first pair | pairs << 32] of the gates, the ups, the downs. + let (mut owned, mut tiles, mut xrow) = (vec![], vec![], vec![]); + let (mut wts, mut inv) = (vec![0f32; nt * k], vec![0i32; nt * k]); + let mut shape = [(GgmlType::F32, 0, 0); 3]; + for (side, mats) in [gates, ups, downs].into_iter().enumerate() { + let mut m0 = 0; + for (m, ps) in mats.iter().zip(pairs) { + let w = self.weight(p, m, &mut owned)?; + if m0 > 0 && shape[side] != (w.ty, w.rows, w.cols) { return None; } + shape[side] = (w.ty, w.rows, w.cols); + for at in (0..ps.len()).step_by(GEMM_BM) { + tiles.extend([w.ptr, (m0 + at) as u64 | (GEMM_BM.min(ps.len() - at) as u64) << 32]); + } + m0 += ps.len(); + } + } + for &(t, j, w) in pairs.iter().flatten() { + (wts[t * k + j], inv[t * k + j]) = (w, xrow.len() as i32); + xrow.push(t as i32); + } + let (n_tiles, ints) = (tiles.len() / 6, 2 * tiles.len()); + if x.len() > p.x.len() / 4 || ints + np + 2 * nt * k > p.y.len() / 4 { return None; } + // Zeroed: the sums, then per pair the activation rows, then per pair the down rows. + let b = p.be.alloc(4 * (nt * nl + np * (nf + nl))).ok()?; + let (ia, ya) = (|i: usize| p.y.addr() + 4 * i as u64, |i: usize| b.addr() + 4 * i as u64); + let (act, down) = (nt * nl, nt * nl + np * nf); + p.be.put(x, &p.x, 0).ok()?; + p.be.put(&tiles, &p.y, 0).ok()?; + p.be.put(&xrow, &p.y, ints).ok()?; + p.be.put(&wts, &p.y, ints + np).ok()?; + p.be.put(&inv, &p.y, ints + np + nt * k).ok()?; + let [(gt, gr, gc), (ut, ur, uc), (dt, dr, dc)] = shape; + p.be.gemm(gt, gr, gc, ia(0), n_tiles, p.x.addr(), gc, nt, ia(ints), ya(act), nf, 0).ok()?; + p.be.gemm(ut, ur, uc, ia(4 * n_tiles), n_tiles, p.x.addr(), uc, nt, ia(ints), ya(act), nf, 1).ok()?; + p.be.gemm(dt, dr, dc, ia(8 * n_tiles), n_tiles, ya(act), nf, np, 0, ya(down), nl, 0).ok()?; + p.be.moe_combine_seq(b.addr(), ya(down), ia(ints + np), ia(ints + np + nt * k), k, 0, 0, nl, nt).ok()?; + let y = p.be.get(&b, 0, nt * nl).ok()?; + drop(owned); + Some(y) + } /// `rows` for several matrices on one chunk of `n` rows: matrix i reads input set `ms[i].1` of `x` (set after /// set). One upload of the sets and one readback for all matrices. None when a matrix is staged or on /// another GPU, or the chunk does not fit the scratch buffers. @@ -435,6 +485,34 @@ pub(crate) mod dev { } p.be.get(&p.y, 0, yo).ok() } + /// Causal attention of `nt` consecutive queries (`q`: `nh` heads of `hd` each) over the f16 rows `k`, `v` + /// (`nkv` heads a position; the first query sits at row `base`), a query seeing its last `win` keys + /// (0: all). None when the backend has no kernel for it or the cache is not f16 there. + pub fn attn_rows(&self, q: &[f32], k: &[u16], v: &[u16], base: usize, nt: usize, nh: usize, nkv: usize, hd: usize, win: usize) -> Option> { + let be = &self.parts.first()?.be; + if be.kv_words(k.len()) != k.len() { return None; } + let (dq, dk, dv, ds, out) = (be.zeros::(q.len()).ok()?, be.zeros::(k.len()).ok()?, be.zeros::(v.len()).ok()?, be.zeros::(1).ok()?, be.zeros::(q.len()).ok()?); + be.put(q, &dq, 0).ok()?; + be.put(k, &dk, 0).ok()?; + be.put(v, &dv, 0).ok()?; + be.put(&[base as i32], &ds, 0).ok()?; + be.attn_prefill_m(dq.addr(), dk.addr(), dv.addr(), 0, out.addr(), ds.addr(), nt, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), 0, 0, 0, win).ok()?; + be.get(&out, 0, q.len()).ok() + } + /// Attention of `nt` queries over their own key lists (`Backend::attn_sel`): `idx` holds `idx.len() / nt` + /// positions a query, `cnt` how many of them count; `k`/`v` are all the f16 rows of the layer. + pub fn attn_sel(&self, q: &[f32], k: &[u16], v: &[u16], idx: &[u32], cnt: &[i32], nt: usize, nh: usize, nkv: usize, hd: usize) -> Option> { + let be = &self.parts.first()?.be; + if be.kv_words(k.len()) != k.len() { return None; } + let (dq, dk, dv, di, dc, out) = (be.zeros::(q.len()).ok()?, be.zeros::(k.len()).ok()?, be.zeros::(v.len()).ok()?, be.zeros::(idx.len()).ok()?, be.zeros::(nt).ok()?, be.zeros::(q.len()).ok()?); + be.put(q, &dq, 0).ok()?; + be.put(k, &dk, 0).ok()?; + be.put(v, &dv, 0).ok()?; + be.put(idx, &di, 0).ok()?; + be.put(cnt, &dc, 0).ok()?; + be.attn_sel(dq.addr(), dk.addr(), dv.addr(), di.addr(), dc.addr(), out.addr(), nt, nh, nkv, hd, idx.len() / nt, 1.0 / (hd as f32).sqrt()).ok()?; + be.get(&out, 0, q.len()).ok() + } /// `rows` for several matrices: job i runs its matrix on its own `n` rows of `x` (after job i-1's rows). /// One upload and one readback for all jobs. None when the batch does not fit the scratch buffers. /// ponytail: None too when the weights are on different GPUs; batch per GPU if a multi-GPU prompt waits here. @@ -524,6 +602,10 @@ pub fn matvec_many_opt(ms: &[Mat], x: &[f32], xs: usize) -> Option> { pub fn situ_chunk(gus: &[Mat], downs: &[Mat], gs: &[f32], pairs: &[Vec<(usize, usize, f32)>], x: &[f32], k: usize, beta: f32, lb: f32) -> Option> { dev::get().and_then(|d| d.lock().unwrap().situ_chunk(gus, downs, gs, pairs, x, k, beta, lb)) } +/// `Dev::swiglu_chunk` on the open GPU path (None without one). +pub fn swiglu_chunk(gates: &[Mat], ups: &[Mat], downs: &[Mat], pairs: &[Vec<(usize, usize, f32)>], x: &[f32], k: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().swiglu_chunk(gates, ups, downs, pairs, x, k)) +} pub fn situ_experts(gus: &[Mat], downs: &[Mat], gs: &[f32], x: &[f32], beta: f32, lb: f32) -> Option> { dev::get().and_then(|d| d.lock().unwrap().situ_experts(gus, downs, gs, x, beta, lb)) } @@ -609,6 +691,14 @@ pub fn budget_left() -> usize { dev::get().map_or(0, |d| d.lock().unwrap().budge pub fn dev_info() -> Option<(&'static str, usize, usize)> { dev::get().map(|d| d.lock().unwrap().info()) } +/// `Dev::attn_rows` on the open GPU path (None without one). +pub fn attn_rows(q: &[f32], k: &[u16], v: &[u16], base: usize, nt: usize, nh: usize, nkv: usize, hd: usize, win: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().attn_rows(q, k, v, base, nt, nh, nkv, hd, win)) +} +/// `Dev::attn_sel` on the first GPU. None without a GPU or when the backend has no such kernel. +pub fn attn_sel(q: &[f32], k: &[u16], v: &[u16], idx: &[u32], cnt: &[i32], nt: usize, nh: usize, nkv: usize, hd: usize) -> Option> { + dev::get().and_then(|d| d.lock().unwrap().attn_sel(q, k, v, idx, cnt, nt, nh, nkv, hd)) +} /// `dev::free`, for a server that changes models. pub fn dev_free() { dev::free() } /// The first GPU's backend, device name and (used, total) bytes of memory, for the server's side panel. diff --git a/src/hy4/forward.rs b/src/hy4/forward.rs index 70eebdb..127e727 100644 --- a/src/hy4/forward.rs +++ b/src/hy4/forward.rs @@ -105,16 +105,16 @@ pub struct Hy4Model<'a> { } /// A table that is only read row by row: never uploaded (the Engram table is 36 GB). -fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result> { +pub(crate) fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result> { let t = g.tensors.get(name).with_context(|| format!("missing tensor {name}"))?; Ok(Mat { data: g.bytes(t), ty: GgmlType::from_u32(t.ty)?, rows: t.dims[1] as usize, cols: t.dims[0] as usize, cpu: false, gpu: None, scale: 1.0 }) } -fn sigmoid(x: f32) -> f32 { +pub(crate) fn sigmoid(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) } -fn silu(x: f32) -> f32 { +pub(crate) fn silu(x: f32) -> f32 { x * sigmoid(x) } @@ -124,7 +124,7 @@ fn act(gate: f32, up: f32, limit: f32) -> f32 { /// Weighted sum of the listed experts' outputs, `(gate, up, down, weight)` each, for the latent input `x`. Experts /// that share a GPU run as two batched round trips; otherwise each matvec runs where its matrix lives. -fn run_experts(list: &[(Mat, Mat, Mat, f32)], x: &[f32], clamp: f32, nl: usize) -> Vec { +pub(crate) fn run_experts(list: &[(Mat, Mat, Mat, f32)], x: &[f32], clamp: f32, nl: usize) -> Vec { let mut mix = vec![0f32; nl]; let Some(first) = list.first() else { return mix }; let (k, nf) = (list.len(), first.0.rows); diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 69ba0cf..41b55e0 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -243,7 +243,7 @@ fn hsum(v: std::arch::x86_64::__m256) -> f32 { /// `p[j * n + row]` += `scale` times the dot of f16 row `row` of `w` (`n` rows) with row j of `x`. /// One to three rows of `x` take the same sums in the same order, so a token gets the same bits alone or in a chunk. -fn dots_h(p: &mut [f32], scale: f32, w: &[f16], x: &[f32], n: usize) { +pub(crate) fn dots_h(p: &mut [f32], scale: f32, w: &[f16], x: &[f32], n: usize) { let hd = w.len() / n; #[cfg(all(target_feature = "f16c", target_feature = "fma"))] if hd % 32 == 0 && x.len() % hd == 0 && p.len() == x.len() / hd * n { @@ -281,7 +281,7 @@ fn dots_k(p: &mut [f32], scale: f32, w: &[f16], x: &[f32], n: us /// Dot of f16 weights and f32 values. The loop controllers are 113 MB of F32 in the file and every token reads them /// twice, at the speed of the memory: as f16 they take half the time (their values stay within 5e-4 relative). -fn dot_h(w: &[f16], x: &[f32]) -> f32 { +pub(crate) fn dot_h(w: &[f16], x: &[f32]) -> f32 { #[cfg(all(target_feature = "f16c", target_feature = "fma"))] { use std::arch::x86_64::*; @@ -322,7 +322,7 @@ fn axpy_h(o: &mut [f32], p: f32, w: &[f16]) { /// Row j of `o` += the sum over the `n` f16 rows of `w` of `p[j * n + row]` times that row. One to three rows of /// `o` take the same sums in the same order. -fn mix_h(o: &mut [f32], p: &[f32], w: &[f16], n: usize) { +pub(crate) fn mix_h(o: &mut [f32], p: &[f32], w: &[f16], n: usize) { let hd = w.len() / n; #[cfg(all(target_feature = "f16c", target_feature = "fma"))] if hd % 32 == 0 && o.len() % hd == 0 && p.len() == o.len() / hd * n { diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 8aa879e..837dd9e 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -168,6 +168,10 @@ fn up(be: &dyn Backend, v: &[T]) -> Result { fn f(floats: usize) -> u64 { 4 * floats as u64 } +/// Rows of a K/V buffer that grows to hold `need`: a quarter more, so that a reply does not grow it at every token +/// and a long prompt does not take twice its rows from the experts. +fn grown(need: usize, max_ctx: usize) -> usize { (need + need / 4).next_multiple_of(1024).min(max_ctx) } + /// Free expert slots until `need` bytes of VRAM are free. fn room(d: &mut dev::Dev, need: usize) { let free = d.parts[0].be.mem_info().map_or(0, |m| m.0); @@ -400,21 +404,40 @@ impl Device { let row_words = d.parts[0].be.kv_words(kw); let full_cap = self.slots.iter().enumerate().find(|&(il, _)| !c.swa[layer_of(c, il)]).map(|(_, s)| s.cap); if let Some(cap) = full_cap && need > cap { - let mut new_cap = cap; - while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } + let new_cap = grown(need, m.max_ctx); let n = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); - room(&mut d, 4 * n * new_cap * row_words + sc_bytes(c, new_cap) + (128 << 20)); + // The margin is the one of `new`: the prompt scratch and the graphs of the reply come after this. + let bytes = 4 * n * new_cap * row_words + sc_bytes(c, new_cap) + (512 << 20); + room(&mut d, bytes); + // The expert cache was not enough: whole layers of experts go, the last loaded first. Their experts + // then run through the expert cache or on the CPU, which costs less than a model without its device state. + let free = |d: &dev::Dev| d.parts[0].be.mem_info().map_or(0, |m| m.0); + if free(&d) < bytes { + d.parts[0].be.sync()?; + let order: Vec = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer).collect(); + // Counted here: the driver may report the freed bytes late. + let mut short = bytes - free(&d); + for &ip in order.iter().rev() { + if short == 0 { break; } + if let Some(fe) = self.layers[ip].full_exps.take() { + // The budget falls too, so the expert cache does not take the room back. + d.parts[0].budget = d.parts[0].budget.saturating_sub(fe.gu.len() + fe.dn.len()); + short = short.saturating_sub(fe.gu.len() + fe.dn.len()); + self.all_full = false; + } + } + } } let be = &*d.parts[0].be; - let need_sc = sc_bytes(c, need); + // The score buffer follows the K/V rows: it is in the room made above, and a reply does not grow it every 64 tokens. + let need_sc = sc_bytes(c, full_cap.map_or(need, |cap| if need > cap { grown(need, m.max_ctx) } else { cap })); if self.sc_buf.len() < need_sc { be.sync()?; self.sc_buf = be.alloc(need_sc)?; } for (il, s) in self.slots.iter_mut().enumerate() { if c.swa[layer_of(c, il)] || need <= s.cap { continue; } - let mut new_cap = s.cap; - while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); } + let new_cap = grown(need, m.max_ctx); for b in [&mut s.k, &mut s.v] { let new = be.alloc(2 * new_cap * row_words)?; be.dtod(b, 0, &new, 0, b.len())?; diff --git a/src/kolibri/chat.rs b/src/kolibri/chat.rs new file mode 100644 index 0000000..7fef368 --- /dev/null +++ b/src/kolibri/chat.rs @@ -0,0 +1,238 @@ +//! `rustingstrata generate|chat|serve` for Kolibri 1.1: greedy, CUDA for the matvecs and expert staging, KV kept across turns. +use super::forward::KolibriModel; +use crate::{chat::{Json, Msg}, gguf::Gguf, tokenizer::Tokenizer}; +use std::io::{BufRead, Write}; + +const END: &str = "<|im_end|>\n"; +const THINK_END: &str = ""; +const CALL: &str = ""; +const CALL_END: &str = ""; + +pub use crate::deepseek::chat::gpu_defaults; + +/// The template's reasoning effort: `reasoning_effort` when given, else "none" when thinking is switched off, else high. +pub fn effort(think: Option, effort: Option<&str>) -> &str { + effort.unwrap_or(if think == Some(false) { "none" } else { "high" }) +} + +/// The GGUF's chat template with `add_generation_prompt`. `effort` is its `reasoning_effort` ("none" disables +/// thinking); `preserve` is its `preserve_thinking`. +pub fn render(msgs: &[Msg], tools: &[Json], effort: &str, preserve: bool) -> String { + let sentence = match effort { + "none" => "Reasoning is disabled. Proceed straight to answering according to the user's instructions.", + "minimal" | "low" => "Reasoning effort is set to low. Think briefly through only the essential steps in the user's language, then proceed directly to the answer.", + "medium" => "Reasoning effort is set to medium. Think through the task methodically in the user's language, check key assumptions, and provide a well-supported answer.", + _ => "Reasoning effort is set to high. Think carefully through the task in the user's language, validate key assumptions, consider plausible alternatives, and prioritize correctness and clarity.", + }; + let mut s = String::from("<|im_start|>system\n"); + if let Some(m) = msgs.first().filter(|m| m.role == "system") { s += &format!("{}\n\n", m.content); } + s += &format!("# Reasoning effort\n\n{sentence}"); + if !tools.is_empty() { + s += "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n"; + for t in tools { s += &format!("\n{}", t.dump()); } + s += "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n"; + } + s += END; + // Replies after the last real user turn keep their thinking. + let last_query = msgs.iter().rposition(|m| m.role == "user" && !(m.content.starts_with("") && m.content.ends_with(""))).unwrap_or(msgs.len().saturating_sub(1)); + for (i, m) in msgs.iter().enumerate() { + match m.role.as_str() { + "system" if i == 0 => {} + "assistant" => { + let (mut content, mut reasoning) = (m.content.as_str(), m.reasoning.as_deref()); + if reasoning.is_none() && let Some((r, c)) = content.rsplit_once(THINK_END) { + reasoning = Some(r.trim_end_matches('\n').rsplit("").next().unwrap_or("")); + content = c; + } + s += "<|im_start|>assistant\n"; + if i > last_query || preserve { + s += &format!("\n{}\n\n\n", reasoning.filter(|r| !r.trim().is_empty()).map_or("", |r| r.trim_matches('\n'))); + } + let content = content.trim_start_matches('\n'); + s += content; + for (k, c) in m.calls.iter().enumerate() { + if k > 0 || !content.is_empty() { s += "\n"; } + s += &format!("{CALL}\n{{\"name\": \"{}\", \"arguments\": {}}}\n{CALL_END}", c.name, c.args.dump()); + } + s += END; + } + "tool" => { + // Consecutive tool messages share one user turn. + if i == 0 || msgs[i - 1].role != "tool" { s += "<|im_start|>user"; } + s += &format!("\n\n{}\n", m.content); + if msgs.get(i + 1).is_none_or(|x| x.role != "tool") { s += END; } + } + role => s += &format!("<|im_start|>{role}\n{}{END}", m.content), + } + } + s += "<|im_start|>assistant\n"; + if effort == "none" { s += "\n\n\n\n"; } + s +} + +/// The tool calls of a reply: the text before the first call and (name, JSON arguments) per call. The thinking part +/// is skipped, so a tag inside it is not a call. +pub fn parse_calls(text: &str) -> Option<(String, Vec<(String, String)>)> { + let from = text.rfind(THINK_END).map_or(0, |p| p + THINK_END.len()); + let start = from + text[from..].find(CALL)?; + let mut calls = vec![]; + for c in text[start..].split(CALL).skip(1) { + let v: serde_json::Value = serde_json::from_str(c.split(CALL_END).next()?.trim()).ok()?; + let args = match &v["arguments"] { serde_json::Value::String(s) => s.clone(), a => a.to_string() }; + calls.push((v["name"].as_str()?.to_string(), args)); + } + (!calls.is_empty()).then(|| (text[from..start].trim().to_string(), calls)) +} + +/// Greedy decode of up to `n` tokens after `logits`; `piece` gets each new piece of text and returns false to stop. +/// Returns the tokens and whether the model ended the reply itself. +fn decode(m: &mut KolibriModel, tok: &Tokenizer, mut logits: Vec, n: usize, mut piece: impl FnMut(&str) -> bool) -> (Vec, bool) { + let eos = tok.eos_ids(); + let (mut out, mut shown) = (vec![], 0); + for i in 0..n { + let next = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + if eos.contains(&next) { return (out, true); } + out.push(next); + let s = tok.decode(&out).unwrap_or_default(); + if !s.ends_with('\u{FFFD}') && s.len() > shown && s.is_char_boundary(shown) { + if !piece(&s[shown..]) { break; } + shown = s.len(); + } + if i + 1 < n { logits = m.step(next); } + } + (out, false) +} + +fn show(s: &str) -> bool { + print!("{s}"); + std::io::stdout().flush().is_ok() +} + +/// `rustingstrata generate`: raw prompt (no template), greedy, prints the continuation. +pub fn generate(g: &Gguf, prompt: &str, n: usize) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = KolibriModel::new(g)?; + let max_ctx = m.cfg.n_ctx; + let ids = tok.encode(prompt)?; + anyhow::ensure!(!ids.is_empty() && ids.len() < max_ctx, "prompt is {} tokens, the limit is {max_ctx}", ids.len()); + if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("prompt tokens: {ids:?}"); } + let logits = m.prefill(&ids); + let (out, _) = decode(&mut m, &tok, logits, n.min(max_ctx - ids.len()), show); + if std::env::var_os("STRATA_DS_TRACE").is_some() { crate::say!("\noutput tokens: {out:?}"); } + println!(); + Ok(()) +} + +pub fn chat(g: &Gguf, system: Option, n: usize, think: bool) -> anyhow::Result<()> { + gpu_defaults(); + let tok = Tokenizer::from_gguf(g)?; + let mut m = KolibriModel::new(g)?; + let max_ctx = m.cfg.n_ctx; + let effort = if think { "high" } else { "none" }; + let stdin = std::io::stdin(); + loop { + print!("{}", crate::term::prompt()); + std::io::stdout().flush()?; + let mut line = String::new(); + if stdin.lock().read_line(&mut line)? == 0 { break; } + let line = line.trim_end(); + if line.is_empty() { continue; } + // First turn: the full template. Later turns: the cache already holds everything up to the reply, so append only + // the end token and the next user turn (earlier think blocks stay in the cache). + let user = [Msg::new("user", line)]; + let text = if m.toks.is_empty() { + let msgs: Vec = system.iter().map(|s| Msg::new("system", s)).chain(user).collect(); + render(&msgs, &[], effort, false) + } else { + format!("{END}{}", render(&user, &[], effort, false).split_once(END).unwrap().1) + }; + let ids = tok.encode(&text)?; + if m.toks.len() + ids.len() >= max_ctx { + println!("context is full ({max_ctx} tokens); restart the chat"); + break; + } + let logits = m.prefill(&ids); + let left = max_ctx - m.toks.len(); + decode(&mut m, &tok, logits, n.min(left), show); + println!(); + } + Ok(()) +} + +/// The chat of `rustingstrata serve` for Kolibri 1.1 (see `serve::Own`): one request at a time, JSON or SSE. +/// ponytail: greedy only, no stop strings; thinking arrives inside `content` up to `` (split it into +/// `reasoning_content` when a client needs that); the KV cache is reused only when the new prompt extends the last +/// sequence. +pub fn serve<'a>(g: &'a Gguf, tok: &'a Tokenizer, name: &'a str) -> anyhow::Result> { + use anyhow::Context; + use serde_json::json; + gpu_defaults(); + let mut m = KolibriModel::new(g)?; + let max_ctx = m.cfg.n_ctx; + Ok(Box::new(move |c: &mut std::net::TcpStream, q: &crate::serve::ChatRequest| { + let text = render(&q.messages, &q.tools, effort(q.think, q.reasoning_effort.as_deref()), q.preserve_thinking.unwrap_or(false)); + let ids = tok.encode(&text).ok().filter(|i| !i.is_empty()).context("cannot encode prompt")?; + anyhow::ensure!(ids.len() < max_ctx, "prompt is {} tokens, the limit is {max_ctx}", ids.len()); + let t = std::time::Instant::now(); + let keep = if m.toks.len() < ids.len() && ids.starts_with(&m.toks) { m.toks.len() } else { m.reset(); 0 }; + if q.stream { let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n"); } + let logits = crate::serve::alive(c, q.stream, || m.prefill(&ids[keep..])); + let prefill_s = t.elapsed().as_secs_f64(); + let n = q.max_tokens.unwrap_or(usize::MAX).min(max_ctx - ids.len()); + let chunk = |d: serde_json::Value, fin: Option<&str>| json!({"object": "chat.completion.chunk", "model": name, "choices": [{"index": 0, "delta": d, "finish_reason": fin}]}); + let tools = q.tool_calls && !q.tools.is_empty(); + let mut hold = crate::chat::Hold::new(tools, vec![]).tagged(CALL); + let mut alive = std::time::Instant::now(); + let (out, stopped) = decode(&mut m, &tok, logits, n, |p| { + let t = hold.push(p); + !q.stream || if t.is_empty() { crate::serve::held(c, &mut alive) } else { write!(c, "data: {}\n\n", chunk(json!({"content": t}), None)).is_ok() } + }); + let calls = if tools { parse_calls(&hold.text) } else { None }; + let done = if calls.is_some() { "tool_calls" } else if stopped { "stop" } else { "length" }; + let calls_json = |(content, calls): &(String, Vec<(String, String)>), stream: bool| { + let c: Vec<_> = calls.iter().enumerate().map(|(k, (f, a))| { + let mut c = json!({"id": format!("call_{k}"), "type": "function", "function": {"name": f, "arguments": a}}); + if stream { c["index"] = k.into(); } + c + }).collect(); + if stream { json!({"tool_calls": c}) } else { json!({"role": "assistant", "content": if content.is_empty() { None } else { Some(content) }, "tool_calls": c}) } + }; + let usage = json!({"prompt_tokens": ids.len(), "completion_tokens": out.len(), "total_tokens": ids.len() + out.len(), "prompt_tokens_details": {"cached_tokens": keep}}); + if q.stream { + match &calls { + Some(x) => { let _ = write!(c, "data: {}\n\n", chunk(calls_json(x, true), None)); } + None if !hold.rest().is_empty() => { let _ = write!(c, "data: {}\n\n", chunk(json!({"content": hold.rest()}), None)); } + None => {} + } + let _ = write!(c, "data: {}\n\n", chunk(json!({}), Some(done))); + if q.include_usage { let _ = write!(c, "data: {}\n\n", json!({"object": "chat.completion.chunk", "model": name, "choices": [], "usage": usage})); } + let _ = write!(c, "data: [DONE]\n\n"); + } else { + let message = match &calls { Some(x) => calls_json(x, false), None => json!({"role": "assistant", "content": hold.text}) }; + let b = json!({"object": "chat.completion", "model": name, "choices": [{"index": 0, "message": message, "finish_reason": done}], "usage": usage}); + crate::serve::send(c, "200 OK", "application/json", &b.to_string()); + } + Ok(crate::serve::Done { prompt: ids.len(), cached: keep, completion: out.len(), prefill_s, finish: done }) + })) +} + +#[test] +fn template_and_calls() { + let user = [Msg::new("user", "hi")]; + assert_eq!(render(&user, &[], "none", false), + "<|im_start|>system\n# Reasoning effort\n\nReasoning is disabled. Proceed straight to answering according to the user's instructions.<|im_end|>\n\ + <|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"); + // A reply before the last user turn loses its thinking; a tool round after it keeps the think block. + let mut a = Msg::new("assistant", "\nplan\n\n\nok"); + let mut msgs = vec![Msg::new("system", "S"), Msg::new("user", "q"), a.clone(), Msg::new("user", "q2")]; + let r = render(&msgs, &[], "low", false); + assert!(r.starts_with("<|im_start|>system\nS\n\n# Reasoning effort\n\nReasoning effort is set to low."), "{r}"); + assert!(r.ends_with("<|im_start|>user\nq<|im_end|>\n<|im_start|>assistant\nok<|im_end|>\n<|im_start|>user\nq2<|im_end|>\n<|im_start|>assistant\n"), "{r}"); + a.calls = vec![crate::chat::Call { name: "get".into(), args: serde_json::from_str(r#"{"city": "Kyiv"}"#).unwrap() }]; + msgs.extend([a, Msg::new("tool", "sun"), Msg::new("tool", "rain")]); + assert!(render(&msgs, &[], "high", false).ends_with("<|im_start|>assistant\n\nplan\n\n\nok\n\n{\"name\": \"get\", \"arguments\": {\"city\": \"Kyiv\"}}\n<|im_end|>\n\ + <|im_start|>user\n\nsun\n\n\nrain\n<|im_end|>\n<|im_start|>assistant\n")); + let reply = "\n no\n\n\nok\n\n{\"name\": \"get\", \"arguments\": {\"city\": \"Kyiv\", \"n\": 3}}\n\n\n{\"name\": \"b\", \"arguments\": {}}\n"; + assert_eq!(parse_calls(reply), Some(("ok".into(), vec![("get".into(), r#"{"city":"Kyiv","n":3}"#.into()), ("b".into(), "{}".into())]))); +} diff --git a/src/kolibri/forward.rs b/src/kolibri/forward.rs new file mode 100644 index 0000000..c98c634 --- /dev/null +++ b/src/kolibri/forward.rs @@ -0,0 +1,743 @@ +//! Kolibri 1.1 forward, mirroring llama.cpp `src/models/kolibri1.cpp` (trace names are its callback names, so +//! `STRATA_DS_DUMP` output lines up with `llama-eval-callback`). Decode is one token at a time; prefill runs a chunk +//! of prompt tokens layer by layer, so a routed expert is read once for all the tokens that picked it. +//! ponytail: attention scores and the indexer run on the CPU; a GPU kernel is the next step for prompt speed. +use super::{KolibriConfig, N_RECENT, N_SINK}; +use crate::deepseek::mat::{Mat, matvec_many, matvec_rows, matvec_rows_many, swiglu_chunk, vec_f32}; +use crate::deepseek::ops::rms_norm_w; +use crate::gguf::Gguf; +use crate::hy4::forward::{host_mat, run_experts, sigmoid, silu}; +use crate::inkling2::forward::{dot_h, dots_h, mix_h}; +use anyhow::Result; +use half::f16; +use half::slice::HalfFloatSliceExt; +use rayon::prelude::*; + +enum Ffn<'a> { + Dense { gate: Mat<'a>, up: Mat<'a>, down: Mat<'a> }, + Moe { gate_inp: Mat<'a>, bias: Vec, gexps: Mat<'a>, uexps: Mat<'a>, dexps: Mat<'a>, gate_sh: Mat<'a>, up_sh: Mat<'a>, down_sh: Mat<'a> }, +} + +struct Layer<'a> { + attn_norm: Vec, + q: Mat<'a>, + q_norm: Vec, + /// K and V projections and the K norm; None on a layer that reads the K/V of another layer. + kv: Option<(Mat<'a>, Mat<'a>, Vec)>, + out: Mat<'a>, + post_attn_norm: Vec, + ffn_norm: Vec, + post_ffw_norm: Vec, + ffn: Ffn<'a>, +} + +pub struct KolibriModel<'a> { + pub cfg: KolibriConfig, + tok_embd: Mat<'a>, + out_norm: Vec, + out_w: Mat<'a>, + layers: Vec>, + /// Per layer with its own K/V and per K/V head: one f16 row of `head_dim` per position from `first[il]` on, as + /// llama.cpp keeps them. Sliding layers: K rotated; sparse layers: K and V rounded to NVFP4. + k: Vec>>, + v: Vec>>, + /// Position of row 0 (a sliding layer drops the rows no later query sees). + first: Vec, + /// Per sparse layer with its own K/V: the rounded mean routing key of each complete block of positions. + blocks: Vec>, + /// Share of a layer's VRAM-cache misses that the CPU computes while the GPU runs the rest (see `ffn`). + cpu_share: std::cell::Cell, + pub toks: Vec, + pub trace: bool, +} + +/// The E4M3 value nearest to `x` > 0 (ties to even), as ggml encodes and decodes the NVFP4 block scale. +fn e4m3(x: f32) -> f32 { + if x >= 448.0 { return 448.0; } + if x < 0.015625 { return (x * 512.0).round_ties_even() / 512.0; } + let b = x.to_bits(); + let frac = f32::from_bits((b & 0x7f_ffff) | 0x3f80_0000) - 1.0; + ((1.0 + (frac * 8.0).round_ties_even() / 8.0) * 2f32.powi((b >> 23) as i32 - 127)).min(448.0) +} + +/// Nearest E2M1 value, ties to even, saturated at 6. +fn e2m1(x: f32) -> f32 { + let a = x.abs(); + let r: f32 = if a <= 0.25 { 0.0 } else if a < 0.75 { 0.5 } else if a <= 1.25 { 1.0 } else if a < 1.75 { 1.5 } + else if a <= 2.5 { 2.0 } else if a < 3.5 { 3.0 } else if a <= 5.0 { 4.0 } else { 6.0 }; + r.copysign(x) +} + +/// ggml `round_nvfp4`: every block of 16 values becomes E2M1 values times one E4M3 scale. +pub(crate) fn round_nvfp4(x: &mut [f32]) { + for g in x.chunks_exact_mut(16) { + let amax = g.iter().fold(0f32, |m, v| m.max(v.abs())); + let scale = e4m3((amax / 6.0).max(0.001953125)); + for v in g { *v = e2m1(*v / scale) * scale; } + } +} + +/// (cos, sin) of a position's rotations, with ggml's running product for the angle. +fn rope_tab(pos: usize, n: usize, base: f32) -> Vec<(f32, f32)> { + let scale = base.powf(-2.0 / n as f32); + let mut theta = pos as f32; + (0..n / 2).map(|_| { + let cs = (theta.cos(), theta.sin()); + theta *= scale; + cs + }).collect() +} + +/// NeoX RoPE of one head: dimension i pairs with i + n/2. +fn rope(x: &mut [f32], tab: &[(f32, f32)]) { + let h = tab.len(); + for (i, &(c, s)) in tab.iter().enumerate() { + let (a, b) = (x[i], x[i + h]); + x[i] = a * c - b * s; + x[i + h] = a * s + b * c; + } +} + +/// The routed experts of one token, best first: the bias only picks, the weight is the sigmoid of the logit. +fn route(logits: &[f32], bias: &[f32], n_used: usize) -> Vec<(usize, f32)> { + let mut sel: Vec = (0..logits.len()).collect(); + sel.sort_by(|&a, &b| (logits[b] + bias[b]).total_cmp(&(logits[a] + bias[a])).then(a.cmp(&b))); + sel.truncate(n_used); + sel.into_iter().map(|e| (e, sigmoid(logits[e]))).collect() +} + +/// The `n` best of `scored` (score, index): highest score first, the lower index on a tie. Returns the indices. +fn top_n(mut scored: Vec<(f32, u32)>, n: usize) -> Vec { + if scored.len() > n { + scored.select_nth_unstable_by(n - 1, |a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1))); + scored.truncate(n); + } + scored.into_iter().map(|s| s.1).collect() +} + +/// The positions a sparse query at `pos` attends, ascending, or None for all of them. `score` rates a position's +/// routing key and `block_score` a block's mean key. A query attends its first `N_SINK` and last `N_RECENT` +/// positions and the `top_k` best of the candidates between them. On an indexer layer the candidates of a long +/// context are narrowed to the `pool_blocks` best complete blocks first; `pool` carries them to the sparse layers +/// that follow (None: every candidate). +fn select(cfg: &KolibriConfig, indexer: bool, pos: usize, pool: &mut Option>, score: impl Fn(u32) -> f32 + Sync, block_score: impl Fn(u32) -> f32 + Sync) -> Option> { + if pos < N_SINK + N_RECENT + cfg.top_k { return None; } + let last = (pos - N_RECENT) as u32; + if indexer { + let live = (pos + 1) / cfg.block; + *pool = (live > cfg.pool_blocks).then(|| { + let mut b = top_n((0..live as u32).into_par_iter().map(|j| (block_score(j), j)).collect(), cfg.pool_blocks); + b.sort_unstable(); + b.into_iter().flat_map(|j| j * cfg.block as u32..(j + 1) * cfg.block as u32).filter(|&p| p >= N_SINK as u32 && p <= last).collect() + }); + } + let scored: Vec<(f32, u32)> = match pool { + Some(p) if p.len() <= cfg.top_k => p.iter().map(|&c| (0.0, c)).collect(), + Some(p) => p.par_iter().map(|&c| (score(c), c)).collect(), + None => (N_SINK as u32..=last).into_par_iter().map(|c| (score(c), c)).collect(), + }; + let mut picks = top_n(scored, cfg.top_k); + picks.sort_unstable(); + Some((0..N_SINK as u32).chain(picks).chain(last + 1..=pos as u32).collect()) +} + +/// Softmax attention of `n` query heads `q` over the f16 key rows `k` with values `v`, into `o` (zeroed). +fn head_group(q: &[f32], k: &[f16], v: &[f16], hd: usize, scale: f32, o: &mut [f32]) { + let (nk, n) = (k.len() / hd, q.len() / hd); + let mut p = vec![0f32; n * nk]; + dots_h(&mut p, scale, k, q, nk); + for p in p.chunks_exact_mut(nk) { + let mx = p.iter().cloned().fold(f32::MIN, f32::max); + let mut z = 0f32; + for s in p.iter_mut() { + *s = (*s - mx).exp(); + z += *s; + } + for s in p.iter_mut() { *s /= z; } + } + mix_h(o, &p, v, nk); +} + +impl<'a> KolibriModel<'a> { + pub fn new(g: &'a Gguf) -> Result { + let cfg = KolibriConfig::from_gguf(g)?; + let mut layers = Vec::with_capacity(cfg.n_layer); + for il in 0..cfg.n_layer { + let m = |n: &str| Mat::load(g, &format!("blk.{il}.{n}.weight")); + let v = |n: &str| vec_f32(g, &format!("blk.{il}.{n}.weight")); + let ffn = if il < cfg.n_dense { + Ffn::Dense { gate: m("ffn_gate")?, up: m("ffn_up")?, down: m("ffn_down")? } + } else { + Ffn::Moe { + gate_inp: m("ffn_gate_inp")?, + bias: vec_f32(g, &format!("blk.{il}.exp_probs_b.bias"))?, + gexps: m("ffn_gate_exps")?, + uexps: m("ffn_up_exps")?, + dexps: m("ffn_down_exps")?, + gate_sh: m("ffn_gate_shexp")?, + up_sh: m("ffn_up_shexp")?, + down_sh: m("ffn_down_shexp")?, + } + }; + layers.push(Layer { + attn_norm: v("attn_norm")?, + q: m("attn_q")?, + q_norm: v("attn_q_norm")?, + kv: if cfg.kv_src[il] == il { Some((m("attn_k")?, m("attn_v")?, v("attn_k_norm")?)) } else { None }, + out: m("attn_output")?, + post_attn_norm: v("post_attention_norm")?, + ffn_norm: v("ffn_norm")?, + post_ffw_norm: v("post_ffw_norm")?, + ffn, + }); + } + let per_head = vec![vec![vec![]; cfg.n_head_kv]; cfg.n_layer]; + Ok(KolibriModel { + tok_embd: host_mat(g, "token_embd.weight")?, + out_norm: vec_f32(g, "output_norm.weight")?, + out_w: Mat::load(g, "output.weight")?, + k: per_head.clone(), + v: per_head, + first: vec![0; cfg.n_layer], + blocks: vec![vec![]; cfg.n_layer], + cpu_share: std::cell::Cell::new(0.5), + layers, + cfg, + toks: vec![], + trace: std::env::var("STRATA_DS_TRACE").is_ok(), + }) + } + + pub fn reset(&mut self) { + for h in self.k.iter_mut().chain(&mut self.v).flatten() { h.clear(); } + for b in &mut self.blocks { b.clear(); } + self.first.fill(0); + self.toks.clear(); + } + + fn tr(&self, name: &str, il: i32, v: &[f32]) { + if let Ok(dir) = std::env::var("STRATA_DS_DUMP") { + use std::io::Write; + let fname = if il < 0 { format!("{dir}/{name}.f32") } else { format!("{dir}/{name}-{il}.f32") }; + let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); + std::fs::OpenOptions::new().create(true).append(true).open(fname).unwrap().write_all(&bytes).unwrap(); + } + if self.trace { + let n = v.len(); + let f = |i: usize| format!("{:12.4}", v[i]); + eprintln!("TRACE {name}-{il} [{} {} {} ... {} {} {}] sum={:.6}", f(0), f(1), f(2), f(n - 3), f(n - 2), f(n - 1), v.iter().sum::()); + } + } + + /// Attention output (before its norm) of the consecutive positions from `p0`. `pools` holds each position's key + /// pool from the last indexer layer. + fn attention(&mut self, il: usize, curs: &[Vec], p0: usize, pools: &mut [Option>]) -> Vec { + let cfg = &self.cfg; + let l = &self.layers[il]; + let (nh, nkv, hd, eps, nt, swa, src) = (cfg.n_head, cfg.n_head_kv, cfg.head_dim, cfg.eps, curs.len(), cfg.swa[il], cfg.kv_src[il]); + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + // One token: the projections share a GPU round trip. + let mats: Vec = std::iter::once(l.q).chain(l.kv.iter().flat_map(|kv| [kv.0, kv.1])).collect(); + let mut proj: Vec> = if nt == 1 { + let y = matvec_many(&mats, xs[0], 0); + let mut at = 0; + mats.iter().map(|m| { at += m.rows; y[at - m.rows..at].to_vec() }).collect() + } else { + mats.iter().map(|m| matvec_rows(m, &xs)).collect() + }; + let tabs: Vec> = if swa { (0..nt).map(|t| rope_tab(p0 + t, hd, cfg.rope_base)).collect() } else { vec![] }; + let mut q = std::mem::take(&mut proj[0]); + let norm_heads = |x: &mut [f32], w: &[f32], per_tok: usize| { + let mut y = vec![0f32; hd]; + for (i, h) in x.chunks_exact_mut(hd).enumerate() { + rms_norm_w(h, w, eps, &mut y); + h.copy_from_slice(&y); + if swa { rope(h, &tabs[i / per_tok]); } + } + }; + if let Some((_, _, k_norm)) = &l.kv { + let (mut k, mut v) = (std::mem::take(&mut proj[1]), std::mem::take(&mut proj[2])); + norm_heads(&mut k, k_norm, nkv); + if nt == 1 { self.tr(if swa { "Kcur_rope" } else { "Kcur_normed" }, il as i32, &k); } + if !swa { + round_nvfp4(&mut k); + round_nvfp4(&mut v); + if nt == 1 { + self.tr("Kcur_nvfp4", il as i32, &k); + self.tr("Vcur_nvfp4", il as i32, &v); + } + } + for (rows, store) in [(&k, &mut self.k[il]), (&v, &mut self.v[il])] { + for (i, h) in rows.chunks_exact(hd).enumerate() { store[i % nkv].extend(h.iter().map(|&x| f16::from_f32(x))); } + } + if !swa { + // The mean routing key of every block that is complete now, summed member by member as ggml does. + let (k0, bs) = (&self.k[il][0], cfg.block); + for j in self.blocks[il].len() / hd..k0.len() / hd / bs { + let mut mean = vec![0f32; hd]; + for row in k0[j * bs * hd..(j + 1) * bs * hd].chunks_exact(hd) { + for (m, x) in mean.iter_mut().zip(row) { *m += x.to_f32(); } + } + for m in &mut mean { *m *= 1.0 / bs as f32; } + round_nvfp4(&mut mean); + self.blocks[il].extend(mean); + } + } + } + norm_heads(&mut q, &l.q_norm, nh); + if nt == 1 { self.tr(if swa { "Qcur_rope" } else { "Qcur_normed" }, il as i32, &q); } + let (ks, vs, first, blocks) = (&self.k[src], &self.v[src], self.first[src], &self.blocks[src]); + let (per, scale) = (nh / nkv, 1.0 / (hd as f32).sqrt()); + // Sparse layers: the keys each query attends (None: all of them). + let sels: Vec>> = if swa { vec![None; nt] } else { + let w = 1.0 / (per as f32 * (hd as f32).sqrt()); + pools.par_iter_mut().enumerate().map(|(t, pool)| { + let rated = |key: &[f16], qr: &Vec| qr.chunks_exact(hd).map(|qh| dot_h(key, qh).max(0.0) * w).sum::(); + let route_q = || { let mut r = q[t * nh * hd..][..per * hd].to_vec(); round_nvfp4(&mut r); r }; + // Made only when the context is longer than the keys a query attends. + let r = std::sync::OnceLock::new(); + select(cfg, cfg.indexer[il], p0 + t, pool, + |c| rated(&ks[0][c as usize * hd..][..hd], r.get_or_init(route_q)), + |j| { let key: Vec = blocks[j as usize * hd..][..hd].iter().map(|&x| f16::from_f32(x)).collect(); rated(&key, r.get_or_init(route_q)) }) + }).collect() + }; + if nt == 1 && let Some(s) = &sels[0] { self.tr("kq_sel", il as i32, &s.iter().map(|&p| p as f32).collect::>()); } + // A chunk whose queries all see a run of consecutive keys (a sliding layer, or a sparse one before it selects) runs on the GPU. + let gpu = nt > 4 && std::env::var_os("STRATA_KOL_CPU_ATTN").is_none(); + // Rows `from..` of a K or V store as the GPU cache: the K/V heads of a position side by side. + let rows = |hs: &Vec>, from: usize| -> Vec { + let mut o = Vec::with_capacity((p0 + nt - from) * nkv * hd); + for r in from - first..p0 + nt - first { + for h in hs { o.extend_from_slice(h[r * hd..(r + 1) * hd].reinterpret_cast()); } + } + o + }; + if gpu && sels.iter().all(|s| s.is_none()) { + let from = if swa { (p0 + 1).saturating_sub(cfg.n_swa).max(first) } else { 0 }; + if let Some(att) = crate::deepseek::mat::attn_rows(&q, &rows(ks, from), &rows(vs, from), p0 - from, nt, nh, nkv, hd, if swa { cfg.n_swa } else { 0 }) { + return matvec_rows(&l.out, &att.chunks_exact(nh * hd).collect::>()); + } + } + // A sparse chunk with selections: each query brings its list of keys (all the earlier ones when it has none). + if gpu && !swa { + let ns = sels.iter().enumerate().map(|(t, s)| s.as_ref().map_or(p0 + t + 1, |s| s.len())).max().unwrap(); + let mut idx = vec![0u32; nt * ns]; + let cnt: Vec = sels.iter().zip(idx.chunks_exact_mut(ns)).enumerate().map(|(t, (s, row))| match s { + Some(s) => { row[..s.len()].copy_from_slice(s); s.len() as i32 } + None => { for (i, x) in row[..p0 + t + 1].iter_mut().enumerate() { *x = i as u32; } (p0 + t + 1) as i32 } + }).collect(); + if let Some(att) = crate::deepseek::mat::attn_sel(&q, &rows(ks, first), &rows(vs, first), &idx, &cnt, nt, nh, nkv, hd) { + return matvec_rows(&l.out, &att.chunks_exact(nh * hd).collect::>()); + } + } + // One task per token and K/V head; the query heads of a K/V head go three at a time (`dots_h`). + let group = if per % 3 == 0 { 3 } else { 1 }; + let mut att = vec![0f32; nt * nh * hd]; + att.par_chunks_mut(per * hd).enumerate().for_each(|(i, o)| { + let (t, g) = (i / nkv, i % nkv); + let pos = p0 + t; + let (gk, gv): (Vec, Vec); + let (k, v) = match &sels[t] { + Some(sel) => { + let gather = |rows: &[f16]| sel.iter().flat_map(|&p| &rows[p as usize * hd..][..hd]).copied().collect(); + (gk, gv) = (gather(&ks[g]), gather(&vs[g])); + (&gk[..], &gv[..]) + } + None => { + let from = if swa { (pos + 1).saturating_sub(cfg.n_swa).max(first) } else { 0 }; + let r = (from - first) * hd..(pos + 1 - first) * hd; + (&ks[g][r.clone()], &vs[g][r]) + } + }; + let qt = &q[i * per * hd..(i + 1) * per * hd]; + for (qh, o) in qt.chunks(group * hd).zip(o.chunks_mut(group * hd)) { head_group(qh, k, v, hd, scale, o); } + }); + if nt == 1 { self.tr("kqv_out", il as i32, &att); } + matvec_rows(&l.out, &att.chunks_exact(nh * hd).collect::>()) + } + + fn ffn(&self, il: usize, cur: &[f32]) -> Vec { + let cfg = &self.cfg; + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => { + let y = matvec_many(&[*gate, *up], cur, 0); + let a: Vec = (0..gate.rows).map(|i| silu(y[i]) * y[gate.rows + i]).collect(); + let mut out = vec![0f32; down.rows]; + down.matvec(&a, &mut out); + out + } + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, gate_sh, up_sh, down_sh } => { + let ne = cfg.n_expert; + // The shared expert rides with the routed ones on the GPU (weight 1); a tensor dump keeps it apart. + let apart = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some() || crate::deepseek::mat::dev_info().is_none(); + let y = if apart { matvec_many(&[*gate_inp, *gate_sh, *up_sh], cur, 0) } else { matvec_many(&[*gate_inp], cur, 0) }; + let (logits, sh) = y.split_at(ne); + self.tr("ffn_moe_logits", il as i32, logits); + let sel = route(logits, bias, cfg.n_used); + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + for &(e, _) in &sel { + for m in [gexps, uexps, dexps] { m.prefetch_expert(e, ne); } + } + } + let nl = dexps.rows / ne; + // Experts resident in VRAM run on the GPU. Of the others, the CPU computes `cpu_share` from the mapped + // file while the GPU uploads and runs the rest, both at once; the share follows the two sides' times. + // `STRATA_DS_CPU_SHARE` fixes it; 0 (also `--fixed-experts`) runs every expert on the GPU, replacing + // the least recently used VRAM slots: the same numerics on every run. + let (share, fixed) = self.share(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, true); if x.gpu.is_some() { x } else { x.staged() } }; + let gates: Vec = sel.iter().map(|s| gexps.expert_opt(s.0, ne, share == 0.0)).collect(); + let n_miss = gates.iter().filter(|m| m.gpu.is_none()).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (g, &(e, w)) in gates.into_iter().zip(&sel) { + if g.gpu.is_none() && left > 0 { + left -= 1; + on_cpu.push((g, uexps.expert_host(e, ne), dexps.expert_host(e, ne), w)); + } else { + on_gpu.push((g, e, w)); + } + } + let cpu_side = || { let t = std::time::Instant::now(); (run_experts(&on_cpu, cur, 0.0, nl), t.elapsed().as_secs_f32()) }; + let gpu_side = || { + let t = std::time::Instant::now(); + let mut list: Vec<_> = on_gpu.iter().map(|&(g, e, w)| (if g.gpu.is_some() { g } else { on(gexps, e) }, on(uexps, e), on(dexps, e), w)).collect(); + if !apart { list.push((*gate_sh, *up_sh, *down_sh, 1.0)); } + (run_experts(&list, cur, 0.0, nl), t.elapsed().as_secs_f32()) + }; + let ((a, tg), (b, tc)) = rayon::join(gpu_side, cpu_side); + if !fixed && n_miss > 0 { self.balance(tg, tc); } + let mix: Vec = a.iter().zip(&b).map(|(a, b)| a + b).collect(); + if !apart { return mix; } + self.tr("ffn_moe_out", il as i32, &mix); + let a: Vec = (0..gate_sh.rows).map(|i| silu(sh[i]) * sh[gate_sh.rows + i]).collect(); + let mut s = vec![0f32; down_sh.rows]; + down_sh.matvec(&a, &mut s); + self.tr("ffn_shexp_out", il as i32, &s); + mix.iter().zip(&s).map(|(a, b)| a + b).collect() + } + } + } + + /// The CPU's share of a layer's VRAM-cache misses, and whether it is fixed (no GPU, or set by the user). + fn share(&self) -> (f32, bool) { + static FIXED: std::sync::OnceLock> = std::sync::OnceLock::new(); + let fixed = *FIXED.get_or_init(|| { + let share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse().ok()); + share.or(std::env::var_os("STRATA_FIXED_EXPERTS").map(|_| 0.0)) + }); + if crate::deepseek::mat::dev_info().is_none() { return (1.0, true); } + (fixed.unwrap_or(self.cpu_share.get()).clamp(0.0, 1.0), fixed.is_some()) + } + + /// Move the share toward the side that finished first (`tg`, `tc`: seconds the GPU and the CPU side took). + fn balance(&self, tg: f32, tc: f32) { + if tg + tc > 0.0 { self.cpu_share.set((self.cpu_share.get() + 0.1 * (tg - tc) / (tg + tc)).clamp(0.0, 1.0)); } + } + + /// `ffn` for the tokens of a prefill chunk, token-major. A routed expert is read once and applied to every token + /// that picked it; the experts are split between the GPU and the CPU like the misses in `ffn`. + fn ffn_batch(&self, il: usize, curs: &[Vec]) -> Vec { + let cfg = &self.cfg; + let xs: Vec<&[f32]> = curs.iter().map(|c| c.as_slice()).collect(); + let swiglu = |gate: &Mat, up: &Mat, down: &Mat, x: &[&[f32]]| -> Vec { + let (gy, uy) = (matvec_rows(gate, x), matvec_rows(up, x)); + let a: Vec = gy.iter().zip(&uy).map(|(g, u)| silu(*g) * u).collect(); + matvec_rows(down, &a.chunks_exact(gate.rows).collect::>()) + }; + match &self.layers[il].ffn { + Ffn::Dense { gate, up, down } => swiglu(gate, up, down, &xs), + Ffn::Moe { gate_inp, bias, gexps, uexps, dexps, gate_sh, up_sh, down_sh } => { + let ne = cfg.n_expert; + let (nf, nl) = (gexps.rows / ne, dexps.rows / ne); + let logits = matvec_rows(gate_inp, &xs); + let sels: Vec> = logits.par_chunks_exact(ne).map(|l| route(l, bias, cfg.n_used)).collect(); + // Per expert: the (token, rank in the token's selection) pairs that use it. + let mut by_e: std::collections::BTreeMap> = Default::default(); + for (t, sel) in sels.iter().enumerate() { + for (k, &(e, _)) in sel.iter().enumerate() { by_e.entry(e).or_default().push((t, k)); } + } + if std::env::var_os("STRATA_DS_NOPREFETCH").is_none() { + // In parallel: a read-ahead call waits for the drive's queue. + by_e.keys().collect::>().par_iter().for_each(|&&e| { + for m in [gexps, uexps, dexps] { m.prefetch_expert(e, ne); } + }); + } + let (share, fixed) = self.share(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, share == 0.0); if x.gpu.is_some() { x } else { x.staged() } }; + let gates: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, gexps.expert_opt(e, ne, share == 0.0))).collect(); + let n_miss = gates.iter().filter(|g| g.1.gpu.is_none()).count(); + let mut left = (share * n_miss as f32).round() as usize; + let (mut on_gpu, mut on_cpu) = (vec![], vec![]); + for (e, g) in gates { + if g.gpu.is_none() && left > 0 { + left -= 1; + on_cpu.push((e, g, uexps.expert_host(e, ne), dexps.expert_host(e, ne))); + } else { + on_gpu.push((e, if g.gpu.is_some() { g } else { g.staged() }, on(uexps, e), on(dexps, e))); + } + } + let rows_of = |e: usize| -> Vec<&[f32]> { by_e[&e].iter().map(|&(t, _)| xs[t]).collect() }; + let gpu = || { + let t = std::time::Instant::now(); + // One round trip for all the experts: the per-token weighted sums come back. + // The shared expert rides along as one more expert of every token, with weight 1, in slot `n_used`. + if std::env::var_os("STRATA_KOL_NOCHUNK").is_none() { + let sh = [gate_sh, up_sh, down_sh]; + let col = |i: usize| -> Vec { on_gpu.iter().map(|g| [g.1, g.2, g.3][i]).chain([*sh[i]]).collect() }; + let mut pairs: Vec> = on_gpu.iter().map(|(e, ..)| by_e[e].iter().map(|&(t, k)| (t, k, sels[t][k].1)).collect()).collect(); + pairs.push((0..xs.len()).map(|t| (t, cfg.n_used, 1.0)).collect()); + if let Some(sum) = swiglu_chunk(&col(0), &col(1), &col(2), &pairs, &xs.concat(), cfg.n_used + 1) { + return (vec![], Some(sum), t.elapsed().as_secs_f32()); + } + } + // Else two batches for all the experts (gates and ups, then downs). + let n_of = |e: &usize| by_e[e].len(); + let mut x = Vec::with_capacity(2 * on_gpu.iter().map(|(e, ..)| n_of(e)).sum::() * cfg.n_embd); + for (e, ..) in &on_gpu { + for _ in 0..2 { for &(t, _) in &by_e[e] { x.extend_from_slice(xs[t]); } } + } + let y = matvec_rows_many(&on_gpu.iter().flat_map(|(e, g, u, _)| [(*g, n_of(e)), (*u, n_of(e))]).collect::>(), &x); + let mut act = Vec::with_capacity(y.len() / 2); + let mut at = 0; + for (e, ..) in &on_gpu { + let n = n_of(e) * nf; + act.extend(y[at..at + n].iter().zip(&y[at + n..at + 2 * n]).map(|(g, u)| silu(*g) * u)); + at += 2 * n; + } + let dy = matvec_rows_many(&on_gpu.iter().map(|(e, _, _, d)| (*d, n_of(e))).collect::>(), &act); + let mut at = 0; + let out: Vec<(usize, Vec)> = on_gpu.iter().map(|(e, ..)| { at += n_of(e) * nl; (*e, dy[at - n_of(e) * nl..at].to_vec()) }).collect(); + (out, None, t.elapsed().as_secs_f32()) + }; + let cpu = || { + let t = std::time::Instant::now(); + // Each weight row is read once for all the tokens of its expert (`matvec_rows`). + let out: Vec<(usize, Vec)> = on_cpu.par_iter().map(|(e, g, u, d)| (*e, swiglu(g, u, d, &rows_of(*e)))).collect(); + (out, t.elapsed().as_secs_f32()) + }; + let ((a, gsum, tg), (b, tc)) = rayon::join(gpu, cpu); + if !fixed && n_miss > 0 { self.balance(tg, tc); } + // Each token sums its experts in its own selection order, as `ffn` does; the shared expert is added last. + let mut ds: Vec> = sels.iter().map(|s| vec![&[][..]; s.len()]).collect(); + for (e, dy) in a.iter().chain(&b) { + for (&(t, k), d) in by_e[e].iter().zip(dy.chunks_exact(nl)) { ds[t][k] = d; } + } + let mut mix = if gsum.is_some() { vec![0f32; xs.len() * nl] } else { swiglu(gate_sh, up_sh, down_sh, &xs) }; + for (t, m) in mix.chunks_exact_mut(nl).enumerate() { + let mut sum = vec![0f32; nl]; + // An expert of the device's chunk has no row here: its weighted output is in `gsum`. + for (d, &(_, w)) in ds[t].iter().zip(&sels[t]).filter(|(d, _)| !d.is_empty()) { + for j in 0..nl { sum[j] += w * d[j]; } + } + if let Some(g) = &gsum { for j in 0..nl { sum[j] += g[t * nl + j]; } } + for j in 0..nl { m[j] += sum[j]; } + } + mix + } + } + } + + pub fn step(&mut self, tok: u32) -> Vec { + self.forward(&[tok], true) + } + + /// Run `toks` through the model; logits only for the last one. All but the last go in chunks of + /// `STRATA_DS_CHUNK` tokens (default 1024, or 1 with a tensor dump, which covers only the tokens that run alone). A chunk reads each routed expert + /// once, so on a machine whose RAM does not hold the experts a larger chunk means less disk traffic per token. + pub fn prefill(&mut self, toks: &[u32]) -> Vec { + let Some((&last, head)) = toks.split_last() else { return vec![] }; + let dump = self.trace || std::env::var_os("STRATA_DS_DUMP").is_some(); + let chunk: usize = std::env::var("STRATA_DS_CHUNK").ok().and_then(|v| v.parse().ok()).unwrap_or(if dump { 1 } else { 1024 }); + for c in head.chunks(chunk.max(1)) { self.forward(c, false); } + self.step(last) + } + + /// Layer-major pass over consecutive tokens; the logits of the last one when `want`. + fn forward(&mut self, toks: &[u32], want: bool) -> Vec { + let t0 = std::time::Instant::now(); + let (n, nt, eps) = (self.cfg.n_embd, toks.len(), self.cfg.eps); + let p0 = self.toks.len(); + self.toks.extend_from_slice(toks); + let mut xs: Vec> = toks.iter().map(|&t| { + let mut emb = vec![0f32; n]; + self.tok_embd.row_into(t as usize, &mut emb); + emb + }).collect(); + let normed = |xs: &[Vec], w: &[f32]| -> Vec> { + xs.iter().map(|x| { let mut h = vec![0f32; n]; rms_norm_w(x, w, eps, &mut h); h }).collect() + }; + let mut pools: Vec>> = vec![None; nt]; + let mut cur = vec![0f32; n]; + let (mut t_attn, mut t_ffn) = (0f64, 0f64); + for il in 0..self.cfg.n_layer { + let t = std::time::Instant::now(); + let hs = normed(&xs, &self.layers[il].attn_norm); + if nt == 1 { self.tr("attn_norm", il as i32, &hs[0]); } + let att = self.attention(il, &hs, p0, &mut pools); + if nt == 1 { self.tr("attn_out", il as i32, &att); } + for (x, a) in xs.iter_mut().zip(att.chunks_exact(n)) { + rms_norm_w(a, &self.layers[il].post_attn_norm, eps, &mut cur); + for j in 0..n { x[j] += cur[j]; } + } + if nt == 1 { self.tr("ffn_inp", il as i32, &xs[0]); } + t_attn += t.elapsed().as_secs_f64(); + let t = std::time::Instant::now(); + let hs = normed(&xs, &self.layers[il].ffn_norm); + if nt == 1 { self.tr("ffn_norm", il as i32, &hs[0]); } + let f = if nt == 1 { self.ffn(il, &hs[0]) } else { self.ffn_batch(il, &hs) }; + for (x, f) in xs.iter_mut().zip(f.chunks_exact(n)) { + rms_norm_w(f, &self.layers[il].post_ffw_norm, eps, &mut cur); + for j in 0..n { x[j] += cur[j]; } + } + if nt == 1 { self.tr("l_out", il as i32, &xs[0]); } else if self.trace { self.tr("l_out", il as i32, &xs.concat()); } + t_ffn += t.elapsed().as_secs_f64(); + } + // A sliding layer keeps the rows its window still reaches. + let (hd, keep) = (self.cfg.head_dim, self.cfg.n_swa); + for il in (0..self.cfg.n_layer).filter(|&il| self.cfg.swa[il]) { + let rows = self.k[il][0].len() / hd; + if rows > 4 * keep { + for h in self.k[il].iter_mut().chain(&mut self.v[il]) { h.drain(..(rows - keep) * hd); } + self.first[il] += rows - keep; + } + } + let mut logits = vec![]; + if want { + rms_norm_w(&xs[nt - 1], &self.out_norm, eps, &mut cur); + self.tr("result_norm", -1, &cur); + logits = vec![0f32; self.out_w.rows]; + self.out_w.matvec(&cur, &mut logits); + } + if std::env::var_os("STRATA_DS_PROF").is_some() { + use std::sync::atomic::Ordering::Relaxed; + let ex = &crate::deepseek::mat::EX_LOOKUPS; + eprintln!("PROF {nt} at {p0}: {:.0} ms (attn {:.0}, ffn {:.0}), expert cache hit {} miss {}, cpu share {:.2}", + t0.elapsed().as_secs_f64() * 1e3, t_attn * 1e3, t_ffn * 1e3, ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), self.cpu_share.get()); + } + logits + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nvfp4_rounding_follows_ggml() { + // Scales: the subnormal floor, a tie in the mantissa (to even), a carry into the exponent, saturation. + for (x, want) in [(0.001953125, 0.001953125), (0.01, 5.0 / 512.0), (1.0625, 1.0), (1.1875, 1.25), (1.96875, 2.0), (1000.0, 448.0), (0.3, 0.3125)] { + assert_eq!(e4m3(x), want, "e4m3({x})"); + } + for (x, want) in [(0.25, 0.0), (0.26, 0.5), (-0.75, -1.0), (1.25, 1.0), (1.75, 2.0), (2.5, 2.0), (3.5, 4.0), (5.0, 4.0), (5.1, 6.0), (-9.0, -6.0)] { + assert_eq!(e2m1(x), want, "e2m1({x})"); + } + // amax 6 gives scale 1: the values round on the E2M1 grid; a block of zeros stays zero. + let mut x = [6.0, -5.1, 3.4, 0.7, 0.2, 1.3, 2.6, -1.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + round_nvfp4(&mut x); + assert_eq!(x[..8], [6.0, -6.0, 3.0, 0.5, 0.0, 1.5, 3.0, -1.5]); + assert!(x[8..].iter().all(|&v| v == 0.0)); + } + + #[test] + fn rope_is_neox() { + let mut x = [1.0, 2.0, 0.0, 0.0]; + rope(&mut x, &rope_tab(1, 4, 10000.0)); + let (c1, s1) = (0.01f32.cos(), 0.01f32.sin()); + assert!((x[0] - 1f32.cos()).abs() < 1e-6 && (x[2] - 1f32.sin()).abs() < 1e-6); + assert!((x[1] - 2.0 * c1).abs() < 1e-6 && (x[3] - 2.0 * s1).abs() < 1e-6); + } + + /// The GPU chunk attention against `head_group` on the same f16 rows, with a window and keys from before the + /// chunk. Skips without a GPU (`STRATA_DS_GPU=1` opens one). + #[test] + fn gpu_window_attention_matches_cpu() { + let (nt, nh, nkv, hd, win, base) = (40usize, 6usize, 2usize, 128usize, 7usize, 5usize); + let mut seed = 1u32; + let mut rnd = |n: usize| -> Vec { (0..n).map(|_| { seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); (seed >> 8) as f32 / (1 << 23) as f32 - 1.0 }).collect() }; + let (q, k, v) = (rnd(nt * nh * hd), rnd((base + nt) * nkv * hd), rnd((base + nt) * nkv * hd)); + let bits = |x: &[f32]| -> Vec { x.iter().map(|&x| f16::from_f32(x).to_bits()).collect() }; + let Some(got) = crate::deepseek::mat::attn_rows(&q, &bits(&k), &bits(&v), base, nt, nh, nkv, hd, win) else { eprintln!("no GPU attention, skipping"); return }; + let (per, scale) = (nh / nkv, 1.0 / (hd as f32).sqrt()); + let mut worst = 0f32; + for t in 0..nt { + for h in 0..nh { + let g = h / per; + let rows = |x: &[f32]| -> Vec { ((base + t + 1).saturating_sub(win)..=base + t).flat_map(|p| x[(p * nkv + g) * hd..][..hd].iter().map(|&x| f16::from_f32(x))).collect() }; + let mut o = vec![0f32; hd]; + head_group(&q[(t * nh + h) * hd..][..hd], &rows(&k), &rows(&v), hd, scale, &mut o); + for (a, b) in o.iter().zip(&got[(t * nh + h) * hd..][..hd]) { worst = worst.max((a - b).abs()); } + } + } + assert!(worst < 5e-3, "GPU window attention differs from the CPU by {worst}"); + } + + /// The GPU attention over key lists against `head_group` on the gathered rows: lists of different lengths, one + /// shorter than a tile of 32 keys. Skips without a GPU (`STRATA_DS_GPU=1` opens one). + #[test] + fn gpu_list_attention_matches_cpu() { + let (nt, nh, nkv, hd, np) = (9usize, 6usize, 2usize, 128usize, 300usize); + let mut seed = 7u32; + let mut next = || { seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); seed >> 8 }; + let mut rnd = |n: usize| -> Vec { (0..n).map(|_| next() as f32 / (1 << 23) as f32 - 1.0).collect() }; + let (q, k, v) = (rnd(nt * nh * hd), rnd(np * nkv * hd), rnd(np * nkv * hd)); + let lens = [1usize, 5, 31, 32, 33, 64, 100, 257, 300]; + let ns = 300; + let mut idx = vec![0u32; nt * ns]; + for (t, row) in idx.chunks_exact_mut(ns).enumerate() { + for (i, x) in row[..lens[t]].iter_mut().enumerate() { *x = ((i * 37 + t * 11) % np) as u32; } + } + let cnt: Vec = lens.iter().map(|&n| n as i32).collect(); + let bits = |x: &[f32]| -> Vec { x.iter().map(|&x| f16::from_f32(x).to_bits()).collect() }; + let Some(got) = crate::deepseek::mat::attn_sel(&q, &bits(&k), &bits(&v), &idx, &cnt, nt, nh, nkv, hd) else { eprintln!("no GPU attention, skipping"); return }; + let (per, scale) = (nh / nkv, 1.0 / (hd as f32).sqrt()); + let mut worst = 0f32; + for t in 0..nt { + for h in 0..nh { + let g = h / per; + let rows = |x: &[f32]| -> Vec { idx[t * ns..][..lens[t]].iter().flat_map(|&p| x[(p as usize * nkv + g) * hd..][..hd].iter().map(|&x| f16::from_f32(x))).collect() }; + let mut o = vec![0f32; hd]; + head_group(&q[(t * nh + h) * hd..][..hd], &rows(&k), &rows(&v), hd, scale, &mut o); + for (a, b) in o.iter().zip(&got[(t * nh + h) * hd..][..hd]) { worst = worst.max((a - b).abs()); } + } + } + assert!(worst < 1e-4, "GPU list attention differs from the CPU by {worst}"); + } + + fn cfg(top_k: usize, pool_blocks: usize) -> KolibriConfig { + KolibriConfig { n_layer: 1, n_ctx: 0, n_embd: 0, n_vocab: 0, n_head: 0, n_head_kv: 0, head_dim: 0, rope_base: 0.0, eps: 0.0, n_expert: 0, n_used: 0, + n_dense: 0, swa: vec![], n_swa: 0, indexer: vec![], kv_src: vec![], top_k, block: 16, pool_blocks } + } + + #[test] + fn sparse_selection() { + let c = cfg(4, 3); + let none = |_: u32| -> f32 { panic!("not scored") }; + // Short context: every key, nothing is scored. + assert_eq!(select(&c, true, 139, &mut None, none, none), None); + // Sinks, the 4 best candidates (ties: the lower position), the recent keys. Candidates are 8..=22 here. + let score = |p: u32| if p == 22 || p == 9 { 2.0 } else if p == 21 { -1.0 } else { 1.0 }; + let mut pool = None; + let sel = select(&cfg(4, 9), true, 150, &mut pool, score, none).unwrap(); + assert_eq!(pool, None); + assert_eq!(sel[..12], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22]); + assert_eq!(sel[12..], (23..=150).collect::>()[..]); + // Long context: 13 complete blocks at position 208; the 3 best blocks (1, 3 and, by the tie, 0) hold the pool. + let block = |j: u32| if j == 3 || j == 1 { 5.0 } else if j == 12 { -1.0 } else { 0.0 }; + let sel = select(&c, true, 208, &mut pool, |p| p as f32, block).unwrap(); + let want: Vec = (8..32).chain(48..64).collect(); + assert_eq!(pool.as_deref(), Some(&want[..])); + assert_eq!(sel[8..12], [60, 61, 62, 63]); + // A sparse layer that is not an indexer selects from the pool it is given. + let sel = select(&c, false, 208, &mut pool, |p| -(p as f32), none).unwrap(); + assert_eq!(sel[8..12], [8, 9, 10, 11]); + assert_eq!(sel.len(), 8 + 4 + 128); + } + + #[test] + fn routing_adds_the_bias_only_to_pick() { + let r = route(&[0.0, 2.0, 1.0, 1.0], &[5.0, 0.0, 0.0, 0.0], 3); + assert_eq!(r.iter().map(|x| x.0).collect::>(), [0, 1, 2]); + assert_eq!(r[0].1, 0.5); + } +} diff --git a/src/kolibri/mod.rs b/src/kolibri/mod.rs new file mode 100644 index 0000000..9dd5a84 --- /dev/null +++ b/src/kolibri/mod.rs @@ -0,0 +1,91 @@ +//! Aleph Alpha Kolibri 1.1 (`kolibri1`): sliding-window layers with RoPE, every fifth layer a sparse layer without +//! positions that attends the best keys of an indexer over K/V rounded to NVFP4, some sparse layers reading the K/V +//! of an earlier one; a dense FFN in the leading layers, then a sigmoid-routed MoE with a shared expert. +//! CPU forward that mirrors llama.cpp `src/models/kolibri1.cpp`; matvecs and routed experts reuse `deepseek::mat`. +pub mod chat; +pub mod forward; + +use crate::gguf::Gguf; +use anyhow::{Context, ensure}; + +pub const ARCH: &str = "kolibri1"; + +/// Keys every sparse query attends: the first `N_SINK` positions and its last `N_RECENT`. +pub const N_SINK: usize = 8; +pub const N_RECENT: usize = 128; + +#[derive(Debug, Clone)] +pub struct KolibriConfig { + pub n_layer: usize, + /// Prompt plus reply limit: `--ctx`, else the trained context. + pub n_ctx: usize, + pub n_embd: usize, + pub n_vocab: usize, + pub n_head: usize, + pub n_head_kv: usize, + pub head_dim: usize, + pub rope_base: f32, + pub eps: f32, + pub n_expert: usize, + pub n_used: usize, + /// Leading layers with a dense FFN instead of the MoE. + pub n_dense: usize, + /// Sliding-window layers (the others are sparse), and the keys a sliding query sees. + pub swa: Vec, + pub n_swa: usize, + /// Sparse layers that choose the pool of keys; the other sparse layers select from the pool of the one before. + pub indexer: Vec, + /// The layer whose K/V a layer attends (itself, or an earlier sparse layer). + pub kv_src: Vec, + /// Keys a sparse query selects, and the pool of a long context: `pool_blocks` blocks of `block` positions. + pub top_k: usize, + pub block: usize, + pub pool_blocks: usize, +} + +impl KolibriConfig { + pub fn from_gguf(g: &Gguf) -> anyhow::Result { + let k = |s: &str| format!("{ARCH}.{s}"); + let u = |s: &str| -> anyhow::Result { Ok(g.get(&k(s))?.as_u64().with_context(|| k(s))? as usize) }; + let f = |s: &str| -> anyhow::Result { g.get(&k(s))?.as_f32().with_context(|| k(s)) }; + let arr_u = |s: &str| -> anyhow::Result> { + g.get(&k(s))?.as_arr().with_context(|| k(s))?.iter().map(|v| Ok(v.as_u64().with_context(|| k(s))? as usize)).collect() + }; + let n_layer = u("block_count")?; + let swa: Vec = arr_u("attention.sliding_window_pattern")?.into_iter().map(|v| v != 0).collect(); + let indexer: Vec = arr_u("attention.indexer.types")?.into_iter().map(|v| v != 0).collect(); + let kv_src = arr_u("attention.kv_source_map")?; + let (head_dim, n_head, n_head_kv) = (u("attention.key_length")?, u("attention.head_count")?, u("attention.head_count_kv")?); + ensure!(swa.len() == n_layer && indexer.len() == n_layer && kv_src.len() == n_layer, "per-layer metadata does not cover {n_layer} layers"); + ensure!(u("expert_gating_func")? == 2 && u("expert_shared_count")? == 1 && u("expert_weights_norm")? == 0, "unsupported Kolibri MoE variant"); + ensure!(head_dim % 16 == 0 && u("attention.value_length")? == head_dim && u("rope.dimension_count")? == head_dim && n_head % n_head_kv == 0, "unsupported Kolibri attention shape"); + let mut seen = false; + for il in 0..n_layer { + let src = kv_src[il]; + ensure!(src <= il && kv_src[src] == src && swa[src] == swa[il] && (!swa[il] || (src == il && !indexer[il])) && (swa[il] || indexer[il] || seen), + "layer {il}: invalid indexer or K/V source"); + seen |= indexer[il]; + } + Ok(KolibriConfig { + n_ctx: crate::ctx_limit(u("context_length")?), + n_layer, + n_embd: u("embedding_length")?, + n_vocab: g.tensors.get("token_embd.weight").context("missing token_embd.weight")?.dims[1] as usize, + n_head, + n_head_kv, + head_dim, + rope_base: f("rope.freq_base")?, + eps: f("attention.layer_norm_rms_epsilon")?, + n_expert: u("expert_count")?, + n_used: u("expert_used_count")?, + n_dense: u("leading_dense_block_count")?, + swa, + n_swa: u("attention.sliding_window")?, + indexer, + kv_src, + top_k: u("attention.indexer.top_k")?, + block: u("attention.indexer.candidate_block_size")?, + pool_blocks: u("attention.indexer.candidate_top_k_blocks")?, + }) + } +} diff --git a/src/lib.rs b/src/lib.rs index 2af3bcb..f7c80f9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,5 +33,6 @@ pub mod deepseek; pub mod gemma4; pub mod glm; pub mod hy4; +pub mod kolibri; pub mod inkling2; pub mod ngram; diff --git a/src/main.rs b/src/main.rs index 4c20e0a..b37125f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1124,6 +1124,22 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let (prompt, cont) = (ids("prompt")?, ids("continuation")?); anyhow::ensure!(!prompt.is_empty() && !cont.is_empty(), "empty prompt or continuation"); let g = Gguf::open(&model)?; + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + engine.ds_env(); + rusting_strata::kolibri::chat::gpu_defaults(); + let mut m = rusting_strata::kolibri::forward::KolibriModel::new(&g)?; + let (mut argmax, mut top5) = (Vec::new(), Vec::new()); + let mut logits = m.prefill(&prompt); + for i in 0..cont.len() { + if i > 0 { logits = m.step(cont[i - 1]); } + let lse = logits.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b)); + let lse = lse + logits.iter().map(|x| (x - lse).exp()).sum::().ln(); + argmax.push(ops::argmax(&logits)); + top5.push(ops::top_k(&logits, 5).into_iter().map(|j| (j, logits[j] - lse)).collect::>()); + } + println!("{}", serde_json::json!({"argmax": argmax, "top5": top5})); + return Ok(()); + } let aux_g = open_mtp_gguf(engine.aux_model_path())?; let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; if let Some(&t) = prompt.iter().chain(&cont).find(|&&t| t as usize >= m.cfg.n_vocab) { @@ -1170,6 +1186,11 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; return rusting_strata::hy4::chat::generate(&g, &prompt, n); } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for kolibri1"); + let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; + return rusting_strata::kolibri::chat::generate(&g, &prompt, n); + } if g.get("general.architecture").ok().and_then(|v| v.as_str()) .is_some_and(rusting_strata::inkling2::is_arch) { let prompt = if prompt == "-" { let mut s = String::new(); std::io::stdin().read_to_string(&mut s)?; s } else { prompt }; let max_ctx = 0; @@ -1276,7 +1297,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { engine.own_warn(&g); engine.ctx = engine.ctx.max(pp.iter().max().unwrap_or(&0) + tg); if let Some(arch) = g.get("general.architecture").ok().and_then(|v| v.as_str()) { - if arch == "deepseek41" || arch == "glm5-next" || arch == rusting_strata::hy4::ARCH || rusting_strata::inkling2::is_arch(arch) { + if arch == "deepseek41" || arch == "glm5-next" || arch == rusting_strata::hy4::ARCH || arch == rusting_strata::kolibri::ARCH || rusting_strata::inkling2::is_arch(arch) { engine.ds_env(); // A --ctx below the test grows to fit it, as on the main engine. if rusting_strata::CTX.load(std::sync::atomic::Ordering::Relaxed) != 0 { rusting_strata::CTX.store(engine.ctx, std::sync::atomic::Ordering::Relaxed); } @@ -1284,6 +1305,8 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { bench_deepseek(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if arch == rusting_strata::hy4::ARCH { bench_hy4(&g, &model, &pp, tg, reps, json_out, &mut engine) + } else if arch == rusting_strata::kolibri::ARCH { + bench_kolibri(&g, &model, &pp, tg, reps, json_out, &mut engine) } else if rusting_strata::inkling2::is_arch(arch) { bench_inkling2(&g, &model, &pp, tg, reps, json_out, &mut engine) } else { @@ -1393,6 +1416,11 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { println!("check: hy_v4_flash ok: {} layers, {} experts ({} used), {} tensors, every tensor of the forward is present", m.cfg.n_layer, m.cfg.n_expert, m.cfg.n_used, g.tensors.len()); return Ok(()); } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + let m = rusting_strata::kolibri::forward::KolibriModel::new(&g)?; + println!("check: kolibri1 ok: {} layers, {} experts ({} used), {} tensors, every tensor of the forward is present", m.cfg.n_layer, m.cfg.n_expert, m.cfg.n_used, g.tensors.len()); + return Ok(()); + } if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some("deepseek41") { let c = rusting_strata::deepseek::DsConfig::from_gguf(&g)?; c.validate(&g)?; @@ -1469,6 +1497,10 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { anyhow::ensure!(image.is_empty(), "--image is not supported for hy_v4_flash"); return rusting_strata::hy4::chat::chat(&g, system, n, think); } + if g.get("general.architecture").ok().and_then(|v| v.as_str()) == Some(rusting_strata::kolibri::ARCH) { + anyhow::ensure!(image.is_empty(), "--image is not supported for kolibri1"); + return rusting_strata::kolibri::chat::chat(&g, system, n, think); + } if g.get("general.architecture").ok().and_then(|v| v.as_str()) .is_some_and(rusting_strata::inkling2::is_arch) { let max_ctx = 0; let mmproj = engine.mmproj.clone().or_else(|| vision::find_sibling(&model)); @@ -1967,6 +1999,7 @@ fn $name(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: }; } bench_tokenwise!(bench_hy4, rusting_strata::hy4::forward::Hy4Model); +bench_tokenwise!(bench_kolibri, rusting_strata::kolibri::forward::KolibriModel); /// `strata bench` for Inkling 2 (uses GPU argmax decode, plus `--draft-model` DSpark / `--spec-type` context lookup). fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { @@ -2893,6 +2926,7 @@ fn serve_model(model: &Path, mut engine: Engine, s: &Serving, w: &mut Option rusting_strata::glm::serve(&g, &tok, &name)?, "deepseek41" => rusting_strata::deepseek::chat::serve(&g, &tok, &name)?, rusting_strata::hy4::ARCH => rusting_strata::hy4::chat::serve(&g, &tok, &name)?, + rusting_strata::kolibri::ARCH => rusting_strata::kolibri::chat::serve(&g, &tok, &name)?, _ => rusting_strata::inkling2::chat::serve(&g, &tok, &name, rusting_strata::inkling2::chat::Inkling2Opts { max_ctx: 0, sampler: engine.sampler(), thinking_budget: engine.thinking_budget, think_default: engine.think_default, mmproj, draft_model: engine.draft_model.clone(), ngram_cfg: engine.ngram_config()? })?, diff --git a/tests/kolibri_forward.rs b/tests/kolibri_forward.rs new file mode 100644 index 0000000..e24d052 --- /dev/null +++ b/tests/kolibri_forward.rs @@ -0,0 +1,28 @@ +//! Gated by STRATA_KOLIBRI_MODEL (path to a Kolibri 1.1 GGUF). Skips when unset. +use rusting_strata::{gguf::Gguf, kolibri::forward::KolibriModel, tokenizer::Tokenizer}; + +#[test] +fn first_token_after_france_prompt_is_paris() { + let Ok(p) = std::env::var("STRATA_KOLIBRI_MODEL") else { eprintln!("STRATA_KOLIBRI_MODEL unset, skipping"); return }; + let g = Gguf::open(std::path::Path::new(&p)).unwrap(); + let tok = Tokenizer::from_gguf(&g).unwrap(); + let mut m = KolibriModel::new(&g).unwrap(); + let logits = m.prefill(&tok.encode("The capital of France is").unwrap()); + let top = logits.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32; + assert_eq!(tok.decode(&[top]).unwrap(), " Paris", "llama.cpp greedy picks ' Paris'"); +} + +/// The CPU path (STRATA_DS_GPU unset) runs the same kernels either way, so the logits agree closely. +#[test] +fn chunked_prefill_matches_token_by_token() { + let Ok(p) = std::env::var("STRATA_KOLIBRI_MODEL") else { eprintln!("STRATA_KOLIBRI_MODEL unset, skipping"); return }; + let g = Gguf::open(std::path::Path::new(&p)).unwrap(); + let tok = Tokenizer::from_gguf(&g).unwrap(); + let toks = tok.encode(&"The capital of France is Paris. ".repeat(12)).unwrap(); + let (mut a, mut b) = (KolibriModel::new(&g).unwrap(), KolibriModel::new(&g).unwrap()); + let chunked = a.prefill(&toks); + let mut stepped = vec![]; + for &t in &toks { stepped = b.step(t); } + let worst = chunked.iter().zip(&stepped).map(|(x, y)| (x - y).abs()).fold(0f32, f32::max); + assert!(worst < 1e-3, "chunked prefill logits differ by {worst}"); +}