experiment: measure int8 matrix-multiply throughput of the integrated GPU through wgpu (STRA-207)

experiments/igpu-spike is a standalone program (own workspace, wgpu 26, WGSL generated as text) that
multiplies int8 matrices with the packed dot-product built-in on the reference laptop's Intel iGPU. The
instruction ceiling is 2.74 TOPS; a naive kernel reached 0.2-0.3 TOPS because private arrays were spilled,
and with named scalars the 8x8-per-thread kernel reaches 0.8-1.3 TOPS on prefill-like shapes (0.5-0.64 at
32 tokens), against about 0.25 TOPS for the CPU's decoder. Only the integer product is measured; the README
lists what is not shown (MXFP4 decoding, block scales, attention, weight upload, memory strategy) and the
decision needed from the owner.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 23:11:55 +02:00
co-authored by Claude Sonnet 5.5
parent 330b31b902
commit 66814b8a02
4 changed files with 1609 additions and 0 deletions
+1238
View File
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "igpu-spike"
version = "0.0.0"
edition = "2024"
publish = false
description = "EXPERIMENT (STRA-207): int8 matrix-multiply throughput of the integrated GPU through wgpu. Not part of the workspace; delete when the spike is decided."
[workspace]
[dependencies]
wgpu = "26"
pollster = "0.4"
bytemuck = "1"
+49
View File
@@ -0,0 +1,49 @@
# iGPU int8 matmul spike (STRA-207)
EXPERIMENT. Not part of the workspace (own `[workspace]`), not built by CI, safe to delete once the
decision below is made. Run: `cargo run --release -- [M] [N] [K] [dispatches]` (builds with `wgpu` 26 from
crates.io; no other downloads, no shader compiler: the kernels are WGSL generated as text).
Question: can the integrated GPU of the reference laptop (Intel Graphics, Core Ultra 7 265U, driver
32.0.101.8860, visible through Vulkan and DX12) multiply int8 matrices fast enough to be worth using for
prefill, which is compute-bound on the CPU (about 17-20 tokens/s)?
## Result (2026-10-14, one run each, machine not isolated)
* wgpu 25's shader translator rejects `dot4I8Packed`; wgpu 26 accepts it and the driver runs it natively.
* Instruction ceiling (register-only loop of packed dot products): **2.74 TOPS int8**.
* A naive tiled matmul reached 0.21-0.30 TOPS. The cause was dynamically indexed private arrays
(accumulators and operands) that the driver spilled to scratch memory; removing the global loads or the
dot products alone changed almost nothing, which exposed it. With every accumulator and operand a named
scalar (the shader text is generated), the 8x8-outputs-per-thread kernel reaches:
| M x N x K | int8 throughput |
| --- | --- |
| 256 x 4096 x 2880 (k-step 4 words) | 1.28 TOPS |
| 512 x 2880 x 2880 | 0.98 TOPS |
| 128 x 5760 x 2880 | 0.93 TOPS |
| 64 x 5760 x 2880 | 0.81 TOPS |
| 32 x 2880 x 2880 | 0.47-0.64 TOPS |
All results were checked against the CPU on sampled outputs. The CPU's practical rate for the same product
in the decoder is about 0.25 TOPS (prefill measured 17-20 tokens/s), so the GPU is roughly 3-5x faster on
the matrix products before any further tuning (subgroup operations, wider loads, f16 accumulation of the
block scales are untried).
## What this does not show
* Only the integer product. MXFP4 weights must be decoded in the shader (a table lookup per nibble) and
every 32-element block needs its float scale applied; that costs ALU and was not measured.
* No attention, routing, or MoE gather/scatter; no weight upload; no end-to-end token rate.
* Memory: wgpu cannot use the memory-mapped model file, so the GPU needs its own copy of the weights
(11.3 GB of experts plus 1.3 GB of dense tensors) in addition to the CPU's page-cache copy. The machine
has 32 GB (about 19 GB free with a browser open). Options: GPU-resident weights for prefill and decode
(one copy, CPU runtime unused for this model), or both copies (about 24 GB, tight), or GPU for the dense
and attention parts only.
## Decision needed from the owner
Whether to build an iGPU prefill/decode backend as a third, separate runtime (a `-sys`-free pure Rust
`wgpu` crate, WGSL kernels, no unsafe), and with which memory strategy. Bionic's Vulkan engine reaches
about 90 tokens/s prefill on this machine; a 4,000-token first prompt takes about 4 minutes on the CPU
runtime and under a minute at that rate.
+305
View File
@@ -0,0 +1,305 @@
//! EXPERIMENT (STRA-207): how fast can the integrated GPU multiply int8 matrices through wgpu?
//!
//! C[m][n] = sum_k A[m][k] * B[n][k] with int8 inputs packed four per u32 and the packed dot-product
//! built-in (`dot4I8Packed`). Reports the adapter, checks a small result against the CPU, then times
//! the kernel on prefill-like shapes. Throughput only, never an inference result.
//!
//! Run: `cargo run --release -- [M] [N] [K] [iterations]`
use std::time::Instant;
use wgpu::util::DeviceExt;
fn shader(tm: u32, tn: u32, ks: u32, mode: u32) -> String {
let bm = 8 * tm;
let bn = 8 * tn;
let loads_a = bm * ks / 64;
let loads_b = bn * ks / 64;
// every accumulator and operand is a named scalar: no dynamically indexed private arrays
let mut declare = String::new();
let mut operands = String::new();
let mut multiply = String::new();
let mut store = String::new();
for i in 0..tm {
for j in 0..tn {
declare += &format!(" var acc_{i}_{j} = 0;\n");
multiply += &format!(" acc_{i}_{j} += dot4I8Packed(a{i}, b{j});\n");
store += &format!(
" {{ let r = row0 + ty * {tm}u + {i}u; let cc = col0 + tx * {tn}u + {j}u; if (r < dims.m && cc < dims.n) {{ c[r * dims.n + cc] = acc_{i}_{j}; }} }}\n"
);
}
}
for i in 0..tm {
operands += &format!(" let a{i} = tile_a[kk * BM + {i}u * 8u + ty];\n");
}
for j in 0..tn {
operands += &format!(" let b{j} = tile_b[kk * BN + {j}u * 8u + tx];\n");
}
format!(
r#"
requires packed_4x8_integer_dot_product;
struct Dims {{ m: u32, n: u32, kw: u32, pad: u32 }}
@group(0) @binding(0) var<uniform> dims: Dims;
@group(0) @binding(1) var<storage, read> a: array<u32>;
@group(0) @binding(2) var<storage, read> b: array<u32>;
@group(0) @binding(3) var<storage, read_write> c: array<i32>;
const TM: u32 = {tm}u;
const TN: u32 = {tn}u;
const BM: u32 = {bm}u;
const BN: u32 = {bn}u;
const KS: u32 = {ks}u;
const MODE: u32 = {mode}u;
var<workgroup> tile_a: array<u32, {ta}>;
var<workgroup> tile_b: array<u32, {tb}>;
@compute @workgroup_size(8, 8)
fn main(@builtin(local_invocation_id) lid: vec3<u32>,
@builtin(workgroup_id) wid: vec3<u32>) {{
let tx = lid.x;
let ty = lid.y;
let flat = ty * 8u + tx;
let row0 = wid.y * BM;
let col0 = wid.x * BN;
{declare}
for (var k0 = 0u; k0 < dims.kw; k0 += KS) {{
for (var i = 0u; i < {loads_a}u; i++) {{
let idx = flat + i * 64u;
let r = idx / KS;
let kk = idx % KS;
var va = 0u;
if (MODE == 1u) {{ va = idx * 7u; }} else if (row0 + r < dims.m && k0 + kk < dims.kw) {{ va = a[(row0 + r) * dims.kw + k0 + kk]; }}
tile_a[kk * BM + (r % TM) * 8u + r / TM] = va;
}}
for (var i = 0u; i < {loads_b}u; i++) {{
let idx = flat + i * 64u;
let r = idx / KS;
let kk = idx % KS;
var vb = 0u;
if (MODE == 1u) {{ vb = idx * 13u; }} else if (col0 + r < dims.n && k0 + kk < dims.kw) {{ vb = b[(col0 + r) * dims.kw + k0 + kk]; }}
tile_b[kk * BN + (r % TN) * 8u + r / TN] = vb;
}}
workgroupBarrier();
for (var kk = 0u; kk < KS; kk++) {{
{operands}{multiply} }}
workgroupBarrier();
}}
{store}}}
"#,
ta = bm * ks,
tb = bn * ks,
)
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Dims {
m: u32,
n: u32,
kw: u32,
pad: u32,
}
fn pack(rows: usize, k: usize, seed: &mut u64) -> (Vec<i8>, Vec<u32>) {
let mut values = Vec::with_capacity(rows * k);
for _ in 0..rows * k {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
values.push(((*seed % 255) as i64 - 127) as i8);
}
let words = values
.chunks_exact(4)
.map(|c| u32::from_le_bytes([c[0] as u8, c[1] as u8, c[2] as u8, c[3] as u8]))
.collect();
(values, words)
}
/// Register-only loop of independent packed dot products: the instruction throughput ceiling.
fn peak(device: &wgpu::Device, queue: &wgpu::Queue) {
const SRC: &str = r#"
requires packed_4x8_integer_dot_product;
@group(0) @binding(0) var<storage, read_write> out: array<i32>;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
var a0 = gid.x * 2654435761u; var a1 = a0 + 1u; var a2 = a0 + 2u; var a3 = a0 + 3u;
var s0 = 0; var s1 = 0; var s2 = 0; var s3 = 0; var s4 = 0; var s5 = 0; var s6 = 0; var s7 = 0;
for (var i = 0u; i < 4096u; i++) {
s0 += dot4I8Packed(a0, a1); s1 += dot4I8Packed(a1, a2);
s2 += dot4I8Packed(a2, a3); s3 += dot4I8Packed(a3, a0);
s4 += dot4I8Packed(a0, a2); s5 += dot4I8Packed(a1, a3);
s6 += dot4I8Packed(a2, a0); s7 += dot4I8Packed(a3, a1);
a0 += 3u; a1 += 5u; a2 += 7u; a3 += 11u;
}
out[gid.x] = s0 + s1 + s2 + s3 + s4 + s5 + s6 + s7;
}
"#;
let threads: u32 = 64 * 4096;
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(threads) * 4,
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("peak"),
source: wgpu::ShaderSource::Wgsl(SRC.into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: None,
module: &module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[wgpu::BindGroupEntry { binding: 0, resource: buf.as_entire_binding() }],
});
let run = |count: usize| {
let mut encoder = device.create_command_encoder(&Default::default());
for _ in 0..count {
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(threads / 64, 1, 1);
}
queue.submit([encoder.finish()]);
device.poll(wgpu::PollType::Wait).expect("poll");
};
run(2);
let mut times = Vec::new();
for _ in 0..5 {
let t = Instant::now();
run(5);
times.push(t.elapsed().as_secs_f64() / 5.0);
}
times.sort_by(|a, b| a.total_cmp(b));
// 8 dot4 per iteration, 4096 iterations, each dot4 = 4 multiplies + 4 adds = 8 ops
let ops = f64::from(threads) * 4096.0 * 8.0 * 8.0;
println!("register-only dot4I8Packed: {:.3} ms, {:.2} TOPS int8 (instruction ceiling)", times[2] * 1e3, ops / times[2] / 1e12);
}
fn main() {
let args: Vec<usize> = std::env::args().skip(1).filter_map(|a| a.parse().ok()).collect();
let (m, n, k, iterations) = (
args.first().copied().unwrap_or(256),
args.get(1).copied().unwrap_or(4096),
args.get(2).copied().unwrap_or(2880),
args.get(3).copied().unwrap_or(20),
);
assert!(k % 64 == 0, "K must be a multiple of 64");
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
..Default::default()
}))
.expect("an adapter");
let info = adapter.get_info();
println!("using: {} ({:?}, {:?})", info.name, info.backend, info.device_type);
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("spike"),
required_limits: adapter.limits(),
..Default::default()
}))
.expect("a device");
let mut seed = 0x1234_5678_9ABC_DEF1u64;
let (a_values, a_words) = pack(m, k, &mut seed);
let (b_values, b_words) = pack(n, k, &mut seed);
let buffer = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage })
};
let dims = Dims { m: m as u32, n: n as u32, kw: (k / 4) as u32, pad: 0 };
let dims_buf = buffer("dims", bytemuck::bytes_of(&dims), wgpu::BufferUsages::UNIFORM);
let a_buf = buffer("a", bytemuck::cast_slice(&a_words), wgpu::BufferUsages::STORAGE);
let b_buf = buffer("b", bytemuck::cast_slice(&b_words), wgpu::BufferUsages::STORAGE);
let c_size = (m * n * 4) as u64;
let c_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("c"),
size: c_size,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let read_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("read"),
size: c_size,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
peak(&device, &queue);
let ops = 2.0 * m as f64 * n as f64 * k as f64;
println!("M={m} N={n} K={k}, {iterations} dispatches per timing, median of 5");
for (tm, tn, ks, mode) in [(8u32, 8u32, 8u32, 0u32), (8, 8, 8, 1), (4, 4, 16, 0), (4, 4, 16, 1), (8, 4, 8, 0), (4, 8, 8, 0), (8, 8, 4, 0), (8, 8, 16, 0)] {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("matmul"),
source: wgpu::ShaderSource::Wgsl(shader(tm, tn, ks, mode).into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("matmul"),
layout: None,
module: &module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: dims_buf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: a_buf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 2, resource: b_buf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 3, resource: c_buf.as_entire_binding() },
],
});
let groups = (n.div_ceil(8 * tn as usize) as u32, m.div_ceil(8 * tm as usize) as u32);
let run = |count: usize| {
let mut encoder = device.create_command_encoder(&Default::default());
for _ in 0..count {
let mut pass = encoder.begin_compute_pass(&Default::default());
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bind, &[]);
pass.dispatch_workgroups(groups.0, groups.1, 1);
}
queue.submit([encoder.finish()]);
device.poll(wgpu::PollType::Wait).expect("poll");
};
run(1);
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_buffer_to_buffer(&c_buf, 0, &read_buf, 0, c_size);
queue.submit([encoder.finish()]);
let slice = read_buf.slice(..);
slice.map_async(wgpu::MapMode::Read, |r| r.expect("map"));
device.poll(wgpu::PollType::Wait).expect("poll");
let result: Vec<i32> = bytemuck::cast_slice(&slice.get_mapped_range()).to_vec();
read_buf.unmap();
let mut wrong = 0;
for &(r, c) in &[(0usize, 0usize), (1, 5), (m - 1, n - 1), (m / 2, n / 3), (m - 1, 0), (0, n - 1), (m / 3, n - 7)] {
let expected: i32 = (0..k).map(|i| i32::from(a_values[r * k + i]) * i32::from(b_values[c * k + i])).sum();
if result[r * n + c] != expected {
wrong += 1;
}
}
run(2);
let mut times = Vec::new();
for _ in 0..5 {
let t = Instant::now();
run(iterations);
times.push(t.elapsed().as_secs_f64() / iterations as f64);
}
times.sort_by(|a, b| a.total_cmp(b));
println!(
"tile {}x{} per thread, k-step {:>2} words, mode {} (0 full, 1 no global loads, 2 no dot4): {:>8.3} ms {:>5.2} TOPS-equivalent {}",
tm,
tn,
ks,
mode,
times[2] * 1e3,
ops / times[2] / 1e12,
if wrong == 0 { "correct" } else { "WRONG" }
);
}
}