diff --git a/.claude/board/entries/2026-11-10-dt64-int8-facet-stride.md b/.claude/board/entries/2026-11-10-dt64-int8-facet-stride.md new file mode 100644 index 000000000..dd069bbb5 --- /dev/null +++ b/.claude/board/entries/2026-11-10-dt64-int8-facet-stride.md @@ -0,0 +1,42 @@ +# 2026-11-10 — INT8 over the DT64 virtual object; FACET STRIDE audit + +**Status:** MEASURED (lab). `crates/dr-isa-stream-lab/src/int8.rs`, +`BENCH-SHAPE.md` § SHAPE-3. + +**INT8 arm.** `u8 × i8 → i32` through `backend::gemm_i8` (AMX TDPBUSD). A is +unsigned and B signed, with no reinterpreting cast (a test pins it). The +results satisfy `C_int8 = C_bf16 + 8·colsum(B)` exactly. + +**At 256 fields:** + +| | INT8 | BF16 | +|---|---|---| +| Warm end-to-end | 85–101 µs | 144–160 µs | +| GEMM | 216–228 GMAC/s | 110–113 GMAC/s | + +**Correction.** #1987's "B preparation" timed the synthetic hash. Read from a +table, prepared B costs 46–62 µs (not 149–181 µs). + +**Audit verdicts:** + +| Operation | Verdict | +|---|---| +| Positional reading (BF16) | REUSED | +| DT64 routing | REUSED | +| AMX accumulation | REUSED | +| LUT / masked fold | NOT APPLICABLE | +| VNNI packing | NOT APPLICABLE (mandatory) | + +**OPTIMIZATION FOUND (lab-local):** +- region A copy: 3.5–6× faster; +- in-place B: 30 ns instead of 58 µs. + +**Open:** ndarray has no strided-A INT8 entry and no prepacked INT8 B (the +twins of #414 / `PackedBf16B`), so INT8 copies A and re-packs B on every +call. Measured apart: the pack is 23–29 µs (36–38% of the INT8 GEMM) and the +A copy 5–7 µs, together about 30–45% of INT8 warm time. A separate ndarray +PR is proposed. + +**Prepared-B reuse** is keyed on object identity, full selection equality, +frame issue, width and operand identity (seed or table instance, plus +revision). There is no digest. diff --git a/.claude/board/entries/README.md b/.claude/board/entries/README.md index 54e22dc64..7d336cb7f 100644 --- a/.claude/board/entries/README.md +++ b/.claude/board/entries/README.md @@ -25,12 +25,13 @@ 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. -590 entries, 2026-08-06 .. 2026-11-10. +591 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 | `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) | | 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) | diff --git a/.claude/knowledge/dr-dt64-locality-execution-contract.md b/.claude/knowledge/dr-dt64-locality-execution-contract.md index 4edc6b97c..1f5048e74 100644 --- a/.claude/knowledge/dr-dt64-locality-execution-contract.md +++ b/.claude/knowledge/dr-dt64-locality-execution-contract.md @@ -120,7 +120,7 @@ field mapping, operand identity and version. | #1987 — BF16 virtual 64×64 and 256×256 objects over source-owned lanes | MEASURED, merged | One binding feeds direct strided AMX (0 bytes of A copied), staged, CBLAS and oracle arms with exact parity; refusals for frame, scope, mapping, basis, coordinate space, foreign lanes and out-of-range selections | | #1988 — `LaneBinding::borrow_all` | VERIFIED-IN-CODE, merged | One check, then every bound lane; N source lookups instead of N² | | Lab resolve on `borrow_all` (follow-up) | MEASURED, not merged | Resolve at 256 fields 1.6–2.0 µs vs 13.8–13.9 µs (#1987 as first measured) and 26–28 µs (`main` after the provenance fix); the old cost was `LaneBinding::addr`, a linear scan called per field | -| INT8 vs BF16 over the same object (follow-up) | MEASURED, not merged | `u8 × i8 → i32` end to end 85–101 µs vs BF16 144–160 µs at 256 fields on one VM; INT8 still copies A and re-packs B per call (no strided-A / prepacked-B INT8 entry in ndarray) | +| INT8 vs BF16 over the same object (follow-up) | MEASURED, not merged | `u8 × i8 → i32` end to end 66–101 µs vs BF16 103–160 µs at 256 fields on one VM; INT8 still copies A (5–7 µs) and re-packs B per call (23–29 µs, 36–38% of its GEMM), because ndarray has no strided-A / prepacked-B INT8 entry | | #1987's "B preparation ≈ GEMM" | REJECTED-BY-MEASUREMENT | That timer included the synthetic operand's hash; from a table built once, prepared B costs about a third of the GEMM | | G2L across different source orders | OPEN | Not demonstrated: every fixture shared one coordinate space, and differing spaces were refused, not translated | | Foundry operational-ontology parity | HYPOTHESIS | Research goal; nothing here establishes it | diff --git a/crates/dr-isa-stream-lab/BENCH-SHAPE.md b/crates/dr-isa-stream-lab/BENCH-SHAPE.md index 0d0da1d08..247033661 100644 --- a/crates/dr-isa-stream-lab/BENCH-SHAPE.md +++ b/crates/dr-isa-stream-lab/BENCH-SHAPE.md @@ -219,3 +219,97 @@ Disable runs, each with the code restored afterwards: | Swallowing item refusals | the `Vanished` test | | The object-identity check | `lanes_from_another_object_are_refused_by_every_arm` | | Placing lanes in binding order instead of view order | the row-order test | + +## D-DT64-GEMM-SHAPE-3: INT8 (u8 × i8 → i32) and the FACET STRIDE audit + +`src/int8.rs` puts the same `VirtualObject` over u8 lanes and runs it as +`u8 × i8 → i32` through ndarray's INT8 facade: `backend::gemm_i8` → +`simd_int_ops::gemm_u8_i8` → AMX `TDPBUSD`. A stays unsigned and B signed, +which is TDPBUSD's native contract; there is no reinterpreting cast, and +`a_is_never_reinterpreted_as_signed` pins it (200 × −1 must give −200·K, not ++56·K). The INT8 and BF16 arms share one fixture. With `A_u8 = A + 8`, the +results satisfy `C_int8 = C_bf16 + 8·colsum(B)` exactly, and a test checks +this. + +### A measurement correction to the results above + +The earlier "B preparation" rows (149–181 µs at 256 fields) timed +`BOperand::value`, a hash computed per element, not data movement. The +benchmark now reads B from a `BTable` built once. Prepared VNNI B then costs +**46–62 µs** at 256 fields, about a third of the GEMM, not about equal to it. +Finding 4 above overstated preparation by about 3×. + +### Results (256 fields, six runs on one host, `results/shape-2026-11-10-int8-run*.txt` holds the last three) + +Same host, same fixture and same B table for every row. Ranges are across +runs. The VM's run-to-run variation is up to about 35%, so differences inside +that band are not findings. + +| Step | BF16 | INT8 | +|---|---|---| +| Resolve (borrow_all) | 2.0–2.5 µs | 2.0–2.8 µs | +| Stage A | 0 B (direct) | 6–10 µs · 64 KiB (one copy per lane) | +| Stage A, per-value walk (baseline) | — | 36–56 µs | +| B | prepared once: 46–62 µs, then reused | in place for a region: 30 ns, 0 B; materialized: 58 µs | +| GEMM | 138–152 µs direct (110–122 GMAC/s) | 61–82 µs (204–275 GMAC/s), B VNNI-packed inside every call, 3 allocs · 12 KiB | +| of which: B band gather + VNNI pack, timed apart with ndarray's own `vnni_pack_i8` | — | 23–29 µs (36–38% of the GEMM; 54% at 64 fields) | +| Warm end-to-end | 103–160 µs | 66–101 µs | + +At 64 fields, warm end-to-end is 6.5–6.7 µs (BF16) and 6.0–10.8 µs (INT8). + +### FACET STRIDE audit + +The six operations are separate, and each gets its own verdict. + +| Operation | Where | Verdict | +|---|---|---| +| 1. Positional source-lane reading | BF16 `direct` reads 16 slab rows in place at the slab pitch; INT8 must copy A because ndarray's INT8 facade takes dense A only | **REUSED** for BF16 (the pattern, not `simd_stride` code). INT8 stays a copy until ndarray gains a strided-A INT8 entry | +| 2. LUT transformation (`lut_u8`, `lut9`) | no byte transform anywhere in these pipelines; `simd_stride` has no GEMM callers in ndarray | **NOT APPLICABLE** | +| 3. Masked folding / reduction | GEMM arms do none; a scattered WHERE mask is compacted by a per-bit walk when A is staged | **NOT APPLICABLE** to the GEMM. The compaction is a candidate for a masking-ops compress; not measured here | +| 4. DT64 coordinate / shape routing | `borrow_all`, one check, O(N) | **REUSED.** The O(N²) `addr` walk is gone (see the borrow_all section) | +| 5. VNNI operand packing | `vnni_pack_bf16` / `vnni_pack_i8` are plain index moves, no shuffles | **NOT APPLICABLE:** required by the hardware. But INT8 re-packs B inside every call because there is no `PackedI8B`; that is repeated work, not a layout problem | +| 6. AMX dot-product accumulation | TDPBF16PS / TDPBUSD through the facade | **REUSED** | + +**Prepared-B reuse key.** Reuse is keyed on authoritative identity, never on a +digest: +- the object that was packed for (one compare); +- for any other object, the selection compared in full, the frame issue and + the width; +- the operand's identity: the defining function's seed, or the immutable + table's construction instance, plus the revision. + +The earlier FNV selection key is gone. Two tables with equal values and an +equal revision are different operands. Tests: `prepared_b_reuse_is_keyed_by_identity_not_a_digest`, +`prepared_b_is_reused_and_invalidated`. + +**OPTIMIZATION FOUND** (measured, lab-local, no semantic change): +- **Copy A per lane.** A region of A is now one copy per lane instead of a + per-value walk: 3.5–6× faster at 256 fields. +- **Borrow B in place.** For a full-width region, B comes straight from the + table: 30 ns instead of 58 µs, and 0 bytes written. +- **Resolve with `borrow_all`.** Single-check resolution is 7× faster than + #1987's original. + +**Not proposed: an ndarray change.** A strided-A INT8 entry plus a prepacked +INT8 B, the INT8 twins of #414 and `PackedBf16B`, would save at most: +- the A copy, 6–10 µs, about 10% of INT8 end-to-end; +- the per-call B pack inside `gemm_i8`, which the facade does not expose and + so was not measured on its own. + +Measured: the per-call B band gather plus pack inside `gemm_i8` is 23–29 µs +at 256 fields, 36–38% of the INT8 GEMM, and the A copy is 5–7 µs. Together +that is about 30–45% of INT8 warm end-to-end time. This is an independently +measured case for a separate ndarray PR. It is proposed, not part of this +change. + +**Central question.** DT64 is routing SoA positions, not moving them. Four +places paid for the same work twice, all found by measurement, and the first +three are now fixed: +1. per-field `addr` scans in resolve; +2. a per-value walk where a region copy would do; +3. hashing inside a "preparation" timer; +4. INT8 B re-packed on every call: measured at 36–38% of the INT8 GEMM, and + open at the ndarray layer. + +The FACET STRIDE guard (`facet-stride-guard.sh --diff`) reports 0 hits on +this change. ndarray is unchanged. diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run1.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run1.txt new file mode 100644 index 000000000..f4ecff860 --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run1.txt @@ -0,0 +1,30 @@ +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 375.1 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3183 ns · 2 allocs | 8873 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1248 ns · 0 allocs · 0 B | 2045 ns · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 13.7 µs | 151.5 µs | +| B preparation (VNNI panels) | 4044 ns · 8192 B written · 8320 B alloc | 45.0 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 5888 ns · 44.5 GMAC/s · 0 allocs · 0 B tmp | 137.9 µs · 121.7 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3802 ns · 68.9 GMAC/s | 124.8 µs · 134.5 GMAC/s | +| Staged AMX (dense A tiles) | 4140 ns · 1 allocs · 2048 B tmp | 83.4 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 32.4 µs · 23 allocs · 54272 B tmp | 939.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) | 6531 ns | 140.5 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 13.7 µs | 213.2 µs | +| Warm repetitions (100, per run, one prepare) | 7340 ns | 154.3 µs | +| INT8 resolve (u8 lanes, one check) | 1220 ns | 1933 ns | +| INT8 stage A (region: one copy per lane) | 289 ns · 4096 B | 7078 ns · 65536 B | +| INT8 stage A, per-value walk (baseline) | 3574 ns | 42.9 µ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) | 4273 ns · 4096 B | 58.0 µs · 65536 B | +| INT8 GEMM `backend::gemm_i8` (packs B per call) | 3553 ns · 73.8 GMAC/s · 3 allocs · 3072 B tmp | 77.3 µs · 217.1 GMAC/s · 3 allocs · 12288 B tmp | +| INT8 B band gather + VNNI pack (done inside each gemm_i8 call) | 1926 ns · 54% of the GEMM row | 29.4 µs · 38% of the GEMM row | +| INT8 end-to-end warm (resolve + stage + GEMM) | 10.5 µs | 87.2 µs | diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run2.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run2.txt new file mode 100644 index 000000000..15feb5009 --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run2.txt @@ -0,0 +1,30 @@ +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 285.5 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3178 ns · 2 allocs | 8808 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1236 ns · 0 allocs · 0 B | 2042 ns · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 11.8 µs | 151.4 µs | +| B preparation (VNNI panels) | 3186 ns · 8192 B written · 8320 B alloc | 45.1 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4316 ns · 60.7 GMAC/s · 0 allocs · 0 B tmp | 138.1 µs · 121.5 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3812 ns · 68.8 GMAC/s | 124.6 µs · 134.6 GMAC/s | +| Staged AMX (dense A tiles) | 4079 ns · 1 allocs · 2048 B tmp | 83.7 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 32.8 µs · 23 allocs · 54272 B tmp | 954.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) | 6516 ns | 103.2 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 13.8 µs | 158.9 µs | +| Warm repetitions (100, per run, one prepare) | 6467 ns | 118.3 µs | +| INT8 resolve (u8 lanes, one check) | 1237 ns | 1553 ns | +| INT8 stage A (region: one copy per lane) | 310 ns · 4096 B | 5364 ns · 65536 B | +| INT8 stage A, per-value walk (baseline) | 3553 ns | 34.5 µs | +| INT8 B for a region, in place from the table | 30 ns · 0 B written | 23 ns · 0 B written | +| INT8 materialize B (row-major i8) | 4242 ns · 4096 B | 45.6 µs · 65536 B | +| INT8 GEMM `backend::gemm_i8` (packs B per call) | 3552 ns · 73.8 GMAC/s · 3 allocs · 3072 B tmp | 61.0 µs · 274.9 GMAC/s · 3 allocs · 12288 B tmp | +| INT8 B band gather + VNNI pack (done inside each gemm_i8 call) | 1927 ns · 54% of the GEMM row | 23.1 µs · 38% of the GEMM row | +| INT8 end-to-end warm (resolve + stage + GEMM) | 5909 ns | 66.3 µs | diff --git a/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run3.txt b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run3.txt new file mode 100644 index 000000000..50c491580 --- /dev/null +++ b/crates/dr-isa-stream-lab/results/shape-2026-11-10-int8-run3.txt @@ -0,0 +1,30 @@ +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 360.4 µs + +| Metric | 64×64 | 256×256 | +|---|---|---| +| Output tiles / K=32 dot-product steps | 16 / 32 | 256 / 2048 | +| DT64 bind (cold) | 3192 ns · 2 allocs | 9047 ns · 6 allocs | +| Resolve: one check + borrows (warm) | 1250 ns · 0 allocs · 0 B | 2028 ns · 0 allocs · 0 B | +| Resolve: `lane()` per field (warm) | 11.7 µs | 151.6 µs | +| B preparation (VNNI panels) | 3224 ns · 8192 B written · 8320 B alloc | 45.0 µs · 131072 B written · 131584 B alloc | +| Direct AMX (A in place) | 4479 ns · 58.5 GMAC/s · 0 allocs · 0 B tmp | 143.9 µs · 116.6 GMAC/s · 0 allocs · 0 B tmp | +| Direct AMX, pitch 65,568 (not 2^k) | 3902 ns · 67.2 GMAC/s | 130.2 µs · 128.9 GMAC/s | +| Staged AMX (dense A tiles) | 4302 ns · 1 allocs · 2048 B tmp | 86.4 µs · 1 allocs · 8192 B tmp | +| ndarray CBLAS BF16 | 32.7 µs · 23 allocs · 54272 B tmp | 952.1 µ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) | 6685 ns | 147.5 µs | +| End-to-end cold (bind + prepare + resolve + direct) | 14.0 µs | 220.7 µs | +| Warm repetitions (100, per run, one prepare) | 6767 ns | 155.2 µs | +| INT8 resolve (u8 lanes, one check) | 1279 ns | 1996 ns | +| INT8 stage A (region: one copy per lane) | 286 ns · 4096 B | 6828 ns · 65536 B | +| INT8 stage A, per-value walk (baseline) | 3541 ns | 42.1 µ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) | 4262 ns · 4096 B | 58.7 µs · 65536 B | +| INT8 GEMM `backend::gemm_i8` (packs B per call) | 3552 ns · 73.8 GMAC/s · 3 allocs · 3072 B tmp | 82.1 µs · 204.3 GMAC/s · 3 allocs · 12288 B tmp | +| INT8 B band gather + VNNI pack (done inside each gemm_i8 call) | 1922 ns · 54% of the GEMM row | 29.4 µs · 36% of the GEMM row | +| INT8 end-to-end warm (resolve + stage + GEMM) | 10.8 µs | 87.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 f9be1a610..826cee7c2 100644 --- a/crates/dr-isa-stream-lab/src/bin/shape.rs +++ b/crates/dr-isa-stream-lab/src/bin/shape.rs @@ -12,8 +12,9 @@ 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::int8; use dr_isa_stream_lab::shape::{ - cblas, direct, oracle, staged, BOperand, PreparedB, Selection, VirtualObject, + cblas, direct, oracle, staged, BOperand, BTable, PreparedB, Selection, VirtualObject, }; use dr_isa_stream_lab::source::{Bf16Lanes, Socket}; use lance_graph_dt64::Extent; @@ -120,6 +121,8 @@ fn main() { seed: 0xB0B, rev: 1, }; + // B read from a table built once, so B preparation times data movement + // and not the synthetic operand's hash (which #1987's first run did). 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) { @@ -150,6 +153,7 @@ fn main() { 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 bt = BTable::new(&b, n + 64, dim); let want: Vec = oracle( &sel, &fields, @@ -163,18 +167,18 @@ fn main() { let bind = || VirtualObject::bind(&world, &socket, &fields, dim, sel.clone()).unwrap(); let obj = bind(); - let (prep, prep_rep) = PreparedB::prepare(&obj, &b); + let (prep, prep_rep) = PreparedB::prepare(&obj, &bt).unwrap(); 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(); + let dr = direct(&obj, &lanes_r, &prep, &bt, &mut c).unwrap(); assert_eq!(c, want, "direct {dim}"); - let sr = staged(&obj, &lanes_r, &prep, b.rev, &mut scratch, &mut c).unwrap(); + let sr = staged(&obj, &lanes_r, &prep, &bt, &mut scratch, &mut c).unwrap(); assert_eq!(c, want, "staged {dim}"); - let cr = cblas(&obj, &lanes_r, &b, &mut am, &mut bm, &mut c).unwrap(); + let cr = cblas(&obj, &lanes_r, &bt, &mut am, &mut bm, &mut c).unwrap(); assert_eq!(c, want, "cblas {dim}"); let t_bind = median_ns(|| { @@ -187,10 +191,10 @@ fn main() { black_box(obj.resolve_per_field(&world, &socket).unwrap()); }); let t_prep = median_ns(|| { - black_box(PreparedB::prepare(&obj, &b)); + black_box(PreparedB::prepare(&obj, &bt).unwrap()); }); let t_direct = median_ns(|| { - direct(&obj, &lanes_r, &prep, b.rev, &mut c).unwrap(); + direct(&obj, &lanes_r, &prep, &bt, &mut c).unwrap(); }); assert_eq!(c, want); // Same values and region, pitch n + 32 (not a multiple of 4 KiB): does @@ -199,53 +203,62 @@ fn main() { 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 (prep2, _) = PreparedB::prepare(&obj2, &bt).unwrap(); let l2 = obj2.resolve(&world, &socket2).unwrap(); - direct(&obj2, &l2, &prep2, b.rev, &mut c).unwrap(); + direct(&obj2, &l2, &prep2, &bt, &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(); + direct(&obj2, &l2, &prep2, &bt, &mut c).unwrap(); }); assert_eq!(c, want); let t_staged = median_ns(|| { - staged(&obj, &lanes_r, &prep, b.rev, &mut scratch, &mut c).unwrap(); + staged(&obj, &lanes_r, &prep, &bt, &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).unwrap(); + cblas(&obj, &lanes_r, &bt, &mut am, &mut bm, &mut c).unwrap(); }); 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(); + direct(&obj, &l, &prep, &bt, &mut c).unwrap(); }); assert_eq!(c, want); let t_cold = median_ns(|| { let o = bind(); - let (p, _) = PreparedB::prepare(&o, &b); + let (p, _) = PreparedB::prepare(&o, &bt).unwrap(); let l = o.resolve(&world, &socket).unwrap(); let mut cc = vec![0f32; o.c_len()]; - direct(&o, &l, &p, b.rev, &mut cc).unwrap(); + direct(&o, &l, &p, &bt, &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); + let (p, _) = PreparedB::prepare(&obj, &bt).unwrap(); for _ in 0..100 { let l = obj.resolve(&world, &socket).unwrap(); - direct(&obj, &l, &p, b.rev, &mut c).unwrap(); + direct(&obj, &l, &p, &bt, &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_prep, m_prep, _) = mem(|| PreparedB::prepare(&obj, &bt).unwrap()); + let (a_dir, m_dir, _) = mem(|| direct(&obj, &lanes_r, &prep, &bt, &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).unwrap()); + mem(|| staged(&obj, &lanes_r, &prep, &bt, &mut Vec::new(), &mut c).unwrap()); + let (a_cbl, m_cbl, _) = mem(|| { + cblas( + &obj, + &lanes_r, + &bt, + &mut Vec::new(), + &mut Vec::new(), + &mut c, + ) + .unwrap() + }); let macs = (dim * dim * dim) as f64; push( @@ -329,6 +342,105 @@ fn main() { fmt(t_rep), ); let _ = (m_bind, a_prep); + + // INT8: the same object over u8 lanes, u8 x i8 -> i32. ndarray's INT8 + // facade takes dense A and packs B inside each call, so the only arm + // is staged; the stage costs are timed apart from the GEMM. + let u8l = int8::U8Lanes::slab_in_order(&fx); + let u8s = int8::U8Socket::in_order(&u8l, dim); + let o8 = VirtualObject::bind(&world, &u8s, &fields, dim, sel.clone()).unwrap(); + let want8: Vec = int8::oracle(&fx, &sel, &fields, dim, &b) + .iter() + .map(|&v| i32::try_from(v).unwrap()) + .collect(); + let l8 = int8::resolve(&o8, &world, &u8s).unwrap(); + let (mut a8, mut b8, mut c8) = (Vec::new(), Vec::new(), vec![0i32; o8.c_len()]); + let r8 = int8::staged(&o8, &l8, &bt, &mut a8, &mut b8, &mut c8).unwrap(); + assert_eq!(c8, want8, "int8 {dim}"); + let t8_resolve = median_ns(|| { + black_box(int8::resolve(&o8, &world, &u8s).unwrap()); + }); + let t8_a = median_ns(|| { + int8::stage_a(&o8, &l8, &mut a8).unwrap(); + }); + let t8_a_pv = median_ns(|| { + int8::stage_a_per_value(&o8, &l8, &mut a8).unwrap(); + }); + let t8_b_inplace = median_ns(|| { + black_box(int8::b_operand(&o8, &bt, &mut b8)); + }); + let t8_b = median_ns(|| { + int8::stage_b(&o8, &bt, &mut b8); + }); + let t8_gemm = median_ns(|| int8::gemm(&o8, &a8, &b8, &mut c8)); + 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). + 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 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); + black_box(&packed); + } + }); + let t8_all = median_ns(|| { + let l = int8::resolve(&o8, &world, &u8s).unwrap(); + int8::staged(&o8, &l, &bt, &mut a8, &mut b8, &mut c8).unwrap(); + }); + assert_eq!(c8, want8); + let (a8_allocs, m8_gemm, _) = mem(|| int8::gemm(&o8, &a8, &b8, &mut c8)); + push("INT8 resolve (u8 lanes, one check)", col, fmt(t8_resolve)); + push( + "INT8 stage A (region: one copy per lane)", + col, + format!("{} · {} B", fmt(t8_a), r8.a_copied), + ); + push("INT8 stage A, per-value walk (baseline)", col, fmt(t8_a_pv)); + push( + "INT8 B for a region, in place from the table", + col, + format!( + "{} · {} B written", + fmt(t8_b_inplace), + int8::b_operand(&o8, &bt, &mut b8).1 + ), + ); + push( + "INT8 materialize B (row-major i8)", + col, + format!("{} · {} B", fmt(t8_b), int8::stage_b(&o8, &bt, &mut b8)), + ); + push( + "INT8 GEMM `backend::gemm_i8` (packs B per call)", + col, + format!( + "{} · {:.1} GMAC/s · {a8_allocs} allocs · {m8_gemm} B tmp", + fmt(t8_gemm), + macs / t8_gemm + ), + ); + push( + "INT8 B band gather + VNNI pack (done inside each gemm_i8 call)", + col, + format!( + "{} · {:.0}% of the GEMM row", + fmt(t8_pack), + 100.0 * t8_pack / t8_gemm + ), + ); + push( + "INT8 end-to-end warm (resolve + stage + GEMM)", + col, + fmt(t8_all), + ); } // Sparse demand: 40 scattered identities, 256 fields x 256 columns. @@ -342,6 +454,7 @@ fn main() { 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 bt = BTable::new(&b, n, 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( @@ -355,14 +468,14 @@ fn main() { .map(|&v| v as f32) .collect(); let obj = VirtualObject::bind(&world, &socket, &fields, dim, sel.clone()).unwrap(); - let (prep, _) = PreparedB::prepare(&obj, &b); + let (prep, _) = PreparedB::prepare(&obj, &bt).unwrap(); 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(); + let r = staged(&obj, &l, &prep, &bt, &mut scratch, &mut c).unwrap(); assert_eq!(c, want); let t = median_ns(|| { - staged(&obj, &l, &prep, b.rev, &mut scratch, &mut c).unwrap(); + staged(&obj, &l, &prep, &bt, &mut scratch, &mut c).unwrap(); }); assert_eq!(c, want); println!( diff --git a/crates/dr-isa-stream-lab/src/bind.rs b/crates/dr-isa-stream-lab/src/bind.rs index 9ae12666e..7cdb18314 100644 --- a/crates/dr-isa-stream-lab/src/bind.rs +++ b/crates/dr-isa-stream-lab/src/bind.rs @@ -8,8 +8,6 @@ use lance_graph_dt64::{ RouteAt, SchemaRev, }; -use crate::source::Socket; - /// The lab's class. pub const CLASS: u32 = 0x5115_0001; /// The ClassView key of the class. @@ -102,9 +100,9 @@ impl World { /// Cold: bind exactly `fields` under `selection`'s row order, at the /// source's current frame. - pub fn bind( + pub fn bind( &self, - socket: &Socket<'_>, + socket: &S, fields: &[u8], selection: CoordSpace, ) -> Result { diff --git a/crates/dr-isa-stream-lab/src/int8.rs b/crates/dr-isa-stream-lab/src/int8.rs new file mode 100644 index 000000000..fd0664854 --- /dev/null +++ b/crates/dr-isa-stream-lab/src/int8.rs @@ -0,0 +1,367 @@ +//! D-DT64-GEMM-SHAPE-3: the same virtual object over u8 lanes, consumed as +//! `u8 x i8 -> i32` (AMX `TDPBUSD`), next to the BF16 arms in [`crate::shape`]. +//! +//! A is the source's lanes as **unsigned** u8; B is the synthetic operand as +//! **signed** i8. That is `TDPBUSD`'s native contract: A is never +//! reinterpreted as signed and no u8/i8 cast is introduced anywhere. +//! +//! 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. + +use std::cell::Cell; + +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 crate::bind::{World, CLASS, READER, SPACE_A}; +use crate::fixture::Fixture; +use crate::shape::{BOperand, BValues, Selection, ShapeRefusal, VirtualObject, Where, MAX_ROWS}; + +/// INT8 tiles consume K in steps of 64. +pub const K_STEP: usize = 64; + +/// `A[i][p]` as u8: the fixture value shifted into [0, 16]. Unsigned by +/// construction; never a reinterpreted i8. +pub fn a_u8(fx: &Fixture, i: usize, p: usize) -> u8 { + u8::try_from(fx.value(i, p) + 8).expect("[-8, 8] + 8 is in u8") +} + +/// `B[i][j]` as i8 (the same synthetic operand as the BF16 arms). +pub fn b_i8(b: &BOperand, i: usize, j: usize) -> i8 { + i8::try_from(b.value(i, j)).expect("[-8, 8] is in i8") +} + +/// One borrowed u8 lane: `n` values at `slab[row * pitch..][..n]`. +#[derive(Debug, Clone, Copy)] +pub struct U8Lane<'a> { + pub slab: &'a [u8], + pub row: usize, + pub pitch: usize, + pub n: usize, +} + +impl<'a> U8Lane<'a> { + /// The lane's values, in the lane's own row order. + pub fn values(&self) -> &'a [u8] { + &self.slab[self.row * self.pitch..self.row * self.pitch + self.n] + } +} + +/// The data owner: u8 lanes in one slab at a pitch padded to [`K_STEP`], +/// and the frame store that lives with them. +#[derive(Debug)] +pub struct U8Lanes { + data: Box<[u8]>, + pitch: usize, + n: usize, + frames: FrameStore, +} + +impl U8Lanes { + /// `fx.props` lanes over `fx.n` identities, field `f` at row `f`. + pub fn slab_in_order(fx: &Fixture) -> U8Lanes { + U8Lanes::from_fn(fx.n, fx.props, |i, p| a_u8(fx, i, p)) + } + + /// `props` lanes over `n` identities from encoded u8 values. + pub fn from_fn(n: usize, props: usize, value: impl Fn(usize, usize) -> u8) -> U8Lanes { + let pitch = n.div_ceil(K_STEP) * K_STEP; + let mut data = vec![0u8; props * pitch].into_boxed_slice(); + for p in 0..props { + for i in 0..n { + data[p * pitch + i] = value(i, p); + } + } + U8Lanes { + data, + pitch, + n, + frames: FrameStore::new(FrameRevisions { + source: 1, + relation_map: 1, + coordinates: 1, + }), + } + } + + /// Mutable frame owner, for advancing the source after a change. + pub fn frames_mut(&mut self) -> &mut FrameStore { + &mut self.frames + } + + /// Physical row `r`, borrowed in place. + pub fn row(&self, r: usize) -> Option> { + (r * self.pitch + self.n <= self.data.len()).then_some(U8Lane { + slab: &self.data, + row: r, + pitch: self.pitch, + n: self.n, + }) + } +} + +/// The DT64 socket over a [`U8Lanes`]: field `f` lives in row `rows[f]`. +pub struct U8Socket<'a> { + pub lanes: &'a U8Lanes, + pub rows: Vec, + pub space: CoordSpace, + pub scope: Scope, + pub borrows: Cell, +} + +impl<'a> U8Socket<'a> { + /// Field `f` at row `f`, in [`SPACE_A`]. + pub fn in_order(lanes: &'a U8Lanes, props: usize) -> U8Socket<'a> { + U8Socket { + lanes, + rows: (0..props).collect(), + space: SPACE_A, + scope: READER, + borrows: Cell::new(0), + } + } +} + +impl LaneSource for U8Socket<'_> { + type Lane<'b> + = U8Lane<'b> + where + Self: 'b; + + fn lane_of( + &self, + class: u32, + rev: SchemaRev, + field: u8, + _basis: &FieldRef, + _frame: &Frame, + ) -> Option { + let f = usize::from(field); + if class != CLASS || rev != SchemaRev(1) || f >= self.rows.len() { + return None; + } + Some(LaneAddr { + space: self.space, + lane: u16::try_from(self.rows[f]).ok()?, + scope: self.scope, + }) + } + + fn borrow(&self, addr: &LaneAddr) -> Option> { + self.borrows.set(self.borrows.get() + 1); + self.lanes.row(usize::from(addr.lane)) + } + + fn frames(&self) -> &FrameStore { + &self.lanes.frames + } +} + +/// The borrowed u8 lanes of an object, with the frame issue and lane +/// addresses they were resolved under. +#[derive(Debug, Clone)] +pub struct U8Lanes64<'s> { + lanes: [U8Lane<'s>; MAX_ROWS], + object: u64, + frame: Frame, + count: usize, +} + +impl<'s> U8Lanes64<'s> { + /// The borrowed lanes. + pub fn lanes(&self) -> &[U8Lane<'s>] { + &self.lanes[..self.count] + } +} + +/// Warm: [`lance_graph_dt64::LaneBinding::borrow_all`] checks the object's +/// binding once and hands out every bound u8 lane; they are placed in the +/// view's row order. Any refusal returns before a lane is placed. No +/// allocation. +pub fn resolve<'s>( + obj: &VirtualObject, + world: &World, + socket: &'s U8Socket<'_>, +) -> Result, ShapeRefusal> { + let binding = obj.binding(); + let mut by_field: [Option>; MAX_ROWS] = [None; MAX_ROWS]; + for item in binding.borrow_all(&world.store, &world.view, socket.frames(), socket)? { + let (field, lane) = item?; + by_field[usize::from(field)] = Some(lane); + } + let lane = |f: u8| by_field[usize::from(f)].ok_or(LaneRefusal::NotBound { field: f }); + let fields = obj.fields(); + let first = lane(fields[0])?; + let mut lanes = [first; MAX_ROWS]; + for (slot, &f) in lanes.iter_mut().zip(fields).skip(1) { + *slot = lane(f)?; + } + Ok(U8Lanes64 { + lanes, + object: obj.id(), + frame: binding.frame().clone(), + count: fields.len(), + }) +} + +fn admit(obj: &VirtualObject, lanes: &U8Lanes64<'_>) -> Result<(), ShapeRefusal> { + let same = lanes.object == obj.id() + && lanes.count == obj.fields().len() + && lanes.frame.same_issue(obj.binding().frame()); + if !same { + return Err(ShapeRefusal::ForeignLanes); + } + let n = lanes.lanes().iter().map(|l| l.n).min().unwrap_or(0); + if let Some(last) = obj.selection().last() { + if last >= n { + return Err(ShapeRefusal::OutOfRange { last, n }); + } + } + Ok(()) +} + +/// What the INT8 arm did. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Int8Report { + /// K after padding to the 64-step. + pub k_pad: usize, + /// Bytes of A copied out of the source (u8, one byte per value). + pub a_copied: usize, + /// Bytes of B materialized row-major (i8). + pub b_materialized: usize, + /// 16 x 16 output tiles. + pub tiles: usize, + /// Logical `TDPBUSD` steps (`tiles x k_pad / 64`); B is re-packed per + /// call inside ndarray and that pack is not counted here. + pub dp_steps: usize, +} + +/// Gather A (`rows x k_pad`, u8, zero-padded) into `a`. +pub fn stage_a( + obj: &VirtualObject, + lanes: &U8Lanes64<'_>, + a: &mut Vec, +) -> Result { + admit(obj, lanes)?; + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + a.clear(); + a.resize(obj.fields().len() * k_pad, 0); + for (r, lane) in lanes.lanes().iter().enumerate() { + let values = lane.values(); + let row = &mut a[r * k_pad..(r + 1) * k_pad]; + match obj.selection().kind { + // A region is contiguous in the lane: one copy, no per-value walk. + 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]), + } + } + Ok(obj.fields().len() * obj.selection().len()) +} + +/// [`stage_a`] with every selection walked value by value, regions too: the +/// baseline the region copy is measured against. +pub fn stage_a_per_value( + obj: &VirtualObject, + lanes: &U8Lanes64<'_>, + a: &mut Vec, +) -> Result { + admit(obj, lanes)?; + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + a.clear(); + a.resize(obj.fields().len() * k_pad, 0); + for (r, lane) in lanes.lanes().iter().enumerate() { + let values = lane.values(); + let row = &mut a[r * k_pad..(r + 1) * k_pad]; + obj.selection().for_each(|k, i| row[k] = values[i]); + } + Ok(obj.fields().len() * obj.selection().len()) +} + +/// B for the GEMM: borrowed in place when the selection is a region whose +/// rows the source holds contiguously at this width and K needs no padding; +/// otherwise materialized into `bm`. Returns the slice and the bytes written. +pub fn b_operand<'b>( + obj: &VirtualObject, + b: &'b impl BValues, + bm: &'b mut Vec, +) -> (&'b [i8], usize) { + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + if let Where::Region { start, len } = obj.selection().kind { + if len == k_pad { + if let Some(rows) = b.i8_rows(start, len, obj.cols()) { + return (rows, 0); + } + } + } + let written = stage_b(obj, b, bm); + (bm.as_slice(), written) +} + +/// Materialize B (`k_pad x cols`, i8, zero rows past the selection) into `bm`. +pub fn stage_b(obj: &VirtualObject, b: &impl BValues, bm: &mut Vec) -> usize { + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + let n = obj.cols(); + bm.clear(); + bm.resize(k_pad * n, 0); + obj.selection().for_each(|k, i| { + for j in 0..n { + bm[k * n + j] = b.i8_at(i, j); + } + }); + obj.selection().len() * n +} + +/// The INT8 GEMM over already staged operands: `c = a x bm`, overwritten. +pub fn gemm(obj: &VirtualObject, a: &[u8], bm: &[i8], c: &mut [i32]) { + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + let (m, n) = (obj.fields().len(), obj.cols()); + assert_eq!(c.len(), m * n); + c.fill(0); + ndarray::backend::gemm_i8(a, bm, c, m, n, k_pad); +} + +/// The INT8 arm end to end: stage A, materialize B, GEMM. +pub fn staged( + obj: &VirtualObject, + lanes: &U8Lanes64<'_>, + b: &impl BValues, + a: &mut Vec, + bm: &mut Vec, + c: &mut [i32], +) -> Result { + crate::shape::admit_operand(obj, b)?; + let a_copied = stage_a(obj, lanes, a)?; + let (b_slice, b_written) = b_operand(obj, b, bm); + gemm(obj, a, b_slice, c); + let k_pad = obj.selection().len().div_ceil(K_STEP) * K_STEP; + Ok(Int8Report { + k_pad, + a_copied, + b_materialized: b_written, + tiles: obj.tiles(), + dp_steps: obj.tiles() * k_pad / K_STEP, + }) +} + +/// The exact answer in i64, from the value functions alone. +pub fn oracle(fx: &Fixture, sel: &Selection, fields: &[u8], cols: usize, b: &BOperand) -> Vec { + let mut c = vec![0i64; fields.len() * cols]; + sel.for_each(|_, i| { + for (p, &f) in fields.iter().enumerate() { + let av = i64::from(a_u8(fx, i, usize::from(f))); + for j in 0..cols { + c[p * cols + j] += av * i64::from(b_i8(b, i, j)); + } + } + }); + c +} diff --git a/crates/dr-isa-stream-lab/src/lib.rs b/crates/dr-isa-stream-lab/src/lib.rs index e847fd7db..e9ef47538 100644 --- a/crates/dr-isa-stream-lab/src/lib.rs +++ b/crates/dr-isa-stream-lab/src/lib.rs @@ -23,6 +23,7 @@ pub mod bind; pub mod cube; pub mod fixture; pub mod gemm; +pub mod int8; 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 index 5a081c287..02e5431a5 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}; +use lance_graph_dt64::{CoordSpace, LaneBinding, LaneRefusal, LaneSource}; use ndarray::simd::{ bf16_tile_gemm_16x16_packed, bf16_tile_gemm_16x16_packed_strided, PackedBf16B, }; @@ -146,30 +146,6 @@ impl Selection { } } } - - /// 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. @@ -208,6 +184,14 @@ pub enum ShapeRefusal { ForeignLanes, /// The selection names identity `last`, but the lanes hold only `n`. OutOfRange { last: usize, n: usize }, + /// B is a table smaller than the object needs: `cols` output columns or + /// row `last`, against a table of `rows x table_cols`. + OperandShape { + cols: usize, + last: usize, + rows: usize, + table_cols: usize, + }, } impl From for ShapeRefusal { @@ -236,9 +220,9 @@ static NEXT_OBJECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64: 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( + pub fn bind( world: &World, - socket: &Socket<'_>, + socket: &S, fields: &[u8], cols: usize, selection: Selection, @@ -264,6 +248,16 @@ impl VirtualObject { }) } + /// Which bind made this object (provenance for resolved lanes). + pub fn id(&self) -> u64 { + self.id + } + + /// The lane binding (addresses only), for arms over other lane types. + pub fn binding(&self) -> &LaneBinding { + &self.binding + } + /// The demanded fields: the view's rows. pub fn fields(&self) -> &[u8] { &self.fields @@ -421,6 +415,153 @@ impl BOperand { } } +/// Where B's values come from: computed per call ([`BOperand`], a hash) or +/// read from a table built once ([`BTable`]). Timing B preparation over a +/// `BOperand` measures the hash, not the data movement; benchmarks use a +/// `BTable`. +pub trait BValues { + /// Which operand this is and at which revision: what prepared-B reuse is + /// keyed on. + fn identity(&self) -> OperandId; + /// `B[i][j]` in bf16. + fn bf16_at(&self, i: usize, j: usize) -> u16; + /// `B[i][j]` in i8. + fn i8_at(&self, i: usize, j: usize) -> i8; + /// Rows `start..start + len` of B in i8, row-major with `cols` columns, + /// borrowed in place if the source holds them that way. + fn i8_rows(&self, _start: usize, _len: usize, _cols: usize) -> Option<&[i8]> { + None + } + /// `(rows, cols)` if B is a finite table, `None` if it is defined + /// everywhere. + fn extent(&self) -> Option<(usize, usize)> { + None + } +} + +/// Refuses an operand that cannot supply every `B[i][j]` the object reads: +/// fewer columns than the output width, or fewer rows than the selection +/// reaches. Checked before any arm reads B, so a mismatch is a refusal and +/// never a silent read of the next row. +pub fn admit_operand(obj: &VirtualObject, b: &impl BValues) -> Result<(), ShapeRefusal> { + let Some((rows, table_cols)) = b.extent() else { + return Ok(()); + }; + let last = obj.selection.last().unwrap_or(0); + if obj.cols > table_cols || last >= rows { + return Err(ShapeRefusal::OperandShape { + cols: obj.cols, + last, + rows, + table_cols, + }); + } + Ok(()) +} + +/// Authoritative operand identity: the source that defines the values and +/// its revision. Not a digest of the values. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OperandId { + /// For a [`BOperand`], its seed (the seed defines the function); for a + /// [`BTable`], the table's construction instance. + pub source: OperandSource, + pub rev: u64, +} + +/// Where an operand's values are defined. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OperandSource { + /// A deterministic function of `(seed, i, j)`. + Function { seed: u64 }, + /// An immutable table, by the construction that filled it. + Table { instance: u64 }, +} + +impl BValues for BOperand { + fn identity(&self) -> OperandId { + OperandId { + source: OperandSource::Function { seed: self.seed }, + rev: self.rev, + } + } + fn bf16_at(&self, i: usize, j: usize) -> u16 { + self.bf16(i, j) + } + fn i8_at(&self, i: usize, j: usize) -> i8 { + i8::try_from(self.value(i, j)).expect("[-8, 8] is in i8") + } +} + +/// B materialized once over the universe, row-major `n x cols`, in both +/// encodings. Reading it is a load, so preparing B from it times movement. +pub struct BTable { + instance: u64, + rev: u64, + cols: usize, + bf16: Vec, + i8: Vec, +} + +impl BTable { + /// Every `B[i][j]` for `i < n`, `j < cols`. + pub fn new(b: &BOperand, n: usize, cols: usize) -> BTable { + let (mut bf16, mut i8s) = (Vec::with_capacity(n * cols), Vec::with_capacity(n * cols)); + for i in 0..n { + for j in 0..cols { + bf16.push(b.bf16_at(i, j)); + i8s.push(b.i8_at(i, j)); + } + } + BTable { + instance: NEXT_TABLE.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + rev: b.rev, + cols, + bf16, + i8: i8s, + } + } +} + +/// Table instances; only uniqueness matters. A table never changes after +/// construction, so instance + revision identifies its values. +static NEXT_TABLE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +impl BValues for BTable { + fn identity(&self) -> OperandId { + OperandId { + source: OperandSource::Table { + instance: self.instance, + }, + rev: self.rev, + } + } + fn bf16_at(&self, i: usize, j: usize) -> u16 { + assert!( + j < self.cols, + "column {j} past a {}-column table", + self.cols + ); + self.bf16[i * self.cols + j] + } + fn i8_at(&self, i: usize, j: usize) -> i8 { + assert!( + j < self.cols, + "column {j} past a {}-column table", + self.cols + ); + self.i8[i * self.cols + j] + } + fn extent(&self) -> Option<(usize, usize)> { + Some((self.i8.len() / self.cols.max(1), self.cols)) + } + fn i8_rows(&self, start: usize, len: usize, cols: usize) -> Option<&[i8]> { + (cols == self.cols) + .then(|| self.i8.get(start * cols..(start + len) * cols)) + .flatten() + } +} + /// Why a prepared B cannot serve an object. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ReuseRefusal { @@ -435,14 +576,17 @@ pub enum ReuseRefusal { } /// 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 +/// object (selection, frame, width) and one operand identity 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, + /// The object it was packed for (fast path: one compare). + object: u64, + /// That object's selection, compared in full when the object differs: + /// equality, never a digest. + selection: Selection, frame: Frame, - rev: u64, + operand: OperandId, panels: Vec, } @@ -459,7 +603,11 @@ pub struct PrepReport { 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) { + pub fn prepare( + obj: &VirtualObject, + b: &impl BValues, + ) -> Result<(PreparedB, PrepReport), ShapeRefusal> { + admit_operand(obj, b)?; let k = obj.selection.k_pad(); let mut panels: Vec = (0..obj.cols / TILE) .map(|_| PackedBf16B::zeroed(k)) @@ -469,18 +617,18 @@ impl PreparedB { 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); + data[PackedBf16B::vnni_index(row, c)] = b.bf16_at(i, t * TILE + c); } written += TILE * 2; } }); let allocated = panels.iter().map(|p| p.data().len() * 2).sum(); - ( + Ok(( PreparedB { - space: obj.selection.space, - selection: obj.selection.key(), + object: obj.id, + selection: obj.selection.clone(), frame: obj.frame().clone(), - rev: b.rev, + operand: b.identity(), panels, }, PrepReport { @@ -488,7 +636,7 @@ impl PreparedB { bytes_written: written, bytes_allocated: allocated, }, - ) + )) } /// Panel `t` (output columns `16t..16t+16`), for inspection. @@ -496,17 +644,26 @@ impl PreparedB { &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() { + /// 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. + 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.rev != rev { - return Err(ReuseRefusal::Operand); - } if self.panels.len() * TILE != obj.cols { return Err(ReuseRefusal::Columns); } @@ -543,10 +700,10 @@ pub fn direct( obj: &VirtualObject, lanes: &Lanes<'_>, b: &PreparedB, - rev: u64, + operand: &impl BValues, c: &mut [f32], ) -> Result { - b.admit(obj, rev).map_err(ShapeRefusal::Reuse)?; + b.admit(obj, operand).map_err(ShapeRefusal::Reuse)?; obj.admit_lanes(lanes)?; let Where::Region { start, len } = obj.selection.kind else { return Err(ShapeRefusal::NotARegion); @@ -593,11 +750,11 @@ pub fn staged( obj: &VirtualObject, lanes: &Lanes<'_>, b: &PreparedB, - rev: u64, + operand: &impl BValues, scratch: &mut Vec, c: &mut [f32], ) -> Result { - b.admit(obj, rev).map_err(ShapeRefusal::Reuse)?; + b.admit(obj, operand).map_err(ShapeRefusal::Reuse)?; obj.admit_lanes(lanes)?; assert_eq!(c.len(), obj.c_len()); let k_pad = obj.selection.k_pad(); @@ -634,12 +791,13 @@ pub fn staged( pub fn cblas( obj: &VirtualObject, lanes: &Lanes<'_>, - b: &BOperand, + b: &impl BValues, a: &mut Vec, bm: &mut Vec, c: &mut [f32], ) -> Result { obj.admit_lanes(lanes)?; + admit_operand(obj, b)?; let m = obj.fields.len(); let n = obj.cols; let k = obj.selection.len(); @@ -655,7 +813,7 @@ pub fn cblas( } obj.selection.for_each(|kk, i| { for j in 0..n { - bm[kk * n + j] = b.bf16(i, j); + bm[kk * n + j] = b.bf16_at(i, j); } }); ndarray::backend::cblas_gemm_bf16bf16f32(a, bm, c, m, n, k); diff --git a/crates/dr-isa-stream-lab/tests/integration/int8.rs b/crates/dr-isa-stream-lab/tests/integration/int8.rs new file mode 100644 index 000000000..783b7a705 --- /dev/null +++ b/crates/dr-isa-stream-lab/tests/integration/int8.rs @@ -0,0 +1,267 @@ +//! D-DT64-GEMM-SHAPE-3: u8 x i8 -> i32 over the same virtual object. + +use dr_isa_stream_lab::bind::{World, SPACE_A}; +use dr_isa_stream_lab::fixture::Fixture; +use dr_isa_stream_lab::int8::{self, U8Lanes, U8Socket}; +use dr_isa_stream_lab::shape::{ + oracle as bf16_oracle, BOperand, Selection, ShapeRefusal, VirtualObject, +}; +use lance_graph_dt64::dr::{FrameRefusal, FrameRevisions}; +use lance_graph_dt64::{Extent, LaneRefusal}; + +const B: BOperand = BOperand { + seed: 0xB0B, + rev: 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 fields(dim: usize) -> Vec { + (0..dim).map(|f| f as u8).collect() +} + +fn fx(n: usize, props: usize) -> Fixture { + Fixture { + n, + props, + seed: 0x5A9E_0000 + (n * props) as u64, + } +} + +fn run( + world: &World, + socket: &U8Socket<'_>, + dim: usize, + sel: Selection, +) -> (Vec, int8::Int8Report) { + let obj = VirtualObject::bind(world, socket, &fields(dim), dim, sel).unwrap(); + let lanes = int8::resolve(&obj, world, socket).unwrap(); + let mut c = vec![0i32; obj.c_len()]; + let r = int8::staged(&obj, &lanes, &B, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap(); + (c, r) +} + +/// Exact against the i64 oracle at both sizes, over a region, K tails 63 +/// and 65 (padded to 64 and 128), and a scattered mask. +#[test] +fn int8_is_exact_at_both_sizes_tails_and_masks() { + 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 sels = [ + Selection::region(SPACE_A, 1024, dim), + Selection::region(SPACE_A, 1000, 63), + Selection::region(SPACE_A, 1000, 65), + Selection::mask(SPACE_A, 4096, (0..40).map(|k| (k * 97 + 13) % 4096)), + ]; + for sel in sels { + let want: Vec = int8::oracle(&fx, &sel, &fields(dim), dim, &B) + .iter() + .map(|&v| i32::try_from(v).unwrap()) + .collect(); + let (got, r) = run(&world, &socket, dim, sel.clone()); + assert_eq!(got, want, "dim {dim}, {:?}", sel.kind); + assert_eq!(r.k_pad, sel.len().div_ceil(64) * 64); + assert_eq!(r.a_copied, dim * sel.len(), "one byte per selected value"); + } + } +} + +/// u8 A is unsigned: 200 x (-1) summed over K is -200 K. Read as i8, 200 +/// would be -56 and the sum +56 K. +#[test] +fn a_is_never_reinterpreted_as_signed() { + let dim = 64; + let lanes = U8Lanes::from_fn(256, dim, |_, _| 200); + let socket = U8Socket::in_order(&lanes, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, 0, 64); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let l = int8::resolve(&obj, &world, &socket).unwrap(); + let mut a = Vec::new(); + int8::stage_a(&obj, &l, &mut a).unwrap(); + let bm = vec![-1i8; 64 * dim]; + let mut c = vec![0i32; obj.c_len()]; + int8::gemm(&obj, &a, &bm, &mut c); + assert!(c.iter().all(|&v| v == -200 * 64), "got {}", c[0]); +} + +/// The INT8 and BF16 arms see the same fixture: A_u8 = A + 8, so +/// C_int8 = C_bf16 + 8 x colsum(B) over the selection, exactly. +#[test] +fn int8_and_bf16_agree_on_the_same_fixture() { + let dim = 64; + let fx = fx(4096, dim); + let sel = Selection::region(SPACE_A, 512, 64); + let bf = bf16_oracle( + &sel, + &fields(dim), + dim, + |i, p| f64::from(fx.value(i, p)), + |i, j| f64::from(B.value(i, j)), + ); + let mut colsum = vec![0i64; dim]; + sel.for_each(|_, i| (0..dim).for_each(|j| colsum[j] += i64::from(B.value(i, j)))); + let lanes = U8Lanes::slab_in_order(&fx); + let socket = U8Socket::in_order(&lanes, dim); + let (got, _) = run(&world(dim), &socket, dim, sel); + for (idx, &g) in got.iter().enumerate() { + assert_eq!(i64::from(g), bf[idx] as i64 + 8 * colsum[idx % dim]); + } +} + +/// The binding refusals hold for u8 lanes too, and foreign or out-of-range +/// lanes are refused before staging. +#[test] +fn int8_refusals() { + let dim = 64; + let fx = fx(1024, dim); + let world = world(dim); + let sel = Selection::region(SPACE_A, 0, 64); + + let mut lanes = U8Lanes::slab_in_order(&fx); + let obj = { + let socket = U8Socket::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 = U8Socket::in_order(&lanes, dim); + assert_eq!( + int8::resolve(&obj, &world, &socket).unwrap_err(), + ShapeRefusal::Lane(LaneRefusal::Frame(FrameRefusal::SourceChanged)) + ); + + // Mapping changed after the bind. + let mut remapped = U8Socket::in_order(&lanes, dim); + let obj = VirtualObject::bind(&world, &remapped, &fields(dim), dim, sel.clone()).unwrap(); + remapped.rows.swap(0, 1); + assert_eq!( + int8::resolve(&obj, &world, &remapped).unwrap_err(), + ShapeRefusal::Lane(LaneRefusal::MappingChanged { field: 0 }) + ); + + // Lanes resolved from another source. + let other = U8Lanes::slab_in_order(&fx); + let other_socket = U8Socket::in_order(&other, dim); + let other_obj = + VirtualObject::bind(&world, &other_socket, &fields(dim), dim, sel.clone()).unwrap(); + let foreign = int8::resolve(&other_obj, &world, &other_socket).unwrap(); + assert_eq!( + int8::stage_a(&obj, &foreign, &mut Vec::new()).unwrap_err(), + ShapeRefusal::ForeignLanes + ); + + // A selection past the source. + let past = VirtualObject::bind( + &world, + &socket, + &fields(dim), + dim, + Selection::region(SPACE_A, 1000, 64), + ) + .unwrap(); + let l = int8::resolve(&past, &world, &socket).unwrap(); + assert_eq!( + int8::stage_a(&past, &l, &mut Vec::new()).unwrap_err(), + ShapeRefusal::OutOfRange { + last: 1063, + n: 1024 + } + ); +} + +/// One borrow per field, whatever the universe. +#[test] +fn int8_resolution_borrows_one_lane_per_field() { + for n in [256, 65_536] { + let fx = fx(n, 256); + let lanes = U8Lanes::slab_in_order(&fx); + let socket = U8Socket::in_order(&lanes, 256); + let world = world(256); + let obj = VirtualObject::bind( + &world, + &socket, + &fields(256), + 256, + Selection::region(SPACE_A, 0, 64), + ) + .unwrap(); + let before = socket.borrows.get(); + int8::resolve(&obj, &world, &socket).unwrap(); + assert_eq!(socket.borrows.get() - before, 256); + } +} + +/// B is borrowed in place from a table for a full-width region (0 bytes +/// written) and materialized otherwise; both are exact. The region copy of A +/// and the per-value walk stage the same bytes. +#[test] +fn b_in_place_and_region_copy_are_exact_and_counted() { + use dr_isa_stream_lab::shape::BTable; + let dim = 64; + let fx = fx(4096, dim); + let lanes = U8Lanes::slab_in_order(&fx); + let socket = U8Socket::in_order(&lanes, dim); + let world = world(dim); + let table = BTable::new(&B, 4096, dim); + let cases = [ + (Selection::region(SPACE_A, 1024, 64), true), + (Selection::region(SPACE_A, 1024, 63), false), // K pads to 64 + (Selection::mask(SPACE_A, 4096, [5, 77, 300]), false), + ]; + for (sel, in_place) in cases { + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel.clone()).unwrap(); + let l = int8::resolve(&obj, &world, &socket).unwrap(); + let mut c = vec![0i32; obj.c_len()]; + let r = int8::staged(&obj, &l, &table, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap(); + let want: Vec = int8::oracle(&fx, &sel, &fields(dim), dim, &B) + .iter() + .map(|&v| i32::try_from(v).unwrap()) + .collect(); + assert_eq!(c, want, "{:?}", sel.kind); + assert_eq!(r.b_materialized == 0, in_place, "{:?}", sel.kind); + let (mut a1, mut a2) = (Vec::new(), Vec::new()); + int8::stage_a(&obj, &l, &mut a1).unwrap(); + int8::stage_a_per_value(&obj, &l, &mut a2).unwrap(); + assert_eq!(a1, a2); + } +} + +/// The INT8 arm refuses a B table narrower than the object instead of +/// reading the next row, and accepts one of the right width. +#[test] +fn int8_refuses_a_b_table_narrower_than_the_object() { + use dr_isa_stream_lab::shape::BTable; + let dim = 64; + let fx = fx(4096, dim); + let lanes = U8Lanes::slab_in_order(&fx); + let socket = U8Socket::in_order(&lanes, dim); + let world = world(dim); + 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 mut c = vec![0i32; obj.c_len()]; + let narrow = BTable::new(&B, 4096, 16); + assert!(matches!( + int8::staged(&obj, &l, &narrow, &mut Vec::new(), &mut Vec::new(), &mut c), + Err(ShapeRefusal::OperandShape { .. }) + )); + let fits = BTable::new(&B, 4096, dim); + int8::staged(&obj, &l, &fits, &mut Vec::new(), &mut Vec::new(), &mut c).unwrap(); + let mut want = vec![0i32; obj.c_len()]; + int8::staged(&obj, &l, &B, &mut Vec::new(), &mut Vec::new(), &mut want).unwrap(); + assert_eq!(c, want); +} diff --git a/crates/dr-isa-stream-lab/tests/integration/main.rs b/crates/dr-isa-stream-lab/tests/integration/main.rs index 1ecf9202d..c8377bb6d 100644 --- a/crates/dr-isa-stream-lab/tests/integration/main.rs +++ b/crates/dr-isa-stream-lab/tests/integration/main.rs @@ -1,4 +1,5 @@ pub mod geometry; +pub mod int8; pub mod numeric; pub mod parity; pub mod refusals; diff --git a/crates/dr-isa-stream-lab/tests/integration/shape.rs b/crates/dr-isa-stream-lab/tests/integration/shape.rs index 4a726dfe8..743b1d21e 100644 --- a/crates/dr-isa-stream-lab/tests/integration/shape.rs +++ b/crates/dr-isa-stream-lab/tests/integration/shape.rs @@ -66,11 +66,11 @@ struct Run { 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 (prep, _) = PreparedB::prepare(&obj, &B).unwrap(); let mut c = vec![0f32; obj.c_len()]; - let direct = direct(&obj, &lanes, &prep, B.rev, &mut c).map(|r| (c.clone(), r)); + let direct = direct(&obj, &lanes, &prep, &B, &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 r = staged(&obj, &lanes, &prep, &B, &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).unwrap(); @@ -216,7 +216,7 @@ fn without_the_over_read_refusal_a_neighbouring_nan_poisons_the_tile() { // 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 (prep, _) = PreparedB::prepare(&obj, &B).unwrap(); 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); @@ -422,11 +422,11 @@ fn prepared_b_is_reused_and_invalidated() { 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 (prep, rep) = PreparedB::prepare(&obj, &B).unwrap(); 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(); + let r = direct(&obj, &l, &prep, &B, &mut c).unwrap(); assert_eq!(c, want1); assert_eq!(r.tiles, (dim / 16) * (dim / 16)); } @@ -439,13 +439,22 @@ fn prepared_b_is_reused_and_invalidated() { ); assert_eq!(rep.bytes_written, dim * dim * 2); - assert_eq!(prep.admit(&obj, B.rev + 1), Err(ReuseRefusal::Operand)); + assert_eq!( + prep.admit( + &obj, + &BOperand { + rev: B.rev + 1, + ..B + } + ), + 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)); + assert_eq!(prep.admit(&obj2, &B), 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)); + assert_eq!(prep.admit(&narrow, &B), Err(ReuseRefusal::Columns)); // Load-bearing: obj2's A against obj1's B gives the wrong answer. let l2 = obj2.resolve(&world, &socket).unwrap(); @@ -468,7 +477,7 @@ fn prepared_b_is_reused_and_invalidated() { }); 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)); + assert_eq!(prep.admit(&rebound, &B), Err(ReuseRefusal::Frame)); } } @@ -568,7 +577,7 @@ fn lanes_from_another_object_are_refused_by_every_arm() { 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 (prep, _) = PreparedB::prepare(&obj, &B).unwrap(); let own = obj.resolve(&world256, &sa).unwrap(); assert!(obj.admit_lanes(&own).is_ok()); @@ -592,12 +601,12 @@ fn lanes_from_another_object_are_refused_by_every_arm() { ] { let mut c = vec![0f32; obj.c_len()]; assert_eq!( - direct(&obj, lanes, &prep, B.rev, &mut c).unwrap_err(), + direct(&obj, lanes, &prep, &B, &mut c).unwrap_err(), ShapeRefusal::ForeignLanes, "direct, {name}" ); assert_eq!( - staged(&obj, lanes, &prep, B.rev, &mut Vec::new(), &mut c).unwrap_err(), + staged(&obj, lanes, &prep, &B, &mut Vec::new(), &mut c).unwrap_err(), ShapeRefusal::ForeignLanes, "staged, {name}" ); @@ -627,12 +636,12 @@ fn a_selection_past_the_source_is_refused_by_every_arm() { 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 (prep, _) = PreparedB::prepare(&obj, &B).unwrap(); 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!(direct(&obj, &l, &prep, &B, &mut c).unwrap_err(), want); assert_eq!( - staged(&obj, &l, &prep, B.rev, &mut Vec::new(), &mut c).unwrap_err(), + staged(&obj, &l, &prep, &B, &mut Vec::new(), &mut c).unwrap_err(), want ); assert_eq!( @@ -686,9 +695,9 @@ fn resolve_keeps_the_view_row_order() { for (k, lane) in l.lanes().iter().enumerate() { assert_eq!(lane.row, usize::from(rev[k]), "row {k}"); } - let (prep, _) = PreparedB::prepare(&obj, &B); + let (prep, _) = PreparedB::prepare(&obj, &B).unwrap(); let mut c = vec![0f32; obj.c_len()]; - staged(&obj, &l, &prep, B.rev, &mut Vec::new(), &mut c).unwrap(); + staged(&obj, &l, &prep, &B, &mut Vec::new(), &mut c).unwrap(); let want: Vec = oracle( &sel, &rev, @@ -701,3 +710,85 @@ fn resolve_keeps_the_view_row_order() { .collect(); assert_eq!(c, want); } + +/// Prepared-B reuse rests on identity and equality, never on a digest: +/// another table with the same revision is another operand; a second object +/// over the same selection, frame and width may share it; one differing +/// mask bit is another selection. +#[test] +fn prepared_b_reuse_is_keyed_by_identity_not_a_digest() { + use dr_isa_stream_lab::shape::BTable; + 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); + let ids: Vec = (0..64).map(|k| k * 61 % 4096).collect(); + let sel = Selection::mask(SPACE_A, 4096, ids.iter().copied()); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel.clone()).unwrap(); + let t1 = BTable::new(&B, 4096, dim); + let t2 = BTable::new(&B, 4096, dim); // same values, same revision + let (prep, _) = PreparedB::prepare(&obj, &t1).unwrap(); + assert_eq!(prep.admit(&obj, &t1), Ok(())); + assert_eq!(prep.admit(&obj, &t2), Err(ReuseRefusal::Operand)); + assert_eq!(prep.admit(&obj, &B), Err(ReuseRefusal::Operand)); + + // A second object with an equal selection, frame and width may share it. + let twin = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + assert_eq!(prep.admit(&twin, &t1), Ok(())); + let l = twin.resolve(&world, &socket).unwrap(); + let mut c = vec![0f32; twin.c_len()]; + staged(&twin, &l, &prep, &t1, &mut Vec::new(), &mut c).unwrap(); + assert_eq!(c, want(&fx, twin.selection(), dim)); + + // One bit different: refused, by full comparison. + let mut ids2 = ids.clone(); + ids2[10] += 1; + let other = VirtualObject::bind( + &world, + &socket, + &fields(dim), + dim, + Selection::mask(SPACE_A, 4096, ids2), + ) + .unwrap(); + assert_eq!(prep.admit(&other, &t1), Err(ReuseRefusal::Selection)); +} + +/// A B table smaller than the object is refused by every arm that reads it, +/// never read past its width into the next row. A table of the right shape +/// passes, so the check discriminates. +#[test] +fn a_b_table_narrower_or_shorter_than_the_object_is_refused() { + use dr_isa_stream_lab::shape::BTable; + 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); + let sel = Selection::mask(SPACE_A, 4096, (0..64).map(|k| k * 61 % 4096)); + let obj = VirtualObject::bind(&world, &socket, &fields(dim), dim, sel).unwrap(); + let l = obj.resolve(&world, &socket).unwrap(); + let last = obj.selection().last().unwrap(); + assert!(last > 100, "fixture must reach past the short table"); + + let narrow = BTable::new(&B, 4096, 16); + let short = BTable::new(&B, 100, dim); + for t in [&narrow, &short] { + assert!(matches!( + PreparedB::prepare(&obj, t), + Err(ShapeRefusal::OperandShape { .. }) + )); + let mut c = vec![0f32; obj.c_len()]; + assert!(matches!( + cblas(&obj, &l, t, &mut Vec::new(), &mut Vec::new(), &mut c), + Err(ShapeRefusal::OperandShape { .. }) + )); + } + + let fits = BTable::new(&B, 4096, dim); + let (prep, _) = PreparedB::prepare(&obj, &fits).unwrap(); + let mut c = vec![0f32; obj.c_len()]; + staged(&obj, &l, &prep, &fits, &mut Vec::new(), &mut c).unwrap(); + assert_eq!(c, want(&fx, obj.selection(), dim)); +}