Mixed-radix indices at symbolic sizes
Lean: GPUProof/MixedRadix.lean. Tests: MojoProofTest/GPUProof/MixedRadix.lean.
Scope. MixedRadix.lt_prod, MixedRadix.eq_iff_digits, MixedRadix.val_append and
MixedRadix.fits hold for every size assignment (every two, for eq_iff_digits), radix list and
width; WordFit.of_lt for every width and number. The tests
prove gemv's write index and the naive matmul's offset facts for every size and thread, and check
the theorems by evaluation at two launches and two matrices of unrelated sizes. Nothing here is
about one kernel's program: the gemv and matmul statements are about the index expressions, not
about the IR that computes them.
Definitions
Sizes, a size assignment:Nat → Nat, the value of each numbered size variable. A variable may stand for a size, a launch register, the member count of a level instance or a bound index.SizeExpr, a symbolic size: a variablevar v, a productmul a bor a quotientdiv a b(rounded down,0when the divisor is0);SizeExpr.eval σis its value atσ.MixedRadix: a list of digits with their radices, bothSizeExprs, the least significant first. Atσ:val: Horner's rule,d₀ + r₀ (d₁ + r₁ (d₂ + …))for the digitsdᵢwith radicesrᵢ;digitVals: the digits' values;radixProd: the product of the radices' values;InRange: every digit's value is below its radix's (decidable).
WordFit w k, what a width ofwbits keeps of the indexk, four fields over Lean'sBitVec:toNat: thew-bit word ofkhas the unsigned valuek(truncation towbits keeps it);toInt: it has the signed valuek;signExtend: its sign extension to every widthvis thev-bit word ofk;add: for everya + b = k, the add of thew-bit words ofaandboverflows neither unsigned (BitVec.uaddOverflow) nor signed (BitVec.saddOverflow), so an LLVMaddwithnuwornswis not poison, and gives the word ofk.
No definition fixes a machine constant: there is no warp width, word width or grid size in the module.
Statements
MixedRadix.lt_prod (hx : x.InRange σ) : x.val σ < x.radixProd σ.MixedRadix.eq_iff_digits (hx : x.InRange σ) (hy : y.InRange τ) (hr : x.digits.map (fun p => p.2.eval σ) = y.digits.map (fun p => p.2.eval τ)) : x.val σ = y.val τ ↔ x.digitVals σ = y.digitVals τ, at two size assignments: the radices ofxatσhave the values of the radices ofyatτ. At one assignment with the same radix list,hrisrfl.MixedRadix.val_append (a b) (σ) : val ⟨a ++ b⟩ σ = val ⟨a⟩ σ + radixProd ⟨a⟩ σ * val ⟨b⟩ σ, Horner's rule split at a digit.MixedRadix.fits (hx : x.InRange σ) (h : x.radixProd σ < 2 ^ (w - 1)) : WordFit w (x.val σ).WordFit.of_lt (h : k < 2 ^ (w - 1)) : WordFit w k, andWordFit.two_mul_lt_iff : 2 * k < 2 ^ w ↔ k < 2 ^ (w - 1), which turns the premise2 k < 2 ^ wof the MojoProof index lemmas intoof_lt's.
Proof
lt_prod: induction on the digits;d + r v < r + r v = r (v + 1) ≤ r · Pfromd < rand the tail'sv < P.eq_iff_digits: induction on the digits ofx, withy's in step (radix values that agree give the same length). The step isMixedRadix.add_mul_eq_iff:a + r v = b + r v' ↔ a = b ∧ v = v'fora, b < r, by the remainder and the quotient byr, with the radixratσequal to the one atτbyhr's head.val_append: induction ona; the step isd + r (v_a + P_a v_b) = (d + r v_a) + (r P_a) v_b.of_lt: from2 k < 2 ^ w(two_mul_lt_iff) the word's sign bit is clear, so its signed value is its unsigned one,k, and its sign extension is its zero extension. Fora + b = kboth parts are below2 ^ (w - 1), so neither sum overflows, as natural numbers or as integers, andBitVec.ofNat_add_ofNatgives the word ofk.fits:of_ltafterlt_prod.
What exists elsewhere
- Mathlib has the value of digits in one base (
Nat.ofDigits), its bound (Nat.ofDigits_lt_base_pow_length), its injectivity at a fixed length (Nat.ofDigits_inj_of_len_eq), and the two-digit mixed radix with constant sizes (finProdFinEquiv,Fin.divNat,Fin.modNat). None has radices that vary by digit, soeq_iff_digitsandlt_prodare written here; their one-base cases are Mathlib's. - FloatLib has digits in base
2 ^ w(FloatLib.Numerics.Packed.ofDigits_lt, the lanes of a packed row), again one base. TorchLean names no theorem on row-major or strided index bounds or injectivity. - The layout algebra's colexicographic digits (
MojoProof.Layout.colex, withMojoProof.Layout.colex_length,colex_appendandcolex_modin MojoProof/Layout/Crd.lean) go the other way, from a value to its digits; its offset lemmas recover the digits of a strided offset (MojoProof.Layout.digits_of_nested) or bound it by the cosize (MojoProof.Layout.sum_colex_le), at extents that are numbers. None islt_prodoreq_iff_digits, so nothing there becomes a corollary. - MojoProof/Sem/Index.lean is the use (it imports this module; the core cannot import it). Its
word lemmas at
2 k < 2 ^ ware corollaries ofWordFit.of_ltthroughtwo_mul_lt_iff: the signed value of the word (BitVec.toInt_ofNat_of_lt) is the fieldtoInt, sign extension (intCast_sext_ofNat) the fieldsignExtend, the two overflow tests of the flagged add (intBin_add_ofNat) the fieldadd, and the signed range (outS_of_lt) isk < 2 ^ (w - 1).coord_onto's bound islt_prodat the three digits of a point of a box.truncandzextof a word ofk < 2 ^ w(intCast_ofNat) stay there:WordFitholds below2 ^ (w - 1)only.
Where the Lean form departs from the design
SizeExprhas a quotient. The design's sizes are variables and products; gemv's warp count per block isntid / W, so a radix needsdiv.fitshas the premisex.InRange σ. The design's has onlyx.radixProd σ < 2 ^ (w - 1), which does not bound the value of an index whose digits are out of range:mutant_rangein the tests is an index out of range whose radix product is below2 ^ 7and whose value does not fit 8 bits, so the design's statement is false without the premise.WordFitis a structure overBitVecwith the four fields above, the design's "sign extension, truncation and non-wrapping adds", where truncation is the unsigned value and a non-wrapping add is the absence of both overflows.- The size variables are numbered (
Sizes := Nat → Nat) rather than named.
Tests (MojoProofTest/GPUProof/MixedRadix.lean)
For every size and thread:
gemv_val: gemv's write index(ctaid * ntid + tid) / Wis the value ofwarpIdx, the warptid / Wwith radixntid / Wand the blockctaidwith radix the grid size, whenWdividesntid(every size assignment).gemv_warp: two threads of the launch write the same index exactly when they are in the same warp of the same block, byeq_iff_digitsat one assignment (hrisrfl).warp_two: the same statement for one key,warpIdx 0 1, at the two threads' assignments, byeq_iff_digitsat two assignments. The assignments differ in the variables0and1(the thread), which the radicesntid / Wand the grid size do not read, sohrisrfl.warp_split:warpIdx 0 1split after its warp digit, byval_append(every size assignment);warp_split_37evaluates it at thread37of block1withntid = 128,W = 32:1 + 4 · 1 = 5 = (1 · 128 + 37) / 32.gemv_lt: the index is below(ntid / W) * grid, the number of rows written, bylt_prod.gemv_fits: it fitswbits when(ntid / W) * grid < 2 ^ (w - 1), byfits;fits_32is an instance at a launch of two blocks of 128 threads.matmul_eq:row * n + k = row' * n + k' ↔ row = row' ∧ k = k'fork, k' < nat symbolicn, byeq_iff_digitswith the radixrow + row' + 1above both rows; theexampleafter it checks thatomegaalone fails on the same goal.
By evaluation (#guard), over every pair of threads of the launches ntid = 96, W = 32 with three
blocks and ntid = 15, W = 5 with seven blocks (launchOk), and over every pair of entries of
3 × 4 and 5 × 7 matrices (matrixOk): InRange, lt_prod, eq_iff_digits, gemv_val,
gemv_warp and matmul_eq, and radixProd as the size (ntid / W) * grid (SizeExpr.mul).
The mutants, decided, one per rule:
mutant_out: threadtid = ntidof block0writes the index of block1's first warp while the digits differ; its digittid / Wis out of range, soeq_iff_digitsfails.mutant_lt: the same thread of the last block writes the radix product, not below it.mutant_dvd: withWnot dividingntid, the write index is notwarpIdx's value.mutant_radices: two indices in range with other radices are equal with other digits.mutant_assign:hrcannot be dropped at two assignments:warpIdx 0 1atntid = 96and atntid = 128(W = 32) is in range at both with the value3, the warp radices3and4differ, and the digits (0, 1and3, 0) differ.mutant_fits:2 ^ (w - 1)does not fitwbits (¬ WordFit 8 128: the signed value of the word is-128).mutant_range: the premiseInRangeoffitscannot be dropped: the digit200with radix1has the radix product1 < 2 ^ 7and the value200, which does not fit 8 bits (the signed value of its word is-56).
Footprints at symbolic sizes: the statements of View.tiling and View.coarsen_tile
Status. Statements and plan only: no module defines them yet. The Lean below elaborates
against this tree's GPUProof.Sig, GPUProof.MixedRadix and the layout algebra of
MojoProof/Layout/ (checked with the proofs left open, outside the repository); the proofs are
the plan after it. It goes in a new core module, GPUProof/View.lean, after the layout algebra's
move into the core (below), and imports Mathlib's Set.iUnion and Pairwise beside it. The
code opens GPUProof.Layout and GPUProof.Layout.Tup (the moved namespaces) and takes
variable {S : Sig}.
Definitions
/-- The instances of level `ℓ` in launch `L`: those that a thread of `L` lies in. -/
def Sig.Inst (S : Sig) (L : S.Launch) (ℓ : S.Level) (g : S.Gid) : Prop :=
∃ t ∈ S.threads L, S.group L ℓ t = g
/-- The sets `T i` tile `D`: each lies in `D`, and two of different indices are disjoint. -/
def Tiling {ι α : Type} (T : ι → Set α) (D : Set α) : Prop :=
(∀ i, T i ⊆ D) ∧ Pairwise fun i j => Disjoint (T i) (T j)
/-- A footprint at symbolic sizes: at each size assignment `σ`, instance `g` of `level` in
launch `L` covers the bytes of buffer `buf` at the offsets `key · cosize + lay(c)`, for the
coordinates `c` below the layout's size, where `key` is valued at `bind L g σ`, the assignment
`σ` with the variables of the key's digits set to `g`'s coordinates. -/
structure View (S : Sig) where
lay : Sizes → Lay
level : S.Level
buf : S.Buf
key : MixedRadix
bind : S.Launch → S.Gid → Sizes → Sizes
namespace View
/-- The offset of coordinate `c` of instance `g`. -/
def off (v : View S) (σ : Sizes) (L : S.Launch) (g : S.Gid) (c : Nat) : Nat :=
v.key.val (v.bind L g σ) * (v.lay σ).cosize + (v.lay σ).call (leaf c false)
/-- The bytes of instance `g`. -/
def tile (v : View S) (σ : Sizes) (L : S.Launch) (g : S.Gid) : Set S.Loc :=
{x | ∃ c < (v.lay σ).size, x = S.place v.buf (v.off σ L g c)}
/-- The bytes the view may cover: the first `radixProd · cosize` offsets of its buffer. -/
def bytes (v : View S) (σ : Sizes) : Set S.Loc :=
{x | ∃ i : Nat, i < v.key.radixProd σ * (v.lay σ).cosize ∧ x = S.place v.buf i}
/-- The tiles of the instances of the view's level in `L`. -/
def tiles (v : View S) (σ : Sizes) (L : S.Launch) : {g // S.Inst L v.level g} → Set S.Loc :=
fun g => v.tile σ L g.1
/-- A well-formed view, at every size assignment: its layout is congruent with positive
extents (so `Lay.call_lt_cosize` bounds its offsets), and at every instance of its level the
key is in range, its radices do not read the bound digits, and the digits tell the instances
apart. -/
structure WF (v : View S) : Prop where
congruent : ∀ σ, congruentL (v.lay σ).shape (v.lay σ).stride = true
pos : ∀ σ, ∀ s ∈ leavesL (v.lay σ).shape, 0 < s
range : ∀ σ L g, S.Inst L v.level g → v.key.InRange (v.bind L g σ)
radices : ∀ σ L g, S.Inst L v.level g →
v.key.digits.map (fun p => p.2.eval (v.bind L g σ)) = v.key.digits.map (fun p => p.2.eval σ)
key_inj : ∀ σ L g g', S.Inst L v.level g → S.Inst L v.level g' →
v.key.digitVals (v.bind L g σ) = v.key.digitVals (v.bind L g' σ) → g = g'
/-- The key's `n` least significant digits, and the others. -/
def inner (v : View S) (n : Nat) : MixedRadix := ⟨v.key.digits.take n⟩
def outer (v : View S) (n : Nat) : MixedRadix := ⟨v.key.digits.drop n⟩
/-- Instance `j` of the view's level lies in instance `i` of `ℓ`: a thread of `L` is in both. -/
def Inside (v : View S) (L : S.Launch) (ℓ : S.Level) (i j : S.Gid) : Prop :=
∃ t ∈ S.threads L, S.group L v.level t = j ∧ S.group L ℓ t = i
/-- The view at level `ℓ`: the key's `n` least significant digits become one more layout mode,
of extent their radix product and stride the cosize; `bind'` binds the other digits at an
instance of `ℓ`. -/
def coarsen (v : View S) (ℓ : S.Level) (n : Nat) (bind' : S.Launch → S.Gid → Sizes → Sizes) :
View S where
lay σ := ⟨(v.lay σ).shape ++ [leaf ((v.inner n).radixProd σ) false],
(v.lay σ).stride ++ [leaf (v.lay σ).cosize false]⟩
level := ℓ
buf := v.buf
key := v.outer n
bind := bind'
Statements
/-- For every machine whose placement is injective, well-formed view, size assignment and
launch, the tiles of the instances of the view's level are in bounds and pairwise disjoint. -/
theorem View.tiling (v : View S) (hp : PlaceInj S.place) (hv : v.WF) (σ : Sizes)
(L : S.Launch) : Tiling (v.tiles σ L) (v.bytes σ)
/-- For every machine, well-formed view, level `ℓ`, digit count `n`, binding, size assignment,
launch and instance `i` of `ℓ`: when the instances inside `i` agree on the outer digits and
realize every inner key value, the coarsened view's tile of `i` is the union of their tiles. -/
theorem View.coarsen_tile (v : View S) (hv : v.WF) {ℓ : S.Level} (n : Nat)
(bind' : S.Launch → S.Gid → Sizes → Sizes) {σ : Sizes} {L : S.Launch} {i : S.Gid}
(hn : ∀ j, v.Inside L ℓ i j → (v.outer n).val (v.bind L j σ) = (v.outer n).val (bind' L i σ))
(ho : ∀ k < (v.inner n).radixProd σ,
∃ j, v.Inside L ℓ i j ∧ (v.inner n).val (v.bind L j σ) = k) :
(v.coarsen ℓ n bind').tile σ L i = ⋃ j ∈ {j | v.Inside L ℓ i j}, v.tile σ L j
Two changes to this module that they need are made (Status. Proved, with the tests
warp_two, mutant_assign, warp_split and warp_split_37 above):
MixedRadix.eq_iff_digitsis restated at two assignments,(hx : x.InRange σ) (hy : y.InRange τ) (hr : x.digits.map (fun p => p.2.eval σ) = y.digits.map (fun p => p.2.eval τ)) : x.val σ = y.val τ ↔ x.digitVals σ = y.digitVals τ, by the same induction. The earlier statement, at one assignment with the premise that the two radix lists are equal, is its caseτ = σand is not kept; its uses in the tests compare two indices with the same radices, so they passrflfor the new premise. Two instances of a view are valued at two assignments (bind L g σ,bind L g' σ), which is why the one-assignment form does not serve.MixedRadix.val_append:MixedRadix.val ⟨a ++ b⟩ σ = MixedRadix.val ⟨a⟩ σ + MixedRadix.radixProd ⟨a⟩ σ * MixedRadix.val ⟨b⟩ σ, Horner's rule split at a digit, forcoarsen_tile.
Proof plan
View.tiling, bounds: an offset isk C + awithkthe key's value andCthe cosize;kis below the radix product atbind L g σ(MixedRadix.lt_prod,WF.range), which is the radix product atσ(WF.radices), anda < C(Lay.call_lt_cosize,WF.congruent,WF.pos), sok C + a < (k + 1) C ≤ radixProd σ · C.View.tiling, disjointness: a byte of two tiles isplace buf (k C + a) = place buf (k' C + a');PlaceInjgivesk C + a = k' C + a',MixedRadix.add_mul_eq_iffwitha, a' < Cgivesk = k', the two-assignmenteq_iff_digits(withWF.rangeandWF.radicesat both) equal digits, andWF.key_injthe same instance. OnlyPlaceInj's injectivity in the offset is used, since a view has one buffer; two views on different buffers are disjoint by its other half (b = b').View.coarsen_tile: the coarse layout's call atc' < size · R(withRthe inner radix product) iscall (c' % size) + C · (c' / size)(the layout algebra'scolex_appendthroughLay.call_scalar), and its cosize isC R.val_appendsplits the key atjasinner + R · outer, whereRatbind L j σisRatσ(WF.radices) andouteris the coarse key ati(hn). So an offset ofj's tile atcis the coarse offset atinner · size + c(withinner < Rbylt_prod), and a coarse offset atc'is the offset of the instancejthathogives fork = c' / size, atc' % size.
Where the statements depart from the design
[Place S]is the premisePlaceInj S.place, the core's law (the fieldSig.placeInjcarries it when a machine gives one). It isPlace.injandPlace.disjointin one implication.layis a layout at each size assignment,Sizes → Lay, not a layout term with symbolic extents: the layout algebra computes at extents that are numbers, and quantifying overσcovers every size without a second, symbolic copy of it.- A view has
bind, the assignment at an instance, because a key's digits are size expressions over numbered variables and an instance's coordinates must enter them;WF.radiceskeeps the radices independent of the instance. Tilingtakes the set it tiles,v.bytes σ: "in bounds" is a subset of the firstradixProd · cosizeoffsets of the buffer.View.coarsentakes the digit countnand the coarse bindingbind', andcoarsen_tilethe premiseshnandho. Withouthothe equation is false when an inner radix exceeds the instances insidei: a warp digit whose radix is one more than a block's warp count gives a coarse tile with a row that no warp of the block covers. The design'sv.level ≤ ℓis not a premise: the proof does not use it, andInsidesays which instances nest.
Instances and tests planned
- gemv's output vector: the warp level, the one-element layout
⟨[leaf 1 true], [leaf 1 true]⟩, the keywarpIdxof the tests above withbindsetting the warp's first lane and its block;WF.key_injholds because the digitstid / Wandctaidname the warp (as ingemv_warp). Coarsened at the block level withn = 1, a block's tile is itsntid / Wrows, byhowhenWdividesntid; the mutant is a warp digit whose radix is one more than the block's warp count, wherehofails and the equation is refused. - The naive matmul's output: the thread level, the one-element layout, the key
entryIdx(the column with radixn, the row with radixm);WF.key_injholds because the row and the column name the thread, andmatmul_eqis the two digits' case ofeq_iff_digits. - Evaluation at two launches and two matrix sizes, as the tests above, and a mutant of each
WFfield (a key out of range, a radix that reads a bound digit, two instances with one key).
The layout algebra's move into the core
The laws the views reindex by (rowMajor_inj and Lay.compose_call in Layout/Laws.lean,
Swizzle.call_call in Layout/Swizzle.lean, placement_call in Layout/Bits.lean,
Swizzle.twoLevel_call in Layout/TwoLevel.lean) are mathematics about layouts. The move, one
build of its own, with no aliases and no import-only files:
- Lean: MojoProof/Layout/Basic.lean (no import), Algebra.lean, Crd.lean, Laws.lean, Bits.lean,
Swizzle.lean and TwoLevel.lean (which import only each other) become GPUProof/Layout/*.lean,
namespace
MojoProof.LayoutbecomingGPUProof.Layout. No MojoProof module outside the directory imports them, so no library module changes but these. - The core's import test, MojoProofTest/GPUProof/Imports.lean, imports the seven modules (it
fails unless every file under GPUProof/ is imported there) and checks that they reach neither
MojoProofnorTorchLean. - lakefile.lean:47, the glob
.submodulesMojoProof.Layout, is deleted;lean_lib GPUProof`'s glob covers the moved modules. - Tests: MojoProofTest/LayoutLaws.lean (imports, lines 1-3, and
open, line 24) moves to MojoProofTest/GPUProof/LayoutLaws.lean. MojoProofTest/LayoutConformance.lean (lines 1, 8, 16) and MojoProofTest/LayoutRuntime.lean (lines 1, 10, 20) stay: they test the claim that the model is Mojo's library. They are generated, so their generators change with them: tests/layout/extract.py:181, 188 and 197, tests/layout/runtime/extract.py:110, 118 and 128, and the headers tests/layout/record.txt:3 and tests/layout/runtime/record.txt:3. - The trusted base: T16, the claim that the model is Mojo's layout library, stays MojoProof's. Its row in docs/TRUST.md:22 cites the moved paths, and scripts/trust.tsv:32-36 lists the five modules by name.
- scripts/laws.tsv:11-15, the five layout laws, and scripts/targets.txt's layout section (33 lines) take the new namespace.
- Documents: docs/proofs/layout-laws.md (7 references), this file (lines 71-75), docs/proofs/README.md:517, roadmap/layout/README.md:38, the 15 layout cards under roadmap/layout/cards/ and roadmap/status.yaml (15); docs/DEPENDENCIES.md and docs/deps/ are regenerated. The ledger's rows keep the paths of their time.
- Not moved: the tensor-core fragment maps (MojoProof/Sem/TensorCore.lean), which are transcriptions of the PTX tables, fixed at 32 lanes and importing TorchLean.