Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ other MCP clients use, and pass it with `--mcp <file>` (or `STRATA_MCP`; the def
contexts. Attention then reads rounded keys and values, so the output can differ from f16; q2 differs most.
The head size must be a multiple of 32, and `--llama-numerics` needs the f16 cache. `calibrate` takes the
same `--kv` value as the runs that will use it.
- `--kv turbo4` (CUDA) uses TurboQuant: each 128-value K/V block is signed-Walsh rotated, quantized with
4-bit Lloyd-Max centroids, and stored in about 28% of the f16 cache size. Q is rotated by the same transform
when the K cache is TurboQuant, and the attention output is de-rotated when the V cache is TurboQuant.
`--kv turbo4-3`, `turbo4-2`, `turbo3`, `turbo2` and `turbo3-2` select narrower K/V centroids.
- `--k TYPE` and `--v TYPE` set the two cache formats independently (CUDA). Either half may be `f16`, `q8`,
`q4`, `q2`, `turbo4`, `turbo3` or `turbo2`; for example `--k f16 --v q4` or `--k turbo4 --v turbo3`.
A mixed layout allocates each half with its own word width. The Vulkan backend only supports symmetric
legacy formats. Text can differ from f16 because attention reads rounded keys and values.
- `calibrate --mtp-model PATH` or `--draft-model PATH` measures with that draft file loaded, so the chunk and the
expert placement see the VRAM it takes, and picks the draft count. Runs with the same `--mtp-model` or
`--draft-model` file use that count unless `--mtp` is given; runs with another draft file or none do not.
Expand Down
5 changes: 4 additions & 1 deletion src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,11 @@ pub trait Backend: Send {
Ok(GpuTensor::new(t.ty, t.rows, t.cols, b).with_scale(t.scale))
}

/// u16 words of a KV cache for `n` values: f16, or q8 with one f16 scale per 32 values.
/// u16 words of a KV cache row for `n` values in the K format (and, separately, the V format).
/// `kv_row_words` is the size of one K row plus one V row.
fn kv_words(&self, n: usize) -> usize;
fn kv_words_v(&self, n: usize) -> usize { self.kv_words(n) }
fn kv_row_words(&self, n: usize) -> usize { self.kv_words(n) + self.kv_words_v(n) }
/// GEMM over a tile list: for each tile, positions m0 .. m0 + cnt get y[m, 0..rows] = W_tile x[xrow[m]] (x row m
/// when `xrow` is 0). `tiles` is a device array of [w, m0 | cnt << 32]. `act`: 0 stores, 1 computes
/// y = silu(y) * result (SwiGLU with the gate already in y), 2 adds to y; `| SAME_X` as below. `n_x`: rows of x
Expand Down
698 changes: 551 additions & 147 deletions src/cuda/kernels.cu

Large diffs are not rendered by default.

133 changes: 92 additions & 41 deletions src/cuda/mod.rs

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions src/gpu_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ impl<'a> GpuModel<'a> {
qn: lt(il, "attn_q_norm.weight")?, kn: lt(il, "attn_k_norm.weight")?, o: lt(il, "attn_output.weight")?,
sink: if c.attn_sinks { Some(lt(il, "attn_sinks.weight")?) } else { None },
kc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * kv))).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * kv))).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words_v(ctx * kv))).collect::<anyhow::Result<_>>()?,
qsa: if qsa_on && il < c.n_layer && m.w.layer(il, "indexer.k_proj.weight").is_ok() {
Some(Qsa {
kp: lt(il, "indexer.k_proj.weight")?, qp: lt(il, "indexer.q_proj.weight")?,
Expand Down Expand Up @@ -820,7 +820,7 @@ impl<'a> GpuModel<'a> {
Some(DFlashConv { base: df_lt("mlp_conv_base")?, proj: df_lt("mlp_conv_proj")? })
} else { None },
kc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * df_kv))).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * df_kv))).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words_v(ctx * df_kv))).collect::<anyhow::Result<_>>()?,
is_swa: dc.layer_swa.get(il).copied().unwrap_or(false),
});
}
Expand Down Expand Up @@ -905,7 +905,7 @@ impl<'a> GpuModel<'a> {
kn: lt(il, "nextn.hnorm.weight")?,
o: lt(il, "attn_output.weight")?,
kc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * eg_kv))).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * eg_kv))).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words_v(ctx * eg_kv))).collect::<anyhow::Result<_>>()?,
qsa: None,
sink: None,
},
Expand Down Expand Up @@ -1109,7 +1109,7 @@ impl<'a> GpuModel<'a> {
let mb = |b: usize| b as f64 / 1048576.0;
crate::say!(
"plan: weights+state+scratch {:.0} MB (KV {:.0} MB for {ctx} tokens{}, prefill {:.0} MB), expert slots {:.0} MB, resident experts {}/{}",
mb(free0.saturating_sub(free1)), mb(2 * 2 * gpu.kv_words(ctx * kv) * c.layers[range.clone()].iter().filter(|&&k| k == LayerKind::Attn).count()),
mb(free0.saturating_sub(free1)), mb((gpu.kv_words(ctx * kv) + gpu.kv_words_v(ctx * kv)) * 2 * c.layers[range.clone()].iter().filter(|&&k| k == LayerKind::Attn).count()),
if ns > 1 { format!(" in each of {ns} slots") } else { String::new() }, mb(pf.as_ref().map_or(0, |p| p.bytes())),
mb(cache.as_ref().map_or(0, |x| x.slot_bytes_total())),
cache.as_ref().map_or(0, |x| x.resident_count()), cache.as_ref().map_or(0, |x| x.total_experts()),
Expand Down
29 changes: 15 additions & 14 deletions src/inkling2/forward/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl PrefillScratch {
let p = PrefillLayout::at(buf.addr(), c, rank, max_nt);
let acc_buf = be.alloc(4 * max_nt * c.n_embd)?;
let kw = c.n_head_kv * c.head_dim;
let rb = 2 * be.kv_words(kw);
let rb = be.kv_row_words(kw);
let kv_bytes = max_nt * rb;
let (kc_tmp, vc_tmp) = (be.alloc(kv_bytes)?, be.alloc(kv_bytes)?);
let max_np = max_nt * c.n_used;
Expand Down Expand Up @@ -254,8 +254,8 @@ impl Device {
[l.wq, l.wk, l.wv, l.wo, l.gate, l.rel, l.sink].iter().chain(l.conv_proj.iter().flatten()).all(dense)
}) { return None; }
let rows: usize = (0..c.n_slot()).map(|il| if c.swa[layer_of(c, il)] { c.n_swa } else { full }).sum();
let row_words = d.parts[0].be.kv_words(kw);
room(&mut d, 4 * rows * row_words + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20));
let kv_bytes = 2 * rows * d.parts[0].be.kv_row_words(kw);
room(&mut d, kv_bytes + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20));
}
let made = (|| -> Result<Self> {
let (mut layers, loops, slots, out_query, out_norm, scr, sc_buf) = {
Expand All @@ -277,10 +277,10 @@ impl Device {
let loops = m.loops.iter().map(|l| {
Ok(DLoop { msg_query: up(be, &l.msg_query)?, down: half(&l.down)?, gain: half(&l.gain)?, forget: half(&l.forget)? })
}).collect::<Result<Vec<_>>>()?;
let row_words = be.kv_words(kw);
let (kwk, kwv) = (be.kv_words(kw), be.kv_words_v(kw));
let slots = (0..c.n_slot()).map(|il| {
let rows = if c.swa[layer_of(c, il)] { c.n_swa } else { full };
Ok(DSlot { k: be.alloc(2 * rows * row_words)?, v: be.alloc(2 * rows * row_words)?, hist: be.zeros::<f32>(hists(c).1)?, cap: rows })
Ok(DSlot { k: be.alloc(2 * rows * kwk)?, v: be.alloc(2 * rows * kwv)?, hist: be.zeros::<f32>(hists(c).1)?, cap: rows })
}).collect::<Result<Vec<_>>>()?;
let sc_buf = be.alloc(sc_bytes(c, (pos + 1).max(64)))?;
let (out_query, out_norm, scr) = (up(be, &m.out_query)?, up(be, &m.out_norm)?, be.alloc(Scratch::at(0, c, rank, m.output.rows).end as usize)?);
Expand Down Expand Up @@ -354,14 +354,14 @@ impl Device {
let be = &*d.parts[0].be;
let len = hists(c).1;
let kw = c.n_head_kv * c.head_dim;
let swa_words = c.n_swa * be.kv_words(kw);
let (swa_k, swa_v) = (c.n_swa * be.kv_words(kw), c.n_swa * be.kv_words_v(kw));
let mut dev_hist = Vec::with_capacity(self.slots.len());
let mut dev_swa = Vec::with_capacity(self.slots.len());
for (il, ds) in self.slots.iter().enumerate() {
dev_hist.push(be.get(&ds.hist, 0, len).expect("inkling2 save_checkpoint hist"));
if c.swa[layer_of(c, il)] {
let k: Vec<u16> = be.get(&ds.k, 0, swa_words).expect("inkling2 save_checkpoint swa k");
let v: Vec<u16> = be.get(&ds.v, 0, swa_words).expect("inkling2 save_checkpoint swa v");
let k: Vec<u16> = be.get(&ds.k, 0, swa_k).expect("inkling2 save_checkpoint swa k");
let v: Vec<u16> = be.get(&ds.v, 0, swa_v).expect("inkling2 save_checkpoint swa v");
dev_swa.push(Some((k, v)));
} else {
dev_swa.push(None);
Expand Down Expand Up @@ -397,13 +397,13 @@ impl Device {
let need = need_pos + 1;
ensure!(need <= m.max_ctx, "context is limited to {} tokens", m.max_ctx);
let mut d = dev::get().unwrap().lock().unwrap();
let row_words = d.parts[0].be.kv_words(kw);
let (kwk, kwv) = (d.parts[0].be.kv_words(kw), d.parts[0].be.kv_words_v(kw));
let full_cap = self.slots.iter().enumerate().find(|&(il, _)| !c.swa[layer_of(c, il)]).map(|(_, s)| s.cap);
if let Some(cap) = full_cap && need > cap {
let mut new_cap = cap;
while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); }
let n = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count();
room(&mut d, 4 * n * new_cap * row_words + sc_bytes(c, new_cap) + (128 << 20));
room(&mut d, 2 * n * new_cap * (kwk + kwv) + sc_bytes(c, new_cap) + (128 << 20));
}
let be = &*d.parts[0].be;
let need_sc = sc_bytes(c, need);
Expand All @@ -415,8 +415,9 @@ impl Device {
if c.swa[layer_of(c, il)] || need <= s.cap { continue; }
let mut new_cap = s.cap;
while new_cap < need { new_cap = (new_cap * 2).min(m.max_ctx); }
for b in [&mut s.k, &mut s.v] {
let new = be.alloc(2 * new_cap * row_words)?;
// K and V are separate buffers with their own word width; sizing both with their sum doubles f16.
for (b, words) in [(&mut s.k, kwk), (&mut s.v, kwv)] {
let new = be.alloc(2 * new_cap * words)?;
be.dtod(b, 0, &new, 0, b.len())?;
be.sync()?; // the copy reads the buffer that `*b = new` frees
*b = new;
Expand Down Expand Up @@ -977,7 +978,7 @@ impl Device {
let d = dev::get().unwrap().lock().unwrap();
let be = &*d.parts[0].be;
let pf = self.pf.as_ref().unwrap();
let rb = 2 * be.kv_words(kw);
let rb = be.kv_row_words(kw);
for (il, ds) in self.slots.iter().enumerate() {
let ip = layer_of(c, il);
if m.layers[ip].swa {
Expand Down Expand Up @@ -1089,7 +1090,7 @@ impl Device {
be.ink_conv_batch(p.k, l.convs[0].addr(), taps[0], hist(0), p.k2, kw, nc, hd, nt)?;
be.ink_conv_batch(p.v, l.convs[1].addr(), taps[1], hist(1), p.v2, kw, nc, hd, nt)?;
let log_alpha = if ml.swa { 0.0 } else { c.log_alpha };
let rb = 2 * be.kv_words(kw);
let rb = be.kv_row_words(kw);
be.ink_clip_n(p.q, l.q_clip.addr(), hd, nh, nt, c.qk_clip, 0.0, 1.0, 0, 0, 1, pos0, log_alpha, c.log_floor)?;
be.ink_clip_n(p.r, l.rel_clip.addr(), nr, nh, nt, c.rel_clip, 0.0, 1.0, 0, 0, 1, pos0, log_alpha, c.log_floor)?;
if verify_mode {
Expand Down
Loading
Loading