From a08e60f49bf9aa9538eeb34bd6e8088cb9808399 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 17:51:35 +0000 Subject: [PATCH 1/3] dr-isa-stream-lab: INT8 direct arm on ndarray's prepacked INT8 entries Adds int8::direct and int8::PreparedI8B. A is read in place at the u8 lanes' pitch and B is prepared once as PackedI8B bands, through ndarray::simd::int8_gemm_packed_strided (AdaWorldAPI/ndarray#418). The prepared-B reuse rule moves into shape::ReuseKey, shared by the BF16 and INT8 prepared operands so the two cannot drift. Measured on one AMX VM (median of 41 warm runs, three runs), 256 fields x 256 columns: the direct GEMM takes 45.5-48.1 us against 78.3-78.8 us for backend::gemm_i8, end to end 47.5-57.9 us against 88.9-92.2 us; at 64 fields 0.98-1.01 us against 3.4-3.6 us. No A copied, no allocation. Needs ndarray#418. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- .../shape-2026-11-10-int8-direct-run1.txt | 33 ++++ .../shape-2026-11-10-int8-direct-run2.txt | 33 ++++ .../shape-2026-11-10-int8-direct-run3.txt | 33 ++++ crates/dr-isa-stream-lab/src/bin/shape.rs | 37 ++++ crates/dr-isa-stream-lab/src/int8.rs | 179 +++++++++++++++++- crates/dr-isa-stream-lab/src/shape.rs | 81 +++++--- .../tests/integration/int8.rs | 94 +++++++++ 7 files changed, 454 insertions(+), 36 deletions(-) create mode 100644 crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run1.txt create mode 100644 crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run2.txt create mode 100644 crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run3.txt diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run1.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run1.txt new file mode 100644 index 000000000..c1173d23d --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run1.txt @@ -0,0 +1,33 @@ +Host: Intel(R) Xeon(R) Processor @ 2.10GHz; 4 logical CPUs; cache (cpu0): L1 Data 48K, L1 Instruction 32K, L2 Unified 2048K, L3 Unified 266240K +Tile tier: AMX TDPBF16PS. Single-threaded. 41 warm runs per row (median). + +Sparse demand (256 fields x 256 cols, 40 scattered identities): logical selection 40 · K padded 64 · lanes borrowed 256 · A bytes copied 20480 · dense dot-product steps 512 · staged AMX 382.6 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3187 ns · 2 allocs | 8623 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1256 ns · 0 allocs · 0 B | 1983 ns · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 11.7 µs | 146.5 µs | +| B preparation (VNNI panels) | 6703 ns · 8192 B written · 8320 B alloc | 98.7 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4306 ns · 60.9 GMAC/s · 0 allocs · 0 B tmp | 137.3 µs · 122.2 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3759 ns · 69.7 GMAC/s | 120.7 µs · 139.0 GMAC/s | +| Staged AMX (dense A tiles) | 4140 ns · 1 allocs · 2048 B tmp | 127.7 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 36.4 µs · 23 allocs · 54272 B tmp | 1081.9 µs · 263 allocs · 803840 B tmp | +| Source bytes copied (direct / staged / CBLAS) | 0 / 8192 / 8192 | 0 / 131072 / 131072 | +| CBLAS B materialized | 8192 B | 131072 B | +| FP32 accumulator (C) | 16384 B | 262144 B | +| End-to-end warm (resolve + direct, B reused) | 6528 ns | 147.9 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 23.0 µs | 303.5 µs | +| Warm repetitions (100, per run, one prepare) | 7019 ns | 154.4 µs | +| INT8 resolve (u8 lanes, one check) | 1213 ns | 1960 ns | +| INT8 stage A (region: one copy per lane) | 310 ns · 4096 B | 4700 ns · 65536 B | +| INT8 stage A, per-value walk (baseline) | 3312 ns | 30.8 µs | +| INT8 B for a region, in place from the table | 30 ns · 0 B written | 30 ns · 0 B written | +| INT8 materialize B (row-major i8) | 7564 ns · 4096 B | 124.1 µs · 65536 B | +| INT8 GEMM `backend::gemm_i8` (packs B per call) | 3552 ns · 73.8 GMAC/s · 3 allocs · 3072 B tmp | 78.3 µs · 214.3 GMAC/s · 3 allocs · 12288 B tmp | +| INT8 B band gather + VNNI pack (done inside each gemm_i8 call) | 2009 ns · 57% of the GEMM row | 29.4 µs · 38% of the GEMM row | +| INT8 end-to-end warm (resolve + stage + GEMM) | 5856 ns | 88.9 µs | +| INT8 prepare B once (PackedI8B bands, `ndarray::simd`) | 6637 ns · 4096 B | 105.3 µs · 65536 B | +| INT8 direct GEMM (A in place, prepared B) | 1011 ns · 259.3 GMAC/s · 0 allocs · 0 B of A copied | 48.1 µs · 348.5 GMAC/s · 0 allocs · 0 B of A copied | +| INT8 direct end-to-end warm (resolve + GEMM) | 3013 ns | 57.9 µs | diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run2.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run2.txt new file mode 100644 index 000000000..a76b40cca --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run2.txt @@ -0,0 +1,33 @@ +Host: Intel(R) Xeon(R) Processor @ 2.10GHz; 4 logical CPUs; cache (cpu0): L1 Data 48K, L1 Instruction 32K, L2 Unified 2048K, L3 Unified 266240K +Tile tier: AMX TDPBF16PS. Single-threaded. 41 warm runs per row (median). + +Sparse demand (256 fields x 256 cols, 40 scattered identities): logical selection 40 · K padded 64 · lanes borrowed 256 · A bytes copied 20480 · dense dot-product steps 512 · staged AMX 385.0 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3088 ns · 2 allocs | 8409 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1181 ns · 0 allocs · 0 B | 2488 ns · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 11.3 µs | 181.1 µs | +| B preparation (VNNI panels) | 6570 ns · 8192 B written · 8320 B alloc | 110.5 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4157 ns · 63.1 GMAC/s · 0 allocs · 0 B tmp | 123.2 µs · 136.2 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3701 ns · 70.8 GMAC/s | 119.5 µs · 140.4 GMAC/s | +| Staged AMX (dense A tiles) | 4007 ns · 1 allocs · 2048 B tmp | 113.1 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 35.7 µs · 23 allocs · 54272 B tmp | 1184.9 µs · 263 allocs · 803840 B tmp | +| Source bytes copied (direct / staged / CBLAS) | 0 / 8192 / 8192 | 0 / 131072 / 131072 | +| CBLAS B materialized | 8192 B | 131072 B | +| FP32 accumulator (C) | 16384 B | 262144 B | +| End-to-end warm (resolve + direct, B reused) | 6254 ns | 131.1 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 21.9 µs | 274.3 µs | +| Warm repetitions (100, per run, one prepare) | 6777 ns | 145.2 µs | +| INT8 resolve (u8 lanes, one check) | 1151 ns | 1979 ns | +| INT8 stage A (region: one copy per lane) | 302 ns · 4096 B | 4704 ns · 65536 B | +| INT8 stage A, per-value walk (baseline) | 3369 ns | 30.4 µs | +| INT8 B for a region, in place from the table | 29 ns · 0 B written | 30 ns · 0 B written | +| INT8 materialize B (row-major i8) | 7343 ns · 4096 B | 125.3 µs · 65536 B | +| INT8 GEMM `backend::gemm_i8` (packs B per call) | 3432 ns · 76.4 GMAC/s · 3 allocs · 3072 B tmp | 78.8 µs · 212.8 GMAC/s · 3 allocs · 12288 B tmp | +| INT8 B band gather + VNNI pack (done inside each gemm_i8 call) | 2149 ns · 63% of the GEMM row | 29.4 µs · 37% of the GEMM row | +| INT8 end-to-end warm (resolve + stage + GEMM) | 5745 ns | 89.0 µs | +| INT8 prepare B once (PackedI8B bands, `ndarray::simd`) | 6444 ns · 4096 B | 105.8 µs · 65536 B | +| INT8 direct GEMM (A in place, prepared B) | 976 ns · 268.6 GMAC/s · 0 allocs · 0 B of A copied | 47.3 µs · 354.7 GMAC/s · 0 allocs · 0 B of A copied | +| INT8 direct end-to-end warm (resolve + GEMM) | 2924 ns | 52.7 µs | diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run3.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run3.txt new file mode 100644 index 000000000..30aa19037 --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-direct-run3.txt @@ -0,0 +1,33 @@ +Host: Intel(R) Xeon(R) Processor @ 2.10GHz; 4 logical CPUs; cache (cpu0): L1 Data 48K, L1 Instruction 32K, L2 Unified 2048K, L3 Unified 266240K +Tile tier: AMX TDPBF16PS. Single-threaded. 41 warm runs per row (median). + +Sparse demand (256 fields x 256 cols, 40 scattered identities): logical selection 40 · K padded 64 · lanes borrowed 256 · A bytes copied 20480 · dense dot-product steps 512 · staged AMX 388.9 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3179 ns · 2 allocs | 8882 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1210 ns · 0 allocs · 0 B | 1991 ns · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 11.7 µs | 151.3 µs | +| B preparation (VNNI panels) | 6703 ns · 8192 B written · 8320 B alloc | 109.0 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4314 ns · 60.8 GMAC/s · 0 allocs · 0 B tmp | 170.5 µs · 98.4 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3804 ns · 68.9 GMAC/s | 152.2 µs · 110.2 GMAC/s | +| Staged AMX (dense A tiles) | 4232 ns · 1 allocs · 2048 B tmp | 146.4 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 36.8 µs · 23 allocs · 54272 B tmp | 1527.3 µs · 263 allocs · 803840 B tmp | +| Source bytes copied (direct / staged / CBLAS) | 0 / 8192 / 8192 | 0 / 131072 / 131072 | +| CBLAS B materialized | 8192 B | 131072 B | +| FP32 accumulator (C) | 16384 B | 262144 B | +| End-to-end warm (resolve + direct, B reused) | 6474 ns | 145.1 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 18.3 µs | 295.9 µs | +| Warm repetitions (100, per run, one prepare) | 6384 ns | 169.6 µs | +| INT8 resolve (u8 lanes, one check) | 1188 ns | 1941 ns | +| INT8 stage A (region: one copy per lane) | 309 ns · 4096 B | 4742 ns · 65536 B | +| INT8 stage A, per-value walk (baseline) | 3424 ns | 29.3 µs | +| INT8 B for a region, in place from the table | 30 ns · 0 B written | 30 ns · 0 B written | +| INT8 materialize B (row-major i8) | 7569 ns · 4096 B | 125.4 µs · 65536 B | +| INT8 GEMM `backend::gemm_i8` (packs B per call) | 3553 ns · 73.8 GMAC/s · 3 allocs · 3072 B tmp | 78.5 µs · 213.8 GMAC/s · 3 allocs · 12288 B tmp | +| INT8 B band gather + VNNI pack (done inside each gemm_i8 call) | 1909 ns · 54% of the GEMM row | 28.6 µs · 37% of the GEMM row | +| INT8 end-to-end warm (resolve + stage + GEMM) | 5878 ns | 92.2 µs | +| INT8 prepare B once (PackedI8B bands, `ndarray::simd`) | 6659 ns · 4096 B | 105.4 µs · 65536 B | +| INT8 direct GEMM (A in place, prepared B) | 1006 ns · 260.6 GMAC/s · 0 allocs · 0 B of A copied | 45.5 µs · 368.3 GMAC/s · 0 allocs · 0 B of A copied | +| INT8 direct end-to-end warm (resolve + GEMM) | 3035 ns | 47.5 µs | diff --git a/crates/dr-isa-stream-lab/src/bin/shape.rs b/crates/dr-isa-stream-lab/src/bin/shape.rs index 826cee7c2..96feaf578 100644 --- a/crates/dr-isa-stream-lab/src/bin/shape.rs +++ b/crates/dr-isa-stream-lab/src/bin/shape.rs @@ -397,6 +397,24 @@ fn main() { }); assert_eq!(c8, want8); let (a8_allocs, m8_gemm, _) = mem(|| int8::gemm(&o8, &a8, &b8, &mut c8)); + // The direct arm: A read in place at the lane pitch, B prepared once + // into PackedI8B bands (ndarray's INT8 twins of #414). + let prep8 = int8::PreparedI8B::prepare(&o8, &bt).unwrap(); + let mut d8 = vec![0i32; o8.c_len()]; + int8::direct(&o8, &l8, &prep8, &bt, &mut d8).unwrap(); + assert_eq!(d8, want8, "int8 direct {dim}"); + let t8_prep = median_ns(|| { + black_box(int8::PreparedI8B::prepare(&o8, &bt).unwrap()); + }); + let t8_direct = median_ns(|| { + int8::direct(&o8, &l8, &prep8, &bt, &mut d8).unwrap(); + }); + let t8_direct_all = median_ns(|| { + let l = int8::resolve(&o8, &world, &u8s).unwrap(); + int8::direct(&o8, &l, &prep8, &bt, &mut d8).unwrap(); + }); + assert_eq!(d8, want8); + let (d8_allocs, _, _) = mem(|| int8::direct(&o8, &l8, &prep8, &bt, &mut d8).unwrap()); push("INT8 resolve (u8 lanes, one check)", col, fmt(t8_resolve)); push( "INT8 stage A (region: one copy per lane)", @@ -441,6 +459,25 @@ fn main() { col, fmt(t8_all), ); + push( + "INT8 prepare B once (PackedI8B bands, `ndarray::simd`)", + col, + format!("{} · {} B", fmt(t8_prep), prep8.bytes()), + ); + push( + "INT8 direct GEMM (A in place, prepared B)", + col, + format!( + "{} · {:.1} GMAC/s · {d8_allocs} allocs · 0 B of A copied", + fmt(t8_direct), + macs / t8_direct + ), + ); + push( + "INT8 direct end-to-end warm (resolve + GEMM)", + col, + fmt(t8_direct_all), + ); } // Sparse demand: 40 scattered identities, 256 fields x 256 columns. diff --git a/crates/dr-isa-stream-lab/src/int8.rs b/crates/dr-isa-stream-lab/src/int8.rs index fd0664854..39c0e8444 100644 --- a/crates/dr-isa-stream-lab/src/int8.rs +++ b/crates/dr-isa-stream-lab/src/int8.rs @@ -8,13 +8,16 @@ //! The binding is the same [`VirtualObject`]: DT64 does not care what a lane //! holds. Only the borrow and the arithmetic change. //! -//! What ndarray's facade offers for INT8 today (audited 2026-11-10): -//! `backend::gemm_i8` -> `simd_int_ops::gemm_u8_i8` -> `int8_gemm_amx_tiled` -//! on 16/16/64-aligned shapes. A must be dense with row stride K, and B is -//! VNNI-packed inside every call. There is no strided-A entry and no prepacked -//! B for INT8 (the BF16 equivalents are `bf16_tile_gemm_16x16_packed_strided` -//! and `PackedBf16B`). So the only INT8 arm here is [`staged`]: a direct -//! (in-place) arm and prepared-B reuse are refused, not emulated. +//! Two INT8 arms: +//! - [`staged`]: `backend::gemm_i8` (-> `int8_gemm_amx_tiled`). A is copied +//! dense with row stride K, and B is gathered and VNNI-packed inside every +//! call. +//! - [`direct`]: A read in place at the lanes' pitch through +//! `ndarray::simd::int8_gemm_packed_strided`, and B prepared +//! once ([`PreparedI8B`], one `PackedI8B` band per 16 output columns) and +//! reused under the same identity rule as the BF16 [`crate::shape::PreparedB`] +//! ([`ReuseKey`]). These are the INT8 twins of the BF16 entries ndarray +//! added in #414. use std::cell::Cell; @@ -22,9 +25,15 @@ use lance_graph_contract::ontology::FieldRef; use lance_graph_dt64::dr::{Frame, FrameRevisions, FrameStore, Scope}; use lance_graph_dt64::{CoordSpace, LaneAddr, LaneRefusal, LaneSource, SchemaRev}; +use ndarray::simd::{int8_gemm_packed_strided, PackedI8B}; + use crate::bind::{World, CLASS, READER, SPACE_A}; use crate::fixture::Fixture; -use crate::shape::{BOperand, BValues, Selection, ShapeRefusal, VirtualObject, Where, MAX_ROWS}; +use crate::gemm::DirectRefusal; +use crate::shape::{ + admit_operand, BOperand, BValues, ReuseKey, Selection, ShapeRefusal, VirtualObject, Where, + MAX_ROWS, TILE, +}; /// INT8 tiles consume K in steps of 64. pub const K_STEP: usize = 64; @@ -365,3 +374,157 @@ pub fn oracle(fx: &Fixture, sel: &Selection, fields: &[u8], cols: usize, b: &BOp }); c } + +/// B as `cols / 16` VNNI-packed `K x 16` i8 bands, prepared once for one +/// object and one operand identity, reused by every output tile and every +/// repeated run. Rows are the selected identities in order; rows past the +/// selection are zero. +pub struct PreparedI8B { + key: ReuseKey, + bands: Vec, +} + +impl PreparedI8B { + /// Pack B for `obj`: `band t row k = B[i_k][16t..16t+16]` in VNNI order. + /// Refuses an operand smaller than the object ([`admit_operand`]). + pub fn prepare(obj: &VirtualObject, b: &impl BValues) -> Result { + admit_operand(obj, b)?; + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + let mut bands: Vec = (0..obj.cols() / TILE) + .map(|_| PackedI8B::zeroed(k_pad)) + .collect(); + obj.selection().for_each(|row, i| { + for (t, band) in bands.iter_mut().enumerate() { + let data = band.data_mut(); + for c in 0..TILE { + data[PackedI8B::vnni_index(row, c)] = b.i8_at(i, t * TILE + c); + } + } + }); + Ok(PreparedI8B { + key: ReuseKey::of(obj, b), + bands, + }) + } + + /// Bytes the bands occupy, K padding included. + pub fn bytes(&self) -> usize { + self.bands.iter().map(|b| b.data().len()).sum() + } +} + +/// Where 16 lanes sit when they can be read as one strided A operand. +struct Geometry<'s> { + slab: &'s [u8], + pitch: usize, + first_row: usize, +} + +/// The 16 lanes of a row tile as one strided operand: one allocation, one +/// pitch, consecutive rows. Anything else is refused, never copied. +fn geometry<'s>(fields: &[u8], lanes: &[U8Lane<'s>]) -> Result, DirectRefusal> { + if lanes.len() < TILE { + return Err(DirectRefusal::PartialRowTile { lanes: lanes.len() }); + } + let first = lanes[0]; + for (k, (lane, &field)) in lanes.iter().zip(fields).enumerate().skip(1) { + if !std::ptr::eq(lane.slab, first.slab) { + return Err(DirectRefusal::NotOneSlab { field }); + } + if lane.pitch != first.pitch { + return Err(DirectRefusal::PitchMismatch { field }); + } + if lane.row != first.row + k { + return Err(DirectRefusal::RowsNotConsecutive { field }); + } + } + Ok(Geometry { + slab: first.slab, + pitch: first.pitch, + first_row: first.row, + }) +} + +/// The INT8 direct arm: A read in place at the lanes' pitch, B from the +/// prepared bands. Needs a region selection; `c` is `rows x cols`, row-major, +/// overwritten. Rows of B past the selection are zero, so the read up to the +/// 64-step padding adds nothing; the read must still stay inside the lane's +/// own row of the slab. +pub fn direct( + obj: &VirtualObject, + lanes: &U8Lanes64<'_>, + b: &PreparedI8B, + operand: &impl BValues, + c: &mut [i32], +) -> Result { + b.key.admit(obj, operand).map_err(ShapeRefusal::Reuse)?; + admit(obj, lanes)?; + let Where::Region { start, len } = obj.selection().kind else { + return Err(ShapeRefusal::NotARegion); + }; + let (rows, cols) = (obj.fields().len(), obj.cols()); + assert_eq!(c.len(), rows * cols); + let k_pad = len.div_ceil(K_STEP) * K_STEP; + let mut report = Int8Report { + k_pad, + ..Int8Report::default() + }; + // One call when every lane is one strided operand (the source's own + // order); otherwise one call per 16-field group, each writing its rows. + if geometry(obj.fields(), lanes.lanes()).is_ok() { + run_rows( + start, + len, + k_pad, + 0, + obj.fields(), + lanes.lanes(), + b, + c, + cols, + &mut report, + )?; + } else { + for (g, (fs, ls)) in obj + .fields() + .chunks(TILE) + .zip(lanes.lanes().chunks(TILE)) + .enumerate() + { + run_rows(start, len, k_pad, g * TILE, fs, ls, b, c, cols, &mut report)?; + } + } + Ok(report) +} + +/// One strided GEMM over the lanes `ls` (fields `fs`), writing C's rows from +/// `row0`. +#[allow(clippy::too_many_arguments)] +fn run_rows( + start: usize, + len: usize, + k_pad: usize, + row0: usize, + fs: &[u8], + ls: &[U8Lane<'_>], + b: &PreparedI8B, + c: &mut [i32], + cols: usize, + report: &mut Int8Report, +) -> Result<(), ShapeRefusal> { + let geo = geometry(fs, ls).map_err(ShapeRefusal::Direct)?; + if start + k_pad > geo.pitch { + return Err(ShapeRefusal::OverRead { + start, + len, + k_pad, + n: ls[0].n, + pitch: geo.pitch, + }); + } + let a = &geo.slab[geo.first_row * geo.pitch + start..]; + int8_gemm_packed_strided(a, geo.pitch, &b.bands, &mut c[row0 * cols..], fs.len()); + report.tiles += fs.len() / TILE * b.bands.len(); + report.dp_steps += fs.len() / TILE * b.bands.len() * (k_pad / K_STEP); + Ok(()) +} diff --git a/crates/dr-isa-stream-lab/src/shape.rs b/crates/dr-isa-stream-lab/src/shape.rs index 02e5431a5..f450718e8 100644 --- a/crates/dr-isa-stream-lab/src/shape.rs +++ b/crates/dr-isa-stream-lab/src/shape.rs @@ -580,6 +580,15 @@ pub enum ReuseRefusal { /// output tile and every repeated run. Rows are the selected identities in /// order; rows past the selection are zero. pub struct PreparedB { + key: ReuseKey, + panels: Vec, +} + +/// What a prepared operand was prepared for, and the one rule for reusing it. +/// Shared by the BF16 [`PreparedB`] and the INT8 `PreparedI8B`, so the two +/// cannot drift apart. +#[derive(Debug, Clone)] +pub struct ReuseKey { /// The object it was packed for (fast path: one compare). object: u64, /// That object's selection, compared in full when the object differs: @@ -587,7 +596,46 @@ pub struct PreparedB { selection: Selection, frame: Frame, operand: OperandId, - panels: Vec, + cols: usize, +} + +impl ReuseKey { + /// The key of an operand prepared for `obj` from `b`. + pub fn of(obj: &VirtualObject, b: &impl BValues) -> ReuseKey { + ReuseKey { + object: obj.id, + selection: obj.selection.clone(), + frame: obj.frame().clone(), + operand: b.identity(), + cols: obj.cols, + } + } + + /// Whether the prepared operand may serve `obj` with operand `b`. + /// + /// The operand is compared by identity (source and revision), always. + /// For the object it was packed for, one identity compare covers the + /// selection, frame and width. For any other object the selection is + /// compared in full, then the frame issue and the width: a prepared B is + /// shared across objects only when all three are equal. + pub fn admit(&self, obj: &VirtualObject, b: &impl BValues) -> Result<(), ReuseRefusal> { + if self.operand != b.identity() { + return Err(ReuseRefusal::Operand); + } + if self.object == obj.id { + return Ok(()); + } + if self.selection != obj.selection { + return Err(ReuseRefusal::Selection); + } + if !self.frame.same_issue(obj.frame()) { + return Err(ReuseRefusal::Frame); + } + if self.cols != obj.cols { + return Err(ReuseRefusal::Columns); + } + Ok(()) + } } /// What preparing B did. @@ -625,10 +673,7 @@ impl PreparedB { let allocated = panels.iter().map(|p| p.data().len() * 2).sum(); Ok(( PreparedB { - object: obj.id, - selection: obj.selection.clone(), - frame: obj.frame().clone(), - operand: b.identity(), + key: ReuseKey::of(obj, b), panels, }, PrepReport { @@ -644,30 +689,10 @@ impl PreparedB { &self.panels[t] } - /// Whether this prepared B may serve `obj` with operand `b`. - /// - /// The operand is compared by identity (source and revision), always. - /// For the object it was packed for, one identity compare covers the - /// selection, frame and width. For any other object the selection is - /// compared in full, then the frame issue and the width: a prepared B is - /// shared across objects only when all three are equal. + /// Whether this prepared B may serve `obj` with operand `b` + /// ([`ReuseKey::admit`]). pub fn admit(&self, obj: &VirtualObject, b: &impl BValues) -> Result<(), ReuseRefusal> { - if self.operand != b.identity() { - return Err(ReuseRefusal::Operand); - } - if self.object == obj.id { - return Ok(()); - } - if self.selection != obj.selection { - return Err(ReuseRefusal::Selection); - } - if !self.frame.same_issue(obj.frame()) { - return Err(ReuseRefusal::Frame); - } - if self.panels.len() * TILE != obj.cols { - return Err(ReuseRefusal::Columns); - } - Ok(()) + self.key.admit(obj, b) } } diff --git a/crates/dr-isa-stream-lab/tests/integration/int8.rs b/crates/dr-isa-stream-lab/tests/integration/int8.rs index 783b7a705..02fe95f22 100644 --- a/crates/dr-isa-stream-lab/tests/integration/int8.rs +++ b/crates/dr-isa-stream-lab/tests/integration/int8.rs @@ -265,3 +265,97 @@ fn int8_refuses_a_b_table_narrower_than_the_object() { int8::staged(&obj, &l, &B, &mut Vec::new(), &mut Vec::new(), &mut want).unwrap(); assert_eq!(c, want); } + +/// The direct arm (A in place, B prepared once) is exact against the i64 +/// oracle and equal to the staged arm, at both sizes and with K tails; its +/// prepared B serves repeated runs unchanged. +#[test] +fn int8_direct_is_exact_and_reuses_its_prepared_b() { + use dr_isa_stream_lab::shape::BTable; + for dim in [64, 256] { + let fx = fx(4096, dim); + let lanes = U8Lanes::slab_in_order(&fx); + let socket = U8Socket::in_order(&lanes, dim); + let world = world(dim); + let bt = BTable::new(&B, 4096, dim); + for (start, len) in [(0, 63), (100, 65), (64, 128), (4096 - 512, 512)] { + let sel = Selection::region(SPACE_A, start, len); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel.clone()).unwrap(); + let l = int8::resolve(&obj, &world, &socket).unwrap(); + let prep = int8::PreparedI8B::prepare(&obj, &bt).unwrap(); + let want: Vec = int8::oracle(&fx, &sel, &fields(dim), dim, &B) + .iter() + .map(|&v| i32::try_from(v).unwrap()) + .collect(); + let mut staged = vec![0i32; obj.c_len()]; + int8::staged(&obj, &l, &bt, &mut Vec::new(), &mut Vec::new(), &mut staged).unwrap(); + for run in 0..2 { + let mut c = vec![7i32; obj.c_len()]; + let r = int8::direct(&obj, &l, &prep, &bt, &mut c).unwrap(); + assert_eq!(c, want, "dim {dim} region ({start}, {len}) run {run}"); + assert_eq!(r.a_copied, 0); + assert_eq!(r.b_materialized, 0); + } + assert_eq!(staged, want); + } + } +} + +/// Lanes that are not one strided operand are refused, never copied: rows +/// out of order, a scattered mask, and a region whose padded read would +/// leave the lane's row. A prepared B for another operand is refused too. +#[test] +fn int8_direct_refuses_what_it_cannot_read_in_place() { + use dr_isa_stream_lab::gemm::DirectRefusal; + use dr_isa_stream_lab::shape::{BTable, ReuseRefusal}; + let dim = 64; + let fx = fx(4096, dim); + let lanes = U8Lanes::slab_in_order(&fx); + let world = world(dim); + let bt = BTable::new(&B, 4096, dim); + + let mut permuted = U8Socket::in_order(&lanes, dim); + permuted.rows.swap(3, 4); + let sel = Selection::region(SPACE_A, 0, 128); + let obj = VirtualObject::bind(&world, &permuted, &fields(dim), dim, sel).unwrap(); + let l = int8::resolve(&obj, &world, &permuted).unwrap(); + let prep = int8::PreparedI8B::prepare(&obj, &bt).unwrap(); + let mut c = vec![0i32; obj.c_len()]; + assert!(matches!( + int8::direct(&obj, &l, &prep, &bt, &mut c), + Err(ShapeRefusal::Direct( + DirectRefusal::RowsNotConsecutive { .. } + )) + )); + + let socket = U8Socket::in_order(&lanes, dim); + let mask = Selection::mask(SPACE_A, 4096, (0..64).map(|k| k * 61 % 4096)); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, mask).unwrap(); + let l = int8::resolve(&obj, &world, &socket).unwrap(); + let prep = int8::PreparedI8B::prepare(&obj, &bt).unwrap(); + assert!(matches!( + int8::direct(&obj, &l, &prep, &bt, &mut vec![0i32; obj.c_len()]), + Err(ShapeRefusal::NotARegion) + )); + + // The pitch is 4096 (already a multiple of 64). A 56-long region at + // 4040 pads to 64 and would read up to 4104, past its own row. + let sel = Selection::region(SPACE_A, 4040, 56); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let l = int8::resolve(&obj, &world, &socket).unwrap(); + let prep = int8::PreparedI8B::prepare(&obj, &bt).unwrap(); + assert!(matches!( + int8::direct(&obj, &l, &prep, &bt, &mut vec![0i32; obj.c_len()]), + Err(ShapeRefusal::OverRead { .. }) + )); + + let sel = Selection::region(SPACE_A, 0, 128); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let l = int8::resolve(&obj, &world, &socket).unwrap(); + let prep = int8::PreparedI8B::prepare(&obj, &bt).unwrap(); + let other = BTable::new(&B, 4096, dim); + assert!(matches!( + int8::direct(&obj, &l, &prep, &other, &mut vec![0i32; obj.c_len()]), + Err(ShapeRefusal::Reuse(ReuseRefusal::Operand)) + )); +} From d024630cc0e506cb4b4af776f0644cce5b7c61ad Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 17:51:54 +0000 Subject: [PATCH 2/3] dr-isa-stream-lab: record the INT8 direct arm results Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- .../2026-11-10-int8-direct-packed-b.md | 21 +++++++++++++ .claude/board/entries/README.md | 3 +- crates/dr-isa-stream-lab/BENCH-SHAPE.md | 31 +++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 .claude/board/entries/2026-11-10-int8-direct-packed-b.md diff --git a/.claude/board/entries/2026-11-10-int8-direct-packed-b.md b/.claude/board/entries/2026-11-10-int8-direct-packed-b.md new file mode 100644 index 000000000..c6448a235 --- /dev/null +++ b/.claude/board/entries/2026-11-10-int8-direct-packed-b.md @@ -0,0 +1,21 @@ +# 2026-11-10 — INT8 direct arm on prepacked INT8 B + +**Status:** MEASURED (lab). Needs AdaWorldAPI/ndarray#418. + +**What.** `dr-isa-stream-lab`'s INT8 arm now reads A in place and takes B +from bands packed once (`PreparedI8B`, `PackedI8B`), through +`ndarray::simd::int8_gemm_packed_strided`. The prepared-operand reuse rule is +one `shape::ReuseKey` for BF16 and INT8. + +**Result** (one AMX VM, 41 warm runs, three runs). At 256 fields the GEMM +goes from 78.3–78.8 µs to 45.5–48.1 µs, end to end from 88.9–92.2 µs to +47.5–57.9 µs; at 64 fields from 3.4–3.6 µs to 0.98–1.01 µs. + +**Negative result.** One call per 16×16 tile (99–108 µs) was slower than +`gemm_i8` with its pack: per-call tile configuration and lost 2×2 blocking. +The pack only pays to hoist when the whole-matrix kernel takes it. + +**Governing question** (`dr-dt64-locality-execution-contract.md`): the VNNI +pack of B was recomputed per operation; it is now done once per binding and +reused under `ReuseKey` (operand identity and revision, selection, frame, +width). diff --git a/.claude/board/entries/README.md b/.claude/board/entries/README.md index 7d336cb7f..be4331891 100644 --- a/.claude/board/entries/README.md +++ b/.claude/board/entries/README.md @@ -25,11 +25,12 @@ index row, (3) no duplicate entry id. Checks 1 and 2 are deliberately opposite directions; the stranding this convention prevents shows up in exactly one of them, never both. -591 entries, 2026-08-06 .. 2026-11-10. +592 entries, 2026-08-06 .. 2026-11-10. | date | entry id | finding | file | |---|---|---|---| | 2026-11-10 | `lab-resolve-borrow-all` | | [2026-11-10-lab-resolve-borrow-all.md](2026-11-10-lab-resolve-borrow-all.md) | +| 2026-11-10 | `int8-direct-packed-b` | | [2026-11-10-int8-direct-packed-b.md](2026-11-10-int8-direct-packed-b.md) | | 2026-11-10 | `dt64-lane-borrow-all` | | [2026-11-10-dt64-lane-borrow-all.md](2026-11-10-dt64-lane-borrow-all.md) | | 2026-11-10 | `dt64-int8-facet-stride` | | [2026-11-10-dt64-int8-facet-stride.md](2026-11-10-dt64-int8-facet-stride.md) | | 2026-11-10 | `D-DT64-GEMM-SHAPE-1` | | [2026-11-10-dt64-gemm-shape.md](2026-11-10-dt64-gemm-shape.md) | diff --git a/crates/dr-isa-stream-lab/BENCH-SHAPE.md b/crates/dr-isa-stream-lab/BENCH-SHAPE.md index 247033661..480a80683 100644 --- a/crates/dr-isa-stream-lab/BENCH-SHAPE.md +++ b/crates/dr-isa-stream-lab/BENCH-SHAPE.md @@ -313,3 +313,34 @@ three are now fixed: The FACET STRIDE guard (`facet-stride-guard.sh --diff`) reports 0 hits on this change. ndarray is unchanged. + +## INT8 direct arm on prepacked INT8 B (ndarray#418) + +The OPTIMIZATION FOUND above, now built. `int8::direct` reads A in place at +the u8 lanes' pitch and takes B from `PreparedI8B` (one `PackedI8B` band per +16 output columns, packed once) through +`ndarray::simd::int8_gemm_packed_strided`. Reuse follows `ReuseKey`, the one +rule now shared with the BF16 `PreparedB`. + +One AMX VM, median of 41 warm runs, three runs +(`results/shape-2026-11-10-int8-direct-run*.txt`): + +| Row | 64 fields | 256 fields | +|---|---|---| +| `backend::gemm_i8` (packs B per call) | 3.4–3.6 µs | 78.3–78.8 µs | +| … of which band gather + VNNI pack | 1.9–2.1 µs | 28.6–29.4 µs | +| **direct GEMM (A in place, B prepared once)** | **0.98–1.01 µs** | **45.5–48.1 µs** (348–368 GMAC/s) | +| prepare B once | 6.4–6.7 µs | 105 µs | +| warm end to end, staged arm | 5.7–5.9 µs | 88.9–92.2 µs | +| **warm end to end, direct arm** | **2.9–3.0 µs** | **47.5–57.9 µs** | + +The direct arm allocates nothing and copies no A. Preparing B costs about +three `gemm_i8` packs, so it pays once B is reused three times. + +**A negative result kept on record.** The first version of this arm called +`int8_tile_gemm_16x16_packed_strided` once per 16×16 tile. It measured 99–108 +µs at 256 fields, slower than `gemm_i8` *with* its per-call pack: 256 calls +each pay the tile configuration (~105 ns), and the per-tile calls lose the +2×2 register blocking. Hoisting the pack was not enough; the whole-matrix +kernel had to take the prepacked bands. That is why ndarray#418 adds +`int8_gemm_packed_strided`. From f97bba5edef1e0ca35f432fdbc61912c4ecf863d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:09:51 +0000 Subject: [PATCH 3/3] dr-isa-stream-lab: time the B pack through ndarray::simd, not hpc The benchmark's pack-timing row called ndarray::hpc::amx_matmul::vnni_pack_i8 directly. hpc is reached only through the ndarray::simd polyfill, so the row now times PackedI8B::pack_from, which packs into the same VNNI layout. The measured share is unchanged (23.1 us, 39% of the gemm_i8 row at 256 fields). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- crates/dr-isa-stream-lab/src/bin/shape.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/dr-isa-stream-lab/src/bin/shape.rs b/crates/dr-isa-stream-lab/src/bin/shape.rs index 96feaf578..d9cbc388d 100644 --- a/crates/dr-isa-stream-lab/src/bin/shape.rs +++ b/crates/dr-isa-stream-lab/src/bin/shape.rs @@ -376,18 +376,19 @@ fn main() { assert_eq!(c8, want8); // The B packing gemm_i8 does inside every call, timed on its own: // per 16-column band, gather the band (K x 16) and VNNI-pack it with - // ndarray's own `vnni_pack_i8` (int8_gemm_amx_tiled_rb's steps, minus - // its three buffer allocations, which the GEMM row reports). + // `ndarray::simd::PackedI8B::pack_from` (the same layout and loop + // int8_gemm_amx_tiled_rb packs with, minus its three buffer + // allocations, which the GEMM row reports). let k8 = r8.k_pad; assert_eq!(b8.len(), k8 * dim, "B materialized row-major"); - let (mut band, mut packed) = (vec![0i8; k8 * 16], vec![0i8; k8 * 16]); + let (mut band, mut packed) = (vec![0i8; k8 * 16], ndarray::simd::PackedI8B::zeroed(k8)); let t8_pack = median_ns(|| { for j in (0..dim).step_by(16) { for kk in 0..k8 { band[kk * 16..kk * 16 + 16] .copy_from_slice(&b8[kk * dim + j..kk * dim + j + 16]); } - ndarray::hpc::amx_matmul::vnni_pack_i8(&band, &mut packed, k8, 16); + packed.pack_from(&band); black_box(&packed); } });