pub enum QTensor {
F32 {
data: Vec<f32>,
rows: usize,
cols: usize,
},
Mapped {
model: Arc<CmfModel>,
idx: usize,
dtype: TensorDtype,
rows: usize,
cols: usize,
row_scale: Vec<f32>,
col_field: Vec<f32>,
vbit_offsets: Vec<usize>,
repack: Vec<u8>,
},
}Variants§
F32
Mapped
Fields
dtype: TensorDtypevbit_offsets: Vec<usize>Vbit only: byte offset of each row’s packed data within the
tensor blob ([rows + 1], computed once at load — the per-
matvec prefix scan over row bit-widths was O(rows) each call).
repack: Vec<u8>q8-family decode repack (load-time, optional): rows in groups of 4, interleaved in 16-byte units — one 64-byte line per iteration feeds all 4 sdot lanes, ONE sequential weight stream per worker instead of four (this is where llama.cpp’s repacked Q8 kernels get their bandwidth). Empty = off (CMF_REPACK=0, non-SDOT arch, or an ineligible shape). Trades an anonymous copy of the quants for mmap pages that go cold.
Implementations§
Source§impl QTensor
impl QTensor
pub fn from_f32(data: Vec<f32>, rows: usize, cols: usize) -> Self
Sourcepub fn from_model(model: &Arc<CmfModel>, name: &str) -> Result<Self, String>
pub fn from_model(model: &Arc<CmfModel>, name: &str) -> Result<Self, String>
Wrap a directory tensor without dequantizing the payload. Falls back to dequantized f32 for dtypes without a fused kernel.
Examples found in repository?
21fn main() {
22 let mut args = std::env::args().skip(1);
23 let path = args
24 .next()
25 .expect("usage: matvec_bw <model.cmf> [sweep|one <tensor>]");
26 let mode = args.next().unwrap_or_else(|| "sweep".to_string());
27 let model = Arc::new(cortiq_core::CmfModel::open(&path).expect("open model"));
28
29 // Real LM activations carry a few heavy channels (>8·rms); measured
30 // mean on this model is ~3.7. NOUT models that distribution.
31 let nout: usize = std::env::var("NOUT")
32 .ok()
33 .and_then(|v| v.parse().ok())
34 .unwrap_or(4);
35 let mk_x = |cols: usize| -> Vec<f32> {
36 let mut x: Vec<f32> = (0..cols).map(|i| ((i % 17) as f32 - 8.0) / 8.0).collect();
37 for k in 0..nout {
38 x[k * 37 % cols] = 40.0;
39 }
40 x
41 };
42
43 if mode == "one" {
44 let name = args
45 .next()
46 .unwrap_or_else(|| "model.embed_tokens.weight".to_string());
47 let entry = model.tensor(&name).expect("tensor not found");
48 let (rows, cols) = (entry.shape[0], entry.shape[1]);
49 let nbytes = entry.nbytes as f64;
50 println!(
51 "tensor {name}: {rows}x{cols} {:?} = {:.1} MB, NOUT={nout}",
52 entry.dtype,
53 nbytes / 1e6
54 );
55 let t = QTensor::from_model(&model, &name).expect("wrap");
56 let x = mk_x(cols);
57 let mut out = vec![0f32; rows];
58 t.matvec(&x, &mut out, None);
59 for nt in [1usize, 2, 4, 6, 8, 10] {
60 let pool = if nt == 1 { None } else { Some(Pool::new(nt)) };
61 let iters = 8;
62 t.matvec(&x, &mut out, pool.as_ref());
63 let t0 = Instant::now();
64 for _ in 0..iters {
65 t.matvec(&x, &mut out, pool.as_ref());
66 }
67 let el = t0.elapsed().as_secs_f64();
68 println!(
69 "threads={nt:2} {:6.2} ms/matvec {:6.1} GB/s (sink {:.3})",
70 el / iters as f64 * 1e3,
71 nbytes * iters as f64 / el / 1e9,
72 out[0]
73 );
74 }
75 return;
76 }
77
78 // sweep: every 2-D q8_2f tensor once = one decode's worth of weights.
79 let names: Vec<String> = model
80 .tensors
81 .iter()
82 .filter(|t| t.dtype == TensorDtype::Q8_2f && t.shape.len() == 2)
83 .map(|t| t.name.clone())
84 .collect();
85 let total_bytes: f64 = model
86 .tensors
87 .iter()
88 .filter(|t| t.dtype == TensorDtype::Q8_2f && t.shape.len() == 2)
89 .map(|t| t.nbytes as f64)
90 .sum();
91 println!(
92 "sweep: {} q8_2f tensors, {:.2} GB total (= weights streamed per decode token), NOUT={nout}",
93 names.len(),
94 total_bytes / 1e9
95 );
96
97 let tensors: Vec<(QTensor, Vec<f32>, Vec<f32>)> = names
98 .iter()
99 .map(|n| {
100 let e = model.tensor(n).unwrap();
101 let (rows, cols) = (e.shape[0], e.shape[1]);
102 (
103 QTensor::from_model(&model, n).expect("wrap"),
104 mk_x(cols),
105 vec![0f32; rows],
106 )
107 })
108 .collect();
109 let mut tensors = tensors;
110
111 // Whole-model residency pass BEFORE any timing: the first touch of a
112 // 4.2 GB mmap faults ~260k pages, which would otherwise be charged to
113 // whichever thread count happens to run first. REVERSE=1 flips the
114 // order as a check that no first-touch cost is left in the table.
115 for _ in 0..2 {
116 for (t, x, out) in tensors.iter_mut() {
117 t.matvec(x, out, None);
118 }
119 }
120 let mut counts = vec![1usize, 2, 4, 6, 8, 10];
121 if std::env::var("REVERSE").is_ok() {
122 counts.reverse();
123 }
124 for nt in counts {
125 let pool = if nt == 1 { None } else { Some(Pool::new(nt)) };
126 // one warm pass, then two measured
127 for (t, x, out) in tensors.iter_mut() {
128 t.matvec(x, out, pool.as_ref());
129 }
130 let iters = 2;
131 let t0 = Instant::now();
132 for _ in 0..iters {
133 for (t, x, out) in tensors.iter_mut() {
134 t.matvec(x, out, pool.as_ref());
135 }
136 }
137 let el = t0.elapsed().as_secs_f64();
138 let per_tok = el / iters as f64;
139 println!(
140 "threads={nt:2} {:7.1} ms/sweep {:6.1} GB/s -> weight-path-only ceiling {:5.1} tok/s",
141 per_tok * 1e3,
142 total_bytes * iters as f64 / el / 1e9,
143 1.0 / per_tok
144 );
145 }
146}pub fn rows(&self) -> usize
pub fn cols(&self) -> usize
Sourcepub fn mapped_q1(&self) -> Option<(&Arc<CmfModel>, usize)>
pub fn mapped_q1(&self) -> Option<(&Arc<CmfModel>, usize)>
(model, tensor idx) for a q1 mapped weight — the wgpu token graph keys its resident VRAM cache by idx. None for any other dtype/kind.
Sourcepub fn graph_weight(&self) -> Option<(&Arc<CmfModel>, usize, u8, &[f32])>
pub fn graph_weight(&self) -> Option<(&Arc<CmfModel>, usize, u8, &[f32])>
(model, idx, kind, row_scale) for a graph-capable mapped weight. kind: 0=q8_row (per-row scales), 1=q1, 2=q4_tiled, 3=q1t (tile-embedded, no rs). None for dtypes the token graph does not handle (q8_2f/q4_block/vbit).
Sourcepub fn as_f32(&self) -> Option<&[f32]>
pub fn as_f32(&self) -> Option<&[f32]>
Dense f32 view — only for owned tensors. Masked/sparse execution paths require it; quantized weights don’t support masks yet.
Sourcepub fn row_f32(&self, r: usize, dst: &mut [f32])
pub fn row_f32(&self, r: usize, dst: &mut [f32])
Dequantize one row into dst (embedding lookup).
Sourcepub fn sparse_col_ok(&self) -> bool
pub fn sparse_col_ok(&self) -> bool
Can this tensor’s columns be read cheaply (for sparse down_proj)? True for F32/Q8Row/Q8_2f (per-row scale, direct strided access); false for group-packed q4/vbit (column access would unpack whole groups — sparse execution falls back to f32 for those).
Sourcepub fn add_col_scaled(&self, c: usize, w: f32, out: &mut [f32])
pub fn add_col_scaled(&self, c: usize, w: f32, out: &mut [f32])
down_proj [hidden, inter]: accumulate w · col(c) into out
[hidden] — reads ONLY column c (one neuron) from the mmap,
no full-matrix dequant. out[k] += w · down[k, c].
Sourcepub fn row_dot(&self, r: usize, x: &[f32], scratch: &mut [f32]) -> f32
pub fn row_dot(&self, r: usize, x: &[f32], scratch: &mut [f32]) -> f32
Dot of row r with x (gate/up active-neuron path). Reads only
row r from the mmap — no full dequant. q4/vbit dequant the row
into scratch first (rare for active-FFN weights).
Sourcepub fn matvec(&self, x: &[f32], out: &mut [f32], pool: Option<&Pool>)
pub fn matvec(&self, x: &[f32], out: &mut [f32], pool: Option<&Pool>)
out = W · x (row-major). F32 delegates to the historical
bit-exact path; Mapped runs the fused int8 kernel.
Examples found in repository?
21fn main() {
22 let mut args = std::env::args().skip(1);
23 let path = args
24 .next()
25 .expect("usage: matvec_bw <model.cmf> [sweep|one <tensor>]");
26 let mode = args.next().unwrap_or_else(|| "sweep".to_string());
27 let model = Arc::new(cortiq_core::CmfModel::open(&path).expect("open model"));
28
29 // Real LM activations carry a few heavy channels (>8·rms); measured
30 // mean on this model is ~3.7. NOUT models that distribution.
31 let nout: usize = std::env::var("NOUT")
32 .ok()
33 .and_then(|v| v.parse().ok())
34 .unwrap_or(4);
35 let mk_x = |cols: usize| -> Vec<f32> {
36 let mut x: Vec<f32> = (0..cols).map(|i| ((i % 17) as f32 - 8.0) / 8.0).collect();
37 for k in 0..nout {
38 x[k * 37 % cols] = 40.0;
39 }
40 x
41 };
42
43 if mode == "one" {
44 let name = args
45 .next()
46 .unwrap_or_else(|| "model.embed_tokens.weight".to_string());
47 let entry = model.tensor(&name).expect("tensor not found");
48 let (rows, cols) = (entry.shape[0], entry.shape[1]);
49 let nbytes = entry.nbytes as f64;
50 println!(
51 "tensor {name}: {rows}x{cols} {:?} = {:.1} MB, NOUT={nout}",
52 entry.dtype,
53 nbytes / 1e6
54 );
55 let t = QTensor::from_model(&model, &name).expect("wrap");
56 let x = mk_x(cols);
57 let mut out = vec![0f32; rows];
58 t.matvec(&x, &mut out, None);
59 for nt in [1usize, 2, 4, 6, 8, 10] {
60 let pool = if nt == 1 { None } else { Some(Pool::new(nt)) };
61 let iters = 8;
62 t.matvec(&x, &mut out, pool.as_ref());
63 let t0 = Instant::now();
64 for _ in 0..iters {
65 t.matvec(&x, &mut out, pool.as_ref());
66 }
67 let el = t0.elapsed().as_secs_f64();
68 println!(
69 "threads={nt:2} {:6.2} ms/matvec {:6.1} GB/s (sink {:.3})",
70 el / iters as f64 * 1e3,
71 nbytes * iters as f64 / el / 1e9,
72 out[0]
73 );
74 }
75 return;
76 }
77
78 // sweep: every 2-D q8_2f tensor once = one decode's worth of weights.
79 let names: Vec<String> = model
80 .tensors
81 .iter()
82 .filter(|t| t.dtype == TensorDtype::Q8_2f && t.shape.len() == 2)
83 .map(|t| t.name.clone())
84 .collect();
85 let total_bytes: f64 = model
86 .tensors
87 .iter()
88 .filter(|t| t.dtype == TensorDtype::Q8_2f && t.shape.len() == 2)
89 .map(|t| t.nbytes as f64)
90 .sum();
91 println!(
92 "sweep: {} q8_2f tensors, {:.2} GB total (= weights streamed per decode token), NOUT={nout}",
93 names.len(),
94 total_bytes / 1e9
95 );
96
97 let tensors: Vec<(QTensor, Vec<f32>, Vec<f32>)> = names
98 .iter()
99 .map(|n| {
100 let e = model.tensor(n).unwrap();
101 let (rows, cols) = (e.shape[0], e.shape[1]);
102 (
103 QTensor::from_model(&model, n).expect("wrap"),
104 mk_x(cols),
105 vec![0f32; rows],
106 )
107 })
108 .collect();
109 let mut tensors = tensors;
110
111 // Whole-model residency pass BEFORE any timing: the first touch of a
112 // 4.2 GB mmap faults ~260k pages, which would otherwise be charged to
113 // whichever thread count happens to run first. REVERSE=1 flips the
114 // order as a check that no first-touch cost is left in the table.
115 for _ in 0..2 {
116 for (t, x, out) in tensors.iter_mut() {
117 t.matvec(x, out, None);
118 }
119 }
120 let mut counts = vec![1usize, 2, 4, 6, 8, 10];
121 if std::env::var("REVERSE").is_ok() {
122 counts.reverse();
123 }
124 for nt in counts {
125 let pool = if nt == 1 { None } else { Some(Pool::new(nt)) };
126 // one warm pass, then two measured
127 for (t, x, out) in tensors.iter_mut() {
128 t.matvec(x, out, pool.as_ref());
129 }
130 let iters = 2;
131 let t0 = Instant::now();
132 for _ in 0..iters {
133 for (t, x, out) in tensors.iter_mut() {
134 t.matvec(x, out, pool.as_ref());
135 }
136 }
137 let el = t0.elapsed().as_secs_f64();
138 let per_tok = el / iters as f64;
139 println!(
140 "threads={nt:2} {:7.1} ms/sweep {:6.1} GB/s -> weight-path-only ceiling {:5.1} tok/s",
141 per_tok * 1e3,
142 total_bytes * iters as f64 / el / 1e9,
143 1.0 / per_tok
144 );
145 }
146}Source§impl QTensor
impl QTensor
Sourcepub fn matmat(
&self,
xs_all: &[f32],
b: usize,
out: &mut [f32],
pool: Option<&Pool>,
)
pub fn matmat( &self, xs_all: &[f32], b: usize, out: &mut [f32], pool: Option<&Pool>, )
Batched matvec (prefill-GEMM): xs — row-major [b, cols], out — row-major [b, rows]. Element-wise semantics are IDENTICAL to b matvec calls (same dot kernels in the same order); the win — the weight row streams from DRAM once per batch, not b times.
Source§impl QTensor
impl QTensor
Sourcepub fn matvec_many<const N: usize>(
ts: [&QTensor; N],
x: &[f32],
outs: [&mut [f32]; N],
pool: Option<&Pool>,
)
pub fn matvec_many<const N: usize>( ts: [&QTensor; N], x: &[f32], outs: [&mut [f32]; N], pool: Option<&Pool>, )
Multi-matrix job (roadmap §3 P0): N tensors sharing one input
run under a SINGLE pool dispatch — QKV or gate+up cost one
barrier instead of N. Per-row math is the exact same kernel as
matvec (bit-identical outputs); only the dispatch is fused.
Falls back to N sequential matvecs when the set is not a uniform
q8-family/F32 group or there is no pool.
Source§impl QTensor
impl QTensor
Sourcepub fn matvec2_many<const N: usize>(
ts: [&QTensor; N],
x1: &[f32],
x2: &[f32],
o1s: [&mut [f32]; N],
o2s: [&mut [f32]; N],
pool: Option<&Pool>,
)
pub fn matvec2_many<const N: usize>( ts: [&QTensor; N], x1: &[f32], x2: &[f32], o1s: [&mut [f32]; N], o2s: [&mut [f32]; N], pool: Option<&Pool>, )
Pair-input multi-matrix job: N tensors × 2 shared inputs under a
single pool dispatch — the MTP/pair decode path publishes one job
for Q/K/V (and one for gate+up) instead of one per tensor.
Per-row math is exactly matvec2’s kernels; bit-identical.
Sourcepub fn matvec_silu_mul(
gate: &QTensor,
up: &QTensor,
x: &[f32],
out: &mut [f32],
pool: Option<&Pool>,
) -> bool
pub fn matvec_silu_mul( gate: &QTensor, up: &QTensor, x: &[f32], out: &mut [f32], pool: Option<&Pool>, ) -> bool
Fused gate+up matvec with SiLU·mul: for each row r, computes
silu(gate·x) * (up·x) and writes to out[r]. ONE pool dispatch,
no intermediate g/u buffers, no separate silu pass. Falls back
(returns false) for unsupported dtype combos.