---------------------------- MODULE SparseTopk ----------------------------
\* Lifecycle of BlockKind::Full WHT-2bit page sketches, sub-block valid_len
\* contiguity across passthrough/mixed-batch steps, layout disjointness, and
\* dynamic Top-K sparse decode selection (src/blocks.rs, src/engine.rs, src/kernels.metal).
\*
\* Recent-window slot semantics (matching `SPARSE_RECENT_BLOCKS = 16` in `src/engine.rs`):
\* - Pinning `Recent` block slots `(nblks - Recent)..(nblks - 1)` covers `(Recent - 1)`
\* sealed 64-token blocks plus `1..=64` positions in the active tail block
\* (`961..=1,024` trailing tokens in production when `Recent = 16`).
\*
\* Sub-block contiguity invariant (`advance_contiguous_sketch_valid_len` in `src/blocks.rs`):
\* - Each block is modeled as 3 sub-blocks `SubBlocks == {1, 2, 3}` (prefix, mid-block, tail).
\* - `builtMask[s] \subseteq SubBlocks` records which sub-blocks have current WHT-2bit sketches.
\* - `validSub[s] \in 0..3` is the contiguous prefix `1..validSub[s]` known valid.
\* - When a passthrough lane writes a needle in sub-block 2 without sketching (`builtMask = {1}`,
\* `validSub = 1`) and then steps sub-block 3 in a mixed batch alongside a sparse lane
\* (`MixedBatchStepSub3`), `k_update_full_sketch_dec` builds sub-block 3 (`builtMask = {1, 3}`),
\* and `validSub` MUST remain `1` (never jump to `3` over unbuilt sub-block 2!) so `validSub < 3`
\* triggers full-slot catch-up (`k_build_full_sketch_slots`) once the lane becomes sparse.
\*
\* `Bug` selects reversed negative witnesses:
\* "nopassthrough" runs sparse selection at `nblks = BudgetBlocks`: PassthroughExact fails.
\* "stalesketch" reusing a freed slot forgets to clear its old sketch: SketchesFreshBeforeScore fails.
\* "spilldirty" GPU SSD restore marks `validSub = 0`, but decode omits catch-up: SketchesFreshBeforeScore fails.
\* "mixedjump" mixed-batch sub-block 3 update jumps `validSub` `1 -> 3` over unbuilt sub-block 2,
\* skipping catch-up when the lane later goes sparse: SketchesFreshBeforeScore fails.
\* "badrank" inverts Top-K score / tie-break order: TopKOptimal fails.
\* "badlayout" omits `* 8` (`NKV`) in `pool_index * FULL_SKETCH_BYTES`: SketchLayoutDisjoint fails.
\* "dropanchor" omits pinned prefix anchor blocks: AnchorsAndRecentPinned fails.
\* "droprecent" omits pinned recent window blocks: AnchorsAndRecentPinned fails.
\* "unsorted" emits `Anchor \o Recent \o TopK` without ascending compaction: SelectedSortedUnique fails.
\* "chunkdrop" wide chunked tournament forgets to carry forward prior-chunk Top-K winners: TopKOptimal fails.
EXTENDS Integers, FiniteSets, Sequences, TLC
CONSTANTS Capacity, MaxGen, Anchors, Recent, TopK, MaxBlocks, Bug
ASSUME /\ Capacity \in Nat \ {0}
/\ MaxGen \in Nat \ {0}
/\ Anchors \in Nat
/\ Recent \in Nat \ {0}
/\ TopK \in Nat \ {0}
/\ MaxBlocks > Anchors + Recent + TopK
/\ MaxBlocks <= Capacity
/\ Bug \in {"none", "nopassthrough", "stalesketch", "spilldirty",
"mixedjump", "badrank", "badlayout",
"dropanchor", "droprecent", "unsorted", "chunkdrop"}
Slots == 1..Capacity
Blocks == 0..(MaxBlocks - 1)
Scores == 1..2
SubBlocks == {1, 2, 3}
BudgetBlocks == Anchors + Recent + TopK
FullSketchBytes == 17408
HeadSketchBytes == 272
VARIABLES gen, refs, skBase, kvVer, trueScore, skVer, skScore, validSub, builtMask,
nblks, bt, btGen, mode, selected
vars == <<gen, refs, skBase, kvVer, trueScore, skVer, skScore, validSub, builtMask,
nblks, bt, btGen, mode, selected>>
SlotBaseAddr(s) ==
IF Bug = "badlayout"
THEN ((s - 1) * 8) * HeadSketchBytes
ELSE ((s - 1) * 8 * 8) * HeadSketchBytes
SortAsc(S) ==
[i \in 1..Cardinality(S) |->
CHOOSE x \in S : Cardinality({y \in S : y < x}) = i - 1]
SeqSet(seq) == {seq[i] : i \in 1..Len(seq)}
CandidateOutranks(scoreFn, b1, b2) ==
IF Bug = "badrank"
THEN \/ scoreFn[b1] < scoreFn[b2]
\/ (scoreFn[b1] = scoreFn[b2] /\ b1 > b2)
ELSE \/ scoreFn[b1] > scoreFn[b2]
\/ (scoreFn[b1] = scoreFn[b2] /\ b1 < b2)
TopKFar(F, scoreFn) ==
{b \in F : Cardinality({x \in F \ {b} : CandidateOutranks(scoreFn, x, b)}) < TopK}
\* Chunked SRAM tournament fold mirroring `k_score_full_sketch_dec_wide`:
\* processes `F` in ascending block order, merging each chunk into the carried-forward
\* running Top-K candidate set (unless `Bug = "chunkdrop"` drops prior-chunk winners).
ChunkedTopKFar(F, scoreFn) ==
IF F = {}
THEN {}
ELSE LET farSeq == SortAsc(F)
n == Len(farSeq)
fold[i \in 0..n] ==
IF i = 0
THEN {}
ELSE LET cand == IF Bug = "chunkdrop"
THEN {farSeq[i]}
ELSE fold[i - 1] \cup {farSeq[i]}
IN TopKFar(cand, scoreFn)
IN fold[n]
TypeOK ==
/\ gen \in [Slots -> 0..MaxGen]
/\ refs \in [Slots -> 0..1]
/\ skBase \in [Slots -> 0..(Capacity * FullSketchBytes)]
/\ kvVer \in [Slots -> 0..MaxGen]
/\ trueScore \in [Slots -> {0} \cup Scores]
/\ skVer \in [Slots -> 0..MaxGen]
/\ skScore \in [Slots -> {0} \cup Scores]
/\ validSub \in [Slots -> 0..3]
/\ builtMask \in [Slots -> SUBSET SubBlocks]
/\ nblks \in 0..MaxBlocks
/\ bt \in [Blocks -> {0} \cup Slots]
/\ btGen \in [Blocks -> 0..MaxGen]
/\ mode \in {"idle", "passthrough", "sparse"}
/\ selected \in Seq(Blocks)
Init ==
/\ gen = [s \in Slots |-> 0]
/\ refs = [s \in Slots |-> 0]
/\ skBase = [s \in Slots |-> 0]
/\ kvVer = [s \in Slots |-> 0]
/\ trueScore = [s \in Slots |-> 0]
/\ skVer = [s \in Slots |-> 0]
/\ skScore = [s \in Slots |-> 0]
/\ validSub = [s \in Slots |-> 0]
/\ builtMask = [s \in Slots |-> {}]
/\ nblks = 0
/\ bt = [b \in Blocks |-> 0]
/\ btGen = [b \in Blocks |-> 0]
/\ mode = "idle"
/\ selected = <<>>
\* Lowest free slot whose generation can advance (`BlockPool::lowest_free` / `take_free` in `src/blocks.rs`).
IsLowestFree(s) ==
/\ s \in Slots /\ refs[s] = 0 /\ gen[s] < MaxGen
/\ \A y \in Slots : (y < s) => ~(refs[y] = 0 /\ gen[y] < MaxGen)
\* Allocate lowest free Full slot `s`, bump its generation, write all 3 sub-blocks (`score = sc`),
\* and build its full WHT-2bit sketch (unless `Bug = "stalesketch"` forgets to clear a reused slot's old sketch).
AppendBlock(s, sc) ==
/\ nblks < MaxBlocks
/\ IsLowestFree(s)
/\ sc \in Scores
/\ LET g1 == gen[s] + 1
keepStale == (Bug = "stalesketch" /\ gen[s] > 0 /\ skVer[s] > 0)
IN /\ gen' = [gen EXCEPT ![s] = g1]
/\ refs' = [refs EXCEPT ![s] = 1]
/\ skBase' = [skBase EXCEPT ![s] = SlotBaseAddr(s)]
/\ kvVer' = [kvVer EXCEPT ![s] = g1]
/\ trueScore' = [trueScore EXCEPT ![s] = sc]
/\ skVer' = [skVer EXCEPT ![s] = IF keepStale THEN @ ELSE g1]
/\ skScore' = [skScore EXCEPT ![s] = IF keepStale THEN @ ELSE sc]
/\ validSub' = [validSub EXCEPT ![s] = 3]
/\ builtMask' = [builtMask EXCEPT ![s] = SubBlocks]
/\ bt' = [bt EXCEPT ![nblks] = s]
/\ btGen' = [btGen EXCEPT ![nblks] = g1]
/\ nblks' = nblks + 1
/\ mode' = "idle"
/\ selected' = <<>>
\* Short-context passthrough lane writes sub-block 1 with sketch (`validSub = 1, builtMask = {1}`),
\* then advances passthrough across sub-block 2 (containing `sc`, e.g. needle `sc = 2`) without sketching.
AppendLazyPassthroughBlock(s, sc) ==
/\ nblks < BudgetBlocks
/\ IsLowestFree(s)
/\ sc \in Scores
/\ LET g1 == gen[s] + 1
IN /\ gen' = [gen EXCEPT ![s] = g1]
/\ refs' = [refs EXCEPT ![s] = 1]
/\ skBase' = [skBase EXCEPT ![s] = SlotBaseAddr(s)]
/\ kvVer' = [kvVer EXCEPT ![s] = g1]
/\ trueScore' = [trueScore EXCEPT ![s] = sc]
/\ skVer' = [skVer EXCEPT ![s] = 0]
/\ skScore' = [skScore EXCEPT ![s] = 1]
/\ validSub' = [validSub EXCEPT ![s] = 1]
/\ builtMask' = [builtMask EXCEPT ![s] = {1}]
/\ bt' = [bt EXCEPT ![nblks] = s]
/\ btGen' = [btGen EXCEPT ![nblks] = g1]
/\ nblks' = nblks + 1
/\ mode' = "idle"
/\ selected' = <<>>
\* Passthrough lane steps sub-block 3 in a mixed batch alongside a sparse lane:
\* `k_update_full_sketch_dec` builds sub-block 3 (`builtMask \cup {3}`), and `advance_contiguous_sketch_valid_len`
\* advances `validSub` to 3 ONLY if `validSub >= 2` (unless `Bug = "mixedjump"` jumps `1 -> 3`!).
MixedBatchStepSub3(b) ==
/\ nblks > 0 /\ nblks <= BudgetBlocks
/\ b \in 0..(nblks - 1)
/\ LET s == bt[b]
IN /\ s \in Slots
/\ validSub[s] < 3
/\ 3 \notin builtMask[s]
/\ builtMask' = [builtMask EXCEPT ![s] = @ \cup {3}]
/\ validSub' = [validSub EXCEPT ![s] =
IF Bug = "mixedjump"
THEN 3
ELSE IF validSub[s] >= 2 THEN 3 ELSE validSub[s]]
/\ mode' = "idle"
/\ selected' = <<>>
/\ UNCHANGED <<gen, refs, skBase, kvVer, trueScore, skVer, skScore, nblks, bt, btGen>>
\* GPU SSD restore: evict mapped block `b` and restore its KV bytes into `s` (`s = old` or lowest free),
\* marking `validSub = 0` dirty so `k_build_full_sketch_slots` rebuilds all sub-blocks before the next sparse score.
SpillRestoreBlock(b, s) ==
/\ b \in 0..(nblks - 1)
/\ LET old == bt[b]
IN /\ old \in Slots
/\ s \in Slots /\ (s = old \/ IsLowestFree(s)) /\ gen[s] < MaxGen
/\ LET g1 == gen[s] + 1
sc == trueScore[old]
IN /\ gen' = [gen EXCEPT ![s] = g1]
/\ refs' = [x \in Slots |-> IF x = s THEN 1 ELSE IF x = old THEN 0 ELSE refs[x]]
/\ skBase' = [skBase EXCEPT ![s] = SlotBaseAddr(s)]
/\ kvVer' = [kvVer EXCEPT ![s] = g1]
/\ trueScore' = [trueScore EXCEPT ![s] = sc]
/\ skVer' = [skVer EXCEPT ![s] = 0]
/\ skScore' = [skScore EXCEPT ![s] = 0]
/\ validSub' = [validSub EXCEPT ![s] = 0]
/\ builtMask' = [builtMask EXCEPT ![s] = {}]
/\ bt' = [bt EXCEPT ![b] = s]
/\ btGen' = [btGen EXCEPT ![b] = g1]
/\ UNCHANGED nblks
/\ mode' = "idle"
/\ selected' = <<>>
\* Host SSD restore (`BlockPool::on_slot_restored_from_spill` on host storage): restores KV bytes into `s`
\* (`s = old` or lowest free) and immediately recomputes all sub-blocks on CPU (`validSub = 3, builtMask = SubBlocks`).
HostSpillRestoreBlock(b, s) ==
/\ b \in 0..(nblks - 1)
/\ LET old == bt[b]
IN /\ old \in Slots
/\ s \in Slots /\ (s = old \/ IsLowestFree(s)) /\ gen[s] < MaxGen
/\ LET g1 == gen[s] + 1
sc == trueScore[old]
IN /\ gen' = [gen EXCEPT ![s] = g1]
/\ refs' = [x \in Slots |-> IF x = s THEN 1 ELSE IF x = old THEN 0 ELSE refs[x]]
/\ skBase' = [skBase EXCEPT ![s] = SlotBaseAddr(s)]
/\ kvVer' = [kvVer EXCEPT ![s] = g1]
/\ trueScore' = [trueScore EXCEPT ![s] = sc]
/\ skVer' = [skVer EXCEPT ![s] = g1]
/\ skScore' = [skScore EXCEPT ![s] = sc]
/\ validSub' = [validSub EXCEPT ![s] = 3]
/\ builtMask' = [builtMask EXCEPT ![s] = SubBlocks]
/\ bt' = [bt EXCEPT ![b] = s]
/\ btGen' = [btGen EXCEPT ![b] = g1]
/\ UNCHANGED nblks
/\ mode' = "idle"
/\ selected' = <<>>
\* End/reset the lane, releasing all mapped Full slots back to the pool for reuse.
ResetLane ==
/\ nblks > 0
/\ refs' = [s \in Slots |-> 0]
/\ nblks' = 0
/\ bt' = [b \in Blocks |-> 0]
/\ btGen' = [b \in Blocks |-> 0]
/\ mode' = "idle"
/\ selected' = <<>>
/\ UNCHANGED <<gen, skBase, kvVer, trueScore, skVer, skScore, validSub, builtMask>>
\* Execute one full-attention decode step over `0..(nblks - 1)`.
DecodeStep ==
/\ nblks > 0
/\ LET forceSparse == (Bug = "nopassthrough" /\ nblks = BudgetBlocks /\ nblks > Anchors + Recent)
usePassthrough == (nblks <= BudgetBlocks /\ ~forceSparse)
IN IF usePassthrough
THEN /\ mode' = "passthrough"
/\ selected' = [i \in 1..nblks |-> i - 1]
/\ UNCHANGED <<gen, refs, skBase, kvVer, trueScore, skVer, skScore, validSub, builtMask, nblks, bt, btGen>>
ELSE LET mappedSlots == {bt[b] : b \in 0..(nblks - 1)}
catchUp(s) == (Bug # "spilldirty") /\ (s \in mappedSlots) /\ (validSub[s] < 3)
validSub1 == [s \in Slots |-> IF catchUp(s) THEN 3 ELSE validSub[s]]
builtMask1 == [s \in Slots |-> IF catchUp(s) THEN SubBlocks ELSE builtMask[s]]
skVer1 == [s \in Slots |-> IF catchUp(s) THEN kvVer[s] ELSE skVer[s]]
skScore1 == [s \in Slots |-> IF catchUp(s) THEN trueScore[s] ELSE skScore[s]]
blkScore == [b \in 0..(nblks - 1) |-> skScore1[bt[b]]]
anchorSet == IF Bug = "dropanchor" THEN {} ELSE 0..(Anchors - 1)
recentSet == IF Bug = "droprecent" THEN {} ELSE (nblks - Recent)..(nblks - 1)
farSet == Anchors..(nblks - Recent - 1)
topkSet == ChunkedTopKFar(farSet, blkScore)
selUnion == anchorSet \cup topkSet \cup recentSet
selSeq == IF Bug = "unsorted"
THEN SortAsc(anchorSet) \o SortAsc(recentSet) \o SortAsc(topkSet)
ELSE SortAsc(selUnion)
IN /\ validSub' = validSub1
/\ builtMask' = builtMask1
/\ skVer' = skVer1
/\ skScore' = skScore1
/\ mode' = "sparse"
/\ selected' = selSeq
/\ UNCHANGED <<gen, refs, skBase, kvVer, trueScore, nblks, bt, btGen>>
Next ==
\/ \E s \in Slots, sc \in Scores : AppendBlock(s, sc)
\/ \E s \in Slots, sc \in Scores : AppendLazyPassthroughBlock(s, sc)
\/ \E b \in Blocks : MixedBatchStepSub3(b)
\/ \E b \in Blocks, s \in Slots : SpillRestoreBlock(b, s)
\/ \E b \in Blocks, s \in Slots : HostSpillRestoreBlock(b, s)
\/ ResetLane
\/ DecodeStep
Spec == Init /\ [][Next]_vars
\* 1. Every live slot `s` (`refs[s] > 0`) has exact base `(s - 1) * FULL_SKETCH_BYTES` (`pool_index * 17,408`)
\* and pairwise non-overlapping `17,408`-byte sketch storage across all live slots.
SketchLayoutDisjoint ==
/\ \A s \in Slots :
(refs[s] > 0) => (skBase[s] = (s - 1) * FullSketchBytes)
/\ \A s1, s2 \in Slots :
(s1 # s2 /\ refs[s1] > 0 /\ refs[s2] > 0) =>
(skBase[s1] + FullSketchBytes <= skBase[s2] \/ skBase[s2] + FullSketchBytes <= skBase[s1])
\* 2. Short-context passthrough runs iff `nblks <= BudgetBlocks`, attending exact `0..(nblks - 1)`.
PassthroughExact ==
/\ (mode = "passthrough") =>
/\ nblks <= BudgetBlocks
/\ selected = [i \in 1..nblks |-> i - 1]
/\ (mode = "sparse") => nblks > BudgetBlocks
\* 3. Every block scored or attended in sparse mode has all 3 sub-blocks built and current with KV.
SketchesFreshBeforeScore ==
(mode = "sparse") =>
\A b \in 0..(nblks - 1) :
LET s == bt[b]
IN /\ s \in Slots
/\ btGen[b] = gen[s]
/\ kvVer[s] = gen[s]
/\ validSub[s] = 3
/\ builtMask[s] = SubBlocks
/\ skVer[s] = kvVer[s]
/\ skScore[s] = trueScore[s]
\* 4. Every anchor block `0..(Anchors - 1)` and recent block `(nblks - Recent)..(nblks - 1)` is retained.
AnchorsAndRecentPinned ==
(mode = "sparse") =>
/\ (0..(Anchors - 1)) \subseteq SeqSet(selected)
/\ ((nblks - Recent)..(nblks - 1)) \subseteq SeqSet(selected)
\* 5. Selected block indices are strictly ascending (unique + deterministic split-K order) and exact-sized.
SelectedSortedUnique ==
/\ (mode # "idle") =>
\A i \in 1..(Len(selected) - 1) : selected[i] < selected[i + 1]
/\ (mode = "sparse") => Len(selected) = BudgetBlocks
\* 6. Non-circular optimality check directly against ground-truth `trueScore[bt[...]]`:
\* every selected far block has `trueScore >` (or `=` with smaller block index `<`) every unselected far block.
TopKOptimal ==
(mode = "sparse") =>
LET farSet == Anchors..(nblks - Recent - 1)
chosenFar == SeqSet(selected) \cap farSet
droppedFar == farSet \ chosenFar
IN /\ Cardinality(chosenFar) = TopK
/\ \A bc \in chosenFar, bd \in droppedFar :
\/ trueScore[bt[bc]] > trueScore[bt[bd]]
\/ (trueScore[bt[bc]] = trueScore[bt[bd]] /\ bc < bd)
=============================================================================