From 639a814e83798ee8e82bbd8ffddafb09ff346c87 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 15:27:33 +0000 Subject: [PATCH 1/4] lab: DT64-shaped virtual 64x64 and 256x256 BF16 objects (D-DT64-GEMM-SHAPE-1/2) A WHERE-selected population is routed through one DT64 lane binding into a virtual object (fields x columns, reduction over selected identities) and consumed as 16 or 256 output tiles by four arms: direct strided AMX, staged dense A tiles, ndarray CBLAS BF16, and a scalar f64 oracle. The object holds addresses and the selection only. B is prepared once as VNNI column panels, keyed to the selection, the frame issue, the B revision and the width, and refused when any of them changes. Direct reads refuse scattered masks, non-slab or permuted lanes, short pitches, and any K padding that would read live neighbouring identities (a NaN there poisons the tile even though B's padding row is zero). 256 demanded fields bind directly under Extent::DR256_SQ_X64 (MAX_FIELDS is 256); no production lane budget changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- .github/workflows/dr-isa-stream-lab.yml | 2 + .../results/shape-2026-11-10-run1.txt | 22 + .../results/shape-2026-11-10-run2.txt | 22 + .../results/shape-2026-11-10-run3.txt | 22 + crates/dr-isa-stream-lab/src/bin/shape.rs | 383 +++++++++++ crates/dr-isa-stream-lab/src/bind.rs | 20 +- crates/dr-isa-stream-lab/src/fixture.rs | 2 +- crates/dr-isa-stream-lab/src/gemm.rs | 15 +- crates/dr-isa-stream-lab/src/lib.rs | 4 + crates/dr-isa-stream-lab/src/shape.rs | 628 ++++++++++++++++++ crates/dr-isa-stream-lab/src/source.rs | 18 + .../tests/integration/main.rs | 1 + .../tests/integration/shape.rs | 555 ++++++++++++++++ 13 files changed, 1683 insertions(+), 11 deletions(-) create mode 100644 crates/dr-isa-stream-lab/results/shape-2026-11-10-run1.txt create mode 100644 crates/dr-isa-stream-lab/results/shape-2026-11-10-run2.txt create mode 100644 crates/dr-isa-stream-lab/results/shape-2026-11-10-run3.txt create mode 100644 crates/dr-isa-stream-lab/src/bin/shape.rs create mode 100644 crates/dr-isa-stream-lab/src/shape.rs create mode 100644 crates/dr-isa-stream-lab/tests/integration/shape.rs diff --git a/.github/workflows/dr-isa-stream-lab.yml b/.github/workflows/dr-isa-stream-lab.yml index 0f50b837c..28120483d 100644 --- a/.github/workflows/dr-isa-stream-lab.yml +++ b/.github/workflows/dr-isa-stream-lab.yml @@ -71,3 +71,5 @@ jobs: run: cargo test --release --manifest-path crates/dr-isa-stream-lab/Cargo.toml -- --nocapture - name: stage costs (every timed result is checked against the oracle) run: cargo run --release --manifest-path crates/dr-isa-stream-lab/Cargo.toml --bin bench + - name: virtual-shape costs, 64x64 and 256x256 (every arm checked against the oracle) + run: cargo run --release --manifest-path crates/dr-isa-stream-lab/Cargo.toml --bin shape diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-run1.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-run1.txt new file mode 100644 index 000000000..e703283f1 --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-run1.txt @@ -0,0 +1,22 @@ +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 410.6 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3362 ns · 2 allocs | 8912 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1848 ns · 0 allocs · 0 B | 13.9 µs · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 15.2 µs | 155.1 µs | +| B preparation (VNNI panels) | 13.2 µs · 8192 B written · 8320 B alloc | 148.7 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 5911 ns · 44.3 GMAC/s · 0 allocs · 0 B tmp | 145.6 µs · 115.3 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3945 ns · 66.4 GMAC/s | 127.0 µs · 132.1 GMAC/s | +| Staged AMX (dense A tiles) | 4472 ns · 1 allocs · 2048 B tmp | 139.7 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 37.8 µs · 23 allocs · 54272 B tmp | 1063.2 µ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) | 7174 ns | 169.6 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 25.9 µs | 368.4 µs | +| Warm repetitions (100, per run, one prepare) | 7413 ns | 168.0 µs | diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-run2.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-run2.txt new file mode 100644 index 000000000..9bd981297 --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-run2.txt @@ -0,0 +1,22 @@ +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 465.2 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3180 ns · 2 allocs | 8803 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1607 ns · 0 allocs · 0 B | 13.9 µs · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 10.8 µs | 151.5 µs | +| B preparation (VNNI panels) | 9532 ns · 8192 B written · 8320 B alloc | 171.0 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4134 ns · 63.4 GMAC/s · 0 allocs · 0 B tmp | 177.7 µs · 94.4 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3659 ns · 71.6 GMAC/s | 148.4 µs · 113.0 GMAC/s | +| Staged AMX (dense A tiles) | 4897 ns · 1 allocs · 2048 B tmp | 155.3 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 38.4 µs · 23 allocs · 54272 B tmp | 1628.7 µ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) | 6872 ns | 196.6 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 22.5 µs | 480.5 µs | +| Warm repetitions (100, per run, one prepare) | 6958 ns | 174.9 µs | diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-run3.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-run3.txt new file mode 100644 index 000000000..ee3a8186f --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-run3.txt @@ -0,0 +1,22 @@ +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 392.4 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3190 ns · 2 allocs | 8868 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1474 ns · 0 allocs · 0 B | 13.8 µs · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 10.4 µs | 195.5 µs | +| B preparation (VNNI panels) | 8921 ns · 8192 B written · 8320 B alloc | 181.1 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4038 ns · 64.9 GMAC/s · 0 allocs · 0 B tmp | 158.3 µs · 106.0 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 4394 ns · 59.7 GMAC/s | 136.3 µs · 123.1 GMAC/s | +| Staged AMX (dense A tiles) | 4102 ns · 1 allocs · 2048 B tmp | 146.4 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 38.4 µs · 23 allocs · 54272 B tmp | 1102.6 µ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) | 6665 ns | 172.7 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 29.1 µs | 399.6 µs | +| Warm repetitions (100, per run, one prepare) | 8035 ns | 203.7 µs | diff --git a/crates/dr-isa-stream-lab/src/bin/shape.rs b/crates/dr-isa-stream-lab/src/bin/shape.rs new file mode 100644 index 000000000..03ec5f894 --- /dev/null +++ b/crates/dr-isa-stream-lab/src/bin/shape.rs @@ -0,0 +1,383 @@ +//! D-DT64-GEMM-SHAPE-1/2 benchmark: 64 x 64 and 256 x 256 virtual objects. +//! +//! `cargo run --release --bin shape`. Every arm is checked against the +//! scalar oracle before timing and after the timed runs. Times are medians +//! of warm runs; allocations and peak temporary bytes come from a counting +//! global allocator, measured on one extra run of each operation. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::hint::black_box; +use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::time::Instant; + +use dr_isa_stream_lab::bind::{World, SPACE_A}; +use dr_isa_stream_lab::fixture::Fixture; +use dr_isa_stream_lab::shape::{ + cblas, direct, oracle, staged, BOperand, PreparedB, Selection, VirtualObject, +}; +use dr_isa_stream_lab::source::{Bf16Lanes, Socket}; +use lance_graph_dt64::Extent; +use ndarray::simd::bf16_tile_gemm_tier; + +struct Counting; +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +static ALLOCS: AtomicUsize = AtomicUsize::new(0); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + ALLOCS.fetch_add(1, Relaxed); + let now = LIVE.fetch_add(l.size(), Relaxed) + l.size(); + PEAK.fetch_max(now, Relaxed); + // SAFETY: forwards the caller's layout to the system allocator. + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + LIVE.fetch_sub(l.size(), Relaxed); + // SAFETY: `p` came from `alloc` with the same layout. + unsafe { System.dealloc(p, l) } + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +/// (allocations, peak temporary bytes above the live set) of one call. +fn mem(f: impl FnOnce() -> R) -> (usize, usize, R) { + let base = LIVE.load(Relaxed); + PEAK.store(base, Relaxed); + let a0 = ALLOCS.load(Relaxed); + let r = f(); + (ALLOCS.load(Relaxed) - a0, PEAK.load(Relaxed) - base, r) +} + +const RUNS: usize = 41; + +fn median_ns(mut f: impl FnMut()) -> f64 { + f(); + let mut t: Vec = (0..RUNS) + .map(|_| { + let s = Instant::now(); + f(); + s.elapsed().as_nanos() as f64 + }) + .collect(); + t.sort_by(|a, b| a.partial_cmp(b).unwrap()); + t[RUNS / 2] +} + +fn fmt(ns: f64) -> String { + if ns < 10_000.0 { + format!("{ns:.0} ns") + } else { + format!("{:.1} µs", ns / 1000.0) + } +} + +fn cache_info() -> String { + let mut out = Vec::new(); + for idx in 0..8 { + let base = format!("/sys/devices/system/cpu/cpu0/cache/index{idx}"); + let read = + |f: &str| std::fs::read_to_string(format!("{base}/{f}")).map(|s| s.trim().to_string()); + if let (Ok(level), Ok(kind), Ok(size)) = (read("level"), read("type"), read("size")) { + out.push(format!("L{level} {kind} {size}")); + } + } + if out.is_empty() { + "not reported".into() + } else { + out.join(", ") + } +} + +struct Row { + metric: &'static str, + v: [String; 2], +} + +fn main() { + let model = std::fs::read_to_string("/proc/cpuinfo") + .ok() + .and_then(|s| { + s.lines() + .find(|l| l.starts_with("model name")) + .map(|l| l.split(':').nth(1).unwrap().trim().to_string()) + }) + .unwrap_or_default(); + println!( + "Host: {model}; {} logical CPUs; cache (cpu0): {}", + std::thread::available_parallelism().map_or(0, |n| n.get()), + cache_info() + ); + println!( + "Tile tier: {}. Single-threaded. {RUNS} warm runs per row (median).\n", + bf16_tile_gemm_tier() + ); + + let n = 65_536; + let b = BOperand { + seed: 0xB0B, + rev: 1, + }; + let mut rows: Vec = Vec::new(); + let mut push = |metric: &'static str, col: usize, v: String| { + if let Some(r) = rows.iter_mut().find(|r| r.metric == metric) { + r.v[col] = v; + } else { + let mut r = Row { + metric, + v: [String::new(), String::new()], + }; + r.v[col] = v; + rows.push(r); + } + }; + + for (col, dim) in [64usize, 256].into_iter().enumerate() { + let fx = Fixture { + n, + props: dim, + seed: 0x5A9E, + }; + let extent = if dim == 64 { + Extent::DR64_CUBE + } else { + Extent::DR256_SQ_X64 + }; + let world = World::with_extent(dim, "isa:f", extent); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let fields: Vec = (0..dim).map(|f| f as u8).collect(); + let sel = Selection::region(SPACE_A, 4096, dim); + let want: Vec = oracle( + &sel, + &fields, + dim, + |i, p| f64::from(fx.value(i, p)), + |i, j| f64::from(b.value(i, j)), + ) + .iter() + .map(|&v| v as f32) + .collect(); + + let bind = || VirtualObject::bind(&world, &socket, &fields, dim, sel.clone()).unwrap(); + let obj = bind(); + let (prep, prep_rep) = PreparedB::prepare(&obj, &b); + let lanes_r = obj.resolve(&world, &socket).unwrap(); + let mut c = vec![0f32; obj.c_len()]; + let mut scratch = Vec::new(); + let (mut am, mut bm) = (Vec::new(), Vec::new()); + + // Correctness before timing. + let dr = direct(&obj, &lanes_r, &prep, b.rev, &mut c).unwrap(); + assert_eq!(c, want, "direct {dim}"); + let sr = staged(&obj, &lanes_r, &prep, b.rev, &mut scratch, &mut c).unwrap(); + assert_eq!(c, want, "staged {dim}"); + let cr = cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c); + assert_eq!(c, want, "cblas {dim}"); + + let t_bind = median_ns(|| { + black_box(bind()); + }); + let t_resolve = median_ns(|| { + black_box(obj.resolve(&world, &socket).unwrap()); + }); + let t_resolve_pf = median_ns(|| { + black_box(obj.resolve_per_field(&world, &socket).unwrap()); + }); + let t_prep = median_ns(|| { + black_box(PreparedB::prepare(&obj, &b)); + }); + let t_direct = median_ns(|| { + direct(&obj, &lanes_r, &prep, b.rev, &mut c).unwrap(); + }); + assert_eq!(c, want); + // Same values and region, pitch n + 32 (not a multiple of 4 KiB): does + // the power-of-two row stride of the 64K universe cost the direct read? + let fx2 = Fixture { n: n + 32, ..fx }; + let lanes2 = Bf16Lanes::slab_in_order(&fx2).unwrap(); + let socket2 = Socket::in_order(&lanes2, dim); + let obj2 = VirtualObject::bind(&world, &socket2, &fields, dim, sel.clone()).unwrap(); + let (prep2, _) = PreparedB::prepare(&obj2, &b); + let l2 = obj2.resolve(&world, &socket2).unwrap(); + direct(&obj2, &l2, &prep2, b.rev, &mut c).unwrap(); + assert_eq!(c, want, "direct, odd pitch {dim}"); + let t_direct_odd = median_ns(|| { + direct(&obj2, &l2, &prep2, b.rev, &mut c).unwrap(); + }); + assert_eq!(c, want); + let t_staged = median_ns(|| { + staged(&obj, &lanes_r, &prep, b.rev, &mut scratch, &mut c).unwrap(); + }); + assert_eq!(c, want); + let t_cblas = median_ns(|| { + cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c); + }); + assert_eq!(c, want); + let t_warm = median_ns(|| { + let l = obj.resolve(&world, &socket).unwrap(); + direct(&obj, &l, &prep, b.rev, &mut c).unwrap(); + }); + assert_eq!(c, want); + let t_cold = median_ns(|| { + let o = bind(); + let (p, _) = PreparedB::prepare(&o, &b); + let l = o.resolve(&world, &socket).unwrap(); + let mut cc = vec![0f32; o.c_len()]; + direct(&o, &l, &p, b.rev, &mut cc).unwrap(); + black_box(cc); + }); + // 100 repetitions with unchanged selection: one prepare, 100 x (resolve + direct). + let s = Instant::now(); + let (p, _) = PreparedB::prepare(&obj, &b); + for _ in 0..100 { + let l = obj.resolve(&world, &socket).unwrap(); + direct(&obj, &l, &p, b.rev, &mut c).unwrap(); + } + let t_rep = s.elapsed().as_nanos() as f64 / 100.0; + assert_eq!(c, want); + + let (a_bind, m_bind, _) = mem(bind); + let (a_res, m_res, _) = mem(|| obj.resolve(&world, &socket).unwrap()); + let (a_prep, m_prep, _) = mem(|| PreparedB::prepare(&obj, &b)); + let (a_dir, m_dir, _) = mem(|| direct(&obj, &lanes_r, &prep, b.rev, &mut c).unwrap()); + let (a_stg, m_stg, _) = + mem(|| staged(&obj, &lanes_r, &prep, b.rev, &mut Vec::new(), &mut c).unwrap()); + let (a_cbl, m_cbl, _) = + mem(|| cblas(&obj, &lanes_r, &b, &mut Vec::new(), &mut Vec::new(), &mut c)); + + let macs = (dim * dim * dim) as f64; + push( + "Output tiles / K=32 dot-product steps", + col, + format!("{} / {}", dr.tiles, dr.dp_steps), + ); + push( + "DT64 bind (cold)", + col, + format!("{} · {a_bind} allocs", fmt(t_bind)), + ); + push( + "Resolve: one check + borrows (warm)", + col, + format!("{} · {a_res} allocs · {m_res} B", fmt(t_resolve)), + ); + push("Resolve: `lane()` per field (warm)", col, fmt(t_resolve_pf)); + push( + "B preparation (VNNI panels)", + col, + format!( + "{} · {} B written · {} B alloc", + fmt(t_prep), + prep_rep.bytes_written, + m_prep + ), + ); + push( + "Direct AMX (A in place)", + col, + format!( + "{} · {:.1} GMAC/s · {a_dir} allocs · {m_dir} B tmp", + fmt(t_direct), + macs / t_direct + ), + ); + push( + "Direct AMX, pitch 65,568 (not 2^k)", + col, + format!("{} · {:.1} GMAC/s", fmt(t_direct_odd), macs / t_direct_odd), + ); + push( + "Staged AMX (dense A tiles)", + col, + format!("{} · {a_stg} allocs · {m_stg} B tmp", fmt(t_staged)), + ); + push( + "ndarray CBLAS BF16", + col, + format!("{} · {a_cbl} allocs · {m_cbl} B tmp", fmt(t_cblas)), + ); + push( + "Source bytes copied (direct / staged / CBLAS)", + col, + format!("{} / {} / {}", dr.a_copied, sr.a_copied, cr.a_copied), + ); + push( + "CBLAS B materialized", + col, + format!("{} B", cr.b_materialized), + ); + push( + "FP32 accumulator (C)", + col, + format!("{} B", obj.c_len() * 4), + ); + push( + "End-to-end warm (resolve + direct, B reused)", + col, + fmt(t_warm), + ); + push( + "End-to-end cold (bind + prepare + resolve + direct)", + col, + fmt(t_cold), + ); + push( + "Warm repetitions (100, per run, one prepare)", + col, + fmt(t_rep), + ); + let _ = (m_bind, a_prep); + } + + // Sparse demand: 40 scattered identities, 256 fields x 256 columns. + { + let dim = 256; + let fx = Fixture { + n, + props: dim, + seed: 0x5A9E, + }; + let world = World::with_extent(dim, "isa:f", Extent::DR256_SQ_X64); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let fields: Vec = (0..dim).map(|f| f as u8).collect(); + let sel = Selection::mask(SPACE_A, n, (0..40).map(|k| (k * 1637 + 11) % n)); + let want: Vec = oracle( + &sel, + &fields, + dim, + |i, p| f64::from(fx.value(i, p)), + |i, j| f64::from(b.value(i, j)), + ) + .iter() + .map(|&v| v as f32) + .collect(); + let obj = VirtualObject::bind(&world, &socket, &fields, dim, sel.clone()).unwrap(); + let (prep, _) = PreparedB::prepare(&obj, &b); + let l = obj.resolve(&world, &socket).unwrap(); + let mut c = vec![0f32; obj.c_len()]; + let mut scratch = Vec::new(); + let r = staged(&obj, &l, &prep, b.rev, &mut scratch, &mut c).unwrap(); + assert_eq!(c, want); + let t = median_ns(|| { + staged(&obj, &l, &prep, b.rev, &mut scratch, &mut c).unwrap(); + }); + assert_eq!(c, want); + println!( + "Sparse demand (256 fields x 256 cols, 40 scattered identities): logical selection {} · K padded {} · lanes borrowed {} · A bytes copied {} · dense dot-product steps {} · staged AMX {}\n", + sel.len(), + sel.k_pad(), + dim, + r.a_copied, + r.dp_steps, + fmt(t) + ); + } + + println!("| Metric | 64×64 | 256×256 |\n|---|---|---|"); + for r in rows { + println!("| {} | {} | {} |", r.metric, r.v[0], r.v[1]); + } +} diff --git a/crates/dr-isa-stream-lab/src/bind.rs b/crates/dr-isa-stream-lab/src/bind.rs index 680b108c7..9ae12666e 100644 --- a/crates/dr-isa-stream-lab/src/bind.rs +++ b/crates/dr-isa-stream-lab/src/bind.rs @@ -59,10 +59,22 @@ pub struct World { impl World { pub fn new() -> World { + World::with_fields(FIELDS, "isa:f") + } + + /// The class with `count` fields named `{prefix}{f}`. Two worlds with + /// different prefixes bind the class over different bases. + pub fn with_fields(count: usize, prefix: &str) -> World { + World::with_extent(count, prefix, Extent::DR64_CUBE) + } + + /// The class with `count` fields under `extent` (DR256 property axes are + /// needed past 64 fields). + pub fn with_extent(count: usize, prefix: &str, extent: Extent) -> World { let mut store = BindStore::new(); let view = View( - (0..FIELDS) - .map(|f| FieldRef::new(format!("isa:f{f}"), format!("F{f}"))) + (0..count) + .map(|f| FieldRef::new(format!("{prefix}{f}"), format!("F{f}"))) .collect(), ); store @@ -71,8 +83,8 @@ impl World { CLASS, ClassSchema { schema_rev: SchemaRev(1), - field_count: FIELDS, - extent: Extent::DR64_CUBE, + field_count: count, + extent, }, Vec::new(), ) diff --git a/crates/dr-isa-stream-lab/src/fixture.rs b/crates/dr-isa-stream-lab/src/fixture.rs index 7b115bf11..00424c2ef 100644 --- a/crates/dr-isa-stream-lab/src/fixture.rs +++ b/crates/dr-isa-stream-lab/src/fixture.rs @@ -15,7 +15,7 @@ pub struct Fixture { pub seed: u64, } -fn mix(mut x: u64) -> u64 { +pub(crate) fn mix(mut x: u64) -> u64 { x ^= x >> 33; x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); x ^= x >> 33; diff --git a/crates/dr-isa-stream-lab/src/gemm.rs b/crates/dr-isa-stream-lab/src/gemm.rs index 7f55e344c..4f4b139ae 100644 --- a/crates/dr-isa-stream-lab/src/gemm.rs +++ b/crates/dr-isa-stream-lab/src/gemm.rs @@ -23,7 +23,7 @@ use crate::fixture::{BLOCK, MASKS, ROWS}; use crate::source::{SlabLane, Socket}; /// bf16 1.0. -const ONE: u16 = 0x3F80; +pub(crate) const ONE: u16 = 0x3F80; /// How A reaches the tile. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -88,13 +88,16 @@ pub struct Report { /// In-place geometry of one row tile: A's row `r` is /// `slab[(first_row + r) * pitch..]`. -struct Geometry<'a> { - slab: &'a [u16], - first_row: usize, - pitch: usize, +pub(crate) struct Geometry<'a> { + pub(crate) slab: &'a [u16], + pub(crate) first_row: usize, + pub(crate) pitch: usize, } -fn geometry<'a>(fields: &[u8], lanes: &[SlabLane<'a>]) -> Result, DirectRefusal> { +pub(crate) fn geometry<'a>( + fields: &[u8], + lanes: &[SlabLane<'a>], +) -> Result, DirectRefusal> { if lanes.len() != ROWS { return Err(DirectRefusal::PartialRowTile { lanes: lanes.len() }); } diff --git a/crates/dr-isa-stream-lab/src/lib.rs b/crates/dr-isa-stream-lab/src/lib.rs index db745c729..e847fd7db 100644 --- a/crates/dr-isa-stream-lab/src/lib.rs +++ b/crates/dr-isa-stream-lab/src/lib.rs @@ -13,6 +13,9 @@ //! `C[p][m] = sum_i lane_p[i] * mask_m(i)`, with A read in place from the //! slab when its geometry allows and staged otherwise. //! * [`oracle`] computes the answer from the fixture alone. +//! * [`shape`] is the D-DT64-GEMM-SHAPE-1/2 probe: a WHERE-selected +//! population routed through the binding into a virtual 64 x 64 or 256 x 256 BF16 +//! object, consumed as 16 output tiles by four arms. //! //! [`LaneSource`]: lance_graph_dt64::LaneSource @@ -21,4 +24,5 @@ pub mod cube; pub mod fixture; pub mod gemm; pub mod oracle; +pub mod shape; pub mod source; diff --git a/crates/dr-isa-stream-lab/src/shape.rs b/crates/dr-isa-stream-lab/src/shape.rs new file mode 100644 index 000000000..bf79a65a1 --- /dev/null +++ b/crates/dr-isa-stream-lab/src/shape.rs @@ -0,0 +1,628 @@ +//! D-DT64-GEMM-SHAPE-1/2: virtual 64 x 64 and 256 x 256 BF16 objects over +//! source-owned lanes. +//! +//! Pipeline: universe -> WHERE -> DT64-shaped virtual object -> BF16 tiles -> +//! GEMM. DR supplies the coordinates, DT64 binds the fields, the source owns +//! the values, and the GEMM is one optional consumer of the shape. +//! +//! * The universe is a [`Bf16Lanes`](crate::source::Bf16Lanes) source: one +//! lane per property over every identity, in one coordinate space. +//! * [`Selection`] is the WHERE result in that space: a contiguous identity +//! **region** (for example one DR64 or DR256 identity tile) or a scattered +//! **mask**. +//! * [`VirtualObject`] is the shaped object: a DT64 [`LaneBinding`] of the +//! demanded fields plus the selection and the output width. It holds +//! addresses and the selection, never values; it is not a matrix store and +//! not a second copy of the universe. +//! +//! Axis semantics, fixed for every arm: +//! * **rows (M)** = demanded fields, in binding order (16 per row tile); +//! * **reduction (K)** = selected identities, ascending in the selection's +//! row order, padded to the 32-step `TDPBF16PS` consumes; +//! * **columns (N)** = output columns of the synthetic operand B (16 per +//! column tile). +//! +//! `C[p][j] = sum over selected i of A[p][i] * B[i][j]`, FP32. At 64 x 64 that +//! is 4 x 4 output tiles of 16 x 16 and K = 64 (two 32-steps); at 256 x 256 it +//! is 16 x 16 output tiles and K = 256 (eight 32-steps). The 256 x 256 here is +//! fields x columns over 256 identities: not an identity x identity adjacency +//! matrix, and not a claim about resident lanes. +//! +//! The logical tile geometry is not the physical operand. Physically, a +//! direct A tile is 16 rows of the source slab at the slab pitch, offset by +//! the region start; a staged A tile is a dense 16 x K buffer; B is N / 16 +//! VNNI-packed K x 16 column panels. +//! +//! Four arms: +//! * [`direct`]: A read in place by `bf16_tile_gemm_16x16_packed_strided`. +//! Refuses unless the selection is a region, every 16-field group is 16 +//! consecutive rows of one slab, and the K padding would read only the +//! slab's zeroed padding, never live neighbouring identities. +//! * [`staged`]: A gathered into a dense 16 x K tile per field group, every +//! copied byte counted. Accepts regions and masks. +//! * [`cblas`]: ndarray's `cblas_gemm_bf16bf16f32` over dense A and B, both +//! materialized here and counted. +//! * [`oracle`]: a scalar `f64` sum from value functions, without lanes, +//! bindings or tiles. + +use lance_graph_dt64::dr::Frame; +use lance_graph_dt64::{CoordSpace, LaneBinding, LaneRefusal, LaneSource}; +use ndarray::simd::{ + bf16_tile_gemm_16x16_packed, bf16_tile_gemm_16x16_packed_strided, PackedBf16B, +}; + +use crate::bind::World; +use crate::fixture::{bf16_exact, mix, BLOCK}; +use crate::gemm::{geometry, DirectRefusal}; +use crate::source::{SlabLane, Socket}; + +/// Edge of one output tile. +pub const TILE: usize = 16; +/// Most fields one object binds (DT64's field positions are `u8`). +pub const MAX_ROWS: usize = 256; + +/// The WHERE result, in one coordinate space. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Where { + /// Identities `start..start + len`. + Region { start: usize, len: usize }, + /// The set bits of `words`, ascending, over `n` identities. + Mask { n: usize, words: Box<[u64]> }, +} + +/// A WHERE result and the row order it is expressed in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Selection { + pub space: CoordSpace, + pub kind: Where, +} + +impl Selection { + /// A contiguous identity region. + pub fn region(space: CoordSpace, start: usize, len: usize) -> Selection { + Selection { + space, + kind: Where::Region { start, len }, + } + } + + /// The identities `ids` (any order; stored as a bitmap) over `n`. + pub fn mask(space: CoordSpace, n: usize, ids: impl IntoIterator) -> Selection { + let mut words = vec![0u64; n.div_ceil(64)].into_boxed_slice(); + for i in ids { + words[i / 64] |= 1 << (i % 64); + } + Selection { + space, + kind: Where::Mask { n, words }, + } + } + + /// Selected identities: K before padding. + pub fn len(&self) -> usize { + match &self.kind { + Where::Region { len, .. } => *len, + Where::Mask { words, .. } => words.iter().map(|w| w.count_ones() as usize).sum(), + } + } + + /// Whether nothing is selected. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// K padded to the 32-identity step the tile GEMM consumes. + pub fn k_pad(&self) -> usize { + self.len().div_ceil(BLOCK) * BLOCK + } + + /// Call `f(k, i)` for the `k`-th selected identity `i`, ascending. + pub fn for_each(&self, mut f: impl FnMut(usize, usize)) { + match &self.kind { + Where::Region { start, len } => (0..*len).for_each(|k| f(k, start + k)), + Where::Mask { words, .. } => { + let mut k = 0; + for (w, &word) in words.iter().enumerate() { + let mut bits = word; + while bits != 0 { + f(k, w * 64 + bits.trailing_zeros() as usize); + k += 1; + bits &= bits - 1; + } + } + } + } + } + + /// A 64-bit witness of which identities are selected (FNV-1a over the + /// region bounds or the mask words). Equal selections give equal keys. + pub fn key(&self) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut eat = |x: u64| { + for b in x.to_le_bytes() { + h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + } + }; + match &self.kind { + Where::Region { start, len } => { + eat(1); + eat(*start as u64); + eat(*len as u64); + } + Where::Mask { n, words } => { + eat(2); + eat(*n as u64); + words.iter().for_each(|&w| eat(w)); + } + } + h + } +} + +/// Why the shape cannot be built or consumed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ShapeRefusal { + /// The DT64 binding refused (frame, space, scope, route, mapping, basis). + Lane(LaneRefusal), + /// The field count is not a multiple of 16 in 16..=256. + FieldCount { fields: usize }, + /// The output width is not a multiple of 16, or is zero. + Columns { cols: usize }, + /// Nothing is selected. + EmptySelection, + /// The selection is in another row order than the binding. + SelectionSpace { + selection: CoordSpace, + binding: CoordSpace, + }, + /// Direct read: the lanes are not one tile load. + Direct(DirectRefusal), + /// Direct read: the WHERE result is a scattered mask, not a region. + NotARegion, + /// Direct read: padding K to the 32-step would read identities that are + /// live data (not the slab's zeroed padding), or past the row. + OverRead { + start: usize, + len: usize, + k_pad: usize, + n: usize, + pitch: usize, + }, + /// The prepared B does not belong to this object. + Reuse(ReuseRefusal), +} + +impl From for ShapeRefusal { + fn from(r: LaneRefusal) -> Self { + ShapeRefusal::Lane(r) + } +} + +/// The shaped object: a lane binding, the WHERE result and the output width. +/// Addresses and the selection only; no values. +#[derive(Debug, Clone)] +pub struct VirtualObject { + binding: LaneBinding, + fields: Vec, + cols: usize, + selection: Selection, +} + +impl VirtualObject { + /// Cold: bind `fields` (a multiple of 16, at most 256) through DT64 under + /// the selection's row order; the view has `cols` output columns. + pub fn bind( + world: &World, + socket: &Socket<'_>, + fields: &[u8], + cols: usize, + selection: Selection, + ) -> Result { + if fields.is_empty() || fields.len() > MAX_ROWS || !fields.len().is_multiple_of(TILE) { + return Err(ShapeRefusal::FieldCount { + fields: fields.len(), + }); + } + if cols == 0 || !cols.is_multiple_of(TILE) { + return Err(ShapeRefusal::Columns { cols }); + } + if selection.is_empty() { + return Err(ShapeRefusal::EmptySelection); + } + let binding = world.bind(socket, fields, selection.space)?; + Ok(VirtualObject { + binding, + fields: fields.to_vec(), + cols, + selection, + }) + } + + /// The demanded fields: the view's rows. + pub fn fields(&self) -> &[u8] { + &self.fields + } + + /// Output columns. + pub fn cols(&self) -> usize { + self.cols + } + + /// The WHERE result: the view's reduction axis. + pub fn selection(&self) -> &Selection { + &self.selection + } + + /// The frame the binding was made at. + pub fn frame(&self) -> &Frame { + self.binding.frame() + } + + /// Output tiles of the view. + pub fn tiles(&self) -> usize { + (self.fields.len() / TILE) * (self.cols / TILE) + } + + /// FP32 result elements (`rows x cols`). + pub fn c_len(&self) -> usize { + self.fields.len() * self.cols + } + + /// Warm: check the binding once against the store, view and source, then + /// borrow every demanded lane. No allocation. + pub fn resolve<'s>( + &self, + world: &World, + socket: &'s Socket<'_>, + ) -> Result, ShapeRefusal> { + if self.selection.space != self.binding.selection() { + return Err(ShapeRefusal::SelectionSpace { + selection: self.selection.space, + binding: self.binding.selection(), + }); + } + self.binding + .check(&world.store, &world.view, socket.lanes.frames(), socket)?; + let borrow = |f: u8| -> Result, ShapeRefusal> { + let addr = self + .binding + .addr(f) + .ok_or(LaneRefusal::NotBound { field: f })?; + Ok(socket + .borrow(addr) + .ok_or(LaneRefusal::Vanished { field: f })?) + }; + let first = borrow(self.fields[0])?; + let mut lanes = [first; MAX_ROWS]; + for (slot, &f) in lanes.iter_mut().zip(&self.fields).skip(1) { + *slot = borrow(f)?; + } + Ok(Lanes { + lanes, + count: self.fields.len(), + }) + } + + /// The same as [`Self::resolve`] the long way: `LaneBinding::lane` per + /// field, which re-checks every bound lane on each call (quadratic in the + /// field count). Kept to measure that cost. + pub fn resolve_per_field<'s>( + &self, + world: &World, + socket: &'s Socket<'_>, + ) -> Result, ShapeRefusal> { + let lane = |f: u8| { + self.binding + .lane(&world.store, &world.view, socket.lanes.frames(), socket, f) + }; + let first = lane(self.fields[0])?; + let mut lanes = [first; MAX_ROWS]; + for (slot, &f) in lanes.iter_mut().zip(&self.fields).skip(1) { + *slot = lane(f)?; + } + Ok(Lanes { + lanes, + count: self.fields.len(), + }) + } +} + +/// The borrowed lanes of a resolved object, in view row order. +#[derive(Debug, Clone, Copy)] +pub struct Lanes<'s> { + lanes: [SlabLane<'s>; MAX_ROWS], + count: usize, +} + +impl<'s> Lanes<'s> { + /// The borrowed lanes. + pub fn lanes(&self) -> &[SlabLane<'s>] { + &self.lanes[..self.count] + } +} + +/// The synthetic B operand: `B[i][j]` for universe identity `i` and output +/// column `j`, an integer in [-8, 8]. `rev` names a revision of B. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BOperand { + pub seed: u64, + pub rev: u64, +} + +impl BOperand { + /// `B[i][j]`. + pub fn value(&self, i: usize, j: usize) -> i32 { + let h = mix(self.seed ^ self.rev.rotate_left(29) ^ ((j as u64) << 44) ^ i as u64); + (h % 17) as i32 - 8 + } + + /// `B[i][j]` in bf16 (always exact). + pub fn bf16(&self, i: usize, j: usize) -> u16 { + bf16_exact(self.value(i, j)).expect("[-8, 8] is exact in bf16") + } +} + +/// Why a prepared B cannot serve an object. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReuseRefusal { + /// Prepared for another selection (another population or row order). + Selection, + /// Prepared under another frame issue: the source has moved since. + Frame, + /// Prepared from another revision of B. + Operand, + /// Prepared for another output width. + Columns, +} + +/// B as `cols / 16` VNNI-packed K x 16 column panels, prepared once for one +/// object (selection, frame, width) and one B revision and reused by every +/// output tile and every repeated run. Rows are the selected identities in +/// order; rows past the selection are zero. +pub struct PreparedB { + space: CoordSpace, + selection: u64, + frame: Frame, + rev: u64, + panels: Vec, +} + +/// What preparing B did. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PrepReport { + /// Panels packed (one per 16 output columns). + pub panels: usize, + /// bf16 entries written into the panels, in bytes. + pub bytes_written: usize, + /// Bytes the panels occupy, K padding included. + pub bytes_allocated: usize, +} + +impl PreparedB { + /// Pack B for `obj`: `panel t row k = B[i_k][16t..16t+16]` in VNNI order. + pub fn prepare(obj: &VirtualObject, b: &BOperand) -> (PreparedB, PrepReport) { + let k = obj.selection.k_pad(); + let mut panels: Vec = (0..obj.cols / TILE) + .map(|_| PackedBf16B::zeroed(k)) + .collect(); + let mut written = 0; + obj.selection.for_each(|row, i| { + for (t, panel) in panels.iter_mut().enumerate() { + let data = panel.data_mut(); + for c in 0..TILE { + data[PackedBf16B::vnni_index(row, c)] = b.bf16(i, t * TILE + c); + } + written += TILE * 2; + } + }); + let allocated = panels.iter().map(|p| p.data().len() * 2).sum(); + ( + PreparedB { + space: obj.selection.space, + selection: obj.selection.key(), + frame: obj.frame().clone(), + rev: b.rev, + panels, + }, + PrepReport { + panels: obj.cols / TILE, + bytes_written: written, + bytes_allocated: allocated, + }, + ) + } + + /// Panel `t` (output columns `16t..16t+16`), for inspection. + pub fn panel(&self, t: usize) -> &PackedBf16B { + &self.panels[t] + } + + /// Whether this prepared B may serve `obj` with B revision `rev`. + pub fn admit(&self, obj: &VirtualObject, rev: u64) -> Result<(), ReuseRefusal> { + if self.space != obj.selection.space || self.selection != obj.selection.key() { + return Err(ReuseRefusal::Selection); + } + if !self.frame.same_issue(obj.frame()) { + return Err(ReuseRefusal::Frame); + } + if self.rev != rev { + return Err(ReuseRefusal::Operand); + } + if self.panels.len() * TILE != obj.cols { + return Err(ReuseRefusal::Columns); + } + Ok(()) + } +} + +/// What one GEMM arm did. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ArmReport { + /// 16 x 16 output tiles computed. + pub tiles: usize, + /// GEMM entry calls. + pub calls: usize, + /// Logical K=32 BF16 dot-product steps (`tiles x k_pad / 32`); excludes + /// tile loads, configuration and packing. + pub dp_steps: usize, + /// Bytes of A copied out of the source. + pub a_copied: usize, + /// Bytes of B materialized row-major (cblas arm only). + pub b_materialized: usize, +} + +fn store_tile(c: &mut [f32], cols: usize, g: usize, t: usize, tile: &[f32; TILE * TILE]) { + for r in 0..TILE { + let row = (g * TILE + r) * cols + t * TILE; + c[row..row + TILE].copy_from_slice(&tile[r * TILE..(r + 1) * TILE]); + } +} + +/// ARM A: A read in place from the slab, one strided tile GEMM per output +/// tile, B from the prepared panels. `c` is `rows x cols`, row-major. +pub fn direct( + obj: &VirtualObject, + lanes: &Lanes<'_>, + b: &PreparedB, + rev: u64, + c: &mut [f32], +) -> Result { + b.admit(obj, rev).map_err(ShapeRefusal::Reuse)?; + let Where::Region { start, len } = obj.selection.kind else { + return Err(ShapeRefusal::NotARegion); + }; + assert_eq!(c.len(), obj.c_len()); + let k_pad = obj.selection.k_pad(); + let mut report = ArmReport::default(); + for (g, (fs, ls)) in obj + .fields + .chunks(TILE) + .zip(lanes.lanes().chunks(TILE)) + .enumerate() + { + let geo = geometry(fs, ls).map_err(ShapeRefusal::Direct)?; + let n = ls[0].n; + // Rows k >= len of B are zero, but 0 * NaN is NaN: the padded read is + // allowed only into the slab's zeroed padding past the last identity. + let pads_into_live = len != k_pad && start + len != n; + if pads_into_live || start + k_pad > geo.pitch { + return Err(ShapeRefusal::OverRead { + start, + len, + k_pad, + n, + pitch: geo.pitch, + }); + } + let a = &geo.slab[geo.first_row * geo.pitch + start..]; + for (t, panel) in b.panels.iter().enumerate() { + let mut tile = [0f32; TILE * TILE]; + bf16_tile_gemm_16x16_packed_strided(a, geo.pitch, panel, &mut tile); + store_tile(c, obj.cols, g, t, &tile); + report.calls += 1; + report.tiles += 1; + report.dp_steps += k_pad / BLOCK; + } + } + Ok(report) +} + +/// ARM B: A gathered into a dense 16 x K tile per field group (in `scratch`, +/// reused across calls), then one packed tile GEMM per output tile. +pub fn staged( + obj: &VirtualObject, + lanes: &Lanes<'_>, + b: &PreparedB, + rev: u64, + scratch: &mut Vec, + c: &mut [f32], +) -> Result { + b.admit(obj, rev).map_err(ShapeRefusal::Reuse)?; + assert_eq!(c.len(), obj.c_len()); + let k_pad = obj.selection.k_pad(); + let len = obj.selection.len(); + let mut report = ArmReport::default(); + for (g, ls) in lanes.lanes().chunks(TILE).enumerate() { + scratch.clear(); + scratch.resize(TILE * k_pad, 0); + for (r, lane) in ls.iter().enumerate() { + let values = lane.values(); + let row = &mut scratch[r * k_pad..(r + 1) * k_pad]; + match &obj.selection.kind { + Where::Region { start, len } => { + row[..*len].copy_from_slice(&values[*start..start + len]) + } + Where::Mask { .. } => obj.selection.for_each(|k, i| row[k] = values[i]), + } + report.a_copied += len * 2; + } + for (t, panel) in b.panels.iter().enumerate() { + let mut tile = [0f32; TILE * TILE]; + bf16_tile_gemm_16x16_packed(scratch, panel, &mut tile); + store_tile(c, obj.cols, g, t, &tile); + report.calls += 1; + report.tiles += 1; + report.dp_steps += k_pad / BLOCK; + } + } + Ok(report) +} + +/// ARM C: ndarray's CBLAS-compatible BF16 GEMM over dense row-major A +/// (rows x K) and B (K x cols), both materialized here into `a` / `bm`. +pub fn cblas( + obj: &VirtualObject, + lanes: &Lanes<'_>, + b: &BOperand, + a: &mut Vec, + bm: &mut Vec, + c: &mut [f32], +) -> ArmReport { + let m = obj.fields.len(); + let n = obj.cols; + let k = obj.selection.len(); + assert_eq!(c.len(), m * n); + a.clear(); + a.resize(m * k, 0); + bm.clear(); + bm.resize(k * n, 0); + for (r, lane) in lanes.lanes().iter().enumerate() { + let values = lane.values(); + let row = &mut a[r * k..(r + 1) * k]; + obj.selection.for_each(|kk, i| row[kk] = values[i]); + } + obj.selection.for_each(|kk, i| { + for j in 0..n { + bm[kk * n + j] = b.bf16(i, j); + } + }); + ndarray::backend::cblas_gemm_bf16bf16f32(a, bm, c, m, n, k); + ArmReport { + tiles: obj.tiles(), + calls: 1, + dp_steps: obj.tiles() * obj.selection.k_pad() / BLOCK, + a_copied: m * k * 2, + b_materialized: k * n * 2, + } +} + +/// ARM D: `C[p][j] = sum over selected i of a(i, field_p) * b(i, j)` in f64, +/// from value functions alone. `rows x cols`, row-major. +pub fn oracle( + selection: &Selection, + fields: &[u8], + cols: usize, + a: impl Fn(usize, usize) -> f64, + b: impl Fn(usize, usize) -> f64, +) -> Vec { + let mut c = vec![0f64; fields.len() * cols]; + selection.for_each(|_, i| { + for (p, &f) in fields.iter().enumerate() { + let av = a(i, usize::from(f)); + for j in 0..cols { + c[p * cols + j] += av * b(i, j); + } + } + }); + c +} diff --git a/crates/dr-isa-stream-lab/src/source.rs b/crates/dr-isa-stream-lab/src/source.rs index b3bbfe5a0..5d77da9c9 100644 --- a/crates/dr-isa-stream-lab/src/source.rs +++ b/crates/dr-isa-stream-lab/src/source.rs @@ -94,6 +94,24 @@ impl Bf16Lanes { }) } + /// `props` lanes over `n` identities in one slab at the padded pitch, in + /// field order, from already-encoded bf16 values (for inputs that were + /// rounded on purpose; the fixture path refuses inexact values). + pub fn slab_encoded(n: usize, props: usize, value: impl Fn(usize, usize) -> u16) -> Bf16Lanes { + let pitch = n.div_ceil(BLOCK) * BLOCK; + let mut data = vec![0u16; props * pitch].into_boxed_slice(); + for p in 0..props { + for i in 0..n { + data[p * pitch + i] = value(i, p); + } + } + Bf16Lanes { + layout: Layout::Slab { data, pitch }, + n, + frames: frames(), + } + } + /// Lanes in one slab, field `f` at row `f`. pub fn slab_in_order(fx: &Fixture) -> Result { let rows: Vec = (0..fx.props).collect(); diff --git a/crates/dr-isa-stream-lab/tests/integration/main.rs b/crates/dr-isa-stream-lab/tests/integration/main.rs index 91492ceb1..1ecf9202d 100644 --- a/crates/dr-isa-stream-lab/tests/integration/main.rs +++ b/crates/dr-isa-stream-lab/tests/integration/main.rs @@ -2,3 +2,4 @@ pub mod geometry; pub mod numeric; pub mod parity; pub mod refusals; +pub mod shape; diff --git a/crates/dr-isa-stream-lab/tests/integration/shape.rs b/crates/dr-isa-stream-lab/tests/integration/shape.rs new file mode 100644 index 000000000..28df4f281 --- /dev/null +++ b/crates/dr-isa-stream-lab/tests/integration/shape.rs @@ -0,0 +1,555 @@ +//! D-DT64-GEMM-SHAPE-1/2: the virtual 64 x 64 and 256 x 256 objects, four +//! arms, and every refusal the shape depends on. + +use dr_isa_stream_lab::bind::{World, READER, SPACE_A, SPACE_OTHER}; +use dr_isa_stream_lab::fixture::{bf16_exact, bf16_round, bf16_value, Fixture}; +use dr_isa_stream_lab::gemm::DirectRefusal; +use dr_isa_stream_lab::shape::{ + cblas, direct, oracle, staged, ArmReport, BOperand, PreparedB, ReuseRefusal, Selection, + ShapeRefusal, VirtualObject, TILE, +}; +use dr_isa_stream_lab::source::{Bf16Lanes, Socket}; +use lance_graph_dt64::dr::{FrameRefusal, FrameRevisions, Scope}; +use lance_graph_dt64::{CoordSpace, Extent, LaneRefusal}; +use ndarray::simd::bf16_tile_gemm_16x16_packed_strided; + +const B: BOperand = BOperand { + seed: 0xB0B, + rev: 1, +}; +/// The row order a property-major (transposed) slab is really in. +const SPACE_PROPS: CoordSpace = CoordSpace { + population: 2, + coordinates: 1, +}; + +fn world(dim: usize) -> World { + let extent = if dim <= 64 { + Extent::DR64_CUBE + } else { + Extent::DR256_SQ_X64 + }; + World::with_extent(dim, "isa:f", extent) +} + +fn fx(n: usize, props: usize) -> Fixture { + Fixture { + n, + props, + seed: 0x5A9E_0000 + (n * props) as u64, + } +} + +fn fields(dim: usize) -> Vec { + (0..dim).map(|f| f as u8).collect() +} + +fn want(fx: &Fixture, sel: &Selection, dim: usize) -> Vec { + oracle( + sel, + &fields(dim), + dim, + |i, p| f64::from(fx.value(i, p)), + |i, j| f64::from(B.value(i, j)), + ) + .iter() + .map(|&v| v as f32) + .collect() +} + +struct Run { + direct: Result<(Vec, ArmReport), ShapeRefusal>, + staged: (Vec, ArmReport), + cblas: (Vec, ArmReport), +} + +fn run(world: &World, socket: &Socket<'_>, dim: usize, sel: Selection) -> Run { + let obj = VirtualObject::bind(world, socket, &fields(dim), dim, sel).unwrap(); + let lanes = obj.resolve(world, socket).unwrap(); + let (prep, _) = PreparedB::prepare(&obj, &B); + let mut c = vec![0f32; obj.c_len()]; + let direct = direct(&obj, &lanes, &prep, B.rev, &mut c).map(|r| (c.clone(), r)); + let mut c = vec![0f32; obj.c_len()]; + let r = staged(&obj, &lanes, &prep, B.rev, &mut Vec::new(), &mut c).unwrap(); + let staged = (c, r); + let mut c = vec![0f32; obj.c_len()]; + let r = cblas(&obj, &lanes, &B, &mut Vec::new(), &mut Vec::new(), &mut c); + Run { + direct, + staged, + cblas: (c, r), + } +} + +/// All four arms agree exactly at 64 x 64 and 256 x 256, over a region of the +/// universe, and each reports what it did. +#[test] +fn four_arms_agree_exactly_at_both_sizes() { + for dim in [64, 256] { + let fx = fx(4096, dim); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, 1024, dim); + let want = want(&fx, &sel, dim); + let r = run(&world, &socket, dim, sel); + let (d, dr) = r.direct.unwrap(); + assert_eq!(d, want, "direct, {dim}"); + assert_eq!(r.staged.0, want, "staged, {dim}"); + assert_eq!(r.cblas.0, want, "cblas, {dim}"); + let tiles = (dim / TILE) * (dim / TILE); + assert_eq!((dr.tiles, dr.calls, dr.a_copied), (tiles, tiles, 0)); + // 64: 16 tiles x 2 steps = 32. 256: 256 tiles x 8 steps = 2048. + assert_eq!(dr.dp_steps, if dim == 64 { 32 } else { 2048 }); + assert_eq!(r.staged.1.a_copied, dim * dim * 2, "8 KiB / 128 KiB of A"); + assert_eq!(r.cblas.1.b_materialized, dim * dim * 2); + } +} + +/// The fixture is not degenerate: every output tile differs from every +/// other, so a misplaced tile cannot pass. Swapping two tiles fails. +#[test] +fn tiles_are_distinct_and_their_order_is_checked() { + let dim = 64; + let fx = fx(4096, dim); + let sel = Selection::region(SPACE_A, 0, dim); + let c = want(&fx, &sel, dim); + let tile = |g: usize, t: usize| -> Vec { + (0..TILE) + .flat_map(|r| c[(g * TILE + r) * dim + t * TILE..][..TILE].to_vec()) + .collect() + }; + let all: Vec> = (0..4) + .flat_map(|g| (0..4).map(move |t| (g, t))) + .map(|(g, t)| tile(g, t)) + .collect(); + for i in 0..all.len() { + for j in i + 1..all.len() { + assert_ne!(all[i], all[j], "tiles {i} and {j} equal"); + } + } + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let (mut got, _) = run(&world(dim), &socket, dim, sel).direct.unwrap(); + assert_eq!(got, c); + for r in 0..TILE { + let (a, b) = (r * dim, r * dim + TILE); + for k in 0..TILE { + got.swap(a + k, b + k); + } + } + assert_ne!(got, c, "swapping tile (0,0) with (0,1) must be caught"); +} + +/// K = 32, 64 and 256 accumulate exactly; the step count follows K. +#[test] +fn k_steps_of_32_64_and_256_accumulate_exactly() { + let dim = 64; + let fx = fx(4096, dim); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let world = world(dim); + for k in [32, 64, 256] { + let sel = Selection::region(SPACE_A, 512, k); + let want = want(&fx, &sel, dim); + let (got, r) = run(&world, &socket, dim, sel).direct.unwrap(); + assert_eq!(got, want, "K = {k}"); + assert_eq!(r.dp_steps, 16 * k / 32); + } +} + +/// Tails 63/64/65: at the end of the universe the padding is the slab's own +/// zeros and direct is exact; in the middle direct refuses (it would read +/// live identities) and staging is exact. +#[test] +fn tails_read_padding_at_the_end_and_refuse_in_the_middle() { + let dim = 64; + let world = world(dim); + for len in [63, 64, 65] { + let fx = fx(1024 + len, dim); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let end = Selection::region(SPACE_A, 1024, len); + let (got, _) = run(&world, &socket, dim, end.clone()).direct.unwrap(); + assert_eq!(got, want(&fx, &end, dim), "end, len {len}"); + + let mid = Selection::region(SPACE_A, 500, len); + let r = run(&world, &socket, dim, mid.clone()); + if len == 64 { + assert_eq!(r.direct.unwrap().0, want(&fx, &mid, dim)); + } else { + assert!( + matches!(r.direct, Err(ShapeRefusal::OverRead { .. })), + "mid, len {len}" + ); + } + assert_eq!(r.staged.0, want(&fx, &mid, dim), "staged mid, len {len}"); + assert_eq!(r.cblas.0, want(&fx, &mid, dim), "cblas mid, len {len}"); + } +} + +/// The over-read refusal is load-bearing: a NaN in the identity just past a +/// 63-wide region poisons a padded in-place read even though B's padding row +/// is zero (0 * NaN = NaN). Staging the same region is clean. +#[test] +fn without_the_over_read_refusal_a_neighbouring_nan_poisons_the_tile() { + let dim = 64; + let fx = fx(1024, dim); + let (start, len) = (256, 63); + let lanes = Bf16Lanes::slab_encoded(1024, dim, |i, p| { + if i == start + len { + 0x7FC0 // bf16 NaN + } else { + bf16_exact(fx.value(i, p)).unwrap() + } + }); + let socket = Socket::in_order(&lanes, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, start, len); + let r = run(&world, &socket, dim, sel.clone()); + assert!(matches!(r.direct, Err(ShapeRefusal::OverRead { .. }))); + assert_eq!( + r.staged.0, + want(&fx, &sel, dim), + "staging never reads the NaN" + ); + + // The read the refusal prevents, done by hand. + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let (prep, _) = PreparedB::prepare(&obj, &B); + let row0 = socket.lanes.row(0).unwrap(); + let mut tile = [0f32; TILE * TILE]; + bf16_tile_gemm_16x16_packed_strided(&row0.slab[start..], row0.pitch, prep.panel(0), &mut tile); + assert!( + tile.iter().any(|v| v.is_nan()), + "the padded read must see the NaN" + ); +} + +/// Sparse demand: a scattered WHERE mask. Direct refuses; staging and CBLAS +/// are exact. Logical selection, bytes copied and dense arithmetic are +/// different numbers: the zero padding is still multiplied. +#[test] +fn a_scattered_selection_is_staged_and_its_arithmetic_stays_dense() { + let dim = 256; + let fx = fx(4096, dim); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let ids: Vec = (0..40).map(|k| (k * 97 + 13) % 4096).collect(); + let sel = Selection::mask(SPACE_A, 4096, ids.iter().copied()); + assert_eq!((sel.len(), sel.k_pad()), (40, 64)); + let want = want(&fx, &sel, dim); + let r = run(&world(dim), &socket, dim, sel); + assert_eq!(r.direct.unwrap_err(), ShapeRefusal::NotARegion); + assert_eq!(r.staged.0, want); + assert_eq!(r.cblas.0, want); + assert_eq!( + r.staged.1.a_copied, + dim * 40 * 2, + "only selected values copied" + ); + assert_eq!( + r.staged.1.dp_steps, + 256 * 2, + "but K is padded to 64: 2 steps per tile" + ); +} + +/// Lanes in separate allocations, or in a permuted row order, are not one +/// tile load: direct refuses with the reason, staging is exact. +#[test] +fn scattered_and_permuted_lanes_refuse_direct_and_stage_exactly() { + let dim = 64; + let fx = fx(2048, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, 64, dim); + let want = want(&fx, &sel, dim); + + let lanes = Bf16Lanes::scattered(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let r = run(&world, &socket, dim, sel.clone()); + assert_eq!( + r.direct.unwrap_err(), + ShapeRefusal::Direct(DirectRefusal::NotOneSlab { field: 1 }) + ); + assert_eq!(r.staged.0, want); + + let rows: Vec = (0..dim).rev().collect(); + let lanes = Bf16Lanes::slab(&fx, &rows).unwrap(); + let socket = Socket::new(&lanes, rows); + let r = run(&world, &socket, dim, sel); + assert_eq!( + r.direct.unwrap_err(), + ShapeRefusal::Direct(DirectRefusal::RowsNotConsecutive { field: 1 }) + ); + assert_eq!(r.staged.0, want); +} + +/// A pitch without block padding refuses a direct read of the tail region. +#[test] +fn a_short_pitch_refuses_direct() { + let dim = 64; + let fx = fx(4001, dim); + let rows: Vec = (0..dim).collect(); + let lanes = Bf16Lanes::slab_with_pitch(&fx, &rows, 4001).unwrap(); + let socket = Socket::new(&lanes, rows); + let sel = Selection::region(SPACE_A, 3937, 64); + let r = run(&world(dim), &socket, dim, sel.clone()); + assert_eq!( + r.direct.unwrap_err(), + ShapeRefusal::Direct(DirectRefusal::ShortPitch { + pitch: 4001, + needed: 4032 + }) + ); + assert_eq!(r.staged.0, want(&fx, &sel, dim)); +} + +/// A square property-major slab has the same shape as the lanes. Declared in +/// the identity row order it reads wrong; declared in its true row order it +/// is refused at bind. +#[test] +fn a_transposed_square_is_wrong_unless_refused() { + let dim = 64; + let fx = fx(64, dim); + // Row r holds identity r's properties: lane "p" is really identity p. + let lanes = Bf16Lanes::slab_encoded(64, dim, |i, p| bf16_exact(fx.value(p, i)).unwrap()); + let world = world(dim); + let sel = Selection::region(SPACE_A, 0, 64); + let socket = Socket::in_order(&lanes, dim); + let (got, _) = run(&world, &socket, dim, sel.clone()).direct.unwrap(); + assert_ne!( + got, + want(&fx, &sel, dim), + "a transposed operand must read wrong" + ); + + let mut socket = Socket::in_order(&lanes, dim); + socket.spaces = vec![SPACE_PROPS; dim]; + match VirtualObject::bind(&world, &socket, &fields(dim), dim, sel) { + Err(ShapeRefusal::Lane(LaneRefusal::CoordinateSpace { field: 0, .. })) => {} + other => panic!("expected a coordinate-space refusal, got {other:?}"), + } +} + +/// A selection in another row order than the lanes is refused at bind. +#[test] +fn a_cross_space_selection_is_refused() { + let dim = 64; + let fx = fx(1024, dim); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let sel = Selection::region(SPACE_OTHER, 0, 64); + assert!(matches!( + VirtualObject::bind(&world(dim), &socket, &fields(dim), dim, sel), + Err(ShapeRefusal::Lane(LaneRefusal::CoordinateSpace { .. })) + )); +} + +/// Stale frame, foreign frame, wrong reader scope, changed mapping and a +/// changed basis are all refused before any lane is borrowed. +#[test] +fn frame_scope_mapping_and_basis_refusals() { + let dim = 64; + let fx = fx(1024, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, 0, 64); + + // Stale: the source advances after the bind. + let mut lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let obj = { + let socket = Socket::in_order(&lanes, dim); + VirtualObject::bind(&world, &socket, &fields(dim), dim, sel.clone()).unwrap() + }; + lanes.frames_mut().advance(FrameRevisions { + source: 2, + relation_map: 1, + coordinates: 1, + }); + let socket = Socket::in_order(&lanes, dim); + let before = socket.borrows.get(); + assert_eq!( + obj.resolve(&world, &socket).unwrap_err(), + ShapeRefusal::Lane(LaneRefusal::Frame(FrameRefusal::SourceChanged)) + ); + assert_eq!(socket.borrows.get(), before, "nothing borrowed"); + + // Foreign: the same layout, another owner. + let other = Bf16Lanes::slab_in_order(&fx).unwrap(); + let other_socket = Socket::in_order(&other, dim); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel.clone()).unwrap(); + assert_eq!( + obj.resolve(&world, &other_socket).unwrap_err(), + ShapeRefusal::Lane(LaneRefusal::Frame(FrameRefusal::ForeignFrame)) + ); + + // Scope: the lanes serve another reader. + let mut scoped = Socket::in_order(&lanes, dim); + scoped.scope = Scope { id: READER.id + 1 }; + assert!(matches!( + VirtualObject::bind(&world, &scoped, &fields(dim), dim, sel.clone()), + Err(ShapeRefusal::Lane(LaneRefusal::Scope { .. })) + )); + + // Mapping: the source moves field 0 to another lane after the bind. + let mut remapped = Socket::in_order(&lanes, dim); + let obj = VirtualObject::bind(&world, &remapped, &fields(dim), dim, sel.clone()).unwrap(); + remapped.rows.swap(0, 1); + assert_eq!( + obj.resolve(&world, &remapped).unwrap_err(), + ShapeRefusal::Lane(LaneRefusal::MappingChanged { field: 0 }) + ); + + // Basis: checked against a store that binds the class over other fields. + let other_world = World::with_extent(dim, "isa:g", Extent::DR64_CUBE); + assert!(matches!( + obj.resolve(&other_world, &socket).unwrap_err(), + ShapeRefusal::Lane(LaneRefusal::StoreBasisMismatch { .. }) + )); +} + +/// Prepared B is packed once and serves every output tile and repeated runs; +/// it is refused after a selection change, a frame change, a new B revision, +/// or for another width. Using a stale one would be wrong. +#[test] +fn prepared_b_is_reused_and_invalidated() { + for dim in [64, 256] { + let fx = fx(4096, dim); + let mut lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let world = world(dim); + let sel = Selection::region(SPACE_A, 1024, dim); + let want1 = want(&fx, &sel, dim); + let (prep, rep, obj) = { + let socket = Socket::in_order(&lanes, dim); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel.clone()).unwrap(); + let (prep, rep) = PreparedB::prepare(&obj, &B); + let l = obj.resolve(&world, &socket).unwrap(); + for _ in 0..3 { + let mut c = vec![0f32; obj.c_len()]; + let r = direct(&obj, &l, &prep, B.rev, &mut c).unwrap(); + assert_eq!(c, want1); + assert_eq!(r.tiles, (dim / 16) * (dim / 16)); + } + (prep, rep, obj) + }; + assert_eq!( + rep.panels, + dim / 16, + "one panel per 16 columns serves every row tile" + ); + assert_eq!(rep.bytes_written, dim * dim * 2); + + assert_eq!(prep.admit(&obj, B.rev + 1), Err(ReuseRefusal::Operand)); + let socket = Socket::in_order(&lanes, dim); + let moved = Selection::region(SPACE_A, 2048, dim); + let obj2 = VirtualObject::bind(&world, &socket, &fields(dim), dim, moved.clone()).unwrap(); + assert_eq!(prep.admit(&obj2, B.rev), Err(ReuseRefusal::Selection)); + let narrow = VirtualObject::bind(&world, &socket, &fields(dim), 32, sel.clone()).unwrap(); + assert_eq!(prep.admit(&narrow, B.rev), Err(ReuseRefusal::Columns)); + + // Load-bearing: obj2's A against obj1's B gives the wrong answer. + let l2 = obj2.resolve(&world, &socket).unwrap(); + let lane0 = l2.lanes()[0]; + let mut tile = [0f32; 256]; + bf16_tile_gemm_16x16_packed_strided( + &lane0.slab[2048..], + lane0.pitch, + prep.panel(0), + &mut tile, + ); + let want2 = want(&fx, &moved, dim); + assert_ne!(tile[..16], want2[..16], "a stale B must read wrong"); + + drop(socket); + lanes.frames_mut().advance(FrameRevisions { + source: 2, + relation_map: 1, + coordinates: 1, + }); + let socket = Socket::in_order(&lanes, dim); + let rebound = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + assert_eq!(prep.admit(&rebound, B.rev), Err(ReuseRefusal::Frame)); + } +} + +/// Inexact values are refused at ingest; values rounded to bf16 on purpose +/// agree across arms to f32 accumulation order and with the unrounded f64 +/// answer to within bf16's input error. +#[test] +fn rounded_inputs_meet_the_documented_tolerance() { + assert!(bf16_exact(257).is_none(), "257 is not exact in bf16"); + let dim = 64; + let n = 1024; + let raw = |i: usize, p: usize| ((i * 131 + p * 17) % 997) as f32 * 0.0137 - 6.3; + let lanes = Bf16Lanes::slab_encoded(n, dim, |i, p| bf16_round(raw(i, p))); + let socket = Socket::in_order(&lanes, dim); + let sel = Selection::region(SPACE_A, 128, 256); + let r = run(&world(dim), &socket, dim, sel.clone()); + let d = r.direct.unwrap().0; + let on_rounded = oracle( + &sel, + &fields(dim), + dim, + |i, p| f64::from(bf16_value(bf16_round(raw(i, p)))), + |i, j| f64::from(B.value(i, j)), + ); + let on_raw = oracle( + &sel, + &fields(dim), + dim, + |i, p| f64::from(raw(i, p)), + |i, j| f64::from(B.value(i, j)), + ); + let mag = oracle( + &sel, + &fields(dim), + dim, + |i, p| f64::from(raw(i, p)).abs(), + |i, j| f64::from(B.value(i, j)).abs(), + ); + for (idx, &m) in mag.iter().enumerate() { + // f32 accumulation over K = 256: |err| <= K * 2^-24 * sum|a*b|, with + // a factor 2 for the rounded-vs-raw magnitude and order differences. + let acc = 2.0 * 256.0 * f64::powi(2.0, -24) * m + 1e-6; + for (arm, got) in [ + ("direct", &d), + ("staged", &r.staged.0), + ("cblas", &r.cblas.0), + ] { + assert!( + (f64::from(got[idx]) - on_rounded[idx]).abs() <= acc, + "{arm} vs rounded at {idx}" + ); + } + // bf16 round-to-nearest (8-bit significand): |a - bf16(a)| <= 2^-8 |a|; + // B is exact. + let input = f64::powi(2.0, -8) * m; + assert!( + (f64::from(d[idx]) - on_raw[idx]).abs() <= input + acc, + "direct vs raw at {idx}" + ); + } +} + +/// Routing needs no global G2L: one resolve borrows exactly one lane per +/// demanded field, whatever the universe size. +#[test] +fn resolution_borrows_one_lane_per_field_independent_of_universe() { + for n in [256, 65_536] { + for dim in [64, 256] { + let fx = fx(n, dim); + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, 0, 64.min(n)); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let before = socket.borrows.get(); + obj.resolve(&world, &socket).unwrap(); + assert_eq!( + socket.borrows.get() - before, + dim as u64, + "n {n}, dim {dim}" + ); + } + } +} From 719d05797404e128028f833df0b9b2f2e776d645 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 15:29:07 +0000 Subject: [PATCH 2/4] docs: D-DT64-GEMM-SHAPE-1/2 results and board entry Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- .../entries/2026-11-10-dt64-gemm-shape.md | 35 ++++ .claude/board/entries/README.md | 3 +- crates/dr-isa-stream-lab/BENCH-SHAPE.md | 167 ++++++++++++++++++ 3 files changed, 204 insertions(+), 1 deletion(-) create mode 100644 .claude/board/entries/2026-11-10-dt64-gemm-shape.md create mode 100644 crates/dr-isa-stream-lab/BENCH-SHAPE.md diff --git a/.claude/board/entries/2026-11-10-dt64-gemm-shape.md b/.claude/board/entries/2026-11-10-dt64-gemm-shape.md new file mode 100644 index 000000000..67b12ffc5 --- /dev/null +++ b/.claude/board/entries/2026-11-10-dt64-gemm-shape.md @@ -0,0 +1,35 @@ +# 2026-11-10 — DT64-shaped 64×64 and 256×256 BF16 objects (D-DT64-GEMM-SHAPE-1/2) + +**Status:** MEASURED (lab, not production admission). Crate: +`crates/dr-isa-stream-lab` (`src/shape.rs`, `src/bin/shape.rs`, +`tests/integration/shape.rs`, `BENCH-SHAPE.md`). + +**Question.** Can DT64 turn source-owned lanes into the exact logical shapes +AMX consumes (64×64, 256×256), paying physical layout costs only where +unavoidable? + +**Answer.** Yes for region-shaped WHERE results; staging otherwise. +**Decision: MIXED.** +- Direct for a region over a block-padded slab: 0 bytes copied, 0 allocations. +- Staged for scattered masks, interior tails, and permuted or scattered lanes. +- B is always prepared once and reused under a selection/frame/revision/width + key. +- ndarray CBLAS BF16 is 7–11× slower and is not a consumer for this shape. + +**Measured (AMX VM, ±35% between runs):** at 256×256 direct takes 146–178 µs, +staged 140–155 µs (inseparable), B preparation 149–181 µs, and a single-check +resolve 14 µs. A per-field `LaneBinding::lane` resolve takes 155 µs +(quadratic). 256 demanded fields bind directly under +`Extent::DR256_SQ_X64`, with no DT64 change. + +**Open:** +- `LaneBinding` has no borrow-all-after-one-check method; the lab works + around it with `check` plus `addr` plus `LaneSource::borrow`. +- Whether the 2^k slab pitch costs the direct read: odd-pitch runs were + 10–20% faster, inside the noise. +- #1984 is stranded on `ccr-8062bcc7-l7lkz9-vcsr` (merged into an + already-merged parent). + +**Fruit:** a `LaneBinding::borrow_all` (one check, N borrows) in +lance-graph-dt64 would remove the quadratic resolve; it needs its own +DT64 PR. diff --git a/.claude/board/entries/README.md b/.claude/board/entries/README.md index 180b28810..38822e7ec 100644 --- a/.claude/board/entries/README.md +++ b/.claude/board/entries/README.md @@ -25,10 +25,11 @@ 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. -587 entries, 2026-08-06 .. 2026-11-08. +588 entries, 2026-08-06 .. 2026-11-10. | date | entry id | finding | file | |---|---|---|---| +| 2026-11-10 | `D-DT64-GEMM-SHAPE-1` | | [2026-11-10-dt64-gemm-shape.md](2026-11-10-dt64-gemm-shape.md) | | 2026-11-08 | `dr-isa-stream-lab` | | [2026-11-08-dr-isa-stream-lab.md](2026-11-08-dr-isa-stream-lab.md) | | 2026-11-07 | `D-DT64-7-L5b` | | [2026-11-07-dt64-l5b-historical-basis.md](2026-11-07-dt64-l5b-historical-basis.md) | | 2026-11-07 | `D-DT64-7-L5a` | | [2026-11-07-dt64-l5a-exact-basis-witness.md](2026-11-07-dt64-l5a-exact-basis-witness.md) | diff --git a/crates/dr-isa-stream-lab/BENCH-SHAPE.md b/crates/dr-isa-stream-lab/BENCH-SHAPE.md new file mode 100644 index 000000000..b55222d4b --- /dev/null +++ b/crates/dr-isa-stream-lab/BENCH-SHAPE.md @@ -0,0 +1,167 @@ +# dr-isa-stream-lab: DT64-shaped 64×64 and 256×256 BF16 objects + +D-DT64-GEMM-SHAPE-1 (64×64) and -2 (256×256). Generated by +`cargo run --release --bin shape`; raw output of three runs is in +`results/shape-2026-11-10-run{1,2,3}.txt`. Before timing and again after the +timed runs, every arm is checked against the scalar oracle. Allocations and +peak temporary bytes come from a counting global allocator. + +**Host.** Intel Xeon @ 2.10 GHz VM (AMX-BF16, AVX-512-BF16), 4 vCPU, +L1d 48 KiB, L2 2 MiB, L3 260 MiB (as reported by the guest). Tile tier +`AMX TDPBF16PS`, single-threaded, rustc 1.99.0. The numbers are not from +dedicated silicon. They moved by up to about 35% between runs with the guest +idle, so differences under that size are not findings. + +## Shape + +``` +universe (65,536 identities x F property lanes, source-owned slab) + -> WHERE (region or scattered mask, in the lanes' coordinate space) + -> VirtualObject: LaneBinding(F fields) + selection + N columns (addresses only) + -> BF16 tiles: rows = fields, K = selected identities, cols = B columns + -> GEMM: C[F x N] FP32 +``` + +| | 64×64 | 256×256 | +|---|---|---| +| Rows (demanded fields) | 64 | 256 | +| K (selected identities) | 64 → 2 steps of 32 | 256 → 8 steps of 32 | +| Output tiles 16×16 | 16 | 256 | +| K=32 dot-product steps (logical) | 32 | 2,048 | +| One BF16 operand | 8 KiB | 128 KiB | +| FP32 C | 16 KiB | 256 KiB | + +At 256, the shape is 256 fields × 256 columns over 256 selected identities. +It is not an identity × identity adjacency matrix. The 256 fields bind +directly under `Extent::DR256_SQ_X64`, because DT64's `MAX_FIELDS` is 256, so +no composition of smaller bindings is needed and no production lane budget +changes. The lab source holds 256 lanes. That says nothing about which lanes +are resident in production (see #1973 §0). + +**Logical tile geometry is not the physical operand.** +- A direct A tile is 16 consecutive slab rows at the slab pitch (65,536 bf16), + offset by the region start. +- A staged A tile is a dense 16 × K buffer. +- B is N/16 VNNI-packed K × 16 column panels. + +## Results (run 1; runs 2 and 3 in `results/`) + +| Metric | 64×64 | 256×256 | +|---|---|---| +| DT64 bind (cold) | 3.4 µs · 2 allocs | 8.9 µs · 6 allocs | +| Resolve: one check + all borrows (warm) | 1.8 µs · 0 allocs | 13.9 µs · 0 allocs | +| Resolve: `LaneBinding::lane` per field | 15.2 µs | 155.1 µs | +| B preparation (VNNI panels) | 13.2 µs · 8,320 B | 148.7 µs · 131,584 B | +| Direct AMX (A in place) | 5.9 µs · 0 allocs · 0 B | 145.6 µs · 0 allocs · 0 B | +| Direct AMX, pitch 65,568 | 3.9 µs | 127.0 µs | +| Staged AMX (dense A tiles) | 4.5 µs · 2,048 B scratch | 139.7 µs · 8,192 B scratch | +| ndarray CBLAS BF16 | 37.8 µs · 23 allocs · 54 KiB | 1,063 µs · 263 allocs · 785 KiB | +| Source bytes copied (direct / staged / CBLAS) | 0 / 8,192 / 8,192 | 0 / 131,072 / 131,072 | +| CBLAS B materialized row-major | 8,192 B | 131,072 B | +| End-to-end warm (resolve + direct, B reused) | 7.2 µs | 169.6 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 25.9 µs | 368.4 µs | +| Warm repetitions (100 runs, one prepare) | 7.4 µs / run | 168.0 µs / run | + +Run-to-run ranges over the three runs: + +| Arm | 64×64 | 256×256 | +|---|---|---| +| Direct | 4.0–5.9 µs | 146–178 µs | +| Staged | 4.1–4.9 µs | 140–155 µs | +| Warm end-to-end | 6.7–7.2 µs | 170–197 µs | + +The staged arm's one allocation is its scratch buffer on first use. A caller +that keeps the buffer, as the timed loop does, allocates nothing. + +**Sparse demand** (256 fields × 256 columns, 40 scattered identities, mask +WHERE): +- logical selection: 40 +- K padded to 64, so 512 dense dot-product steps: the padding is multiplied +- lanes borrowed: 256 (descriptors, not bytes) +- A bytes copied: 20,480 (only the selected values) +- staged AMX: 392–557 µs over five runs, slower than the dense 256-identity region. Each + value is gathered by a bit walk; the arithmetic is not the cost. + +A sparse selection does not give sparse arithmetic here. It compacts K, then +pays for the gather. + +## Findings + +1. **The shape routes; DT64 stores nothing.** At both sizes one binding with + one check yields every lane, with no allocation. A direct read copies 0 + source bytes. Resolve borrows exactly one lane per field, whatever the + universe size (tested at 256 and 65,536). No global G2L is used. +2. **Direct and staged are not separable by time on this host.** Copying A + costs 8 KiB or 128 KiB, and at these sizes that is hidden in the tile + loads; the two arms overlap within run-to-run noise. Direct's advantage + is structural: zero copy, zero allocation, zero scratch. It is not a speed + claim. +3. **The power-of-two pitch probably costs a little.** With a 65,568-wide + pitch instead of 65,536, the direct read was 10–20% faster at 256 in every + run. That is consistent with the 16 A rows (128 KiB apart) sharing L1 + sets. It is inside the noise band, so it is a hypothesis to test on + dedicated silicon, not a finding. +4. **Preparing B is the price at 256.** Packing B costs about as much as the + GEMM (149 µs vs 146 µs). Reusing the prepared B halves end-to-end time + (cold 368 µs vs warm 170 µs). The reuse is keyed to the selection, the + frame issue, the B revision and the width, and is refused when any of + them changes. Tests show that using a stale B gives a wrong answer. +5. **Resolve with a check per field is quadratic.** `LaneBinding::lane` + re-checks every bound lane on each call: 155 µs at 256 fields, against + 14 µs for one check plus borrows. At 256 the single check is still about + 8% of warm end-to-end time. +6. **Scaling 16 → 256 tiles is sensible.** MACs grow 64× (fields, columns + and K each grow 4×). Direct time grew 25–44×, so throughput rose from + about 45–70 to 95–130 GMAC/s. B preparation grew 11–20× for 16× the + bytes. At 256, arithmetic and preparation are about equal, and the + single check is the third cost. +7. **ndarray CBLAS BF16 is 7–11× slower than either tile arm.** It makes 263 + allocations and 785 KiB of temporaries at 256: it packs both operands and + re-packs B per 16×16 tile. #1984 measured about 20× on its whole-lane + workload. + +## Refusals (all tested) + +Each refusal is tested two-sided where a bypass is constructible, with the +wrong answer shown: +- **Direct:** a scattered mask (`NotARegion`); separately allocated lanes; + permuted rows; a pitch without block padding. +- **Tails:** + - At the end of the universe, tails of 63 and 65 read the slab's zeroed + padding and are exact. + - In the middle of the universe they are refused (`OverRead`). Without + that refusal, a NaN in the next identity poisons the tile, even though + B's padding row is zero. +- **Orientation:** + - A square transposed slab declared in the identity row order reads wrong. + - The same slab declared in its true row order is refused at bind. +- **Binding:** a cross-space selection; a stale frame; a foreign frame; the + wrong reader scope; a changed field mapping; a different schema basis. +- **Prepared B:** a different selection, frame issue, B revision or width. + +Disable runs: removing the over-read guard, the selection witness in the B +reuse key, or the binding check in resolve each fail the matching tests. + +**Error policy.** BF16-exact integer fixtures must match exactly across all +four arms (accumulation stays below 2^24). For inputs rounded to bf16 on +purpose, the bounds are: +- between arms: `2 × K × 2^-24 × Σ|a·b|` (FP32 accumulation order); +- against the unrounded f64 answer: an additional `2^-8 × Σ|a·b|` (bf16 + round-to-nearest on A; B is exact). + +## Relation to #1984 + +#1984 ("Virtual CSR over the DR cube…") was merged into the branch of #1983 +after #1983 had itself merged, so its commits (`1f47c03e9`, `edbf2fa44`, +`d563af107`) never reached `main`. They survive on +`ccr-8062bcc7-l7lkz9-vcsr`. This PR neither cherry-picks nor rewrites them; +its benchmark is preserved there unchanged. Its reference numbers come from +a different workload, so no speed-up is claimed across the two: + +| #1984 workload | Result | +|---|---| +| WHERE 16×16 over 65,536 identities | direct AMX 172.5 µs, ndarray CBLAS 3,397.3 µs | +| Degree-8 graph | CSR 11.6 ms, AMX 32.3 ms | +| Degree-64 local graph | staged AMX 12.5 ms, CSR 75 ms | + +Its graph conclusions stay separate from these matrix-shaping conclusions. From fe3491a82d0ad90a8faa14883cd79249cb61e925 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 16:28:52 +0000 Subject: [PATCH 3/4] lab: arms refuse lanes resolved by another object (Codex P2 on #1987) Lanes now carry the frame issue and per-row lane addresses of the object that resolved them. direct, staged and cblas refuse lanes from another source or frame, with another field count, or under another mapping (ShapeRefusal::ForeignLanes), before any arithmetic. Before this, lanes from a foreign source passed whenever the geometry fit, and 64-field lanes on a 256-field object silently computed 64 rows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- crates/dr-isa-stream-lab/src/bin/shape.rs | 6 +- crates/dr-isa-stream-lab/src/shape.rs | 64 +++++++++++++++---- .../tests/integration/shape.rs | 58 ++++++++++++++++- 3 files changed, 112 insertions(+), 16 deletions(-) diff --git a/crates/dr-isa-stream-lab/src/bin/shape.rs b/crates/dr-isa-stream-lab/src/bin/shape.rs index 03ec5f894..f9be1a610 100644 --- a/crates/dr-isa-stream-lab/src/bin/shape.rs +++ b/crates/dr-isa-stream-lab/src/bin/shape.rs @@ -174,7 +174,7 @@ fn main() { assert_eq!(c, want, "direct {dim}"); let sr = staged(&obj, &lanes_r, &prep, b.rev, &mut scratch, &mut c).unwrap(); assert_eq!(c, want, "staged {dim}"); - let cr = cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c); + let cr = cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c).unwrap(); assert_eq!(c, want, "cblas {dim}"); let t_bind = median_ns(|| { @@ -212,7 +212,7 @@ fn main() { }); assert_eq!(c, want); let t_cblas = median_ns(|| { - cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c); + cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c).unwrap(); }); assert_eq!(c, want); let t_warm = median_ns(|| { @@ -245,7 +245,7 @@ fn main() { let (a_stg, m_stg, _) = mem(|| staged(&obj, &lanes_r, &prep, b.rev, &mut Vec::new(), &mut c).unwrap()); let (a_cbl, m_cbl, _) = - mem(|| cblas(&obj, &lanes_r, &b, &mut Vec::new(), &mut Vec::new(), &mut c)); + mem(|| cblas(&obj, &lanes_r, &b, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap()); let macs = (dim * dim * dim) as f64; push( diff --git a/crates/dr-isa-stream-lab/src/shape.rs b/crates/dr-isa-stream-lab/src/shape.rs index bf79a65a1..0b4fd22cb 100644 --- a/crates/dr-isa-stream-lab/src/shape.rs +++ b/crates/dr-isa-stream-lab/src/shape.rs @@ -46,7 +46,7 @@ //! bindings or tiles. use lance_graph_dt64::dr::Frame; -use lance_graph_dt64::{CoordSpace, LaneBinding, LaneRefusal, LaneSource}; +use lance_graph_dt64::{CoordSpace, LaneAddr, LaneBinding, LaneRefusal, LaneSource}; use ndarray::simd::{ bf16_tile_gemm_16x16_packed, bf16_tile_gemm_16x16_packed_strided, PackedBf16B, }; @@ -190,6 +190,9 @@ pub enum ShapeRefusal { }, /// The prepared B does not belong to this object. Reuse(ReuseRefusal), + /// The lanes were resolved by another object: another source or frame, + /// another field count, or another lane mapping. + ForeignLanes, } impl From for ShapeRefusal { @@ -297,10 +300,43 @@ impl VirtualObject { for (slot, &f) in lanes.iter_mut().zip(&self.fields).skip(1) { *slot = borrow(f)?; } - Ok(Lanes { + Ok(self.stamp(lanes)) + } + + /// Lanes with their provenance: the frame issue and the address of every + /// row, as this object's binding holds them. + fn stamp<'s>(&self, lanes: [SlabLane<'s>; MAX_ROWS]) -> Lanes<'s> { + let first = ( + self.fields[0], + *self.binding.addr(self.fields[0]).expect("bound"), + ); + let mut addrs = [first; MAX_ROWS]; + for (slot, &f) in addrs.iter_mut().zip(&self.fields).skip(1) { + *slot = (f, *self.binding.addr(f).expect("bound")); + } + Lanes { lanes, + addrs, + frame: self.binding.frame().clone(), count: self.fields.len(), - }) + } + } + + /// Refuse lanes this object did not resolve: another frame issue (another + /// source, or the source has moved), another field count, or another + /// lane address in any row. + pub fn admit_lanes(&self, lanes: &Lanes<'_>) -> Result<(), ShapeRefusal> { + let same = lanes.count == self.fields.len() + && lanes.frame.same_issue(self.binding.frame()) + && lanes.addrs[..lanes.count] + .iter() + .zip(&self.fields) + .all(|((f, addr), &want)| *f == want && self.binding.addr(want) == Some(addr)); + if same { + Ok(()) + } else { + Err(ShapeRefusal::ForeignLanes) + } } /// The same as [`Self::resolve`] the long way: `LaneBinding::lane` per @@ -320,17 +356,18 @@ impl VirtualObject { for (slot, &f) in lanes.iter_mut().zip(&self.fields).skip(1) { *slot = lane(f)?; } - Ok(Lanes { - lanes, - count: self.fields.len(), - }) + Ok(self.stamp(lanes)) } } -/// The borrowed lanes of a resolved object, in view row order. -#[derive(Debug, Clone, Copy)] +/// The borrowed lanes of a resolved object, in view row order, with the +/// frame issue and lane addresses they were resolved under, so an arm can +/// refuse lanes that belong to another object. +#[derive(Debug, Clone)] pub struct Lanes<'s> { lanes: [SlabLane<'s>; MAX_ROWS], + addrs: [(u8, LaneAddr); MAX_ROWS], + frame: Frame, count: usize, } @@ -488,6 +525,7 @@ pub fn direct( c: &mut [f32], ) -> Result { b.admit(obj, rev).map_err(ShapeRefusal::Reuse)?; + obj.admit_lanes(lanes)?; let Where::Region { start, len } = obj.selection.kind else { return Err(ShapeRefusal::NotARegion); }; @@ -538,6 +576,7 @@ pub fn staged( c: &mut [f32], ) -> Result { b.admit(obj, rev).map_err(ShapeRefusal::Reuse)?; + obj.admit_lanes(lanes)?; assert_eq!(c.len(), obj.c_len()); let k_pad = obj.selection.k_pad(); let len = obj.selection.len(); @@ -577,7 +616,8 @@ pub fn cblas( a: &mut Vec, bm: &mut Vec, c: &mut [f32], -) -> ArmReport { +) -> Result { + obj.admit_lanes(lanes)?; let m = obj.fields.len(); let n = obj.cols; let k = obj.selection.len(); @@ -597,13 +637,13 @@ pub fn cblas( } }); ndarray::backend::cblas_gemm_bf16bf16f32(a, bm, c, m, n, k); - ArmReport { + Ok(ArmReport { tiles: obj.tiles(), calls: 1, dp_steps: obj.tiles() * obj.selection.k_pad() / BLOCK, a_copied: m * k * 2, b_materialized: k * n * 2, - } + }) } /// ARM D: `C[p][j] = sum over selected i of a(i, field_p) * b(i, j)` in f64, diff --git a/crates/dr-isa-stream-lab/tests/integration/shape.rs b/crates/dr-isa-stream-lab/tests/integration/shape.rs index 28df4f281..fd9e4656d 100644 --- a/crates/dr-isa-stream-lab/tests/integration/shape.rs +++ b/crates/dr-isa-stream-lab/tests/integration/shape.rs @@ -73,7 +73,7 @@ fn run(world: &World, socket: &Socket<'_>, dim: usize, sel: Selection) -> Run { let r = staged(&obj, &lanes, &prep, B.rev, &mut Vec::new(), &mut c).unwrap(); let staged = (c, r); let mut c = vec![0f32; obj.c_len()]; - let r = cblas(&obj, &lanes, &B, &mut Vec::new(), &mut Vec::new(), &mut c); + let r = cblas(&obj, &lanes, &B, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap(); Run { direct, staged, @@ -553,3 +553,59 @@ fn resolution_borrows_one_lane_per_field_independent_of_universe() { } } } + +/// Lanes resolved by one object cannot feed another: another source (and +/// so another frame issue), another field count, or another lane mapping is +/// refused by every arm before any arithmetic. +#[test] +fn lanes_from_another_object_are_refused_by_every_arm() { + let fx = fx(4096, 256); + let world256 = world(256); + let world64 = world(64); + let a = Bf16Lanes::slab_in_order(&fx).unwrap(); + let b = Bf16Lanes::slab_in_order(&fx).unwrap(); + // `sb` is over the SAME source as `sa`, so "narrow" differs only in count. + let (sa, sb) = (Socket::in_order(&a, 256), Socket::in_order(&a, 64)); + let sel = Selection::region(SPACE_A, 0, 64); + let obj = VirtualObject::bind(&world256, &sa, &fields(256), 256, sel.clone()).unwrap(); + let (prep, _) = PreparedB::prepare(&obj, &B); + let own = obj.resolve(&world256, &sa).unwrap(); + assert!(obj.admit_lanes(&own).is_ok()); + + // Another source: identical bytes, another owner. + let sb256 = Socket::in_order(&b, 256); + let other = VirtualObject::bind(&world256, &sb256, &fields(256), 256, sel.clone()).unwrap(); + let foreign = other.resolve(&world256, &sb256).unwrap(); + // Too few rows: 64 lanes offered to the 256-field object. + let narrow_obj = VirtualObject::bind(&world64, &sb, &fields(64), 256, sel.clone()).unwrap(); + let narrow = narrow_obj.resolve(&world64, &sb).unwrap(); + // Same source and frame, another mapping (rows reversed). + let rev_rows: Vec = (0..256).rev().collect(); + let sr = Socket::new(&a, rev_rows); + let remapped_obj = VirtualObject::bind(&world256, &sr, &fields(256), 256, sel).unwrap(); + let remapped = remapped_obj.resolve(&world256, &sr).unwrap(); + + for (name, lanes) in [ + ("foreign", &foreign), + ("narrow", &narrow), + ("remapped", &remapped), + ] { + let mut c = vec![0f32; obj.c_len()]; + assert_eq!( + direct(&obj, lanes, &prep, B.rev, &mut c).unwrap_err(), + ShapeRefusal::ForeignLanes, + "direct, {name}" + ); + assert_eq!( + staged(&obj, lanes, &prep, B.rev, &mut Vec::new(), &mut c).unwrap_err(), + ShapeRefusal::ForeignLanes, + "staged, {name}" + ); + assert_eq!( + cblas(&obj, lanes, &B, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap_err(), + ShapeRefusal::ForeignLanes, + "cblas, {name}" + ); + assert!(c.iter().all(|&v| v == 0.0), "nothing computed, {name}"); + } +} From afe8d156d93d492860c79438434de456d83ac3bd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 16:32:24 +0000 Subject: [PATCH 4/4] lab: refuse selections past the lanes' length (Codex P2 on #1987) A region past the source's logical length that still fit the padded pitch passed every guard: direct read the slab's zero padding as selected values and returned Ok, while staged and cblas panicked. admit_lanes, which all three arms call, now refuses any selected identity at or past the shortest lane's length (ShapeRefusal::OutOfRange). Padding stays allowed as K padding only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XAqKMMWgnUU9g7Ldyn6sbk --- crates/dr-isa-stream-lab/src/shape.rs | 31 +++++++++++++--- .../tests/integration/shape.rs | 36 +++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/dr-isa-stream-lab/src/shape.rs b/crates/dr-isa-stream-lab/src/shape.rs index 0b4fd22cb..85226b0c4 100644 --- a/crates/dr-isa-stream-lab/src/shape.rs +++ b/crates/dr-isa-stream-lab/src/shape.rs @@ -111,6 +111,19 @@ impl Selection { self.len() == 0 } + /// The highest selected identity, if any. + pub fn last(&self) -> Option { + match &self.kind { + Where::Region { start, len } => len.checked_sub(1).map(|l| start + l), + Where::Mask { words, .. } => words + .iter() + .enumerate() + .rev() + .find(|(_, &w)| w != 0) + .map(|(i, &w)| i * 64 + 63 - w.leading_zeros() as usize), + } + } + /// K padded to the 32-identity step the tile GEMM consumes. pub fn k_pad(&self) -> usize { self.len().div_ceil(BLOCK) * BLOCK @@ -193,6 +206,8 @@ pub enum ShapeRefusal { /// The lanes were resolved by another object: another source or frame, /// another field count, or another lane mapping. ForeignLanes, + /// The selection names identity `last`, but the lanes hold only `n`. + OutOfRange { last: usize, n: usize }, } impl From for ShapeRefusal { @@ -332,11 +347,19 @@ impl VirtualObject { .iter() .zip(&self.fields) .all(|((f, addr), &want)| *f == want && self.binding.addr(want) == Some(addr)); - if same { - Ok(()) - } else { - Err(ShapeRefusal::ForeignLanes) + if !same { + return Err(ShapeRefusal::ForeignLanes); + } + // Every selected identity must exist in every lane: slab padding past + // the lane's logical length is allowed as GEMM K padding (`direct` + // checks that separately), never as a selected value. + let n = lanes.lanes().iter().map(|l| l.n).min().unwrap_or(0); + if let Some(last) = self.selection.last() { + if last >= n { + return Err(ShapeRefusal::OutOfRange { last, n }); + } } + Ok(()) } /// The same as [`Self::resolve`] the long way: `LaneBinding::lane` per diff --git a/crates/dr-isa-stream-lab/tests/integration/shape.rs b/crates/dr-isa-stream-lab/tests/integration/shape.rs index fd9e4656d..365429557 100644 --- a/crates/dr-isa-stream-lab/tests/integration/shape.rs +++ b/crates/dr-isa-stream-lab/tests/integration/shape.rs @@ -609,3 +609,39 @@ fn lanes_from_another_object_are_refused_by_every_arm() { assert!(c.iter().all(|&v| v == 0.0), "nothing computed, {name}"); } } + +/// A selection that names identities past the lanes' length is refused by +/// every arm, even when the slab padding would make the direct read fit: +/// padding may pad K, never stand in for a selected value. +#[test] +fn a_selection_past_the_source_is_refused_by_every_arm() { + let dim = 64; + let fx = fx(65, dim); // pitch 96: identities 65..96 are padding + let lanes = Bf16Lanes::slab_in_order(&fx).unwrap(); + let socket = Socket::in_order(&lanes, dim); + let world = world(dim); + let cases = [ + (Selection::region(SPACE_A, 64, 32), 95), // fits the pitch exactly + (Selection::mask(SPACE_A, 128, [3, 70]), 70), + ]; + for (sel, last) in cases { + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let l = obj.resolve(&world, &socket).unwrap(); + let (prep, _) = PreparedB::prepare(&obj, &B); + let want = ShapeRefusal::OutOfRange { last, n: 65 }; + let mut c = vec![0f32; obj.c_len()]; + assert_eq!(direct(&obj, &l, &prep, B.rev, &mut c).unwrap_err(), want); + assert_eq!( + staged(&obj, &l, &prep, B.rev, &mut Vec::new(), &mut c).unwrap_err(), + want + ); + assert_eq!( + cblas(&obj, &l, &B, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap_err(), + want + ); + } + // The last valid identity is accepted. + let ok = Selection::region(SPACE_A, 33, 32); + let r = run(&world, &socket, dim, ok.clone()); + assert_eq!(r.staged.0, want(&fx, &ok, dim)); +}