Skip to content
Merged
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
34 changes: 34 additions & 0 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,48 @@ other MCP clients use, and pass it with `--mcp <file>` (or `STRATA_MCP`; the def
Drafts only pay when most experts are in VRAM: on the 12 GB reference machine with the IQ2_XS file (CPU experts
on most tokens) `--mtp 1` decodes slower than no drafts. With a `--device 0,1` split the head runs on the
last device (EAGLE3 heads excepted: those decode without drafts on a split).
- `--draft-model PATH` speculative decoding with a separate draft model (needs `--gpu` and one stream, so not with
`--parallel`). The target checks every drafted token, so a draft never decides a token; sampling keeps its
distribution. As with `--mtp`, the batched check rounds differently from one-token decoding, so greedy output can
differ from a run without drafts at a near tie. Two kinds of file work:
- a DFlash or DFlash2 draft: a small block-diffusion model trained for one target model. It reads hidden states
of the target and predicts a whole block of tokens in one pass; the target then checks the block in one
batched pass and keeps the tokens that match. `--mtp N` caps the drafted tokens per step (default: the
draft's block size minus one). The draft must be made for this target: its embedding width, its target
layers and its tensor shapes are checked at load, and a file that does not fit is refused. When the target
GGUF has its own MTP head, the DFlash draft is used instead of that head.
- an ordinary smaller model with the same vocabulary as the target (default `--mtp 4`).

`PATH` is a `.gguf` file, a Hugging Face `.safetensors` file with its `config.json` next to it, or a
directory holding either. Safetensors DFlash checkpoints are converted once and written next to the source as
`model-dflash-q4_0.gguf` (`STRATA_DFLASH_Q8=1` writes and reads `model-dflash-q8_0.gguf`;
`STRATA_DFLASH_RECONVERT=1` converts again). `STRATA_DFLASH_BLOCK=N` fixes the block size instead of adapting
it to how many drafts are accepted.
- `--spec-type LIST` drafts from text that is already in the context, with no draft model: a comma-separated
list of `suffix`, `ngram-simple`, `ngram-map-k`, `ngram-map-k4v`, `ngram-mod`, `ngram-cache`. It pays on
output that repeats the prompt (code edits, quoting, structured data). It combines with `--mtp`,
`--mtp-model` and `--draft-model`: the lookup drafts when it finds a match (next to a DFlash draft, only on a
long match) and the model drafts otherwise.
- `--chunk`, `--threads` prefill chunk size and CPU expert threads. On a GPU `--threads` defaults to the physical
core count (SMT siblings only add contention; on the 6-core/12-thread reference machine 6 beats 12 by ~20%).
`rustingstrata calibrate` measures the best chunk and later runs read it from
`~/.cache/rusting_strata/strata-<model>.json` unless flags override.
- `STRATA_AVX512=1` uses the AVX-512 kernels for experts that run on the CPU, in a build for a CPU that has
AVX-512 VNNI and VBMI (a `target-cpu=native` build on such a machine; the release binaries do not have them). Their
results differ from the default kernels in the last bits, so greedy output can change at a near tie.
- `--vram-margin` MB of VRAM left free. One value applies to every device; `512,256` gives one per device in
`--device` order, and `0:512,1:256` gives one per GPU index. On a GPU that drives no display, `--vram-margin 256` keeps more experts
resident (+1-2% prefill); 128 runs out of memory.
- `--kv q8` halves the KV cache (345 instead of 650 MB at 32K) at about 6% slower 32K decode and 14% slower 32K prefill.
`--kv q4` and `--kv q2` store it in 4-bit and 2-bit form (about 28% and 19% of the f16 size) for very long
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.
- `--thinking-budget N` (`chat` and `serve`) ends the thinking block after `N` tokens by inserting `</think>`,
so the model goes on to the answer (0, the default, is no limit). A request overrides it with
`thinking_budget` or `chat_template_kwargs.thinking_budget` (Anthropic: `thinking.budget_tokens`).
- `--short N` prompts shorter than `N` tokens skip the batched prefill and go token by token (default: from
`rustingstrata calibrate`, else 32).
- `--allowed-hosts ai-server.lan` (or `STRATA_ALLOWED_HOSTS`) allows a LAN name when `serve` is bound to `0.0.0.0`.
- `--lora PATH:SCALE` applies a LoRA adapter at runtime, see [LORA.md](LORA.md).
- `--mcp FILE` (`serve` only, or `STRATA_MCP`) lists the MCP servers whose tools the chat page may call, see
Expand Down
38 changes: 35 additions & 3 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,21 @@ const _: () = assert!(ATT_SPLITS <= 256); // attn_merge keeps one weight per spl
/// Positions per GEMM tile. Prefill cuts its tile lists at this size.
pub const GEMM_BM: usize = 128;

/// `len` bytes of device memory at device address `addr`, freed when the owner drops.
/// `len` bytes of device memory at device address `addr`, freed when the last clone drops.
#[derive(Clone)]
pub struct Buf {
addr: u64,
len: usize,
_owner: Box<dyn Any + Send + Sync>,
_owner: std::sync::Arc<dyn Any + Send + Sync>,
}

impl Buf {
pub fn new(addr: u64, len: usize, owner: impl Any + Send + Sync) -> Buf { Buf { addr, len, _owner: Box::new(owner) } }
pub fn new(addr: u64, len: usize, owner: impl Any + Send + Sync) -> Buf { Buf { addr, len, _owner: std::sync::Arc::new(owner) } }
pub fn addr(&self) -> u64 { self.addr }
pub fn len(&self) -> usize { self.len }
}

#[derive(Clone)]
pub struct GpuTensor {
pub ty: GgmlType,
pub rows: usize,
Expand Down Expand Up @@ -85,6 +87,10 @@ pub trait Backend: Send {
fn name(&self) -> &'static str;
/// The GPU's name as the driver reports it.
fn device(&self) -> String;
/// Create a lightweight handle sharing the same underlying GPU device/context for an auxiliary draft model.
fn share(&self) -> anyhow::Result<Box<dyn Backend>> {
anyhow::bail!("backend {} does not support device sharing", self.name())
}
/// Zeroed buffer of `bytes` (at least 1).
fn alloc(&self, bytes: usize) -> anyhow::Result<Buf>;
fn htod(&self, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()>;
Expand Down Expand Up @@ -157,6 +163,12 @@ pub trait Backend: Send {
}
}

fn upload_raw(&self, t: &Tensor) -> anyhow::Result<GpuTensor> {
let b = self.alloc(t.data.len())?;
self.htod(t.data, &b, 0)?;
Ok(GpuTensor::new(t.ty, t.rows, t.cols, b))
}

/// u16 words of a KV cache for `n` values: f16, or q8 with one f16 scale per 32 values.
fn kv_words(&self, n: usize) -> usize;
/// 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
Expand All @@ -182,6 +194,19 @@ pub trait Backend: Send {
self.gemvq(a, x, x_stride, xq, ya, a.rows, nt)?;
self.gemvq(b, x, x_stride, xq, yb, b.rows, nt)
}
/// Whether this backend supports indexed-row GEMV (`gemv_rows`).
fn supports_gemv_rows(&self) -> bool { false }
/// `y[i] = W[ids[i]] x` for `i < n_rows` (indexed subset of rows of `w`).
fn gemv_rows(&self, _w: &GpuTensor, _x: u64, _ids: u64, _n_rows: usize, _y: u64) -> anyhow::Result<()> {
anyhow::bail!("gemv_rows unsupported on this backend")
}
/// `y[t * n_rows + i] = W[ids[i]] x[t]` for `t < nt`, `i < n_rows`.
fn gemv_rows_n(&self, w: &GpuTensor, x: u64, x_stride: usize, _xq: u64, ids: u64, n_rows: usize, y: u64, nt: usize) -> anyhow::Result<()> {
for t in 0..nt {
self.gemv_rows(w, x + (t * x_stride * 4) as u64, ids, n_rows, y + (t * n_rows * 4) as u64)?;
}
Ok(())
}
/// For j < k with ids[j] >= 0: y[j] = W_j x[j / xg], where W_j is the `rows` x `cols` matrix at w + ids[j] * stride
/// bytes. `pair` = (w2, y2) also computes the same product for the matrices at byte offset w2 into the output at
/// byte offset y2. `xq` (not 0): x pre-quantized by `quant_xq` (k / xg rows), read in place of x.
Expand Down Expand Up @@ -256,8 +281,15 @@ pub trait Backend: Send {
/// `interleave`: value head h reads key head h / (nv / nk), else h % nk.
/// `dt_bias` not 0: beta and g are raw, and the kernel applies `ssm_gates` (with `dt_bias` and `a`) as it reads them.
fn deltanet(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize) -> anyhow::Result<()>;
/// Stride (in tokens) between saved DeltaNet checkpoints in `snap` (`1` saves every token, `4` saves every 4th token).
fn delta_snap_stride(&self) -> usize { 1 }
fn deltanet_strided(&self, y: u64, s: u64, beta: u64, g: u64, dt_bias: u64, a: u64, o: u64, nk: usize, nv: usize, interleave: bool, dk: usize, dv: usize, scale: f32, t: usize, ych: usize, snap: u64, nsnap: usize, _snap_stride: usize) -> anyhow::Result<()> {
self.deltanet(y, s, beta, g, dt_bias, a, o, nk, nv, interleave, dk, dv, scale, t, ych, snap, nsnap)
}
/// Causal conv + SiLU over `t` tokens of `ch` channels, then roll the conv state forward (snapshots as in `deltanet`).
fn conv_seq(&self, qkv: u64, state: u64, w: u64, y: u64, ch: usize, kw: usize, t: usize, snap: u64, nsnap: usize) -> anyhow::Result<()>;
/// Grouped dynamic causal convolution for DFlash2 (`part = 0` prepare, `part = 1` finish).
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<()>;
/// `qg` 0: no output gate.
fn attn_prefill(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32) -> anyhow::Result<()> {
self.attn_prefill_m(q, kc, vc, qg, out, step, t, nh, nkv, hd, scale, 0, 0, 0, 0)
Expand Down
115 changes: 107 additions & 8 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,35 @@ pub struct Eagle3Config {
pub d2t: Vec<i32>,
}

/// Standalone DFlash parallel block-diffusion draft model parameters.
#[derive(Clone, Debug)]
pub struct DFlashConfig {
pub target_layer_ids: Vec<usize>,
pub block_size: usize,
pub mask_token_id: u32,
pub n_layer: usize,
pub n_embd: usize,
pub n_ff: usize,
pub n_head: usize,
pub n_head_kv: usize,
pub head_dim: usize,
pub n_rot: usize,
pub rope_base: f32,
pub eps: f32,
pub sliding_window: usize,
pub layer_swa: Vec<bool>,
pub input_embedding_scale: f32,
pub output_multiplier: f32,
pub conv_kernel_size: usize,
pub conv_group_size: usize,
pub selector_rank: usize,
pub selector_top_k: usize,
}

impl DFlashConfig {
pub fn is_dflash2(&self) -> bool { self.selector_rank > 0 }
}

/// What differs between the supported architectures; everything else comes from GGUF metadata.
struct Arch {
/// DeltaNet layers with full attention every `full_attention_interval` layers; otherwise all attention.
Expand All @@ -37,8 +66,16 @@ struct Arch {

fn arch(name: &str) -> Option<Arch> {
const FFN_NORM: &[(&str, &str)] = &[("post_attention_norm.weight", "ffn_norm.weight")];
const SENSENOVA_LOOP: &[(&str, &str)] = &[
("mhc_attn.weight", "hc_attn_fn.weight"),
("mhc_attn.bias", "hc_attn_fn.bias"),
("mhc_ffn.weight", "hc_ffn_fn.weight"),
("mhc_ffn.bias", "hc_ffn_fn.bias"),
];
Some(match name {
"qwen35" | "qwen35moe" => Arch { hybrid: true, q_gate: true, k_interleave: false, aliases: &[] },
// SenseNova-Loop: Qwen3.5 hybrid DeltaNet/Attn with shared-weight looped middle layers and mHC Sinkhorn routing.
"sensenova_loop" => Arch { hybrid: true, q_gate: true, k_interleave: false, aliases: SENSENOVA_LOOP },
// Qwen3.8-Flash-Next: qwen35-style DeltaNet pairing, plus hyper-connections and PLE read from metadata.
"qwen4exp" => Arch { hybrid: true, q_gate: true, k_interleave: false, aliases: &[] },
"qwen3next" => Arch { hybrid: true, q_gate: true, k_interleave: true, aliases: &[] },
Expand Down Expand Up @@ -93,6 +130,12 @@ pub struct ModelConfig {
/// Hyper-connection residual streams and their low rank (qwen4exp; 0 = plain residual).
pub hc_n: usize,
pub hc_rank: usize,
/// SenseNova-Loop manifold-constrained hyper-connection (mHC) stream count (0 = none) and per-layer phase flags
/// (`0` = plain, `1` = enter, `4` = carry, `2` = leave, `3` = enter+leave).
pub mhc_streams: usize,
pub mhc_layer_kinds: Vec<u8>,
/// Physical weight layer index for each virtual execution layer `0..n_layer` (`phys_layer[il] == il` unless looped).
pub phys_layer: Vec<usize>,
/// Per-layer (n-gram) embedding width (qwen4exp; 0 = none).
pub n_embd_ple: usize,
/// QSA sparse attention indexer (qwen4exp): heads, head size, and the number of cells kept per row
Expand All @@ -106,13 +149,14 @@ pub struct ModelConfig {
pub k_interleave: bool,
pub aliases: &'static [(&'static str, &'static str)],
pub eagle3: Option<Eagle3Config>,
pub dflash: Option<DFlashConfig>,
}

impl ModelConfig {
pub fn from_gguf(g: &Gguf) -> anyhow::Result<ModelConfig> {
let arch = g.get("general.architecture")?.as_str().context("general.architecture")?.to_string();
let Some(a) = self::arch(&arch) else {
bail!("unsupported architecture '{arch}' (supported: qwen3, qwen3moe, qwen3next, qwen35, qwen35moe, qwen4exp, flint)")
bail!("unsupported architecture '{arch}' (supported: qwen3, qwen3moe, qwen3next, qwen35, qwen35moe, qwen4exp, flint, sensenova_loop)")
};
let opt = |k: &str| g.meta.get(&format!("{arch}.{k}")).and_then(|v| v.as_u64()).unwrap_or(0) as usize;
let req = |k: &str| -> anyhow::Result<usize> {
Expand All @@ -122,7 +166,19 @@ impl ModelConfig {
let f = |k: &str| g.meta.get(&format!("{arch}.{k}")).and_then(|v| v.as_f32());
let n_nextn = opt("nextn_predict_layers");
let n_layer = req("block_count")? - n_nextn;
let layers: Vec<LayerKind> = if a.hybrid {
let flags = |k: &str| -> anyhow::Result<Option<Vec<bool>>> {
let key = format!("{arch}.{k}");
let Some(v) = g.meta.get(&key) else { return Ok(None) };
let a = v.as_arr().with_context(|| format!("{key}: not an array"))?;
anyhow::ensure!(a.len() >= n_layer, "{key} has {} entries for {n_layer} layers", a.len());
Ok(Some(a[..n_layer].iter().map(|v| match v {
crate::gguf::Value::Bool(b) => *b,
_ => v.as_u64().unwrap_or(0) != 0,
}).collect()))
};
let layers: Vec<LayerKind> = if let Some(rec) = flags("attention.recurrent_layers")? {
rec.into_iter().map(|r| if r { LayerKind::Delta } else { LayerKind::Attn }).collect()
} else if a.hybrid {
let every = match opt("full_attention_interval") { 0 => 4, v => v };
(0..n_layer).map(|il| if (il + 1) % every == 0 { LayerKind::Attn } else { LayerKind::Delta }).collect()
} else {
Expand All @@ -136,13 +192,52 @@ impl ModelConfig {
anyhow::ensure!(n_expert <= 512, "{n_expert} experts (at most 512 supported)");
let n_dense = opt("leading_dense_block_count");
anyhow::ensure!(n_dense <= n_layer, "{n_dense} leading dense blocks for {n_layer} layers");
let flags = |k: &str| -> anyhow::Result<Option<Vec<bool>>> {
let key = format!("{arch}.{k}");
let Some(v) = g.meta.get(&key) else { return Ok(None) };
let a = v.as_arr().with_context(|| format!("{key}: not an array"))?;
anyhow::ensure!(a.len() >= n_layer, "{key} has {} entries for {n_layer} layers", a.len());
Ok(Some(a[..n_layer].iter().map(|v| v.as_u64().unwrap_or(0) != 0).collect()))
let mhc_streams = opt("mhc.streams");
let loop_start = opt("loop.start");
let loop_end = opt("loop.end");
let loop_count = opt("loop.count").max(1);
let mhc_layer_kinds: Vec<u8> = match g.meta.get(&format!("{arch}.mhc.layer_kinds")).and_then(|v| v.as_arr()) {
Some(arr) if arr.len() >= n_layer => arr[..n_layer].iter().map(|v| v.as_u64().unwrap_or(0) as u8).collect(),
_ if mhc_streams > 0 && opt("mhc.end") > opt("mhc.start") => {
let (ms, me) = (opt("mhc.start"), opt("mhc.end"));
let total_mhc = (ms + (me - ms) * loop_count).min(n_layer);
(0..n_layer).map(|il| {
if il < ms || il >= total_mhc { 0 }
else if il == ms { 1 }
else if il + 1 == total_mhc { 2 }
else { 4 }
}).collect()
}
_ => Vec::new(),
};
anyhow::ensure!(mhc_streams == 0 || matches!(mhc_streams, 2 | 4), "unsupported mhc.streams {mhc_streams} (expected 2 or 4)");
let has_blk = |il: usize| {
g.tensors.contains_key(&format!("blk.{il}.attn_norm.weight"))
|| g.tensors.contains_key(&format!("blk.{il}.hc_attn_norm.weight"))
};
let loop_span = if loop_end > loop_start {
Some((loop_start, loop_end))
} else if !mhc_layer_kinds.is_empty() {
let s = mhc_layer_kinds.iter().position(|&k| k & 1 != 0);
let e = s.and_then(|st| mhc_layer_kinds[st..].iter().position(|&k| k & 2 != 0).map(|o| st + o + 1));
s.zip(e).filter(|&(st, en)| en > st)
} else {
None
};
let first_missing = (0..n_layer).find(|&il| !has_blk(il));
let phys_layer: Vec<usize> = (0..n_layer).map(|il| {
if has_blk(il) {
il
} else if let Some((st, en)) = loop_span {
st + (il.saturating_sub(st)) % (en - st)
} else if let Some(fm) = first_missing.filter(|&fm| fm > 0) {
let miss_end = (fm..n_layer).find(|&j| has_blk(j)).unwrap_or(n_layer);
let span = (miss_end - fm).min(fm).max(1);
(fm - span) + (il - fm) % span
} else {
il
}
}).collect();
let swa = flags("attention.sliding_window_pattern")?.unwrap_or_else(|| vec![false; n_layer]);
let rope_layer = flags("attention.rope_pattern")?.unwrap_or_else(|| vec![true; n_layer]);
let n_swa = opt("attention.sliding_window");
Expand Down Expand Up @@ -184,6 +279,9 @@ impl ModelConfig {
ssm_conv: ssm("ssm.conv_kernel")?,
hc_n: opt("hyper_connection.count"),
hc_rank: opt("hyper_connection.low_rank"),
mhc_streams,
mhc_layer_kinds,
phys_layer,
n_embd_ple: opt("embedding_length_per_layer_input"),
idx_n_head: opt("attention.indexer.head_count"),
idx_head_dim: opt("attention.indexer.key_length"),
Expand All @@ -194,6 +292,7 @@ impl ModelConfig {
aliases: a.aliases,
arch,
eagle3: None,
dflash: None,
};
// Kernels divide by these and index value heads by nv / nk key heads.
let (nk, nv) = (c.ssm_n_group, c.ssm_dt_rank);
Expand Down
Loading
Loading