diff --git a/docs/HIP.md b/docs/HIP.md index 594228cc..ad56cdcf 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -131,6 +131,8 @@ the KV cache than a 16 GB card has left over for experts, so the run above strea - `STRATA_NO_GRAPH=1` turns capture off for both GPU backends. - `STRATA_HIP_WMMA=0` uses the CUDA-core multiplications in the prefill GEMM and in both products of the prefill attention instead of the matrix cores. +- `STRATA_DS_FAST_KERNELS=0` runs Inkling 2 on the older attention and controller kernels (see "Faster Inkling 2 + kernels" below); `1` forces the faster ones under `--fixed-experts` too. ## Why the prefill GEMM does not use int8 matrix cores @@ -188,6 +190,101 @@ FP32 scan, and on CUDA it is 0.73-0.87x, i.e. slower. 2. Decode on an MoE model: the expert residency policy, not a kernel. That is where the multi-x is (see the reference numbers from Strata in the handoff). +## Inkling 2 decode + +Inkling 2 Mini UD-Q4_K_XL, 9070 XT, X470 (PCIe 3.0) with dual-channel DDR4 (36 GB/s read), `bench --pp 512 --tg 64`. +The core layers (6..18, run three times) and the prelude keep all 128 experts in VRAM as slabs. What does not fit runs +as hybrid layers: the host routes, the GPU runs the cached experts and the CPU the rest. These are the coda, layers +20-23 of which are Q8_0 at 8.5 MB an expert. + +| | 18 slabs (desktop holds 3.3 GB) | 22 slabs (desktop idle) | +|---|---|---| +| before | 34.5 tok/s | 48.2 tok/s | +| after | 39.5 tok/s | 51.8 tok/s | + +A token at 18 slabs: 13.5 ms of kernels, then ~9 ms of CPU experts (32 of the coda's 48, 260 MB at 29 GB/s, near the +DRAM limit). What changed, largest first: + +- Copying a missed expert up for one use cost 2.5 ms and the CPU 0.25 ms. The share controller balanced the two sides' + times, but a layer has about six misses, so it settled on one copy in most layers and a sync in every one. `plan` + now picks the split from the measured cost of one expert on each side (`stage_count`): here, no copies. +- The VRAM cache froze with what prefill touched first. `Dev::admit` gives a slot to an expert used more often than + the coldest resident one. The coda routes are skewed (100 experts out of 768 take 60-67% of the uses), and layers + 18-19 went from about 9 to 15 of their 16 uses on the GPU. Q8_0 layers cannot take NVFP4 slots, and no VRAM is left. +- The core passes run as one graph in the hybrid step (`core_graph`): 0.8 ms. + +### The expert pool + +Since then, every layer keeps only its most used experts in VRAM (`inkling2/forward/pool.rs`), and a decode token +never comes back to the host: + +- `ink_route` routes on the device, and `ink_slots` looks each expert up in the layer's slot table. An expert that + is not in VRAM goes to the CPU worker (`worker.rs`) through the mailbox of `cpu_worker`, with the routing and + the activation. `ink_ffn_sum_mb` waits for the worker's sum only in a layer run that missed. The token is one + graph. +- After each token the routing counts (decayed per token) decide the placement. Up to 4 missed experts go into free + slots and 2 into the slots of less used ones. The long counts are saved as + `~/.cache/rusting_strata/inkling2-profile-*.f32` when the model goes, and they place the next load. +- A prompt chunk runs from the same slots. The chunk's other experts are copied into 32 staging slots a pool, in + rounds, before the GEMMs run. + +| 12 GB weight budget, desktop holds 3 GB | pp 512 | pp 4096 | decode | +|---|---|---|---| +| slabs and hybrid layers (above) | 443 tok/s | 438 tok/s | 39.8 / 38.9 tok/s | +| pool, no profile yet | 329 | 378 | 49.7 / 55.7 | +| pool, profile of one earlier run | 436 | 426 | 60.5 / 58.9 | + +Decode after the prompt of each column. At this budget the pool holds 68% of each layout's experts and keeps 98% of +a token's expert uses in VRAM; the CPU worker takes 1.8 ms a token. Greedy text is no longer bit-identical to +Vulkan: the placement decides which experts round on the CPU. `--fixed-experts` keeps the slabs and is. +`STRATA_INK_SLABS=1` keeps the slabs and pools only the layers they leave out. + +### Prompt chunks of 2048 rows + +A prompt chunk copies each layer run's missing experts into the staging slots, and a chunk of 256 rows already +touches most of a layer's 128 experts, so the copies repeated every 256 tokens. Prompt chunks now have 2048 rows +(`STRATA_DS_PF_TOKENS`); the scratch costs about 0.55 GB of VRAM per 1024 rows, and the chunk halves when it does +not fit. 9.5 GB weight budget, desktop at 2.2 GB, `bench --pp 512,4096 --tg 32`: + +| rows | pp 512 | pp 4096 | decode | peak VRAM, card | +|---|---|---|---|---| +| 256 | 265 tok/s | 278 tok/s | 49.5 tok/s | 13.47 GB | +| 2048 | 387 | 767 | 48.9 | 14.61 GB | +| 4096 | 393 | 891 | 48.8 | 15.48 GB | + +At 2048 rows a core layer run still misses 40-45 of the ~125 experts it uses (6-7% of the uses); most of those +serve 9 or more rows. + +The missed experts are copied on a second stream (`Backend::htod_side`) into two halves of the staging slots: the +residents run while the first two rounds copy in, then each round runs while the next one fills the other half. +pp 4096 went from 775 to 834 tok/s (same routing profile, greedy text unchanged); with the copies left out it would +be 1105. What is left is the host's copy into the pinned ring (one thread, about 10 GB/s; more threads did not help) +and the routing read at each layer, before which no copy can start. + +`STRATA_INK_PIN=1` page-locks the pooled experts in the mapped file (`hipHostRegister`, read-only; 15.8 GB in +1.8 s), so the staging copies and the pool's swaps between tokens are DMAs from the file's pages: pp 4096 855 tok/s, +decode 51-53. It keeps that much RAM locked while the model is loaded, so it is not the default. 64 or 96 staging +slots instead of 32 were slower (838, 823): each one is a pool slot less. + +Left: `ink_mix` runs 120 times a token at 12 µs in one workgroup (about 1 ms, but a faster reduction order breaks the +bit parity with Vulkan), and a first run without a profile. + +### Faster Inkling 2 kernels + +By default HIP runs Inkling 2 on the kernels that the CUDA backend uses only with two cards (`InkFlags`): the +key-parallel prompt attention `ink_attn_prefill_128_kp16`, the tiled loop controllers for prompt chunks and the +128-key decode attention `ink_attn_128`. They sum in another order than the older kernels, so greedy text can differ +from the older kernels and from Vulkan at a near tie. `--fixed-experts` keeps the older kernels, and its output stays +bit-identical to Vulkan. `STRATA_DS_FAST_KERNELS` switches them as on CUDA. + +The prompt attention was 54% of the kernel time of a 4096-token prompt. With the faster set, `bench --pp 512,4096 +--tg 64`, alternating runs with a browser open on the desktop: + +| | pp 4096 | decode | +|---|---|---| +| older kernels | 701, 908, 1001 tok/s | 51-62 tok/s | +| faster kernels | 1531, 1648, 1686 tok/s | 52-66 tok/s | + ## Credits The compatibility shim follows the structure and several implementations of Strata's diff --git a/docs/USAGE.md b/docs/USAGE.md index 715796d6..2633475b 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -340,7 +340,7 @@ The two-card plan uses these knobs: |---|---|---| | `STRATA_DS_FAST_KERNELS` | `auto` | as above; one card keeps the old kernels unless forced | | `STRATA_DS_PLAIN_FIRST` | unset; `chat`/`serve`/`bench` set `1` | keep the plain weights on GPU 0, where the decode state lives | -| `STRATA_DS_PF_TOKENS` | 256 one card, 512 two | tokens of one prompt chunk (at most 2048) | +| `STRATA_DS_PF_TOKENS` | 2048 one card, 512 two | tokens of one prompt chunk (at most 2048) | | `STRATA_DS_KV_TOKENS` | `--ctx` | KV rows GPU 0 must still be able to take before it gives up a slab | | `STRATA_DS_PROF` | unset | print `inkling2: preloaded N/24 ...` and the per-chunk profile | | `STRATA_DS_NO_AFFINITY` | unset | pick the GPU per expert instead of per stacked tensor | diff --git a/src/backend.rs b/src/backend.rs index b0ebdd82..99cb3f3d 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -142,6 +142,18 @@ pub trait Backend: Send { fn mem_info(&self) -> anyhow::Result<(usize, usize)>; /// Wait for all queued device work. fn sync(&self) -> anyhow::Result<()>; + /// A second queue for host-to-device copies, so they run beside the kernels (a prompt chunk's expert staging). + /// `htod_side` queues a copy there; `side_mark`/`main_mark` record the point each queue has reached, and + /// `main_waits`/`side_waits` hold the other queue there. A backend with one queue copies in order with its + /// kernels, so these defaults are already correct. + fn htod_side(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod(src, dst, off) } + /// Page-lock `data` (host memory that outlives this backend, such as the mapped model file), so `htod` from it + /// is a DMA without a copy through a staging buffer. False when the backend does not do that. + fn pin_host(&self, _data: &[u8]) -> anyhow::Result { Ok(false) } + fn side_mark(&self) -> anyhow::Result { Ok(0) } + fn main_waits(&self, _side_mark: usize) -> anyhow::Result<()> { Ok(()) } + fn main_mark(&self) -> anyhow::Result { Ok(0) } + fn side_waits(&self, _main_mark: usize) -> anyhow::Result<()> { Ok(()) } /// Run the ops `f` queues as the graph recorded under `key`, recording it on first use. `f` runs only when /// recording, so its ops must read per-call values from device memory. fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()>; @@ -433,6 +445,17 @@ pub trait Backend: Send { /// Attention of a vision encoder: each of the `n` rows of `q` sees all `n` keys (no mask). `q`, `k`, `v` and `out` /// are f32 `[n][nh][hd]`. fn vit_attn(&self, _q: u64, _k: u64, _v: u64, _out: u64, _n: usize, _nh: usize, _hd: usize, _scale: f32) -> anyhow::Result<()> { anyhow::bail!("{}: vision attention not implemented", self.name()) } + /// Whether `ink_slots` and `ink_ffn_sum_mb` exist here. + fn ink_pool(&self) -> bool { false } + /// Inkling 2 decode with an expert pool: the lookup of `ink_route`'s experts in `table` (`slots`, `wh`), the + /// routing and on a miss `h` (nh floats, at word `h_off`) written to the CPU worker's mailbox `mb`. + fn ink_slots(&self, _ids: u64, _wts: u64, _table: u64, _slots: u64, _wh: u64, _h: u64, _mb: u64, _nh: usize, _h_off: usize, _step: u64, _k: usize) -> anyhow::Result<()> { + anyhow::bail!("{}: no Inkling 2 expert pool kernels", self.name()) + } + /// `ink_ffn_sum` of the pool's experts, plus the CPU worker's answer at word `y_off` of `mb` when one missed. + fn ink_ffn_sum_mb(&self, _acc: u64, _d: u64, _wh: u64, _k: usize, _n: usize, _mb: u64, _y_off: usize, _step: u64, _slots: u64) -> anyhow::Result<()> { + anyhow::bail!("{}: no Inkling 2 expert pool kernels", 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/cpu_worker.rs b/src/cpu_worker.rs index 4c89e139..85e57248 100644 --- a/src/cpu_worker.rs +++ b/src/cpu_worker.rs @@ -197,7 +197,7 @@ impl CpuWorker { /// Copies `out.len()` (a multiple of 4) words from 16-byte aligned `p`. On write-combining memory (the Vulkan BAR /// mailbox) streaming loads fetch a whole 64-byte line per read instead of one uncached read per load. -unsafe fn read_wc(p: *const u32, out: &mut [u32]) { +pub(crate) unsafe fn read_wc(p: *const u32, out: &mut [u32]) { #[cfg(target_feature = "sse4.1")] for (i, c) in out.chunks_exact_mut(4).enumerate() { use std::arch::x86_64::*; diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index b31c5616..57eeff20 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -2564,6 +2564,59 @@ extern "C" __global__ void vit_attn(const float* q, const float* k, const float* } } +// Inkling 2 decode, after ink_route: the expert pool lookup of the k routed experts (slots[j] = table[ids[j]], -1 = +// on the CPU; wh[j] = wts[j] on a hit, else 0), the routing copied to the host-mapped mailbox `mb` (cpu_worker's +// layout for one token), and the request flag raised with the activation `h` when an expert missed, else only the +// skip flag. One block; step[1] is the CPU worker's sequence number. +extern "C" __global__ void ink_slots(const int* ids, const float* wts, const int* table, int* slots, float* wh, + const float* h, unsigned int* mb, int nh, int h_off, const int* step, int k) { + __shared__ int miss; + unsigned int seq = step[1]; + if (threadIdx.x == 0) miss = 0; + __syncthreads(); + if (threadIdx.x < k) { + int j = threadIdx.x, id = ids[j], s = table[id]; + float w = wts[j]; + slots[j] = s; wh[j] = s >= 0 ? w : 0.0f; + mb[32 + j] = id; mb[32 + k + j] = __float_as_uint(w); mb[32 + 2 * k + j] = s; + if (s < 0) miss = 1; + } + __syncthreads(); + if (threadIdx.x == 0) mb[1] = 1; + if (!miss) { if (threadIdx.x == 0) ((volatile unsigned int*)mb)[2] = seq; return; } + for (int i = threadIdx.x; i < nh; i += blockDim.x) mb[h_off + i] = __float_as_uint(h[i]); + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) *(volatile unsigned int*)mb = seq; +} + +// ink_ffn_sum of the pool's experts (wh, 0 for an expert on the CPU) plus, when one missed, the CPU worker's sum at +// word y_off of the mailbox, once its done flag is step[1]. +extern "C" __global__ void ink_ffn_sum_mb(float* acc, const float* d, const float* wh, int k, int n, const unsigned int* mb, + int y_off, const int* step, const int* slots) { + unsigned int seq = step[1]; + __shared__ int miss; + if (threadIdx.x == 0) { + int m = 0; + for (int j = 0; j < k; j++) m |= slots[j] < 0; + if (m) { + unsigned int spins = 0; + while (((volatile const unsigned int*)mb)[16] != seq) { + __nanosleep(100); + if (++spins == (1u << 27)) __trap(); // ~15 s: CPU worker gone + } + __threadfence_system(); + } + miss = m; + } + __syncthreads(); + int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= n) return; + float o = miss ? __uint_as_float(((volatile const unsigned int*)mb)[y_off + c]) : 0.f; + for (int e = 0; e < k; e++) if (wh[e] != 0.f) o += wh[e] * d[(size_t)e * n + c]; + acc[c] = o; +} + __device__ __forceinline__ unsigned ink_f2key(float x) { unsigned u = __float_as_uint(x == 0.0f ? 0.0f : x); return (u & 0x80000000u) ? ~u : (u ^ 0x80000000u); diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index f033877b..a7a51493 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; 71] = [ +pub(crate) const KERNELS: [&str; 73] = [ "rope_freq", "rope_cs", "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", "kv_store_turbo", "attn_merge", "ha_post", "ha_wait", "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", "gemm_splitk_sum", "x_to_f16", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_attn_prefill_128_kp16", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_route", "attn_sel", "vit_attn", + "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_attn_prefill_128_kp16", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_ffn_sum_mb", "ink_slots", "ink_route", "attn_sel", "vit_attn", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; @@ -32,21 +32,22 @@ use crate::backend::ATT_SPLITS_1; /// Kernel-choice flags read from the environment once, when the `Gpu` is made: they sit on the token path, so a /// lookup per launch is not worth it. #[derive(Clone, Copy)] -struct InkFlags { +pub(crate) struct InkFlags { /// `STRATA_DS_FAST_KERNELS=auto` (default) uses the tiled controllers, `ink_attn_128` and `kp16` only when /// the run has more than one device; `1` forces them on, `0` forces the old kernels. One card keeps the - /// `main` kernels (the greedy output must not change). - fast: bool, + /// `main` kernels (the greedy output must not change). The HIP backend passes its own default here (see + /// `hip::ink_flags_from`). + pub(crate) fast: bool, /// `STRATA_CTRL_TILE=0` forces the per-token `ink_ctrl_*` pair; unset follows `fast`. - ctrl_tile: bool, + pub(crate) ctrl_tile: bool, /// `STRATA_DS_ATTN_OLD=1` keeps the scalar/one-query-a-warp attention kernels for a measurement window. - attn_old: bool, + pub(crate) attn_old: bool, /// `STRATA_DS_ATTN_KP4=1` selects the four-query 128-key tile prefill kernel. - attn_kp4: bool, + pub(crate) attn_kp4: bool, } impl InkFlags { - fn from_parts(fast: Option<&str>, multi: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> Self { + pub(crate) fn from_parts(fast: Option<&str>, multi: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> Self { let on = |v: Option<&str>, default: bool| v.map_or(default, |v| v != "0"); let fast = match fast { None | Some("auto") => multi, @@ -1526,6 +1527,16 @@ impl Backend for Gpu { launch!(self, "ink_ffn_sum", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), acc, d, wts, ne as i32, n as i32, cpu); Ok(()) } + fn ink_pool(&self) -> bool { true } + fn ink_slots(&self, ids: u64, wts: u64, table: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, k: usize) -> anyhow::Result<()> { + anyhow::ensure!(k <= 32, "ink_slots: k={k}"); + launch!(self, "ink_slots", cfg((1, 1), 256, 0), ids, wts, table, slots, wh, h, mb, nh as i32, h_off as i32, step, k as i32); + Ok(()) + } + fn ink_ffn_sum_mb(&self, acc: u64, d: u64, wh: u64, k: usize, n: usize, mb: u64, y_off: usize, step: u64, slots: u64) -> anyhow::Result<()> { + launch!(self, "ink_ffn_sum_mb", cfg((n.div_ceil(256) as u32, 1), 256, 0), acc, d, wh, k as i32, n as i32, mb, y_off as i32, step, slots); + Ok(()) + } 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::ensure!(n_expert <= 512 && k <= 32, "ink_route: n_expert={n_expert} k={k}"); launch!(self, "ink_route", cfg((rows as u32, 1), 32, 0), logits, bias, ids, wts, gu_sc, dn_sc, gsc_out, n_expert as i32, k as i32, exp_scale); @@ -1917,8 +1928,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 439); - assert_eq!(sm70.len(), 370); + assert_eq!(sm80.len(), 441); + assert_eq!(sm70.len(), 372); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index beeb6a7a..38bd1ff4 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -47,6 +47,10 @@ pub(crate) mod dev { /// Local patch: stacked expert tensor base address -> GPU that holds all of its experts; bytes promised per GPU. aff: std::collections::HashMap, aff_bytes: Vec, + /// Use counts of expert matrices that missed, keyed like `ex` and halved with the slots' counts (see `admit`). + seen: std::collections::HashMap, + /// Entries that are views of slots someone else owns (`pin`): never evicted or released here. + pinned: std::collections::HashSet, } static DEV: LazyLock> = LazyLock::new(Default::default); /// Whether `DEV` is open: None before the first `get` and after `free`. @@ -194,6 +198,16 @@ pub(crate) mod dev { } Some(arc) } + /// `alloc_slab_on` GPU 0 without contents: room for slots the caller fills. + pub fn alloc_room(&mut self, bytes: usize, budget_reserve: usize, free_reserve: usize) -> Option> { + self.reclaim(); + let p = self.parts.first_mut()?; + if bytes == 0 || p.bytes + bytes + budget_reserve > p.budget { return None; } + if let Ok((free, _)) = p.be.mem_info() && free < bytes + free_reserve { return None; } + let b = p.be.alloc(bytes).ok()?; + p.bytes += bytes; + Some(std::sync::Arc::new(SlabBuf { buf: b, bytes, acct: bytes, freed: self.freed.clone() })) + } /// The GPU that takes `len` more bytes of plain weights: the current one while they fit, then the next; the last takes all. pub fn pick(&mut self, len: usize) -> usize { self.reclaim(); @@ -232,7 +246,7 @@ pub(crate) mod dev { /// the room back. Returns the bytes freed. pub fn release(&mut self, d: usize, bytes: usize) -> usize { if self.parts[d].be.sync().is_err() { return 0; } - let mut old: Vec<(u64, usize)> = self.exs.iter().filter(|e| gpu_of(e.0) == d).map(|e| (e.2, e.1)).collect(); + let mut old: Vec<(u64, usize)> = self.exs.iter().filter(|e| gpu_of(e.0) == d && !self.pinned.contains(&e.1)).map(|e| (e.2, e.1)).collect(); old.sort_unstable(); let mut freed = 0; for (_, k) in old { @@ -282,7 +296,10 @@ pub(crate) mod dev { self.now += 1; self.lookups += 1; let now = self.now; - if self.lookups % 4096 == 0 { for e in &mut self.exs { e.3 *= 0.5; } } + if self.lookups % 4096 == 0 { + for e in &mut self.exs { e.3 *= 0.5; } + self.seen.retain(|_, c| { *c *= 0.5; *c >= 0.25 }); + } if let Some(&p) = self.ex.get(&k) { self.exs[p].2 = now; self.exs[p].3 += 1.0; @@ -306,7 +323,7 @@ pub(crate) mod dev { if !evict || self.parts.iter().all(|p| p.budget == 0) || data.len() > STAGE || std::env::var_os("STRATA_DS_NOEVICT").is_some() { return None; } let lfu = std::env::var_os("STRATA_DS_LFU").is_some(); let victim = self.exs.iter().enumerate() - .filter(|(_, e)| e.2 + 96 <= now && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) + .filter(|(_, e)| e.2 + 96 <= now && !self.pinned.contains(&e.1) && { let t = self.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) .min_by(|(_, a), (_, b)| if lfu { a.3.total_cmp(&b.3).then(a.2.cmp(&b.2)) } else { a.2.cmp(&b.2) }) .map(|(p, _)| p); let Some(p) = victim else { return Some(STAGED) }; @@ -320,6 +337,72 @@ pub(crate) mod dev { self.exs[p] = (i, k, now, 1.0); Some(i) } + /// Count one use of each candidate (an expert's matrices that are not all in VRAM, given as + /// `(data, type, rows, cols, scale)`), then copy the most used of them into the slots of the least used resident + /// expert when it has been used more often (by more than one). One expert at most a call: a copy over PCIe costs + /// as much as the CPU takes for several experts, so a slot changes hands only for a lasting difference. + /// The victim's slots were not touched in the last 96 lookups and the caller has synchronised the queue, so no + /// kernel still reads them. Returns the index of the candidate that now is resident. + pub fn admit(&mut self, cands: &[[(&[u8], GgmlType, usize, usize, f32); 2]]) -> Option { + // One GPU only: on a split, a layer's experts belong to one GPU (`affinity`), and a victim slot could be on the other. + if self.parts.len() > 1 { return None; } + self.reclaim(); + let mut best: Option<(usize, f32)> = None; + for (i, c) in cands.iter().enumerate() { + let n = self.seen.entry(c[0].0.as_ptr() as usize).or_insert(0.0); + *n += 1.0; + if best.is_none_or(|b| *n > b.1) { best = Some((i, *n)); } + } + let (i, count) = best?; + let now = self.now; + // The coldest slot of each matrix's shape that is free to overwrite. + let victim = |s: &Self, ty: GgmlType, rows: usize, cols: usize, not: Option| s.exs.iter().enumerate() + .filter(|&(p, e)| e.2 + 96 <= now && Some(p) != not && !s.pinned.contains(&e.1) && { let t = s.tensor(e.0); t.ty == ty && t.rows == rows && t.cols == cols }) + .min_by(|a, b| a.1.3.total_cmp(&b.1.3)).map(|(p, e)| (p, e.3)); + let mut plan = vec![]; + for &(data, ty, rows, cols, _) in &cands[i] { + if self.ex.contains_key(&(data.as_ptr() as usize)) { continue; } + let (p, c) = victim(self, ty, rows, cols, plan.first().map(|&(p, _)| p))?; + if count <= c + 1.0 { return None; } + plan.push((p, data)); + } + for (p, data) in plan { + let (id, old, _, c) = self.exs[p]; + let (be, t) = (&self.parts[gpu_of(id)].be, self.tensor(id)); + if data.len() > t.bytes() || be.htod(data, &Buf::new(t.ptr, data.len(), ()), 0).is_err() { return None; } + let scale = cands[i].iter().find(|m| std::ptr::eq(m.0, data)).unwrap().4; + self.parts[gpu_of(id)].ts[(id & (1 << SHIFT) - 1) as usize].scale = scale; + self.ex.remove(&old); + self.seen.insert(old, c); + let k = data.as_ptr() as usize; + self.ex.insert(k, p); + self.exs[p] = (id, k, now, self.seen.remove(&k).unwrap_or(count)); + } + Some(i) + } + /// Make the matrix at `data` resident as a view of VRAM at `addr` that the caller owns (an expert pool slot), + /// so lookups such as a prompt chunk's find it. Not counted against the budget, never evicted here; `unpin` + /// before the slot changes. Nothing changes when the matrix already has an entry. + pub fn pin(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, addr: u64) { + let k = data.as_ptr() as usize; + if self.ex.contains_key(&k) { return; } + let p = &mut self.parts[0]; + p.ts.push(GpuTensor::new(ty, rows, cols, Buf::new(addr, data.len(), ())).with_scale(scale)); + let i = p.ts.len() as u32 - 1; + self.ex.insert(k, self.exs.len()); + self.exs.push((i, k, self.now, 0.0)); + self.pinned.insert(k); + } + /// Drop the `pin` of the matrix at `data`. + pub fn unpin(&mut self, data: &[u8]) { + let k = data.as_ptr() as usize; + if !self.pinned.remove(&k) { return; } + let p = self.ex.remove(&k).unwrap(); + let (i, ..) = self.exs.swap_remove(p); + if p < self.exs.len() { self.ex.insert(self.exs[p].1, p); } + let t = &mut self.parts[gpu_of(i)].ts[(i & (1 << SHIFT) - 1) as usize]; + *t = GpuTensor::new(t.ty, 0, 0, Buf::new(0, 0, ())); + } pub fn gemv(&self, i: u32, x: &[f32], y: &mut [f32], staged: Option<(&[u8], GgmlType, usize, usize, f32)>) { let p = &self.parts[if i == STAGED { 0 } else { gpu_of(i) }]; p.be.put(x, &p.x, 0).unwrap(); diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 3166768a..0f073b87 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -24,6 +24,8 @@ pub const MEMCPY_D2H: c_int = 2; pub const MEMCPY_D2D: c_int = 3; pub const HOST_MALLOC_PORTABLE: u32 = 1; pub const HOST_MALLOC_MAPPED: u32 = 2; +pub const HOST_REGISTER_PORTABLE: u32 = 1; +pub const HOST_REGISTER_READ_ONLY: u32 = 8; pub const EVENT_DISABLE_TIMING: u32 = 2; pub const STREAM_NON_BLOCKING: u32 = 1; pub const CAPTURE_MODE_THREAD_LOCAL: c_int = 1; @@ -87,9 +89,12 @@ pub struct Hip { pub event_record: unsafe extern "C" fn(Event, Stream) -> c_int, pub event_sync: unsafe extern "C" fn(Event) -> c_int, pub event_destroy: unsafe extern "C" fn(Event) -> c_int, + pub stream_wait_event: unsafe extern "C" fn(Stream, Event, u32) -> c_int, pub host_malloc: unsafe extern "C" fn(*mut *mut c_void, usize, u32) -> c_int, pub host_free: unsafe extern "C" fn(*mut c_void) -> c_int, pub host_device_ptr: unsafe extern "C" fn(*mut *mut c_void, *mut c_void, u32) -> c_int, + pub host_register: unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int, + pub host_unregister: unsafe extern "C" fn(*mut c_void) -> c_int, pub module_load: unsafe extern "C" fn(*mut Module, *const c_void) -> c_int, pub function: unsafe extern "C" fn(*mut Func, Module, *const c_char) -> c_int, pub launch: unsafe extern "C" fn(Func, u32, u32, u32, u32, u32, u32, u32, Stream, *mut *mut c_void, *mut *mut c_void) -> c_int, @@ -147,9 +152,12 @@ impl Hip { event_record: g!("hipEventRecord"), event_sync: g!("hipEventSynchronize"), event_destroy: g!("hipEventDestroy"), + stream_wait_event: g!("hipStreamWaitEvent"), host_malloc: g!("hipHostMalloc"), host_free: g!("hipHostFree"), host_device_ptr: g!("hipHostGetDevicePointer"), + host_register: g!("hipHostRegister"), + host_unregister: g!("hipHostUnregister"), module_load: g!("hipModuleLoadData"), function: g!("hipModuleGetFunction"), launch: g!("hipModuleLaunchKernel"), @@ -191,6 +199,14 @@ impl Hip { find_gfx(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), PROP_BUF) }) } + /// The device's PCI address as sysfs names it ("0000:0c:00.0"), or None when the runtime does not give it. + pub fn pci_bus_id(&self, device: c_int) -> Option { + let f: unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int = unsafe { Self::sym(&self._lib, "hipDeviceGetPCIBusId") }?; + let mut buf = [0 as c_char; 64]; + if unsafe { f(buf.as_mut_ptr(), 64, device) } != HIP_SUCCESS { return None } + Some(unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy().to_lowercase()) + } + pub fn device_name(&self, device: c_int) -> String { let mut buf = [0 as c_char; 256]; let r = unsafe { (self.device_name)(buf.as_mut_ptr(), 256, device) }; diff --git a/src/hip/mod.rs b/src/hip/mod.rs index 677c5da9..44ec0f74 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -35,11 +35,22 @@ pub struct Gpu { hip: Arc, device: usize, stream: ffi::Stream, + /// The copy queue of `htod_side`, and the events its marks are recorded in (reused round robin: a wait already + /// queued keeps the record it saw). + side: ffi::Stream, + marks: Vec, + next_mark: std::sync::atomic::AtomicUsize, + /// Host ranges `pin_host` registered (start, end, the address registered): `htod` copies from them directly. + pinned: std::sync::RwLock>, fns: HashMap, /// "gfx1201": the target hiprtc compiled for. arch: String, /// `--kv q8` (the kernels were compiled with `KV_MODE` 0 or 1; HIP has no q4/q2 cache rows). pub kv_q8: bool, + /// The Inkling 2 kernel-choice flags (`STRATA_DS_FAST_KERNELS` and friends), read once at creation. + flags: crate::cuda::InkFlags, + /// The card's PCI address ("0000:0c:00.0"), read once: `mem_info` finds the card's sysfs entry by it. + pci: Option, /// Opt-in shared memory per block on this device (64 KiB on RDNA). max_smem: usize, /// `argmax_rows` partials. @@ -178,6 +189,9 @@ impl Gpu { let obj = compile_cached(rtc, &src, &arch, &tag)?; let mut stream: ffi::Stream = std::ptr::null_mut(); hip.check(unsafe { (hip.stream_create)(&mut stream, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate")?; + let mut side: ffi::Stream = std::ptr::null_mut(); + hip.check(unsafe { (hip.stream_create)(&mut side, ffi::STREAM_NON_BLOCKING) }, "hipStreamCreate(side)")?; + let marks = (0..MARKS).map(|_| Event::new(&hip)).collect::>>()?; let mut module: ffi::Module = std::ptr::null_mut(); hip.check(unsafe { (hip.module_load)(&mut module, obj.as_ptr().cast()) }, "hipModuleLoadData")?; let mut fns = HashMap::new(); @@ -209,7 +223,8 @@ impl Gpu { let mut dev: *mut c_void = std::ptr::null_mut(); hip.check(unsafe { (hip.host_device_ptr)(&mut dev, host, 0) }, "hipHostGetDevicePointer(ring)")?; let staging = Staging { _pin: Buf::new(dev as u64, RING, PinnedHost { hip: hip.clone(), p: host }), host: host.cast(), head: 0, busy: VecDeque::new() }; - Ok(Gpu { hip, device, stream, fns, arch, kv_q8, max_smem, am: am_buf, + let pci = hip.pci_bus_id(device as i32); + Ok(Gpu { hip, device, stream, side, marks, next_mark: Default::default(), pinned: Default::default(), fns, arch, kv_q8, flags: ink_flags(), pci, max_smem, am: am_buf, graphs: Mutex::new(HashMap::new()), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) } @@ -234,9 +249,53 @@ impl Gpu { } fn wait(&self) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_sync)(self.side) }, "hipStreamSynchronize(side)")?; self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, "hipStreamSynchronize") } + /// Record the point `stream` has reached in the next mark event. + fn mark(&self, stream: ffi::Stream) -> anyhow::Result { + let i = self.next_mark.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % MARKS; + self.marks[i].record(stream)?; + Ok(i) + } + + /// `htod` on `stream`: queue the copy and return once `src` may be reused. From pageable memory the runtime + /// stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not stop the + /// host (expert streaming during prefill). + fn htod_on(&self, stream: ffi::Stream, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); + let (s0, s1) = (src.as_ptr() as usize, src.as_ptr() as usize + src.len()); + if src.len() < RING_MIN || self.pinned.read().unwrap().iter().any(|&(a, b, _)| a <= s0 && s1 <= b) { + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), + ffi::MEMCPY_H2D, stream) }; + return self.hip.check(r, "hipMemcpyAsync(htod)"); + } + let mut g = self.staging.lock().unwrap(); + for (i, c) in src.chunks(RING).enumerate() { + if g.head + c.len() > RING { g.head = 0; } + let (a, b) = (g.head, g.head + c.len()); + // Regions still being read by an earlier copy have to complete before the host overwrites them. + while g.busy.iter().any(|&(s, e, _)| s < b && a < e) { + let (_, _, ev) = g.busy.pop_front().unwrap(); + self.hip.check(unsafe { (self.hip.event_sync)(ev.ev) }, "hipEventSynchronize")?; + } + unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), g.host.add(a), c.len()) }; + let r = unsafe { (self.hip.memcpy_async)((dst.addr() + (off + i * RING) as u64) as *mut c_void, + g.host.add(a) as *const c_void, c.len(), ffi::MEMCPY_H2D, stream) }; + self.hip.check(r, "hipMemcpyAsync(htod ring)")?; + let ev = Event::new(&self.hip)?; + ev.record(stream)?; + g.busy.push_back((a, b, ev)); + g.head = b; + } + Ok(()) + } + + fn wait_mark(&self, stream: ffi::Stream, i: usize) -> anyhow::Result<()> { + self.hip.check(unsafe { (self.hip.stream_wait_event)(stream, self.marks[i % MARKS].ev, 0) }, "hipStreamWaitEvent") + } + fn ptr(&self, b: &Buf) -> u64 { b.addr() } /// qwen35moe and the other models this backend targets dequantize in the kernel, so the ops below are the @@ -305,7 +364,17 @@ impl Gpu { /// `pair.1` (token stride `pair.2`). fn gemvq_pair(&self, w: &GpuTensor, x: u64, x_stride: usize, xq: u64, y: u64, y_stride: usize, nt: usize, pair: (i64, i64, i32, f32), z: u32) -> anyhow::Result<()> { - if !(1..=4).contains(&nt) { bail!("gemvn: {nt} inputs (1 to 4)"); } + // gemvn takes 4 inputs at most; a larger batch (Inkling 2's draft verify, up to 16 rows) runs 4 at a time and + // quantizes x itself, since xq holds the scales of all nt rows after all the rows (as on CUDA). + if nt > 4 { + for t0 in (0..nt).step_by(4) { + let (xt, yt) = (x + 4 * (t0 * x_stride) as u64, y + 4 * (t0 * y_stride) as u64); + let y2 = if z == 2 { pair.1 + 4 * t0 as i64 * (pair.2 as i64 - y_stride as i64) } else { 0 }; + self.gemvq_pair(w, xt, x_stride, 0, yt, y_stride, (nt - t0).min(4), (pair.0, y2, pair.2, pair.3), z)?; + } + return Ok(()); + } + if nt == 0 { bail!("gemvn: no inputs"); } let (ncols, k1) = Self::gemv_cols("gemv", w.ty, w.cols)?; let (mut c, rpw) = Self::gemv_cfg(w.ty, w.rows, w.cols, 1); let per = c.shared_mem_bytes; @@ -377,6 +446,35 @@ impl Gpu { } fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } + + /// The decode attention kernel and its key positions per block, chosen as on CUDA (`cuda::Gpu::ink_attn_kernel`). + fn ink_attn_kernel(&self, hd: usize, nr: usize) -> (&'static str, usize) { + if hd == 128 && nr <= 32 && !self.kv_q8 && self.flags.fast && !self.flags.attn_old { ("ink_attn_128", 128) } else { ("ink_attn", 64) } + } +} + +/// `flags` for a HIP `Gpu`, from the same variables as CUDA's: `STRATA_DS_FAST_KERNELS` `0`/`1` mean what they do +/// there, but unset or `auto` is the fast set. `--fixed-experts` (`STRATA_FIXED_EXPERTS`) keeps the old kernels, as +/// its output must stay bit-identical to Vulkan (`docs/HIP.md`). +fn ink_flags_from(fast: Option<&str>, fixed: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> crate::cuda::InkFlags { + let default = !fixed; + let fast = match fast { + None | Some("auto") => default, + Some("0") => false, + Some(_) => true, + }; + // The tiled pair follows `fast` when `STRATA_CTRL_TILE` is unset, as on CUDA. + crate::cuda::InkFlags::from_parts(Some(if fast { "1" } else { "0" }), false, ctrl, attn_old, attn_kp4) +} + +fn ink_flags() -> crate::cuda::InkFlags { + ink_flags_from( + std::env::var("STRATA_DS_FAST_KERNELS").ok().as_deref(), + std::env::var_os("STRATA_FIXED_EXPERTS").is_some(), + std::env::var("STRATA_CTRL_TILE").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_OLD").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_KP4").ok().as_deref(), + ) } /// Pinned host allocation freed with the runtime that made it. @@ -398,6 +496,14 @@ struct Staging { busy: VecDeque<(usize, usize, Event)>, } +impl Drop for Gpu { + /// Unlock what `pin_host` locked, before the mapping it belongs to goes. + fn drop(&mut self) { + let _ = self.wait(); + for &(_, _, p) in self.pinned.read().unwrap().iter() { unsafe { (self.hip.host_unregister)(p as *mut c_void) }; } + } +} + /// A `hipEvent_t` that destroys itself. struct Event { hip: Arc, ev: ffi::Event } @@ -420,6 +526,8 @@ impl Drop for Event { const GRAPHS_MAX: usize = 32; const RING: usize = 64 << 20; +/// Mark events of the copy queue (`Gpu::mark`). +const MARKS: usize = 64; const RING_MIN: usize = 256 << 10; fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { @@ -448,6 +556,24 @@ fn compile_cached(rtc: &ffi::Rtc, src: &str, arch: &str, tag: &str) -> anyhow::R Ok(b) } +/// Free VRAM as the kernel driver counts it, for the amdgpu card at PCI address `bus`. When the runtime gives no +/// address or no card has it, the card whose VRAM size is `total` (to 256 MiB; with two cards of one size that may be +/// the other card). `hipMemGetInfo` counts only compute allocations, so the desktop and other graphics clients look +/// free to it and a budget taken from it squeezes them out (the compositor then fails to pin its framebuffer). +/// Vulkan's memory budget already counts them. +fn drm_free(total: usize, bus: Option<&str>) -> Option { + let read = |p: std::path::PathBuf| std::fs::read_to_string(p).ok()?.trim().parse::().ok(); + let free_where = |ours: &dyn Fn(&std::path::Path, usize) -> bool| std::fs::read_dir("/sys/class/drm").ok()?.flatten().find_map(|e| { + let dev = e.path().join("device"); + let t = read(dev.join("mem_info_vram_total"))?; + if !ours(&dev, t) { return None } + Some(t.saturating_sub(read(dev.join("mem_info_vram_used"))?)) + }); + let at_bus = |dev: &std::path::Path, _| bus.is_some_and(|b| std::fs::canonicalize(dev).ok() + .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_lowercase())).is_some_and(|n| n == b)); + free_where(&at_bus).or_else(|| free_where(&|_, t: usize| t.abs_diff(total) <= 256 << 20)) +} + /// The kernel names to load: `cuda::kernel_names(false)` has no int8-mma GEMM, which needs no separate list here. fn kernel_names() -> Vec { crate::cuda::kernel_names(false) } @@ -462,36 +588,32 @@ impl Backend for Gpu { Ok(b) } - /// Queue a host-to-device copy on the stream and return once `src` may be reused: from pageable memory the - /// runtime stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not - /// stop the host (expert streaming during prefill). - fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { - anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); - if src.len() < RING_MIN { - let r = unsafe { (self.hip.memcpy_async)((dst.addr() + off as u64) as *mut c_void, src.as_ptr().cast(), src.len(), - ffi::MEMCPY_H2D, self.stream) }; - return self.hip.check(r, "hipMemcpyAsync(htod)"); - } - let mut g = self.staging.lock().unwrap(); - for (i, c) in src.chunks(RING).enumerate() { - if g.head + c.len() > RING { g.head = 0; } - let (a, b) = (g.head, g.head + c.len()); - // Regions still being read by an earlier copy have to complete before the host overwrites them. - while g.busy.iter().any(|&(s, e, _)| s < b && a < e) { - let (_, _, ev) = g.busy.pop_front().unwrap(); - self.hip.check(unsafe { (self.hip.event_sync)(ev.ev) }, "hipEventSynchronize")?; + /// `htod_on` the kernels' stream. + fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod_on(self.stream, src, dst, off) } + + fn htod_side(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { self.htod_on(self.side, src, dst, off) } + + /// `hipHostRegister` of the pages under `data`, read-only when the runtime takes that flag (the model file is + /// mapped read-only). + fn pin_host(&self, data: &[u8]) -> anyhow::Result { + const PAGE: usize = 4096; + let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len()); + if self.pinned.read().unwrap().iter().any(|&(s, e, _)| s <= a && b <= e) { return Ok(true); } + let (pa, pb) = (a & !(PAGE - 1), b.div_ceil(PAGE) * PAGE); + let mut last = 0; + for flags in [ffi::HOST_REGISTER_READ_ONLY | ffi::HOST_REGISTER_PORTABLE, ffi::HOST_REGISTER_PORTABLE] { + last = unsafe { (self.hip.host_register)(pa as *mut c_void, pb - pa, flags) }; + if last == ffi::HIP_SUCCESS { + self.pinned.write().unwrap().push((pa, pb, pa)); + return Ok(true); } - unsafe { std::ptr::copy_nonoverlapping(c.as_ptr(), g.host.add(a), c.len()) }; - let r = unsafe { (self.hip.memcpy_async)((dst.addr() + (off + i * RING) as u64) as *mut c_void, - g.host.add(a) as *const c_void, c.len(), ffi::MEMCPY_H2D, self.stream) }; - self.hip.check(r, "hipMemcpyAsync(htod ring)")?; - let ev = Event::new(&self.hip)?; - ev.record(self.stream)?; - g.busy.push_back((a, b, ev)); - g.head = b; } - Ok(()) + self.hip.check(last, "hipHostRegister").map(|_| false) } + fn side_mark(&self) -> anyhow::Result { self.mark(self.side) } + fn main_waits(&self, m: usize) -> anyhow::Result<()> { self.wait_mark(self.stream, m) } + fn main_mark(&self) -> anyhow::Result { self.mark(self.stream) } + fn side_waits(&self, m: usize) -> anyhow::Result<()> { self.wait_mark(self.side, m) } fn dtoh(&self, src: &Buf, off: usize, dst: &mut [u8]) -> anyhow::Result<()> { anyhow::ensure!(off + dst.len() <= src.len(), "dtoh: {} bytes at {off} from {}", dst.len(), src.len()); @@ -517,7 +639,7 @@ impl Backend for Gpu { fn mem_info(&self) -> anyhow::Result<(usize, usize)> { let (mut free, mut total) = (0usize, 0usize); self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?; - Ok((free, total)) + Ok((free.min(drm_free(total, self.pci.as_deref()).unwrap_or(usize::MAX)), total)) } fn sync(&self) -> anyhow::Result<()> { self.wait() } @@ -752,6 +874,157 @@ impl Backend for Gpu { launch!(self, "conv_state", Self::grid(ch), qkv, state, ch as i32, kw as i32, t as i32, snap, nsnap as i32); Ok(()) } + fn graph_drop(&self, key: u64) -> anyhow::Result<()> { + self.graphs.lock().unwrap().remove(&key); + Ok(()) + } + + fn situ(&self, y: u64, n: usize, rows: usize, scale: u64, beta: f32, lb: f32) -> anyhow::Result<()> { + launch!(self, "situ", Self::grid(n * rows), y, n as i32, rows as i32, scale, beta, lb); + Ok(()) + } + + fn situ_q(&self, y: u64, n: usize, rows: usize, s: u64, beta: f32, lb: f32, xq: u64) -> anyhow::Result<()> { + anyhow::ensure!(n % 32 == 0, "situ_q: n ({n}) must be a multiple of 32"); + launch!(self, "situ_q", cfg((n.div_ceil(256) as u32, rows as u32), 32, 0), y, n as i32, s, beta, lb, xq); + Ok(()) + } + + fn softcap(&self, x: u64, n: usize, cap: f32) -> anyhow::Result<()> { + launch!(self, "softcap", Self::grid(n), x, n as i32, cap); + Ok(()) + } + + fn hadamard(&self, x: u64, u: u64, s: u64, out: u64, n: usize, block: usize, rows: usize) -> anyhow::Result<()> { + anyhow::ensure!(block <= 1024, "prism.hadamard.block_size {block}: at most 1024 on the GPU"); + launch!(self, "hadamard", cfg(((rows * n / block) as u32, 1), block as u32, 0), x, u, s, out, n as i32, block as i32, 1.0 / (block as f32).sqrt()); + Ok(()) + } + + // ---- Inkling 2 (the same kernels and launch shapes as src/cuda) ---- + + fn ink_mix_n(&self, blocks: u64, nb: usize, cur: u64, q: u64, nq: usize, out: u64, n: usize, nt: usize) -> anyhow::Result<()> { + launch!(self, "ink_mix", cfg((nq as u32, nt as u32), 256, 0), blocks, nb as i32, cur, q, out, n as i32, nt as i32); + Ok(()) + } + + fn ink_ctrl_n(&self, down: u64, gain: u64, forget: u64, cur: u64, nins: usize, msg: u64, gate: u64, out: u64, n: usize, rank: usize, count: usize, nt: usize) -> anyhow::Result<()> { + // As CUDA: a prompt chunk uses the tiled pair (a weight row is read once per 64 tokens), a decoded token + // the per-token pair. Both pairs read and write the same gate layout. + if nt >= 64 && rank <= 64 && n % 64 == 0 && self.flags.ctrl_tile { + let g1 = cfg((count as u32, nt.div_ceil(64) as u32), 256, 0); + let g2 = LaunchConfig { grid_dim: (count as u32, n.div_ceil(64) as u32, nt.div_ceil(64) as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate_b", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out_b", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + return Ok(()); + } + let g1 = LaunchConfig { grid_dim: (rank as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + let g2 = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + Ok(()) + } + + fn ink_conv(&self, cur: u64, w: u64, taps: u64, hist: u64, out: u64, n: usize, n_conv: usize, per: usize) -> anyhow::Result<()> { + launch!(self, "ink_conv", Self::grid(n), cur, w, taps, hist, out, n as i32, n_conv as i32, per as i32); + Ok(()) + } + + fn ink_conv_batch(&self, cur: u64, w: u64, taps: u64, hist: u64, out: u64, n: usize, n_conv: usize, per: usize, nt: usize) -> anyhow::Result<()> { + anyhow::ensure!(cur != out, "ink_conv_batch: out must not alias cur"); + anyhow::ensure!(n_conv <= 8, "ink_conv_batch: n_conv={n_conv} > 8"); + launch!(self, "ink_conv_batch", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), cur, w, taps, hist, out, n as i32, n_conv as i32, per as i32, nt as i32, 0i32); + launch!(self, "ink_conv_batch", Self::grid(n), cur, w, taps, hist, out, n as i32, n_conv as i32, per as i32, nt as i32, 1i32); + Ok(()) + } + + fn ink_clip_n(&self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, thr: f32, eps: f32, mul: f32, + dst: u64, dst_at0: usize, dst_ring: usize, pos0: usize, log_alpha: f32, log_floor: f32) -> anyhow::Result<()> { + anyhow::ensure!(w <= 128, "ink_clip_n: w={w} > 128"); + anyhow::ensure!(crate::cuda::kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; + let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; + launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), + x, scale, w as i32, thr, eps, mul, dst, dst_at0 as i32, ring as i32, pos0 as i32, log_alpha, fl, 0u64); + Ok(()) + } + + fn ink_clip_pos(&self, x: u64, scale: u64, w: usize, rows: usize, nt: usize, thr: f32, eps: f32, mul: f32, + dst: u64, dst_ring: usize, pos_ptr: u64, log_alpha: f32, log_floor: f32) -> anyhow::Result<()> { + anyhow::ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); + anyhow::ensure!(crate::cuda::kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; + let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; + launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), + x, scale, w as i32, thr, eps, mul, dst, 0i32, ring as i32, 0i32, log_alpha, fl, pos_ptr); + Ok(()) + } + + fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { + let (kn, ck) = self.ink_attn_kernel(hd, nr); + let chunks = rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); + Ok(()) + } + + fn ink_attn_pos(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, max_rows: usize, ring: usize, pos_ptr: u64, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { + let (kn, ck) = self.ink_attn_kernel(hd, nr); + let chunks = max_rows.div_ceil(ck) as u32; + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); + Ok(()) + } + + fn ink_attn_prefill(&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<()> { + // The key-parallel kernels are the same choice as CUDA's; they need the f16 cache (kp16/kp are compiled + // for KV_MODE 0 only). `win` rides in the kernel's `ring` argument as on CUDA's old path. + if hd == 128 && !self.kv_q8 && (self.flags.fast || self.flags.attn_kp4) && !self.flags.attn_old { + let (kn, qb) = if self.flags.attn_kp4 { ("ink_attn_prefill_128_kp", 4) } else { ("ink_attn_prefill_128_kp16", 16) }; + launch!(self, kn, cfg((nt.div_ceil(qb) 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); + return Ok(()); + } + if hd == 128 && self.flags.attn_old { + launch!(self, "ink_attn_prefill_128_old", 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); + return Ok(()); + } + let kn = match hd { + 32 => "ink_attn_prefill_32", + 64 => "ink_attn_prefill_64", + 128 => "ink_attn_prefill_128", + _ => 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); + Ok(()) + } + + fn ink_ffn_sum_n(&self, acc: u64, d: u64, wts: u64, ne: usize, n: usize, nt: usize, cpu: u64) -> anyhow::Result<()> { + launch!(self, "ink_ffn_sum", cfg((n.div_ceil(256) as u32, nt as u32), 256, 0), acc, d, wts, ne as i32, n as i32, cpu); + Ok(()) + } + + fn ink_pool(&self) -> bool { true } + fn ink_slots(&self, ids: u64, wts: u64, table: u64, slots: u64, wh: u64, h: u64, mb: u64, nh: usize, h_off: usize, step: u64, k: usize) -> anyhow::Result<()> { + anyhow::ensure!(k <= 32, "ink_slots: k={k}"); + launch!(self, "ink_slots", cfg((1, 1), 256, 0), ids, wts, table, slots, wh, h, mb, nh as i32, h_off as i32, step, k as i32); + Ok(()) + } + fn ink_ffn_sum_mb(&self, acc: u64, d: u64, wh: u64, k: usize, n: usize, mb: u64, y_off: usize, step: u64, slots: u64) -> anyhow::Result<()> { + launch!(self, "ink_ffn_sum_mb", cfg((n.div_ceil(256) as u32, 1), 256, 0), acc, d, wh, k as i32, n as i32, mb, y_off as i32, step, slots); + Ok(()) + } + 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::ensure!(n_expert <= 512 && k <= 32, "ink_route: n_expert={n_expert} k={k}"); + launch!(self, "ink_route", cfg((rows as u32, 1), 32, 0), logits, bias, ids, wts, gu_sc, dn_sc, gsc_out, n_expert as i32, k as i32, exp_scale); + Ok(()) + } fn dflash2_conv(&self, x: u64, dyn_w: u64, base: u64, out: u64, h: usize, gs: usize, k: usize, t: usize, part: usize) -> anyhow::Result<()> { launch!(self, "dflash2_conv", cfg((h.div_ceil(256) as u32, t as u32), 256, 0), x, dyn_w, base, out, h as i32, gs as i32, k as i32, t as i32, part as i32); @@ -1116,6 +1389,26 @@ mod tests { } } + /// The desktop's VRAM is found on the card the device runs on, through its PCI address, and through the VRAM + /// size when no card has the address. + #[test] + fn drm_free_finds_the_device_by_its_pci_address() { + let g = match Gpu::new(0) { + Ok(g) => g, + Err(e) => { eprintln!("skipping: HIP unavailable: {e:#}"); return; } + }; + let Some(bus) = g.pci.clone() else { eprintln!("skipping: no PCI address from the runtime"); return }; + let (mut free, mut total) = (0usize, 0usize); + g.hip.check(unsafe { (g.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo").unwrap(); + let drm = drm_free(total, Some(&bus)).unwrap_or_else(|| panic!("no amdgpu card at {bus} in /sys/class/drm")); + eprintln!("{bus}: {:.2} GB free by the driver, {:.2} GB by HIP", drm as f64 / 1e9, free as f64 / 1e9); + assert!(drm <= total); + // The same card in another PCI function, which no card has: the size match finds the card. + let other = format!("{}{}", &bus[..bus.len() - 1], if bus.ends_with('7') { '6' } else { '7' }); + let by_size = drm_free(total, Some(&other)).expect("the VRAM size finds the card when no card has the address"); + assert!(by_size.abs_diff(drm) < 256 << 20, "{other}: {by_size} free, {bus}: {drm}"); + } + /// The generated source compiles for this device through hiprtc (the CUDA source with `STRATA_HIP` taken). #[test] fn hiprtc_compiles_the_kernels() { diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 0d162708..9f0be922 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -15,6 +15,8 @@ use half::{f16, slice::HalfFloatSliceExt}; use rayon::prelude::*; mod device; +mod pool; +mod worker; /// Epsilon of the norms without a weight (depth mix, loop controllers). const MIX_EPS: f32 = 1e-6; @@ -96,10 +98,14 @@ pub struct Inkling2Model<'a> { out_norm: Vec, output: Mat<'a>, slots: Vec, - /// Share of a layer's VRAM-cache misses the CPU computes; it follows the two sides' times. + /// Share of a verify chunk's VRAM-cache misses the CPU computes; it follows the two sides' times. cpu_share: std::cell::Cell, /// The same share for a chunk of tokens, where an expert runs once for all its tokens. chunk_share: std::cell::Cell, + /// One token's split of the last `plan` (CPU experts, staged experts), and the seconds one expert takes on the + /// CPU and to copy up and run, with the plans since the copy was last timed (see `stage_count`). + split: std::cell::Cell<(usize, usize)>, + split_cost: std::cell::Cell<[f32; 3]>, pub toks: Vec, pub trace: bool, /// Seconds per part of a token, printed with `STRATA_DS_PROF`; see `PROF`. @@ -119,6 +125,10 @@ pub struct Inkling2Model<'a> { /// A token of `device` counts all the device work before the router as "mix": the queue runs while the host waits /// for the router's input. +/// Per-token expert counters of `plan` for STRATA_DS_PROF: CPU bytes, CPU experts, GPU experts copied up for one +/// use, GPU experts; and the experts `Dev::admit` moved into VRAM. +static ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static HYB: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; const PROF: [&str; 8] = ["mix", "proj", "scores", "out-proj", "route", "experts-gpu", "experts-cpu", "logits"]; /// A tensor read from the mapped file only: never uploaded. @@ -546,6 +556,8 @@ impl<'a> Inkling2Model<'a> { slots: (0..cfg.n_slot()).map(|_| Slot::default()).collect(), cpu_share: std::cell::Cell::new(0.5), chunk_share: std::cell::Cell::new(0.3), + split: Default::default(), + split_cost: Default::default(), toks: vec![], trace: std::env::var_os("STRATA_DS_TRACE").is_some(), prof: Default::default(), @@ -807,14 +819,37 @@ impl<'a> Inkling2Model<'a> { for m in [&l.gate_up, &l.down] { m.prefetch_expert(e, 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 (see `hy4::forward`). `STRATA_DS_CPU_SHARE` fixes the + // Experts resident in VRAM run on the GPU. Of the others, the CPU computes some from the mapped file while the + // GPU uploads and runs the rest, both at once (`stage_count` picks how many). `STRATA_DS_CPU_SHARE` fixes the // share; 0 (also `--fixed-experts`) runs every expert on the GPU: the same numerics on every run. self.lap(4, t); let (share, fixed) = self.share(&self.cpu_share); - let gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt_in(s.0, ne, share == 0.0, &l.gate_up, l.down.data.len())).collect(); + let mut gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt_in(s.0, ne, share == 0.0, &l.gate_up, l.down.data.len())).collect(); + if !fixed && let Some(d) = crate::deepseek::mat::dev::get() { + // An expert runs on the GPU when both its matrices are in VRAM. The most used of the others may take the + // slots of a less used one (`Dev::admit`): the cache follows what this text routes to. + let mut d = d.lock().unwrap(); + let mat = |m: &Mat<'a>| (m.data, m.ty, m.rows, m.cols, m.scale); + let mut miss = vec![]; + for (gu, &(e, _)) in gus.iter_mut().zip(&sel) { + let dn = l.down.expert_host(e, ne); + if gu.gpu.is_some() && d.resident(dn.data) { continue; } + gu.gpu = None; + miss.push((e, [mat(&l.gate_up.expert_host(e, ne)), mat(&dn)])); + } + let cands: Vec<_> = miss.iter().map(|m| m.1).collect(); + if let Some(i) = d.admit(&cands) { + let e = miss[i].0; + let j = sel.iter().position(|s| s.0 == e).unwrap(); + gus[j] = l.gate_up.expert_host(e, ne); + gus[j].gpu = d.ex.get(&(gus[j].data.as_ptr() as usize)).map(|&p| d.exs[p].0); + ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } let n_miss = gus.iter().filter(|m| m.gpu.is_none()).count(); - let mut left = (share * n_miss as f32).round() as usize; + let n_stage = if fixed { n_miss - (share * n_miss as f32).round() as usize } else { self.stage_count(n_miss) }; + let mut left = n_miss - n_stage; + self.split.set((left, n_stage)); let (mut on_gpu, mut on_cpu) = (vec![], vec![]); for (gu, &(e, w)) in gus.into_iter().zip(&sel) { if gu.gpu.is_none() && left > 0 { @@ -824,7 +859,44 @@ impl<'a> Inkling2Model<'a> { on_gpu.push((gu, e, w)); } } - (on_gpu, on_cpu, !fixed && n_miss > 0) + { + use std::sync::atomic::Ordering::Relaxed; + let b = |m: &Mat| m.data.len() as u64; + HYB[0].fetch_add(on_cpu.iter().map(|e| b(&e.0) + b(&e.1)).sum(), Relaxed); + HYB[1].fetch_add(on_cpu.len() as u64, Relaxed); + HYB[2].fetch_add(on_gpu.iter().filter(|e| e.0.gpu.is_none()).count() as u64, Relaxed); + HYB[3].fetch_add(on_gpu.len() as u64, Relaxed); + } + (on_gpu, on_cpu, !fixed && n_stage > 0) + } + + /// How many of a token's `n_miss` routed experts outside VRAM the GPU copies up for this use; the CPU computes + /// the rest from the mapped file. The two run at once, so the split is the one whose slower side is fastest, from + /// the measured time of one expert on each side. A layer has a handful of misses, and one copy can cost more than + /// the CPU takes for all of them (PCIe 3.0 against dual-channel DDR4, an 8.5 MB Q8_0 expert: 2.5 ms against + /// 0.25 ms): then nothing is copied. The copy cost is measured on first use and again every 512 plans. + fn stage_count(&self, n_miss: usize) -> usize { + if n_miss == 0 { return 0; } + let [cpu, up, since] = self.split_cost.get(); + if up == 0.0 || since >= 512.0 { + self.split_cost.set([cpu, up, 0.0]); + return 1; + } + self.split_cost.set([cpu, up, since + 1.0]); + let t = |s: usize| ((n_miss - s) as f32 * cpu).max(s as f32 * up); + (0..=n_miss).min_by(|&a, &b| t(a).total_cmp(&t(b))).unwrap() + } + + /// The times of the two sides of the last `plan` of one token: the per-expert costs `stage_count` splits by. + /// `staged`: the GPU side copied experts up and waited for its queue, so `tg` is their cost. + fn balance_split(&self, staged: bool, tg: f32, tc: f32) { + self.prof[5].set(self.prof[5].get() + tg as f64); + self.prof[6].set(self.prof[6].get() + tc as f64); + let ((n_cpu, n_stage), [mut cpu, mut up, since]) = (self.split.get(), self.split_cost.get()); + let ema = |old: f32, new: f32| if old == 0.0 { new } else { 0.8 * old + 0.2 * new }; + if n_cpu > 0 { cpu = ema(cpu, tc / n_cpu as f32); } + if staged && n_stage > 0 { up = ema(up, tg / n_stage as f32); } + self.split_cost.set([cpu, up, since]); } /// The GPU's experts of `plan` with both matrices in VRAM: in a cache slot, or copied up for this use. @@ -854,7 +926,7 @@ impl<'a> Inkling2Model<'a> { (run_experts(&on_cpu, x, cfg), t.elapsed().as_secs_f32()) }; let ((a, tg), (b, tc)) = rayon::join(gpu_side, cpu_side); - self.balance(&self.cpu_share, adapt, tg, tc); + self.balance_split(adapt, tg, tc); a.iter().zip(&b).map(|(a, b)| a + b).collect() } @@ -1309,6 +1381,7 @@ impl<'a> Inkling2Model<'a> { match d.prepare(self, target_end) { Ok(()) => { let chunk = env_chunk.unwrap_or(device::pf_tokens()).clamp(1, device::pf_tokens()); + let chunk = d.prefill_rows(self, chunk.min(seq.len()).max(1)); let mut logits = vec![]; let mut done = 0usize; let mut failed = None; @@ -1436,8 +1509,9 @@ impl<'a> Inkling2Model<'a> { use std::sync::atomic::Ordering::Relaxed; let ex = &crate::deepseek::mat::EX_LOOKUPS; let parts: Vec = PROF.iter().zip(&self.prof).map(|(n, c)| format!("{n} {:.1}", c.replace(0.0) * 1e3)).collect(); - eprintln!("PROF pos {pos}, {nt} tokens: {:.1} ms ({}), expert cache hit {} miss {}, cpu share {:.2} chunk {:.2}", - t0.elapsed().as_secs_f64() * 1e3, parts.join(", "), ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), self.cpu_share.get(), self.chunk_share.get()); + eprintln!("PROF pos {pos}, {nt} tokens: {:.1} ms ({}), expert cache hit {} miss {}, expert ms cpu {:.2} copy {:.2}, chunk share {:.2}, CPU experts {} MB in {}, copied up {} of the GPU's {}, admitted {}", + t0.elapsed().as_secs_f64() * 1e3, parts.join(", "), ex[0].swap(0, Relaxed), ex[1].swap(0, Relaxed), self.split_cost.get()[0] * 1e3, self.split_cost.get()[1] * 1e3, self.chunk_share.get(), + HYB[0].swap(0, Relaxed) >> 20, HYB[1].swap(0, Relaxed), HYB[2].swap(0, Relaxed), HYB[3].swap(0, Relaxed), ADMITS.swap(0, Relaxed)); } } } diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index 6697cdbf..c7d0814f 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -44,12 +44,14 @@ struct DSlot { k: Buf, v: Buf, hist: Buf, cap: usize } /// prompt chunk on, a prefill scratch. The activations come over the host once per layer run (about 10 KB per token). struct Remote { part: usize, scr: Buf, s: Scratch, pf: Option } -/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 256 on one card, 512 on two or more; -/// at most 2048). +/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 2048 on one card, 512 on two or more; +/// at most 2048). On one card each chunk copies the pool's missing experts into the +/// staging slots again, so a longer chunk spreads that copy over more tokens; the scratch costs about 0.55 GB of VRAM +/// per 1024 rows, and `prefill_rows` halves the chunk when VRAM has no room for it. pub(super) fn pf_tokens() -> usize { let multi = std::env::var("STRATA_DS_DEVICES") .map_or(false, |v| v.split(',').filter(|d| !d.trim().is_empty()).count() > 1); - let default = if multi { 512 } else { 256 }; + let default = if multi { 512 } else { 2048 }; std::env::var("STRATA_DS_PF_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(default).clamp(1, 2048) } @@ -57,7 +59,7 @@ pub(super) fn pf_tokens() -> usize { #[derive(Clone, Copy)] struct Scratch { cur: u64, x: u64, blocks: u64, bank: u64, outb: u64, prelude: u64, msg: u64, ins: u64, ins2: u64, gate: u64, nrm: u64, nrm_xq: u64, - q: u64, r: u64, sink: u64, og: u64, k: u64, v: u64, kp: u64, vp: u64, att: u64, proj: u64, h: u64, h2: u64, hn: u64, + q: u64, r: u64, sink: u64, og: u64, k: u64, v: u64, kp: u64, vp: u64, att: u64, proj: u64, h: u64, h2: u64, hn: u64, wh: u64, step: u64, y: u64, d: u64, ids: u64, xh: u64, xq: u64, wc: u64, rlogits: u64, amax: u64, pos: u64, acc: u64, logits: u64, end: u64, } @@ -70,7 +72,7 @@ impl Scratch { cur: f(n), x: f(n), blocks: f(4 * n), bank: f(4 * n), outb: f(n), prelude: f(n), msg: f(4 * n), ins: f(3 * n), ins2: f(3 * n), gate: f(4 * rank), nrm: f(3 * n), nrm_xq: f(3 * xq_row_floats), q: f(q), r: f(c.n_head * c.n_rel), sink: f(c.n_head), og: f(q), k: f(c.n_head_kv * c.head_dim), v: f(c.n_head_kv * c.head_dim), kp: f(c.n_head_kv * c.n_conv), vp: f(c.n_head_kv * c.n_conv), att: f(q), proj: f(n), h: f(n), - h2: f(n), hn: f(n), y: f(c.n_used * 2 * c.n_ff_exp), d: f(c.n_used * n), ids: f(3 * c.n_used), xh: f(n), xq: f(c.n_used * c.n_ff_exp), wc: f(c.n_used + n), rlogits: f(c.n_expert), amax: f(16), pos: f(1), acc: f(n), + h2: f(n), hn: f(n), wh: f(c.n_used), step: f(2), y: f(c.n_used * 2 * c.n_ff_exp), d: f(c.n_used * n), ids: f(3 * c.n_used), xh: f(n), xq: f(c.n_used * c.n_ff_exp), wc: f(c.n_used + n), rlogits: f(c.n_expert), amax: f(16), pos: f(1), acc: f(n), logits: f(vocab), end: a - base, } } @@ -183,6 +185,7 @@ pub(super) struct Device { pf: Option, s: Scratch, rank: usize, + /// Every layer's experts run on the device: in a slab, or in `pool` with the CPU worker for the rest. all_full: bool, /// GPU 1's share of the FFN layers (None when every layer's experts are on GPU 0). rem: Option, @@ -190,8 +193,10 @@ pub(super) struct Device { seg_graph: bool, /// Blocks in the depth mix after the loop (what `layer_attn` counted when the loop graph was recorded). loop_nb: usize, - /// Key of the recorded `step_fast` graph, by `argmax` (0: none). - graph_keys: [u64; 2], + /// VRAM slots and the CPU worker for the layers without a slab (decode only; None under `--fixed-experts`). + pool: Option, + /// Keys of the recorded `step_fast` graphs, by `argmax`, and of `core_graph` (0: none). + graph_keys: [u64; 3], /// Positions whose rows both sides hold, and whether the device has run tokens after them. synced: usize, ahead: bool, @@ -255,6 +260,17 @@ fn shapes_fit(m: &Inkling2Model, rank: usize) -> bool { } /// The layer whose weights slot `il` runs. +/// (slot, layer) of each layer run of a token, in the order it runs them. +fn run_order(c: &Inkling2Config) -> Vec<(usize, usize)> { + let core = c.loop_end - c.loop_start; + let mut runs: Vec<(usize, usize)> = (0..c.loop_start).map(|il| (il, il)).collect(); + for pass in 0..c.loop_count { + runs.extend((c.loop_start..c.loop_end).map(|ip| (if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }, ip))); + } + runs.extend((c.loop_end..c.n_layer).map(|il| (il, il))); + runs +} + fn layer_of(c: &Inkling2Config, il: usize) -> usize { if il < c.n_layer { il } else { c.loop_start + (il - c.n_layer) % (c.loop_end - c.loop_start) } } @@ -338,7 +354,13 @@ impl Device { let cpu_share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse::().ok()).unwrap_or(0.0); let (mut n_full, mut slab_bytes, mut per_part) = (0usize, 0usize, [0usize; 2]); let mut rem: Option = None; - if cpu_share <= 0.0 && c.n_expert <= 512 && c.n_used <= 32 { + // With the expert pool (`pool`), every layer keeps its most used experts in VRAM instead: no slabs. + // STRATA_INK_SLABS=1 keeps the slabs and pools only the layers they leave out. One GPU only: a split + // keeps upstream's slabs on both cards. + let one_gpu = dev::get().unwrap().lock().unwrap().parts.len() == 1; + let pooled = one_gpu && cpu_share <= 0.0 && std::env::var_os("STRATA_FIXED_EXPERTS").is_none() + && std::env::var_os("STRATA_INK_SLABS").is_none() && dev::get().unwrap().lock().unwrap().parts[0].be.ink_pool(); + if cpu_share <= 0.0 && c.n_expert <= 512 && c.n_used <= 32 && !pooled { let (b_res, f_res) = (64 << 20, 384 << 20); let (n_parts, pf_cap, vocab) = (dev::get().unwrap().lock().unwrap().parts.len().min(2), pf_tokens(), m.output.rows); let (res0, res1) = { @@ -411,16 +433,24 @@ impl Device { } } if std::env::var_os("STRATA_DS_PROF").is_some() { - crate::say!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB: {:.2} on GPU 0, {:.2} on GPU 1) as contiguous slabs", - c.n_layer, slab_bytes as f64 / 1e9, per_part[0] as f64 / 1e9, per_part[1] as f64 / 1e9); + crate::say!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB: {:.2} on GPU 0, {:.2} on GPU 1) as contiguous slabs; {} experts, {} used, core {}..{} x{}, budget left {:.2} GB", + c.n_layer, slab_bytes as f64 / 1e9, per_part[0] as f64 / 1e9, per_part[1] as f64 / 1e9, + c.n_expert, c.n_used, c.loop_start, c.loop_end, c.loop_count, crate::deepseek::mat::budget_left() as f64 / 1e9); } - let all_full = rem.is_none() && layers.iter().all(|l| l.full_exps.is_some()); + // The layers without a slab: a pool of expert slots in what the budget has left, the CPU worker for the + // rest. Not under --fixed-experts, whose numerics must not depend on the placement, and not on a split. + let need: Vec = (0..c.n_layer).filter(|&ip| layers[ip].full_exps.is_none()).collect(); + let pool = (one_gpu && !need.is_empty() && cpu_share <= 0.0 && std::env::var_os("STRATA_FIXED_EXPERTS").is_none()).then(|| { + let runs = run_order(c).into_iter().filter(|r| need.contains(&r.1)).collect(); + super::pool::Pool::new(m, &mut dev::get().unwrap().lock().unwrap(), &need, runs) + }).flatten(); + let all_full = rem.is_none() && (0..c.n_layer).all(|ip| layers[ip].full_exps.is_some() || pool.as_ref().is_some_and(|p| p.layer(ip).is_some())); let core = c.loop_end - c.loop_start; let seg_graph = rem.is_some() && std::env::var_os("STRATA_DS_NO_SEG_GRAPH").is_none() && layers.iter().all(|l| l.full_exps.is_some()) && (c.loop_start..c.loop_end).all(|ip| layers[ip].full_exps.as_ref().is_some_and(|fe| fe.part == 0)) && (c.loop_count * core) % 2 == 0; - Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, rem, seg_graph, loop_nb: 0, graph_keys: [0; 2], synced: 0, ahead: false }) + Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, rem, seg_graph, loop_nb: 0, pool, graph_keys: [0; 3], synced: 0, ahead: false }) })(); made.inspect_err(|e| crate::say!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do")).ok() } @@ -587,12 +617,14 @@ impl Device { let (mut emb, mut cur) = (vec![0f32; n], vec![0f32; n]); m.tok_embd.row_into(tok as usize, &mut emb); rms_norm_w(&emb, &m.tok_norm, c.eps, &mut cur); - let d = dev::get().unwrap().lock().unwrap(); + let mut d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; - (|| -> Result<(Vec, u32)> { + let out = (|| -> Result<(Vec, u32)> { if !self.ahead { self.to_device(m, be, pos)?; } be.put(&cur, &self.scr, ((self.s.cur - o) / 4) as usize)?; be.put(&[pos as i32], &self.scr, ((self.s.pos - o) / 4) as usize)?; + let seq = self.pool.as_mut().map_or(0, |p| p.worker.begin()); + be.put(&[pos as i32, seq as i32], &self.scr, ((self.s.step - o) / 4) as usize)?; let key = { use std::hash::{Hash, Hasher}; let mut h = std::hash::DefaultHasher::new(); @@ -695,13 +727,88 @@ impl Device { be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; } } - if argmax { - let id = be.get::(&self.scr, ((self.s.amax - o) / 4) as usize, 1)?[0] as u32; - Ok((Vec::new(), id)) + let out = if argmax { + (Vec::new(), be.get::(&self.scr, ((self.s.amax - o) / 4) as usize, 1)?[0] as u32) } else { - Ok((be.get(&self.scr, ((self.s.logits - o) / 4) as usize, c.n_vocab)?, 0)) + (be.get(&self.scr, ((self.s.logits - o) / 4) as usize, c.n_vocab)?, 0) + }; + Ok(out) + })().expect("inkling2 device fast step"); + // The read waited for the token: the pool's slots are free to change. + if let Some(p) = &mut self.pool { + p.adapt(&mut d).expect("inkling2 expert pool"); + if std::env::var_os("STRATA_DS_PROF").is_some() && pos % 32 == 0 { + let [hit, miss, moved] = std::mem::take(&mut p.stats); + eprintln!("PROF pool at {pos}: {hit} expert uses in VRAM, {miss} on the CPU, {moved} copied in; CPU worker {:.1} ms a token", + p.worker.busy().as_secs_f64() * 1e3 / p.tokens.max(1) as f64); + } + } + out + } + + /// The core passes as one HIP/CUDA graph when every core layer has its experts in VRAM: about 1100 launches a + /// token that would otherwise each leave the card idle for a few microseconds. Recorded again every 64 + /// positions (the attention's row bound) and when a buffer moves. False: the caller runs the layers one by one. + fn core_graph(&mut self, m: &Inkling2Model, pos: usize, nb: &mut usize) -> bool { + let c = &m.cfg; + if !(c.loop_start..c.loop_end).all(|ip| self.layers[ip].full_exps.as_ref().is_some_and(|fe| fe.part == 0)) { return false; } + let (n, core, o) = (c.n_embd, c.loop_end - c.loop_start, self.scr.addr()); + let n_pre = *nb; + // The block count after the last pass: the passes after the first start again from the prelude's. + let nb_end = n_pre + (c.loop_start..c.loop_end).filter(|ip| ip % c.block_size == 0).count(); + let swaps = core * c.loop_count; + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + let key = { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + (pos / 64, n_pre, self.sc_buf.addr(), self.s.cur).hash(&mut h); + for sl in &self.slots { sl.k.addr().hash(&mut h); } + 0x494E_4B43_0000_0000u64 | (h.finish() & 0x0000_FFFF_FFFF_FFFF) + }; + let last = std::mem::replace(&mut self.graph_keys[2], key); + let s0 = self.s; + (|| -> Result<()> { + if last != 0 && last != key { be.graph_drop(last)?; } + be.put(&[pos as i32], &self.scr, ((self.s.pos - o) / 4) as usize)?; + let mut ran = false; + be.graph(key, &mut || { + ran = true; + self.s = s0; + let mut nb = n_pre; + for pass in 0..c.loop_count { + let n_bank = nb.saturating_sub(n_pre + 1); + if pass > 0 { + let s = self.s; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + for ip in c.loop_start..c.loop_end { + let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; + if pass > 0 { + let s = self.s; + be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + } + self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, ip)?; + } + } + anyhow::ensure!(nb == nb_end, "inkling2 core graph: {nb} blocks, expected {nb_end}"); + Ok(()) + })?; + // A replay runs nothing here: put the scratch roles where the layers would have left them. + if !ran { + self.s = s0; + if swaps % 2 == 1 { (self.s.cur, self.s.x) = (s0.x, s0.cur); } } - })().expect("inkling2 device fast step") + Ok(()) + })().expect("inkling2 device core graph"); + *nb = nb_end; + true } fn step_layers(&mut self, m: &Inkling2Model, tok: u32) -> usize { @@ -723,6 +830,10 @@ impl Device { // Every pass of the core starts from the prelude output. copy(&*lock().parts[0].be, &self.scr, self.s.cur, self.s.prelude); let n_pre = nb; + if self.core_graph(m, pos, &mut nb) { + for il in c.loop_end..c.n_layer { self.layer(m, il, il, false, pos, &mut nb); } + return nb; + } for pass in 0..c.loop_count { // The bank of the previous pass: its blocks after the first core block, and its output. let n_bank = nb.saturating_sub(n_pre + 1); @@ -816,7 +927,10 @@ impl Device { } let target = need_nt.max(pf_tokens()); let mut tries = vec![target]; - if need_nt < target { tries.push(need_nt.max(128)); tries.push(need_nt.max(64)); tries.push(need_nt); } + // A smaller scratch when VRAM is short: halve down to 256 rows, then the old small sizes. + let mut cap = target / 2; + while cap >= 256 && cap >= need_nt { tries.push(cap); cap /= 2; } + if need_nt < 256 { tries.push(need_nt.max(128)); tries.push(need_nt.max(64)); tries.push(need_nt); } let mut last_err = None; for cap in tries { match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap, false) { @@ -901,6 +1015,15 @@ impl Device { /// Run a chunk of token IDs or raw vision embeddings (`Some(emb)` skips `tok_norm`, matching `inkling2.cpp::build_inputs`). /// When `capture_dspark` is true, also returns the 4 target layer hidden states `[5, 23, 41, 48]` (`[4][nt][n_embd]`). + /// Rows the next prompt chunks may have: `want`, or half of it down to 256 when VRAM has no room for that scratch. + pub(super) fn prefill_rows(&mut self, m: &Inkling2Model, want: usize) -> usize { + let d = dev::get().unwrap().lock().unwrap(); + let be = &*d.parts[0].be; + let mut cap = want; + while cap > 256 && self.ensure_pf(be, &m.cfg, m.output.rows, cap).is_err() { cap /= 2; } + cap + } + pub(super) fn prefill_chunk_seq( &mut self, m: &Inkling2Model, @@ -1365,6 +1488,19 @@ impl Device { be.add(*x_a, p.acc2, nt * n)?; m.lap(5, t_gpu); true + } else if self.pool.as_ref().is_some_and(|q| q.has_room(ip)) { + m.lap(0, t_prep); + let t_gpu = std::time::Instant::now(); + let on = self.prefill_ffn_pool(be, m, ip, nt, small, h)?; + if on { + if verify_mode { + be.dtod(&pf.acc_buf, 0, &pf.conv_log, log_base + 4 * VERIFY_MAX * (2 * kw + n), 4 * nt * n)?; + } + be.ink_conv_batch(pf.acc_buf.addr(), l.convs[3].addr(), 0, hist(3), p.acc2, n, nc, hd, nt)?; + be.add(*x_a, p.acc2, nt * n)?; + m.lap(5, t_gpu); + } + on } else { be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; m.lap(0, t_prep); @@ -1483,6 +1619,135 @@ impl Device { Ok(()) } + /// The routed experts of a prompt chunk in a pool layer: the pool's slots, and the chunk's other experts copied + /// into the staging slots in rounds of `pool::STAGE`, with a wait before each refill. The experts run in the + /// order of their rounds, so a round's rows are one block. False: a small batch with more misses than staging + /// slots, left to the host path (`p.hn` holds the normed input). + fn prefill_ffn_pool(&self, be: &dyn Backend, m: &Inkling2Model, ip: usize, nt: usize, small: bool, h: u64) -> Result { + use super::pool::STAGE; + let (c, ml, l) = (&m.cfg, &m.layers[ip], &self.layers[ip]); + let pool = self.pool.as_ref().unwrap(); + let pl = pool.layer(ip).unwrap(); + let pf = self.pf.as_ref().unwrap(); + let (p, buf_o) = (pf.p, pf.buf.addr()); + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); + let ((gt, gr, gc), (dt, dr, dc)) = (pl.gu, pl.dn); + let (base, stride) = pool.base(pl); + let (dn_base, st0) = (base + pl.dn_off as u64, pool.stage(pl)); + let use_gemm = !small && gc % 64 == 0 && dc % 64 == 0; + if use_gemm || gt.float_x() { + be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; + } else { + be.rms_norm_q(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps, p.xh, 0)?; + } + Self::proj_n(be, &pl.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; + let gu_sc = pl.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = pl.dn_scale.as_ref().map_or(0, |b| b.addr()); + be.ink_route(p.rlogits, pl.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, if gu_sc != 0 { p.gsc } else { 0 }, c.n_expert, k, c.exp_scale, nt)?; + let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; + let mut by_e: Vec> = vec![vec![]; c.n_expert]; + for (t, row) in ids.chunks_exact(k).enumerate() { + for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } + } + let mut slot = vec![-1i32; c.n_expert]; + let (mut resident, mut missing) = (vec![], vec![]); + for e in (0..c.n_expert).filter(|&e| !by_e[e].is_empty()) { + slot[e] = pool.slot(ip, e); + if slot[e] >= 0 { resident.push(e) } else { missing.push(e) } + } + // Staging copies go on the copy queue (`Backend::htod_side`) into `st0 + first..`, and return its mark. The + // copy queue first waits for the kernels queued so far, which may still read those slots (an earlier round or + // layer run). + let stage = |round: &[usize], first: usize, slot: &mut [i32]| -> Result { + be.side_waits(be.main_mark()?)?; + for (j, &e) in round.iter().enumerate() { + pool.upload_on(be, ip, e, st0 + first + j, true)?; + slot[e] = (st0 + first + j) as i32; + } + be.side_mark() + }; + if !use_gemm { + if missing.len() > STAGE { return Ok(false); } + if !missing.is_empty() { let m = stage(&missing, 0, &mut slot)?; be.main_waits(m)?; } + let sids: Vec = ids.iter().map(|&e| slot[e as usize]).collect(); + be.put(&sids, &pf.buf, ((p.ids - buf_o) / 4) as usize)?; + let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + for tok0 in (0..nt).step_by(16) { + let (bt, ids_a) = ((nt - tok0).min(16), p.ids + (4 * tok0 * k) as u64); + let np = bt * k; + let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; + let (hn_a, xh_a, acc_a) = (p.hn + f(tok0 * n), p.xh + f(tok0 * xh_tok_floats), pf.acc_buf.addr() + f(tok0 * n)); + be.moe_gemv(gt, gr, gc, base, stride, ids_a, np, hn_a, n, k, p.y, None, xh_a)?; + if dt.float_x() || nf % 32 != 0 { + be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(dt, dr, dc, dn_base, stride, ids_a, np, p.y, 2 * nf, 1, p.d, None, 0)?; + } else { + be.situ_q(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; + be.moe_gemv(dt, dr, dc, dn_base, stride, ids_a, np, p.y, 2 * nf, 1, p.d, None, p.xq)?; + } + be.ink_ffn_sum_n(acc_a, p.d, p.wts + f(tok0 * k), k, n, bt, 0)?; + } + return Ok(true); + } + use crate::backend::GEMM_BM; + // Groups: the residents, then one per round of misses. The rounds alternate between the two halves of the + // staging slots: while the kernels run on one half, the copy queue fills the other, and the residents run + // while the first two rounds copy in. + const HALF: usize = STAGE / 2; + let mut groups: Vec> = vec![resident]; + groups.extend(missing.chunks(HALF).map(|r| r.to_vec())); + let rounds = groups.len() - 1; + let mut ready = vec![0usize; rounds]; + let np = nt * k; + let (mut xrow, mut inv, mut gsc_rows) = (Vec::with_capacity(np), vec![0i32; np], Vec::with_capacity(np)); + let mut rows = vec![(0usize, 0usize); c.n_expert]; + for &e in groups.iter().flatten() { + rows[e] = (xrow.len(), by_e[e].len()); + for &(t, j) in &by_e[e] { + inv[t * k + j] = xrow.len() as i32; + xrow.push(t as i32); + if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } + } + } + let max_tiles = (0..c.n_expert).map(|e| by_e[e].len().div_ceil(GEMM_BM)).sum::(); + let dn_off = 16 * max_tiles; + let xr_off = 2 * dn_off; + let inv_off = xr_off + 4 * np; + ensure!(inv_off + 4 * np <= pf.meta.len(), "prefill meta overflow"); + be.put(&xrow, &pf.meta, xr_off / 4)?; + be.put(&inv, &pf.meta, inv_off / 4)?; + let gsc_a = if !gsc_rows.is_empty() { be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; p.gsc } else { 0 }; + let ma = pf.meta.addr(); + for (gi, g) in groups.iter().enumerate() { + // The first two rounds are staged once the residents' kernels are queued: the host's part of a copy (into + // the pinned ring) then runs while the card works. + if gi == 1 { for i in 0..rounds.min(2) { ready[i] = stage(&groups[1 + i], (i % 2) * HALF, &mut slot)?; } } + if gi > 0 { be.main_waits(ready[gi - 1])?; } + let (mut tg, mut td) = (vec![], vec![]); + for &e in g { + let (m0, cnt) = rows[e]; + let at = slot[e] as u64 * stride as u64; + for a in (0..cnt).step_by(GEMM_BM) { + let tag = (m0 + a) as u64 | ((GEMM_BM.min(cnt - a) as u64) << 32); + tg.extend([base + at, tag]); + td.extend([dn_base + at, tag]); + } + } + if tg.is_empty() { continue; } + be.put(&tg, &pf.meta, 0)?; + be.put(&td, &pf.meta, dn_off / 8)?; + let (r0, r1) = (rows[g[0]].0, g.iter().map(|&e| rows[e].0 + rows[e].1).max().unwrap()); + be.gemm(gt, gr, gc, ma, tg.len() / 2, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; + be.situ(p.y + f(r0 * 2 * nf), nf, r1 - r0, if gsc_a != 0 { gsc_a + f(r0) } else { 0 }, c.situ_beta, c.situ_linear_beta)?; + be.gemm(dt, dr, dc, ma + dn_off as u64, td.len() / 2, p.y, 2 * nf, np, 0, p.d, n, 0)?; + // Round r + 2 takes this round's half once the kernels above are done with it (`stage` waits for them). + if gi > 0 && gi + 1 < rounds { ready[gi + 1] = stage(&groups[gi + 2], ((gi - 1) % 2) * HALF, &mut slot)?; } + } + be.memset(&pf.acc_buf)?; + be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + Ok(true) + } + fn layer_attn(&self, be: &dyn Backend, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize, msgs: bool, pos: usize, graph: bool, nb: &mut usize) -> Result<()> { let (c, ml, l, ds, s, rank) = (&m.cfg, &m.layers[ip], &self.layers[ip], &self.slots[il], self.s, self.rank); let (n, hd, nh, nkv, nr, nc) = (c.n_embd, c.head_dim, c.n_head, c.n_head_kv, c.n_rel, c.n_conv); @@ -1608,7 +1873,7 @@ impl Device { } fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { - let Some(fe) = &self.layers[ip].full_exps else { return Ok(false) }; + let Some(fe) = &self.layers[ip].full_exps else { return self.layer_ffn_pool(be, m, il, ip) }; Self::ffn_core(be, &m.cfg, self.s, fe)?; self.ffn_tail(be, m, il, ip)?; Ok(true) @@ -1634,6 +1899,39 @@ impl Device { Ok(true) } + /// `layer_ffn_gpu` of a layer in the expert pool: the router and the slot lookup on the device, the experts in a + /// slot there, the others on the CPU worker (mailbox `il`), whose sum the combine waits for only after a miss. + fn layer_ffn_pool(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let Some(pool) = &self.pool else { return Ok(false) }; + let Some(pl) = pool.layer(ip) else { return Ok(false) }; + let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); + let (n, hd, nc, nf, k) = (c.n_embd, c.head_dim, c.n_conv, c.n_ff_exp, c.n_used); + let hist3 = ds.hist.addr() + f(hists(c).0[3]); + let (base, stride) = pool.base(pl); + let mb = pool.worker.mb(il); + let slots = s.ids + f(k); + be.gemv(&pl.gate_inp, s.hn, s.rlogits)?; + let gu_sc = pl.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = pl.dn_scale.as_ref().map_or(0, |b| b.addr()); + let gsc_a = if gu_sc != 0 { s.ids + f(2 * k) } else { 0 }; + be.ink_route(s.rlogits, pl.bias.addr(), s.ids, s.wc, gu_sc, dn_sc, gsc_a, c.n_expert, k, c.exp_scale, 1)?; + be.ink_slots(s.ids, s.wc, pl.table_dev.addr(), slots, s.wh, s.hn, mb, n, pool.worker.layout.h, s.step, k)?; + let ((gt, gr, gc), (dt, dr, dc)) = (pl.gu, pl.dn); + be.moe_gemv(gt, gr, gc, base, stride, slots, k, s.hn, n, k, s.y, None, s.xh)?; + if dt.float_x() { + be.situ(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(dt, dr, dc, base + pl.dn_off as u64, stride, slots, k, s.y, 2 * nf, 1, s.d, None, 0)?; + } else { + be.situ_q(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta, s.xq)?; + be.moe_gemv(dt, dr, dc, base + pl.dn_off as u64, stride, slots, k, s.y, 2 * nf, 1, s.d, None, s.xq)?; + } + be.ink_ffn_sum_mb(s.acc, s.d, s.wh, k, n, mb, pool.worker.layout.y, s.step, slots)?; + be.ink_conv(s.acc, self.layers[ip].convs[3].addr(), 0, hist3, s.acc, n, nc, hd)?; + be.add(s.x, s.acc, n)?; + (self.s.cur, self.s.x) = (s.x, s.cur); + Ok(true) + } + /// One layer run of the token (hybrid path): slot `il` with weights of layer `ip`. fn layer(&mut self, m: &Inkling2Model, il: usize, ip: usize, msgs: bool, pos: usize, nb: &mut usize) { let (c, ml, ds, s) = (&m.cfg, &m.layers[ip], &self.slots[il], self.s); @@ -1712,7 +2010,7 @@ impl Device { let be = &*d.parts[0].be; match gpu { Some(tg) => { - m.balance(&m.cpu_share, adapt, tg, tc); + m.balance_split(adapt, tg, tc); // `cpu` and `r` are per-dimension sums (`run_experts` returns the weighted mix), not per-expert // weights: both have length `n`, and the elementwise add is the host total. debug_assert_eq!(cpu.len(), n); diff --git a/src/inkling2/forward/pool.rs b/src/inkling2/forward/pool.rs new file mode 100644 index 00000000..055d9c12 --- /dev/null +++ b/src/inkling2/forward/pool.rs @@ -0,0 +1,274 @@ +//! VRAM slots for the routed experts of the layers without a slab (see `device`): one pool of equal slots per +//! expert layout, a table per layer (expert -> slot, -1 = on the CPU) that `ink_slots` reads, and usage counts that +//! decide which experts hold the slots. Routes skew hard: in the coda of Inkling 2 Mini, 100 of 768 experts take +//! 60-67% of a text's uses. The table changes between tokens only, with the queue idle. +use super::*; +use super::worker::{HostExperts, InkWorker}; +use crate::backend::{Buf, GpuTensor}; +use crate::deepseek::mat::dev::{self, SlabBuf}; +use crate::quant::GgmlType; +use std::sync::Arc; + +/// Share of a usage count kept per token: a count forgets in a few hundred tokens. +const KEEP: f32 = 0.995; +/// Experts copied into free slots per token while a pool fills, and into a less used expert's slot once it is full. +/// A copy of an 8.5 MB expert takes about 0.7 ms over PCIe 3.0. +const FILLS: usize = 4; +const SWAPS: usize = 2; +/// Share of a long count kept per token: the saved profile, which places the next run's experts at load. +const LONG_KEEP: f32 = 0.9999; +/// Slots past each pool's own for a prompt chunk's experts that are not in it (`stage`). +pub(super) const STAGE: usize = 32; + +pub(super) struct PoolLayer { + pub pool: usize, + pub table_dev: Buf, + table: Vec, + pub gate_inp: GpuTensor, + _gi: Arc, + pub bias: Arc, + pub gu_scale: Option>, + pub dn_scale: Option>, + /// (type, rows, cols) of one expert's gate_up and down matrices; down starts `dn_off` bytes into a slot. + pub gu: (GgmlType, usize, usize), + pub dn: (GgmlType, usize, usize), + pub dn_off: usize, + host: HostExperts, +} + +/// `owner.len()` slots of `bytes`, then `STAGE` more for a prompt chunk. +struct Slots { buf: Option>, bytes: usize, owner: Vec> } + +pub(super) struct Pool { + slots: Vec, + pub layers: Vec>, + /// Decayed uses, [layer * n_expert + expert]. + counts: Vec, + /// The same with a memory of some ten thousand tokens: saved when the pool goes, read at the next load. + long: Vec, + profile: std::path::PathBuf, + ne: usize, + pub worker: InkWorker, + /// (mailbox, layer) of the runs with a pool layer, in token order. + runs: Vec<(usize, usize)>, + /// Since the last PROF line: expert uses found in a slot, uses on the CPU, experts copied in. + pub stats: [usize; 3], + pub tokens: usize, +} + +impl Pool { + /// The pool for layers `need` with what the weight budget has left, or None when nothing fits or the backend + /// has no pool kernels. + pub fn new(m: &Inkling2Model, d: &mut dev::Dev, need: &[usize], runs: Vec<(usize, usize)>) -> Option { + let (c, ne) = (&m.cfg, m.cfg.n_expert); + if !d.parts[0].be.ink_pool() { return None; } + let (b_res, f_res) = (64 << 20, 384 << 20); + let bytes = |x: &[f32]| -> Vec { x.iter().flat_map(|v| v.to_le_bytes()).collect() }; + // Layout of a slot per layer, and the layers of each layout. + let mut kinds: Vec<((GgmlType, usize, usize, GgmlType, usize, usize), usize, Vec)> = vec![]; + let mut layers: Vec> = (0..c.n_layer).map(|_| None).collect(); + let mut host: Vec> = vec![None; c.n_layer]; + for &ip in need { + let ml = &m.layers[ip]; + let (gu, dn) = (ml.gate_up.expert_host(0, ne), ml.down.expert_host(0, ne)); + let dn_off = gu.data.len().next_multiple_of(256); + let slot = (dn_off + dn.data.len()).next_multiple_of(256); + let key = (gu.ty, gu.rows, gu.cols, dn.ty, dn.rows, dn.cols); + let g = kinds.iter().position(|k| k.0 == key).unwrap_or_else(|| { kinds.push((key, slot, vec![])); kinds.len() - 1 }); + kinds[g].2.push(ip); + let gi = d.alloc_slab_on(0, &bytes(&ml.gate_inp), None, b_res, f_res)?; + let bias = d.alloc_slab_on(0, &bytes(&ml.bias), None, b_res, f_res)?; + let sc = |v: &[f32], d: &mut dev::Dev| if v.is_empty() { Some(None) } else { d.alloc_slab_on(0, &bytes(v), None, b_res, f_res).map(Some) }; + let (gu_scale, dn_scale) = (sc(&ml.gu_scale, d)?, sc(&ml.down_scale, d)?); + let be = &*d.parts[0].be; + let table = vec![-1i32; ne]; + let table_dev = be.alloc(4 * ne).ok()?; + be.put(&table, &table_dev, 0).ok()?; + // SAFETY: the mapped file outlives the model, which owns the device state and so the worker (joined on drop). + let st = |x: Mat| unsafe { std::mem::transmute::, Mat<'static>>(x) }; + let he = HostExperts { gate_up: st(ml.gate_up), down: st(ml.down), gu_scale: ml.gu_scale.clone() }; + host[ip] = Some(he.clone()); + layers[ip] = Some(PoolLayer { + pool: g, table_dev, table, + gate_inp: GpuTensor::new(GgmlType::F32, ne, c.n_embd, Buf::new(gi.addr(), gi.len(), ())), _gi: gi, + bias, gu_scale, dn_scale, + gu: (gu.ty, gu.rows, gu.cols), dn: (dn.ty, dn.rows, dn.cols), dn_off, host: he, + }); + } + // STRATA_INK_PIN=1: page-lock the pooled layers' experts in the mapped file, so a prompt chunk's staging copies + // are DMAs from there (`Backend::pin_host`) instead of a host copy through the pinned ring. + if std::env::var_os("STRATA_INK_PIN").is_some() { + let t0 = std::time::Instant::now(); + let (mut gb, mut ok) = (0.0, true); + for &ip in need { + let ml = &m.layers[ip]; + for data in [ml.gate_up.data, ml.down.data] { + match d.parts[0].be.pin_host(data) { + Ok(true) => gb += data.len() as f64 / 1e9, + Ok(false) => ok = false, + Err(e) => { eprintln!("inkling2: pinning the experts failed ({e:#}); staging copies go through the ring"); ok = false; } + } + if !ok { break; } + } + if !ok { break; } + } + eprintln!("inkling2: pinned {gb:.2} GB of experts in {:.1} s", t0.elapsed().as_secs_f64()); + } + // Slots in proportion to each layout's experts, from what the budget and the card have left. + let total: usize = kinds.iter().map(|k| k.1 * ne * k.2.len()).sum(); + let free = d.parts[0].be.mem_info().map_or(0, |m| m.0).saturating_sub(f_res + (64 << 20)); + let room = d.budget_left().saturating_sub(b_res).min(free); + let frac = (room as f64 / total.max(1) as f64).min(1.0); + let mut slots = vec![]; + for k in &kinds { + let n = (frac * (ne * k.2.len()) as f64) as usize; + let n = n.saturating_sub(STAGE).min(ne * k.2.len()); + let buf = d.alloc_room((n + STAGE) * k.1, b_res, f_res); + let n = if buf.is_some() { n } else { 0 }; + slots.push(Slots { buf, bytes: k.1, owner: vec![None; n] }); + } + if std::env::var_os("STRATA_DS_PROF").is_some() { + let desc: Vec = kinds.iter().zip(&slots).map(|(k, s)| format!("{:?} layers {:?}: {} of {} experts ({:.2} GB)", + k.0.0, k.2, s.owner.len(), ne * k.2.len(), (s.owner.len() * k.1) as f64 / 1e9)).collect(); + eprintln!("inkling2: expert pool {}", desc.join("; ")); + } + if slots.iter().all(|s| s.buf.is_none()) { return None; } + let worker = InkWorker::new(&*d.parts[0].be, c, runs.clone(), host).inspect_err(|e| eprintln!("inkling2: no CPU expert worker ({e:#})")).ok()?; + let profile = crate::expert_cache::cache_dir().join(format!("inkling2-profile-{}x{}-{}-{:?}.f32", c.n_layer, ne, c.n_embd, m.layers[0].gate_up.ty)); + let long: Vec = std::fs::read(&profile).ok().filter(|b| b.len() == 4 * c.n_layer * ne) + .map(|b| b.chunks_exact(4).map(|x| f32::from_le_bytes(x.try_into().unwrap())).collect()).unwrap_or_default(); + let mut pool = Pool { slots, layers, counts: vec![0.0; c.n_layer * ne], long, profile, ne, worker, runs, stats: [0; 3], tokens: 0 }; + pool.fill(d).inspect_err(|e| eprintln!("inkling2: expert pool fill: {e:#}")).ok()?; + Some(pool) + } + + pub fn layer(&self, ip: usize) -> Option<&PoolLayer> { self.layers[ip].as_ref() } + + /// The first placement: the saved profile's most used experts, else in every layer the same share of experts + /// for each time a token runs it (a core layer runs three times). + fn fill(&mut self, d: &mut dev::Dev) -> Result<()> { + let ne = self.ne; + let per: Vec = (0..self.layers.len()).map(|ip| self.runs.iter().filter(|r| r.1 == ip).count() as f32).collect(); + let runs = |ip: usize| per[ip]; + let have = !self.long.is_empty(); + if !have { self.long = vec![0.0; self.counts.len()]; } + for g in 0..self.slots.len() { + let mut cand: Vec<(f32, usize, usize)> = self.layers.iter().enumerate() + .filter(|(_, l)| l.as_ref().is_some_and(|l| l.pool == g)) + .flat_map(|(ip, _)| (0..ne).map(move |e| (ip, e))) + .map(|(ip, e)| (if have { self.long[ip * ne + e] } else { runs(ip) / (e + 1) as f32 }, ip, e)).collect(); + cand.sort_by(|a, b| b.0.total_cmp(&a.0)); + for (slot, &(_, ip, e)) in cand.iter().take(self.slots[g].owner.len()).enumerate() { self.place(d, g, slot, ip, e)?; } + } + // Counts start from the profile at their steady size, so the first tokens move no more than later ones. + let steady = 1.0 / (1.0 - KEEP); + for (ip, l) in self.long.chunks(ne).enumerate() { + let s: f32 = l.iter().sum(); + if s > 0.0 { for e in 0..ne { self.counts[ip * ne + e] = l[e] / s * steady * 8.0; } } + } + for pl in self.layers.iter().flatten() { d.parts[0].be.put(&pl.table, &pl.table_dev, 0)?; } + Ok(()) + } + + /// Copy expert `e` of layer `ip` into slot `slot` of pool `g` and point the table (on the host) at it. + fn place(&mut self, d: &mut dev::Dev, g: usize, slot: usize, ip: usize, e: usize) -> Result<()> { + let ne = self.ne; + let at = self.upload(&*d.parts[0].be, ip, e, slot)?; + let pl = self.layers[ip].as_mut().unwrap(); + let (gu, dn) = (pl.host.gate_up.expert_host(e, ne), pl.host.down.expert_host(e, ne)); + // A prompt chunk's host lookups find the slot too (`Dev::expert`). + d.pin(gu.data, gu.ty, gu.rows, gu.cols, gu.scale, at); + d.pin(dn.data, dn.ty, dn.rows, dn.cols, dn.scale, at + pl.dn_off as u64); + pl.table[e] = slot as i32; + self.slots[g].owner[slot] = Some((ip, e)); + Ok(()) + } + + /// Copy expert `e` of layer `ip` into slot `slot` (a staging slot too) of its pool: its address. + pub fn upload(&self, be: &dyn crate::backend::Backend, ip: usize, e: usize, slot: usize) -> Result { + self.upload_on(be, ip, e, slot, false) + } + + /// `upload`, on the backend's copy queue when `side` (`Backend::htod_side`). + pub fn upload_on(&self, be: &dyn crate::backend::Backend, ip: usize, e: usize, slot: usize, side: bool) -> Result { + let pl = self.layers[ip].as_ref().unwrap(); + let sl = &self.slots[pl.pool]; + let at = sl.buf.as_ref().unwrap().addr() + (slot * sl.bytes) as u64; + let (gu, dn) = (pl.host.gate_up.expert_host(e, self.ne), pl.host.down.expert_host(e, self.ne)); + let (gb, db) = (Buf::new(at, gu.data.len(), ()), Buf::new(at + pl.dn_off as u64, dn.data.len(), ())); + if side { be.htod_side(gu.data, &gb, 0)?; be.htod_side(dn.data, &db, 0)?; } + else { be.htod(gu.data, &gb, 0)?; be.htod(dn.data, &db, 0)?; } + Ok(at) + } + + /// Slot of expert `e` of layer `ip` (-1: not in the pool), and the first of the pool's `STAGE` staging slots. + pub fn slot(&self, ip: usize, e: usize) -> i32 { self.layers[ip].as_ref().unwrap().table[e] } + pub fn stage(&self, pl: &PoolLayer) -> usize { self.slots[pl.pool].owner.len() } + /// Whether layer `ip`'s pool got VRAM (its staging slots exist, so a prompt chunk can run there). + pub fn has_room(&self, ip: usize) -> bool { self.layers[ip].as_ref().is_some_and(|pl| self.slots[pl.pool].buf.is_some()) } + + /// Base address and slot size of layer `ip`'s pool. + pub fn base(&self, pl: &PoolLayer) -> (u64, usize) { let s = &self.slots[pl.pool]; (s.buf.as_ref().map_or(0, |b| b.addr()), s.bytes) } + + /// After a token, with the queue idle: count its routing, copy the most used missed experts into free slots, and + /// give a full pool's least used slot to a missed expert used more often (by more than one). + pub fn adapt(&mut self, d: &mut dev::Dev) -> Result<()> { + let ne = self.ne; + self.tokens += 1; + for v in &mut self.counts { *v *= KEEP; } + for v in &mut self.long { *v *= LONG_KEEP; } + let mut missed = vec![]; + for &(il, ip) in &self.runs { + for (e, s) in self.worker.routing(il) { + if e >= ne { continue; } + self.counts[ip * ne + e] += 1.0; + self.long[ip * ne + e] += 1.0; + if s < 0 { missed.push((ip, e)); self.stats[1] += 1; } else { self.stats[0] += 1; } + } + } + missed.sort_by(|a, b| self.counts[b.0 * ne + b.1].total_cmp(&self.counts[a.0 * ne + a.1])); + missed.dedup(); + let (mut fills, mut swaps, mut changed) = (0, 0, vec![]); + for (ip, e) in missed { + let g = self.layers[ip].as_ref().unwrap().pool; + if self.layers[ip].as_ref().unwrap().table[e] >= 0 { continue; } + let slot = match self.slots[g].owner.iter().position(|o| o.is_none()) { + Some(s) if fills < FILLS => { fills += 1; s } + Some(_) => continue, + None if swaps < SWAPS => { + let Some((s, (vip, ve))) = self.slots[g].owner.iter().enumerate().filter_map(|(s, o)| o.map(|o| (s, o))) + .min_by(|a, b| self.counts[a.1.0 * ne + a.1.1].total_cmp(&self.counts[b.1.0 * ne + b.1.1])) else { continue }; + if self.counts[ip * ne + e] <= self.counts[vip * ne + ve] + 1.0 { continue; } + let vl = self.layers[vip].as_mut().unwrap(); + vl.table[ve] = -1; + d.unpin(vl.host.gate_up.expert_host(ve, ne).data); + d.unpin(vl.host.down.expert_host(ve, ne).data); + changed.push(vip); + swaps += 1; + s + } + None => continue, + }; + self.place(d, g, slot, ip, e)?; + changed.push(ip); + self.stats[2] += 1; + } + changed.sort_unstable(); + changed.dedup(); + for ip in changed { + let pl = self.layers[ip].as_ref().unwrap(); + d.parts[0].be.put(&pl.table, &pl.table_dev, 0)?; + } + Ok(()) + } +} + +impl Drop for Pool { + /// Save the long counts: the next load places from them. + fn drop(&mut self) { + if self.tokens < 16 { return; } + let bytes: Vec = self.long.iter().flat_map(|v| v.to_le_bytes()).collect(); + if let Some(dir) = self.profile.parent() { let _ = std::fs::create_dir_all(dir); } + if let Err(e) = std::fs::write(&self.profile, bytes) { eprintln!("inkling2: expert profile {}: {e}", self.profile.display()); } + } +} diff --git a/src/inkling2/forward/worker.rs b/src/inkling2/forward/worker.rs new file mode 100644 index 00000000..75118265 --- /dev/null +++ b/src/inkling2/forward/worker.rs @@ -0,0 +1,112 @@ +//! The CPU side of the expert pool in a decode token (see `pool`): the mailboxes and flags of `crate::cpu_worker`, +//! one per layer run whose experts are not all in VRAM, answered with `run_experts` as `plan`'s CPU experts are. +//! `ink_slots` raises a run's request flag when one of its experts missed, else its skip flag; +//! `ink_ffn_sum_mb` waits for the done flag only after a miss. +use super::*; +use crate::backend::{Backend, Buf}; +use crate::cpu_worker::{DONE, IDS, Mailbox, REQ, SKIP, read_wc}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering, fence}; +use std::sync::{Arc, mpsc}; +use std::thread::JoinHandle; + +/// A layer's routed experts in the mapped file, for the worker thread. +#[derive(Clone)] +pub(super) struct HostExperts { pub gate_up: Mat<'static>, pub down: Mat<'static>, pub gu_scale: Vec } + +pub(super) struct InkWorker { + _mem: Buf, + host: usize, + /// Device address of the mailboxes: run `il` at `dev + 4 * il * layout.stride`. + pub dev: u64, + pub layout: Mailbox, + seq: u32, + tx: Option>, + stop: Arc, + busy_ns: Arc, + thread: Option>, +} + +impl InkWorker { + /// `runs`: (mailbox index, layer) of every layer run with a mailbox, in the order a token runs them; + /// `experts[ip]` the host experts of each such layer. + pub fn new(be: &dyn Backend, cfg: &Inkling2Config, runs: Vec<(usize, usize)>, experts: Vec>) -> Result { + let layout = Mailbox::new(cfg.n_used, cfg.n_embd); + let len = layout.stride * runs.iter().map(|r| r.0 + 1).max().unwrap_or(1); + let (mem, host) = be.host_mailbox(len)?; + let (host, dev) = (host as usize, mem.addr()); + let (tx, rx) = mpsc::channel::(); + let (stop, busy_ns) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicU64::new(0))); + let (st, bn, cfg) = (stop.clone(), busy_ns.clone(), cfg.clone()); + let lay = Mailbox::new(cfg.n_used, cfg.n_embd); + // Its own pool, as `CpuWorker`'s: the expert passes start on the spinning thread at once. + let pool = rayon::ThreadPoolBuilder::new().num_threads(rayon::current_num_threads()) + .thread_name(|i| format!("inkling-experts-{i}")).build()?; + let thread = std::thread::Builder::new().name("inkling-cpu-experts".into()).spawn(move || pool.install(move || { + let w = |i: usize| (host + 4 * i) as *mut u32; + let ne = cfg.n_expert; + while let Ok(seq) = rx.recv() { + for &(il, ip) in &runs { + let at = |o: usize| w(il * lay.stride + o); + // A newer seq anywhere: the GPU moved on without waiting for this one. + let ahead = |v: u32| v != 0 && (v.wrapping_sub(seq) as i32) >= 0; + let mut r; + while { r = unsafe { at(REQ).read_volatile() }; r != seq } { + if st.load(Ordering::Relaxed) { return; } + if ahead(r) || ahead(unsafe { at(SKIP).read_volatile() }) { break; } + std::hint::spin_loop(); + } + if r != seq { continue; } + fence(Ordering::SeqCst); + let t0 = std::time::Instant::now(); + let k = lay.k; + let mut v = vec![0u32; (3 * k).next_multiple_of(4)]; + unsafe { read_wc(at(IDS), &mut v) }; + let mut h = vec![0u32; lay.n.next_multiple_of(4)]; + unsafe { read_wc(at(lay.h), &mut h) }; + let h: Vec = h[..lay.n].iter().map(|&b| f32::from_bits(b)).collect(); + let ex = experts[ip].as_ref().expect("a mailbox run of a layer without host experts"); + let list: Vec<_> = (0..k).filter(|&j| (v[2 * k + j] as i32) < 0).map(|j| { + let e = v[j] as usize; + (ex.gate_up.expert_host(e, ne), ex.down.expert_host(e, ne), f32::from_bits(v[k + j]), ex.gu_scale[e]) + }).collect(); + let y = run_experts(&list, &h, &cfg); + unsafe { std::ptr::copy_nonoverlapping(y.as_ptr(), at(lay.y) as *mut f32, lay.n) }; + fence(Ordering::SeqCst); + unsafe { at(DONE).write_volatile(seq) }; + fence(Ordering::SeqCst); + bn.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed); + } + } + }))?; + Ok(InkWorker { _mem: mem, host, dev, layout, seq: 0, tx: Some(tx), stop, busy_ns, thread: Some(thread) }) + } + + /// Start a token: the sequence number the kernels must find in `step[1]`. + pub fn begin(&mut self) -> u32 { + self.seq = self.seq.wrapping_add(1).max(1); + let _ = self.tx.as_ref().unwrap().send(self.seq); + self.seq + } + + /// Mailbox of run `il` on the device. + pub fn mb(&self, il: usize) -> u64 { self.dev + (4 * il * self.layout.stride) as u64 } + + /// The routing of run `il` in the last token: (expert, slot or -1) for each of its k experts. + pub fn routing(&self, il: usize) -> Vec<(usize, i32)> { + let k = self.layout.k; + let mut v = vec![0u32; (3 * k).next_multiple_of(4)]; + unsafe { read_wc((self.host as *const u32).add(il * self.layout.stride + IDS), &mut v) }; + (0..k).map(|j| (v[j] as usize, v[2 * k + j] as i32)).collect() + } + + /// Time the worker spent computing experts. + pub fn busy(&self) -> std::time::Duration { std::time::Duration::from_nanos(self.busy_ns.load(Ordering::Relaxed)) } +} + +impl Drop for InkWorker { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + self.tx = None; + if let Some(t) = self.thread.take() { let _ = t.join(); } + } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index e250560b..6220c632 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -65,8 +65,18 @@ pub fn backends() -> Vec<(&'static str, Box)> { } else { eprintln!("SKIP: vulkan (filtered)"); } + if wanted("hip") { + match rusting_strata::hip::Gpu::new(0) { + Ok(g) => v.push(("hip", Box::new(g))), + // A missing runtime and a missing hiprtc both carry "HIP init" in the chain, the second under more context. + Err(e) if e.chain().any(|c| c.to_string() == "HIP init") => eprintln!("SKIP: hip: {e:#}"), + Err(e) => panic!("{e:#}"), + } + } else { + eprintln!("SKIP: hip (filtered)"); + } if let Some(sel) = sel { - for name in sel.iter().filter(|n| !matches!(n.as_str(), "cuda" | "vulkan")) { + for name in sel.iter().filter(|n| !matches!(n.as_str(), "cuda" | "vulkan" | "hip")) { eprintln!("SKIP: {name} (filtered)"); } } diff --git a/tests/inkling2_ctrl.rs b/tests/inkling2_ctrl.rs index 5a56f44d..b783322b 100644 --- a/tests/inkling2_ctrl.rs +++ b/tests/inkling2_ctrl.rs @@ -17,7 +17,7 @@ fn tiled_controllers_match_per_token() { unsafe { std::env::set_var("STRATA_DS_FAST_KERNELS", "1") }; for (bk, gpu) in common::backends() { let gpu = &*gpu; - if bk != "cuda" { continue; } + if bk != "cuda" && bk != "hip" { continue; } let (rank, count, n, nt) = (4usize, 3usize, 128usize, 64usize); let down_w: Vec = xs(count * rank * 2 * n + 7)[7..].iter().map(|&v| half::f16::from_f32(v * 0.25).to_bits()).collect(); let gain_w: Vec = xs(count * rank * n + 13)[13..].iter().map(|&v| half::f16::from_f32(v * 0.25).to_bits()).collect(); diff --git a/tests/inkling2_prefill.rs b/tests/inkling2_prefill.rs index 098046d4..f8bfb293 100644 --- a/tests/inkling2_prefill.rs +++ b/tests/inkling2_prefill.rs @@ -21,9 +21,9 @@ fn ink_attn_prefill_kp16_fallback_covers_every_query() { unsafe { std::env::set_var("STRATA_DS_FAST_KERNELS", "1") }; for (bk, gpu) in common::backends() { let gpu = &*gpu; - // kp16 is the CUDA f16-cache path; Vulkan has its own prefill, and a quantized KV or the measurement knobs - // select another kernel. - if bk != "cuda" + // kp16 is the f16-cache path of the CUDA and HIP backends; Vulkan has its own prefill, and a quantized KV + // or the measurement knobs select another kernel. + if (bk != "cuda" && bk != "hip") || std::env::var_os("STRATA_KV").is_some() || std::env::var_os("STRATA_DS_ATTN_OLD").is_some() || std::env::var_os("STRATA_DS_ATTN_KP4").is_some() { continue; }