Skip to content
Open
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
5 changes: 5 additions & 0 deletions docs/HIP.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,11 @@ By default HIP runs Inkling 2 on the faster attention and controller kernels. Th
text can differ from the older kernels and from Vulkan at a near tie. `--fixed-experts` keeps the older kernels.
`STRATA_DS_FAST_KERNELS=0` selects the older kernels, and `1` the faster ones under `--fixed-experts` too.

On WMMA cards the prompt attention is `ink_attn_prefill_128_wm` and the decode attention `ink_attn_128_g3`
(three query heads sharing a KV head in one block). Both run the `q8` cache format on either side, so `--kv` pairs
like `f16-q8` and `q8` keep the fast kernels: q8 K rows ride through shared memory as packed 8-byte units and are
expanded there, halving the KV memory for 1038 pp / 48.1 tok/s against f16's 1200 / 50.4.

`bench --pp 512,4096 --tg 64`, alternating runs with a browser open on the desktop:

| | pp 4096 | decode |
Expand Down
5 changes: 4 additions & 1 deletion src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ unsafe impl Plain for u64 {}
/// Pointer arguments are device addresses; strides are in floats unless named otherwise.
/// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan.
/// Refuses a `--device` list with several indices on the HIP backend: `hip::Gpu` opens one device per process
/// (hipSetDevice runs once, in `Gpu::new`), so a split over two cards would run both layers on the first one.
/// (`hipSetDevice` is per-thread, so every thread that calls into a `Gpu` reselects its card), so a split over two
/// cards would run both layers on the first one.
pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<()> {
if kind == Some("hip") && devices.len() > 1 {
anyhow::bail!("the hip backend runs one device: --device {} needs cuda or vulkan", devices.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(","));
Expand Down Expand Up @@ -215,6 +216,8 @@ pub trait Backend: Send {
/// Free the graph recorded under `key`, if there is one. For a caller whose keys change as it runs (a graph holds
/// device memory, and CUDA stops recording at a fixed number of them).
fn graph_drop(&self, _key: u64) -> anyhow::Result<()> { Ok(()) }
/// Whether the stream is recording a graph right now: no synchronous call may be issued inside one.
fn capturing(&self) -> bool { false }
/// Free every recorded graph, after buffers they use were replaced (a slot's KV cache grew).
fn graph_clear(&self) -> anyhow::Result<()> { Ok(()) }
/// Queue the ops of `f`, none of which reads what another writes, with no ordering among them (Vulkan: no
Expand Down
530 changes: 521 additions & 9 deletions src/cuda/kernels.cu

Large diffs are not rendered by default.

86 changes: 55 additions & 31 deletions src/cuda/mod.rs

Large diffs are not rendered by default.

610 changes: 598 additions & 12 deletions src/hip/mod.rs

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion src/inkling2/forward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ impl DraftGate {
/// 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"];
const PROF: [&str; 11] = ["mix", "proj", "scores", "out-proj", "route", "experts-gpu", "experts-cpu", "logits", "attn", "ffn", "step"];

/// A tensor read from the mapped file only: never uploaded.
fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result<Mat<'a>> {
Expand Down Expand Up @@ -501,6 +501,9 @@ impl<'a> Inkling2Model<'a> {
unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.6,0.9"); }
}
let cfg = Inkling2Config::from_gguf(g)?;
crate::say!("inkling2: {} layers (core {}..{} x{}), n_embd {}, n_head {} @ head_dim {}, n_head_kv {}, n_expert {}, used {}, n_ff_exp {}, n_conv {}, window {}",
cfg.n_layer, cfg.loop_start, cfg.loop_end, cfg.loop_count, cfg.n_embd, cfg.n_head, cfg.head_dim,
cfg.n_head_kv, cfg.n_expert, cfg.n_used, cfg.n_ff_exp, cfg.n_conv, cfg.n_swa);
let has = |n: &str| g.tensors.contains_key(n);
let mut layers = vec![];
for il in 0..cfg.n_layer {
Expand Down
41 changes: 33 additions & 8 deletions src/inkling2/forward/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,19 +339,30 @@ impl Device {
pub(super) fn new(m: &Inkling2Model) -> Option<Self> {
let (c, pos) = (&m.cfg, m.toks.len());
let off = std::env::var("STRATA_DS_DEVICE").is_ok_and(|v| v == "0") || m.trace || std::env::var_os("STRATA_DS_DUMP").is_some();
if off || c.n_conv > 8 || 128 % c.head_dim != 0 || m.loops.is_empty() { return None; }
let decline = |why: &str| crate::say!("inkling2: device path declined ({why}); the tokens run as prompt chunks do");
if off { return None; }
if c.n_conv > 8 { decline(&format!("n_conv {}", c.n_conv)); return None; }
if 128 % c.head_dim != 0 { decline(&format!("head_dim {}", c.head_dim)); return None; }
if m.loops.is_empty() { decline("no core loop"); return None; }
let rank = m.loops[0].down[0].len() / (2 * c.n_embd);
if !shapes_fit(m, rank) { return None; }
if !shapes_fit(m, rank) { decline("shapes the kernels do not take"); return None; }
let (kw, nr, ext) = (c.n_head_kv * c.head_dim, c.n_rel, c.rel_extent);
let full = (2 * (pos + 1)).clamp(4096.min(m.max_ctx), m.max_ctx);
{
let mut d = dev::get()?.lock().unwrap();
let Some(g) = dev::get() else { decline("no GPU pool (STRATA_DS_GPU=0?)"); return None };
let mut d = g.lock().unwrap();
// Local patch: several GPUs are fine as long as the plain weights are on GPU 0 (see STRATA_DS_PLAIN_FIRST); the
// experts that live on another GPU run as a third share in `layer`.
let dense = |x: &Mat| !x.host_only() && d.on_first(x);
if !dense(&m.output) || !m.layers.iter().all(|l| {
[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; }
if !dense(&m.output) { decline("the output head is not in VRAM"); return None; }
if let Some((ip, name)) = m.layers.iter().enumerate().find_map(|(ip, l)| {
let bad = [("wq", &l.wq), ("wk", &l.wk), ("wv", &l.wv), ("wo", &l.wo), ("gate", &l.gate), ("rel", &l.rel), ("sink", &l.sink)]
.into_iter().find(|(_, x)| !dense(x)).map(|(n, _)| n)
.or(l.conv_proj.iter().flatten().find(|x| !dense(x)).map(|_| "conv_proj"));
bad.map(|n| (ip, n))
}) {
decline(&format!("layer {ip} weight {name} is not in VRAM")); 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 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));
Expand Down Expand Up @@ -505,6 +516,7 @@ impl Device {
d.parts[0].budget = d.parts[0].budget.saturating_sub(over);
}
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()));
crate::say!("inkling2: device path on: expert slabs {n_full}/{}, pool {}, everything on device: {}", n_full, pool.is_some(), all_full);
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())
Expand Down Expand Up @@ -728,11 +740,16 @@ impl Device {
if last != 0 && last != key { be.graph_drop(last)?; }
if !self.seg_graph {
be.graph(key, &mut || {
let prof = std::env::var_os("STRATA_DS_PROF").is_some() && !be.capturing();
let mut tt = std::time::Instant::now();
let mut nb = 0usize;
for il in 0..c.loop_start {
self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?;
if prof { be.sync()?; m.lap(8, tt); tt = std::time::Instant::now(); }
self.layer_ffn_gpu(be, m, il, il)?;
if prof { be.sync()?; m.lap(9, tt); tt = std::time::Instant::now(); }
}
if prof { be.sync()?; m.lap(0, tt); tt = std::time::Instant::now(); }
be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?;
let n_pre = nb;
for pass in 0..c.loop_count {
Expand All @@ -746,24 +763,32 @@ impl Device {
be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?;
nb = n_pre;
}
let pt = tt;
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)?;
if prof { be.sync()?; m.lap(8, tt); tt = std::time::Instant::now(); }
self.layer_ffn_gpu(be, m, il, ip)?;
if prof { be.sync()?; m.lap(9, tt); tt = std::time::Instant::now(); }
}
if prof { m.lap(1 + pass, pt); }
}
for il in c.loop_end..c.n_layer {
self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?;
if prof { be.sync()?; m.lap(8, tt); tt = std::time::Instant::now(); }
self.layer_ffn_gpu(be, m, il, il)?;
if prof { be.sync()?; m.lap(9, tt); tt = std::time::Instant::now(); }
}
if prof { be.sync()?; m.lap(4, tt); tt = std::time::Instant::now(); }
self.finish_logits(be, &d, m, nb)?;
if argmax {
be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?;
}
if prof { be.sync()?; m.lap(7, tt); }
Ok(())
})?;
} else {
Expand Down Expand Up @@ -968,7 +993,7 @@ impl Device {
if self.all_full || self.seg_graph {
let t = std::time::Instant::now();
let (logits, _) = self.step_fast(m, tok, false);
m.lap(7, t);
m.lap(10, t);
return logits;
}
let nb = self.step_layers(m, tok);
Expand All @@ -992,7 +1017,7 @@ impl Device {
if self.all_full || self.seg_graph {
let t = std::time::Instant::now();
let (_, id) = self.step_fast(m, tok, true);
m.lap(7, t);
m.lap(10, t);
return id;
}
let nb = self.step_layers(m, tok);
Expand Down
19 changes: 13 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,8 +211,9 @@ struct Engine {
#[arg(long, value_parser = parse_effort)]
reasoning_effort: Option<String>,
/// KV cache format (GPU): f16, q8 (q8_0, half KV memory), q4 (q4_0, quarter KV memory), or q2 (2-bit affine,
/// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16).
#[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo4-3", "turbo4-2", "turbo3", "turbo2", "turbo3-2"])]
/// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). A "K-V" pair like f16-q8 sets the two
/// cache types independently.
#[arg(long, default_value = "f16", value_parser = parse_kv_arg)]
kv: String,
/// K cache type; overrides the K half of `--kv`. Supported: f16, q8, q4, q2, turbo4, turbo3, turbo2.
#[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])]
Expand Down Expand Up @@ -253,13 +254,19 @@ struct Engine {
}

/// Resolve the independent K and V cache types. `--kv` supplies both unless `--k`/`--v` override a half.
fn parse_kv_arg(s: &str) -> Result<String, String> {
let valid = |x: &str| matches!(x, "f16" | "q8" | "q4" | "q2" | "turbo4" | "turbo3" | "turbo2" | "4" | "3" | "2");
if valid(s) || s.split_once('-').is_some_and(|(a, b)| valid(a) && valid(b)) { Ok(s.to_string()) }
else { Err(format!("unsupported --kv {s} (f16, q8, q4, q2, turbo4/3/2 or a pair like f16-q8)")) }
}

fn effective_kv(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result<(String, String)> {
let valid = |s: &str| matches!(s, "f16" | "q8" | "q4" | "q2" | "turbo4" | "turbo3" | "turbo2");
fn canon(s: &str) -> &str { match s { "4" => "turbo4", "3" => "turbo3", "2" => "turbo2", other => other } }
let base = match kv {
"turbo4-3" => ("turbo4", "turbo3"),
"turbo4-2" => ("turbo4", "turbo2"),
"turbo3-2" => ("turbo3", "turbo2"),
other => (other, other),
"turbo4v3" => ("turbo4", "turbo3"), "turbo4v2" => ("turbo4", "turbo2"), "turbo3v2" => ("turbo3", "turbo2"),
// "a-b" is a K/V pair, validated side by side below: "f16-q8", the legacy "turbo4-3" (short V names).
s => match s.split_once('-') { Some((a, b)) => (canon(a), canon(b)), None => (s, s) },
};
let (k, v) = match (k, v) {
(None, None) => base,
Expand Down
1 change: 1 addition & 0 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1866,6 +1866,7 @@ mod tests {

#[test]
fn sensenova_loop_mhc_cpu_matches_gpu() {
if crate::cuda::kv_mode() != 0 { eprintln!("skipping: quantized KV caches change the numerics"); return; }
let dir = std::env::temp_dir().join(format!("strata_snloop_test_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Expand Down