Skip to content

Commit aeaef40

Browse files
joaclaude
andcommitted
phobos-gguf: Send a Q8_0 prompt projection's whole 128-row tiles through the staged kernel
Where n is a multiple of 64 and k of 256; the rows left over take the tiles below as before, and PHOBOS_Q8_QGEMM=0 keeps the deep q8_qmma tile. Split along k by the staged projection's rule. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_013RsvdtnrmKHFtgKKXaXTjJ
1 parent 81e57a3 commit aeaef40

8 files changed

Lines changed: 137 additions & 2 deletions

File tree

‎ENV.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ one, as the `PHOBOS_FUSED_*` stages fall back to `PHOBOS_FUSED`).
7979
| `PHOBOS_QGEMM_SPLIT` | opt-out | on | Split-K on the staged projection when its grid is under three quarters of a wave (two CTAs per SM), which a short prompt or a wide card leaves it. Splits only while each slice stays deep enough to pay for the reduction pass. |
8080
| `PHOBOS_QGEMM_SUMS` | opt-out | on | The activation's per-block (scale, sum) pairs for the Q4_K staged projection's minimum term, written once per quantized activation by `block_pairs` and read by the kernel in place of the scales. Off, the kernel sums the staged tile itself, as Q5_K's does either way: with `dp4a` on Turing, against ones on the tensor cores from sm_80. |
8181
| `PHOBOS_RAW_QMMA` | opt-out, or a comma list of formats (`IQ1_S,IQ2_XXS`) | on, all formats | Which raw formats take the fused prompt projection rather than expansion. A list names them; an opt-out spelling means all or none. |
82+
| `PHOBOS_Q8_QGEMM` | opt-out | on | The staged projection, the raw formats' kernel over the Q8_0 planes, for the Q8_0 prompt projection's whole 128-row tiles where `n` is a multiple of 64 and `k` of 256; the rows left over take the tiles below it. Off, the deep `q8_qmma` tile takes them. Splits along `k` by the staged projection's rule where `PHOBOS_QMMA_SPLIT` allows. |
8283
| `PHOBOS_QMMA_SPLIT` | opt-out | on | Split-K on the Q8_0 prompt projection's deep tile when the grid is starved, which a short prompt leaves it. Up to 48 SMs only an eight-way split is taken, since a smaller one does not pay for its reduction pass; past 48 SMs a grid under two blocks per SM splits at least four ways. |
8384
| `PHOBOS_QMMA_NARROW` | opt-in | off | The narrow-CTA form of the Q8_0 prompt projection's deep tile. Wins at pp128, regresses pp512 on some models; opt-in for that reason. |
8485
| `PHOBOS_QMMA_TILE` | `TMxTNxCTA`, e.g. `128x64x256` | the format's | The fused prompt projection's tile and CTA, for a sweep without a rebuild. Each distinct value is a distinct compiled kernel. |

‎phobos-gguf/examples/backend_check/main.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@ use phobos_gguf::quant::{Packed, Quant, pack_q8_0};
1717

1818
mod moe;
1919
mod norm;
20+
mod q8;
2021
mod raw;
2122
mod topk;
2223

2324
use moe::check_moe_slots;
2425
use norm::check_norms_q;
26+
use q8::check_q8_handoff;
2527
use raw::{check_hadamard, check_raw_formats};
2628
use topk::check_topk;
2729

@@ -869,6 +871,8 @@ fn main() -> Result<()> {
869871
check(&format!("rms_norm [{rows} x {width}]"), &run(&host)?, &run(&gpu)?);
870872
}
871873

874+
check_q8_handoff(&host, &gpu, &check_within, &mut next)?;
875+
872876
let _ = Buf(0);
873877
println!("\nworst relative error {:.3e}", worst.get());
874878
if failures.get() > 0 {
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// The Q8_0 projection's handoff from the staged kernel to the tiles below it.
2+
3+
use super::*;
4+
use raw::CheckWithin;
5+
6+
/// The staged kernel takes whole 128-row tiles and passes the rest down:
7+
/// 200 = 128 + 64 + 8 rows gives it, the shallow tile and the row kernel
8+
/// each a share. Runs last, as a check inserted earlier would change every
9+
/// later one's data.
10+
pub(super) fn check_q8_handoff(
11+
host: &dyn Backend,
12+
gpu: &dyn Backend,
13+
check_within: &CheckWithin,
14+
next: &mut dyn FnMut() -> f32,
15+
) -> Result<()> {
16+
let (m, k, n) = (200usize, 1024usize, 512usize);
17+
let qs: Vec<i8> = (0..k * n).map(|_| (next() * 127.0) as i8).collect();
18+
let scales: Vec<f32> = (0..(k / 32) * n).map(|_| next().abs() + 0.01).collect();
19+
let a: Vec<f32> = (0..m * k).map(|_| next()).collect();
20+
let packed = pack_q8_0(&qs, &scales, k, n)?;
21+
let run = |b: &dyn Backend| -> Result<Vec<f32>> {
22+
let ab = b.upload(&a)?;
23+
let wb = b.constant_quant(&format!("q{m}x{k}x{n}"), &packed)?;
24+
let out = b.alloc(m * n)?;
25+
b.matmul_quant(ab, m, k, wb, n, out)?;
26+
read_vec(b, out, m * n)
27+
};
28+
check_within(&format!("matmul_quant [{m} x {k} x {n}]"), 1e-3, &run(host)?, &run(gpu)?);
29+
Ok(())
30+
}

‎phobos-gguf/src/backend/device/init.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,9 @@ impl DeviceBackend {
142142
qdot_split_mods: RefCell::new(HashMap::new()),
143143
qdot_split_on: env_flag_on("PHOBOS_QDOT_SPLIT"),
144144
q8_qmma_narrow: RefCell::new(None),
145+
q8_qgemm: RefCell::new(None),
146+
q8_qgemm_split: RefCell::new(HashMap::new()),
147+
q8_qgemm_on: env_flag_on("PHOBOS_Q8_QGEMM"),
145148
lanes_kernels: RefCell::new(HashMap::new()),
146149
q8_split,
147150
q8_qdot,

‎phobos-gguf/src/backend/device/kernels/dump.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ fn dump_raw_kernel_sources() {
3737
}
3838
sources.push(("qgemm_reduce".to_string(), qgemm_reduce_src(2560, 3, false)));
3939
sources.push(("qgemm_reduce_add".to_string(), qgemm_reduce_src(2560, 3, true)));
40+
sources.push(("q8_qgemm".to_string(), q8_qgemm_src()));
41+
sources.push(("q8_qgemm_split".to_string(), q8_qgemm_split_src(2560, 9216, 3)));
4042
sources.push(("attn_tc".to_string(), attn_tc_src(256, 4)));
4143
sources.push(("attn_merge".to_string(), attn_merge_src(256, 4)));
4244
for (name, form) in [("attn_flash", FlashForm::Streamed), ("attn_flash_resident", FlashForm::Resident)] {

‎phobos-gguf/src/backend/device/kernels/quant.rs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Q8_0 kernel sources: the activation quantizer, the dp4a and imma
22
// contractions, the fused dot, and the split-k reduction.
33

4+
use super::qgemm::{QGEMM_CTA, QGEMM_TM, QGEMM_TN};
45
use crate::backend::Q8_BLOCK;
56

67
/// Output tile along N for the quantized single-row matmul.
@@ -153,6 +154,51 @@ kernel q8_qmma(A: tensor<i8>[M, K], AS: tensor<f32>[M, KB],
153154
)
154155
}
155156

157+
/// The staged projection over the Q8_0 planes, `q8_qgemm_t`, for a prompt's
158+
/// whole 128-row tiles: the raw formats' kernel (see [`super::qgemm`]) with
159+
/// the quants copied as they are.
160+
pub(crate) fn q8_qgemm_src() -> String {
161+
format!(
162+
"@launch({QGEMM_CTA}, 2)
163+
@autotune(TM in [{QGEMM_TM}], TN in [{QGEMM_TN}])
164+
@aligned(M = TM, N = TN, K = 256)
165+
kernel q8_qgemm(A: tensor<i8>[M, K], AS: tensor<f32>[M, KB],
166+
W: tensor<i8>[N, K], WS: tensor<f32>[KB, N], C: tensor<f32>[M, N]) {{
167+
let pm = ctx.block.x
168+
let pn = ctx.block.y
169+
C[pm * TM :+ TM, pn * TN :+ TN] = q8_qgemm_t(A[pm * TM :+ TM, :], AS[pm * TM :+ TM, :],
170+
W[pn * TN :+ TN, :], WS[:, pn * TN :+ TN])
171+
}}
172+
"
173+
)
174+
}
175+
176+
/// [`q8_qgemm_src`] split `s` ways along `k`, as [`super::qgemm_split_src`]
177+
/// splits the grouped formats: program `(pm, ps * gn + pn)` contracts slice
178+
/// `ps` into column tile `ps * gn + pn` of the partial `P`, which
179+
/// [`super::qgemm_reduce_src`] sums.
180+
pub(crate) fn q8_qgemm_split_src(n: usize, k: usize, s: usize) -> String {
181+
let gn = n / QGEMM_TN;
182+
let sk = k / s;
183+
let skb = sk / Q8_BLOCK;
184+
format!(
185+
"@launch({QGEMM_CTA}, 2)
186+
@autotune(TM in [{QGEMM_TM}], TN in [{QGEMM_TN}])
187+
@aligned(M = TM, N = TN, K = {sk}, KB = {skb}, NP = TN)
188+
kernel q8_qgemm_split(A: tensor<i8>[M, K], AS: tensor<f32>[M, KB],
189+
W: tensor<i8>[N, K], WS: tensor<f32>[KB, N], P: tensor<f32>[M, NP]) {{
190+
let pm = ctx.block.x
191+
let pid = ctx.block.y
192+
let ps = pid / {gn}
193+
let pn = pid - ps * {gn}
194+
P[pm * TM :+ TM, pid * TN :+ TN] = q8_qgemm_t(A[pm * TM :+ TM, ps * {sk} :+ {sk}],
195+
AS[pm * TM :+ TM, ps * {skb} :+ {skb}], W[pn * TN :+ TN, ps * {sk} :+ {sk}],
196+
WS[ps * {skb} :+ {skb}, pn * TN :+ TN])
197+
}}
198+
"
199+
)
200+
}
201+
156202
/// Output tiles of the `q8_qmma` projection: the depth, and the available
157203
/// widths, widest first.
158204
///

‎phobos-gguf/src/backend/device/matmul.rs‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,14 @@ impl DeviceBackend {
8787
};
8888

8989
// Deepest tile first. Each kernel takes the whole tiles it can and
90-
// passes the remaining rows on: q8_qmma at two depths, then q8_mma,
91-
// then a matvec per leftover row.
90+
// passes the remaining rows on: the staged kernel where the shape
91+
// lets it, q8_qmma at two depths, then q8_mma, then a matvec per
92+
// leftover row.
9293
let mut qmma_rows = 0;
94+
if self.q8_qgemm_on && m >= QGEMM_TM && n.is_multiple_of(QGEMM_TN) && k.is_multiple_of(256) {
95+
qmma_rows = m - m % QGEMM_TM;
96+
self.launch_q8_qgemm(&tiles, qmma_rows)?;
97+
}
9398
if qmma_takes(n) {
9499
let wide = qmma_width(n);
95100
for (module, depth, tn) in [
@@ -226,6 +231,39 @@ impl DeviceBackend {
226231
Ok(())
227232
}
228233

234+
/// The staged projection over `rows` whole 128-row tiles of the Q8_0
235+
/// planes, split along `k` where the grid is starved (see
236+
/// [`qgemm_splits`]) with a reduce summing the partial planes.
237+
fn launch_q8_qgemm(&self, tiles: &Q8Tiles, rows: usize) -> Result<()> {
238+
let (k, n) = (tiles.k, tiles.n);
239+
let band = tiles.band(0, rows);
240+
let grid = ((rows / QGEMM_TM) as u32, (n / QGEMM_TN) as u32);
241+
let splits = if self.qmma_split { qgemm_splits(rows, n, k, 256, self.sms) } else { 1 };
242+
if splits == 1 {
243+
if self.q8_qgemm.borrow().is_none() {
244+
let module = compile(&q8_qgemm_src(), &[("TM", QGEMM_TM), ("TN", QGEMM_TN)], "q8_qgemm")?;
245+
*self.q8_qgemm.borrow_mut() = Some(module);
246+
}
247+
let cache = self.q8_qgemm.borrow();
248+
let module = cache.as_ref().expect("filled just above");
249+
return self.launch(module, "q8_qgemm", &band, (grid.0, grid.1, 1));
250+
}
251+
let key = (n, k, splits);
252+
if !self.q8_qgemm_split.borrow().contains_key(&key) {
253+
let split = compile(&q8_qgemm_split_src(n, k, splits), &[("TM", QGEMM_TM), ("TN", QGEMM_TN)], "q8_qgemm_split")?;
254+
let reduce = compile(&qgemm_reduce_src(n, splits, false), &[("TN", QGEMM_TN)], "qgemm_reduce")?;
255+
self.q8_qgemm_split.borrow_mut().insert(key, (split, reduce));
256+
}
257+
let cache = self.q8_qgemm_split.borrow();
258+
let (split, reduce) = &cache[&key];
259+
let partials = self.split_partials(rows * n * splits)?;
260+
let plane = (partials, [rows as i64, (n * splits) as i64]);
261+
let mut operands = band[..4].to_vec();
262+
operands.push(plane);
263+
self.launch(split, "q8_qgemm_split", &operands, (grid.0, grid.1 * splits as u32, 1))?;
264+
self.launch(reduce, "qgemm_reduce", &[plane, band[4]], (rows as u32, grid.1, 1))
265+
}
266+
229267
/// Split-K path for `q8_qmma`'s deep tile on a small grid. Each of
230268
/// `splits` programs covers one slice of `k` and writes a partial plane.
231269
/// A second launch sums the planes into `out`.

‎phobos-gguf/src/backend/device/mod.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,10 @@ use raw::DeviceRaw;
122122
/// [`kernels::q8_qmma_split_src`].
123123
type QmmaSplitKey = (usize, usize, usize);
124124

125+
/// `n`, `k` and split count: the parameters of
126+
/// [`kernels::q8_qgemm_split_src`].
127+
type Q8gemmSplitKey = (usize, usize, usize);
128+
125129
/// Format, `n`, `k`, slice count, and whether the sum adds into its
126130
/// destination, of a split decode matvec.
127131
type QdotSplitKey = (Quant, usize, usize, usize, bool);
@@ -208,6 +212,13 @@ pub struct DeviceBackend {
208212
/// tile, same per-warp patch. Compiled lazily when
209213
/// [`Self::qmma_narrow`] is set.
210214
q8_qmma_narrow: RefCell<Option<Module>>,
215+
/// The staged form of the Q8_0 prompt projection (`q8_qgemm_t`), and
216+
/// its split-K form with the reduce by `n`, `k` and split count, each
217+
/// compiled on first use. `PHOBOS_Q8_QGEMM=0` keeps the deep `q8_qmma`
218+
/// tile instead.
219+
q8_qgemm: RefCell<Option<Module>>,
220+
q8_qgemm_split: RefCell<HashMap<Q8gemmSplitKey, (Module, Module)>>,
221+
q8_qgemm_on: bool,
211222
lanes_kernels: RefCell<HashMap<Quant, Module>>,
212223
q8_split: Variants,
213224
q8_qdot: Module,

0 commit comments

Comments
 (0)