The warp's dot product: strided loops and a butterfly (stride, groupDot, warpDot, sum_stride, length_stride, bfly_stride, bfly_matVec, bfly_vecMat, bfly_stride_error, groupDot_error, groupDot_matVec, groupDot_vecMat, warpDot_error, warpDot_matVec, warpDot_vecMat, bflyRounds_nanEq, bfly_stride_nanEq, groupDot_nanEq, groupDot_eq, warpDot_nanEq, warpDot_eq, bflyRoundsAt_nanEq, bflyDeliver_nanEq, bflyDeliver_error)
Lean: proved, for every format, length, group of 2 ^ k lanes, flag and oracle as stated below, in
MojoProof/Sem/WarpDot.lean, and gevm_kernel's transposition through shared memory in
MojoProof/Sem/Transpose.lean (its own section below). Instances: MojoProofTest/WarpDot.lean, tests
of one example each (binary32, 40 pairs, over 32 lanes and over 8), and
MojoProofTest/Transpose.lean. The loop is dotLoop
(MojoProof/Sem/Matmul.lean), the rounds and their tree are bflyRounds and bflyTree
(MojoProof/Sem/Bfly.lean, see bfly.md), the exact values are TorchLean's contract … .matVec and
contract … .vecMat, and the bounds and the reference words are FloatLib's. The statements are
about a function of the factor pairs; that a grid run of a kernel computes it is not proved (see
"Not proved").
What the kernels compute
Both kernels in tests/corpus/gemv/ compute each output entry as a dot product over K factor
pairs, in the same order. The pairs are split by position modulo 32 into 32 strided lists; lane
l folds list l from +0 with fmul contract then fadd contract (one dotStep); and the
five butterfly rounds at the offsets 16, 8, 4, 2, 1 (bfly.md) add the 32 lanes' sums, lane 0's
value being the output.
gemv_kernel: lanelof rowi's warp folds the pairs(a[i, 32 j + l], b[32 j + l]), the strided lists ofmatVecPairs A v i, the pairs of TorchLean's matrix-vector entryi.gevm_kernel: thread(w, l)folds the pairs(a[32 j + w], b[32 j + w, 32 β + l]), listwof column32 β + l; the sums are transposed through shared memory, so that lanelof warpwholds the sum of listlof column32 β + w, and warpw's five rounds leave column32 β + w's total at lane 0. A column's pairs arevecMatPairs v A j, the pairs of TorchLean's vector-matrix entryj.
Statements
Write stride w l xs for the elements of xs at the positions ≡ l (mod w), in order, and
groupDot k c o ps for lane 0's value after the rounds of FloatLib's Model.add at
bflyOffsets k (bfly.md) from lane l's value dotLoop c (o l) (+0) (stride (2 ^ k) l ps), with
the contract flag c and lane l's oracle numbers o l: the dot product over a group of
2 ^ k lanes. warpDot is by definition groupDot 5, the warp's 32 lanes. A kernel's fadd of a
round goes through deliver, which changes only a NaN result (nanEq_deliver); groupDot adds
without it. Write u for FloatLib's
unit roundoff Model.unitRoundoffAt fmt, η for its underflow allowance
Model.underflowErrorAt fmt, and E(W, d, L) for the error of
GPUProof.laneGrade (.ieee fmt) W d L n a x ga gx at the real values a k, x k of the words and
the grades ⟨0, 0⟩ (spec.md), which is
E(W, d, L) = ((1 + u) ^ (L + d) - 1) T + W (1 + u) ^ d (2 + u) η ((1 + u) ^ L - 1) / u,
with T = Σₖ |aₖ xₖ|. The bound of statements 5 and 6 is this one, laneGrade's, the same as
the graded GPUProof.Approx statements of MojoProof/Tile/MatVec.lean (stride_approx,
bfly_approx, groupDot_approx).
sum_stride: in every commutative monoid, for everyw > 0, mapgand listxs,Σ_{l<w} Σ g (stride w l xs) = Σ g xs.length_stride: for alll < wand every list of lengthK,stride w l xshasK / w + [l < K % w]elements;length_stride_le: at most⌈K / w⌉ = (K + w - 1) / w.bfly_stride: in every commutative monoid, for all offsetsms, lanesland widthswwhose lanes0, ..., w - 1are the leaves ofbflyTree ms l, each once (leaves_warp: everyl < 32atwarpOffsetswithw = 32), lanel's value after the rounds of+from lanej's exact sumΣ g (stride w j xs)isΣ g xs.- Over
ℝ, for every format and all sizes:vecMat_cell_real:Σ aₖ bₖovervecMatPairs v A jis entryjofcontract v' A' _ _ [n] .vecMat, withv',A'the tensors mapped byModel.toReal; so (statement 3 withgthe real product)bfly_matVec: the rounds of+over the lanes' exact sums of the strided lists ofmatVecPairs A v igive entryiofcontract A' v' _ _ [m] .matVec, andbfly_vecMat: those ofvecMatPairs v A jgive entryjofcontract v' A' _ _ [n] .vecMat, for everyms,w,lof statement 3. bfly_stride_error: in every IEEE format, for every flagc, oracle familyo, wordsw k,v kfork < n(the pairsps), offsets, lane and widthWof statement 3, and everyLat least the length of each strided list: if lanel's valuerafter the rounds ofModel.addover the loopsdotLoop c (o j) (+0) (stride W j ps)is finite, then|r - Σ wₖ vₖ| ≤ E(W, ms.length, L).groupDot_error: in every IEEE format, for everykandnpairs,groupDot k c o ps, if finite, is withinE(2 ^ k, k, ⌈n / 2 ^ k⌉)ofΣ wₖ vₖ;groupDot_matVecandgroupDot_vecMat: the same against TorchLean's real entries atmatVecPairs A v i(⌈n / 2 ^ k⌉) andvecMatPairs v A j(⌈m / 2 ^ k⌉).warpDot_error,warpDot_matVecandwarpDot_vecMatare their casesk = 5:E(32, 5, ⌈n / 32⌉).bflyRounds_nanEq: in every format, for all operationsf,gsuch thatf x yandg x' y'areNaNEq(same word or both NaNs) wheneverx, x'andy, y'are, all offsets, valuesv,v'that are lane by laneNaNEq, and every lane, the rounds offovervand ofgoverv'areNaNEq. Atf = g = Model.addthey arewarpDot's rounds; atf x y = deliver (Model.add x y) nandg = Model.add, the semantics'faddat one oracle numbernfor every lane and round.bfly_stride_nanEq: in every format, for every flagcand oracle familyowith the contraction off (cfalse, or no oracle number 2 modulo 3), the value of statement 5 and FloatLib'sModel.reduceAlong fmt fmtalongbflyTree ms lof the in-order dot productsModel.dotInOrder fmt fmt (stride w j ps)areNaNEq.groupDot_nanEq: statement 7 at a group of2 ^ klanes,groupDot k c o psagainst FloatLib's reduction alongbflyTree (bflyOffsets k) 0of the in-order dot products of the listsstride (2 ^ k) j ps;groupDot_eq: when FloatLib's word is not a NaN,groupDot k c o psis that word, bit for bit, and one is a NaN exactly when the other is.warpDot_nanEqandwarpDot_eqare their casesk = 5, alongbflyTree warpOffsets 0.- Write
bflyRoundsAt F ms v(bfly.md) for the rounds in which lanelof roundr(counted from0) combines byF r l;bflyRounds f ms vis by definition its caseF r l = f.bflyRoundsAt_nanEq: in every format, for every familyFand operationgsuch thatF r l x yandg x' y'areNaNEqwheneverx, x'andy, y'are, for every round and lane, and values and lanes as in statement 7, the rounds ofFovervand ofgoverv'areNaNEq.bflyDeliver_nanEq: in every format, for every oracle familyoby round and lane, the rounds ofdeliver (Model.add x y) (o r l), the semantics'faddwith its own oracle number in every round and lane, areNaNEqto those ofModel.add.bflyDeliver_error: in every IEEE format, for every sucho, values, offsetsms, laneland widthwwith lanel's tree over the lanes beloww, each once: if the lane's delivered value is finite, it is theModel.addrounds' value, every value belowwis finite, and it is within((1 + u) ^ ms.length - 1) · Σ_{j<w} |v j|ofΣ_{j<w} v j.
With K pairs the bound's exponent is ⌈K / 32⌉ + 5, against K for the sequential loop
(GPUProof.dotGrade, laneGrade at one lane and depth 0), and its underflow term has
32 (1 + u) ^ 5 loops of ⌈K / 32⌉ iterations.
Proofs
- Generalize the start index of
zipIdxand induct on the list: the head at positionsgoes to lists % wonly, andΣ_{l<w} [s % w = l] g x = g x(List.sum_map_eq_nsmul_single,s % w < w). - The filter's length is the count of
k < Kwithk % w = l(induction on the list), which is Mathlib'sNat.count_modEq_card; the bound follows fromK = w (K / w) + K % wandK % w < w(omega). eval_bflyTreemakes the rounds an evaluation of lanel's tree; FloatLib'seval_add_eq_summakes it the sum over the leaves, a permutation of0, ..., w - 1, and then statement 1.- TorchLean's
getScalar_contract_vecMatanddotSum_ofFn, as formatVec_cell_real; then statement 3. - Lane
l's value istreeDot(dot.md) alongbflyTree ms l(eval_bflyTree), whose depth isms.length(depth_bflyTree), over the listsstride W j ps; their sums over the lanes are the sums over the pairs (statement 1). So it is dot.md'streeDot_errorat the real values with the grades⟨0, 0⟩, each word within0of its own real value. There is no induction here: the loops' bound (lanes_error) and the tree's (Float.sum_error) are combined once, intreeDot_error. - Statement 5 at
leaves_offsets k 0(bfly.md, statement 3),length_stride_leand(bflyOffsets k).length = k; thenmatVec_cell_realorvecMat_cell_realand the pairs' length. The warp's statements are the general ones atk = 5, where2 ^ 5reduces to 32. - Statement 9's
bflyRoundsAt_nanEqat one operation in every round and lane, which isbflyRoundsby definition; atModel.addthe premise isNaNEq.opatfadd, and atdeliverit isnanEq_deliverfollowed byNaNEq.op. Theneval_bflyTreeon FloatLib's side,dotLoop_nanEqat each lane, andcast_self_nanEqforreduceAlong's final cast to the same format. - Statement 7 at
bflyOffsets k,w = 2 ^ k,l = 0;NaNEq.eq_isNaN. The warp's are the casek = 5. - Induction on the offsets, generalizing the family: one round is the premise at round
0on lanejand lanej ^^^ m, and the later rounds are the family shifted by one round.bflyDeliver_nanEq: the premise isnanEq_deliverfollowed byNaNEq.opatfadd.bflyDeliver_error: a finite value is not a NaN, soNaNEq.eq_isNaNmakes it theModel.addrounds' value; thenbfly_add_error(bfly.md, statement 6).
Instances
In MojoProofTest/WarpDot.lean, a test of one example: binary32, the 40 pairs (2 ^ 24, 1) then 39
times (1, 1), the pairs of entry 0 of the product of the vector [2 ^ 24, 1, …, 1] and the
40 × 1 matrix of ones (pairs40), whose exact sum is 2 ^ 24 + 39.
lens40: lists 0 to 7 have 2 pairs and lists 8 to 31 have 1 (statement 2,⌈40 / 32⌉ = 2).vals40: without thecontractflag the warp's word is2 ^ 24 + 38, and FloatLib's in-order dot product of the 40 pairs is2 ^ 24: the butterfly's order and the sequential order give different words, so statement 8's reference is the tree's reduction, not the sequential fold that TorchLean's binary32contractcomputes.eq40: statement 8 with thecontractflag under the oracle numbers(0, 0).error40: statement 6 (warpDot_vecMat) atm = 40, with the finite premise by evaluation: the bound isE(32, 5, 2),laneGrade (.ieee .binary32) 32 5 2 40's error.eq8,error8: statements 8 (groupDot_eq) and 6 (groupDot_vecMat) over a group of 8 lanes (k = 3, 5 pairs per lane), the second without thecontractflag, with the finite premise by evaluation: the bound isE(8, 3, 5),laneGrade (.ieee .binary32) 8 3 5 40's error.mutant_exact: the roundoff terms cannot be dropped. AtL = d = 0,E(32, 0, 0)is0, and the warp's word without thecontractflag (2 ^ 24 + 38,vals40) is not the exact sum2 ^ 24 + 39, so statement 6's conclusion fails at that bound.deliver5: statement 7 atf x y = deliver (Model.add x y) 7andg = Model.add, over lane 5 holding the quiet NaN0x7fc00000and the other lanes1(nan5): lane 0's delivered value is a NaN, becauseModel.add's is (by evaluation).deliverAt5,deliverAt_ones: statement 9'sbflyDeliver_nanEqandbflyDeliver_errorwith the oracle number32 r + l + 7in roundrat lanel(oracleAt): overnan5lane 0's value is a NaN; over 32 lanes1(ones32) it is finite (by evaluation), so it is theModel.addrounds' value and within((1 + u) ^ 5 - 1) · 32of32.
The transposition through shared memory (tpose, tpose_lt, tpose_tpose, tpose_bijOn, Launch.tpose_env, Tiling.tpose, racy_tpose, warpDot_tpose)
Lean: proved in MojoProof/Sem/Transpose.lean: statement 2 for every valid launch with ntid.x =
1024 and every thread of every block, the others for every n, trace and content of the shared
array as stated. In gevm_kernel (gemv.md), thread t = 32 w + l of block β (warp w = t / 32,
lane l = t % 32) folds list w of column 32 β + l and stores the sum to the shared cell %62 =
32 l + w (line 75, a 4-byte float, store at line 78); after the barrier (line 79) it loads cell
%65 = tid.x = t (lines 80-82), and the warp's five rounds (lines 83-102) add the 32 values it
loaded.
Write tpose n t = n (t % n) + t / n, the position of t in the transpose of an n × n square
stored by rows; the store cell is tpose 32 t.
tpose_lt,tpose_tpose: for everynandt < n²,tpose n t < n²andtpose n (tpose n t) = t; so (tpose_bijOn)tpose nis a bijection of[0, n²)onto itself (Set.BijOn), its own inverse. Atn = 32threadtwrites celltpose 32 t, and cellt(which threadtreads) is written by threadtpose 32 talone.Launch.tpose_env: for every valid launch withntid.x = 1024and every thread numberk, the block has 1024 threads,tid.x = k % 1024, the lane number isk % 32, and32 · laneid + tid.x / 32 = tpose 32 (k % 1024): the kernel's store cell istpose 32of the thread's number in its block.Tiling.tpose n w β: for everyn > 0, cell widthwand block of threadsβ, threadkofβ(k / n² = β) owns thewbytes attpose n (k % n²) · w, every other thread the empty tile at 0, insiden² wbytes; aTiling Nat, one owner per cell.racy_tpose: for every trace, everyn > 0andw, a mapofShfrom a memory block to the block of threads whose shared array it is, and an ownershipGof the other blocks: if every access to blockβ's array is by a thread ofβ(cta andk / n² = β), in phase 0 is thewbytes of its celltpose n (k % n²), in later phases is a read, and every access to another block followsGwith each thread its own tile (Owned G id), the trace has no race. Withn = 32,w = 4and 1024 threads per block (k / 1024is the thread's block, statement 2) this is the kernel's discipline: one owner per cell before the barrier, reads after it.warpDot_tpose: for every format, flagc, oracle familyoby thread, pair listsPby lane and array contentM: if every threadt < 1024stored at celltpose 32 tits loop sumdotLoop c (o t) (+0) (stride 32 (t / 32) (P (t % 32))), then for every warpw < 32the rounds ofModel.addatwarpOffsetsover the cells32 w + lgive lane 0 the value of the same rounds over the loop sumsdotLoop c (o (32 l + w)) (+0) (stride 32 l (P w)), which iswarpDot c (fun l => o (32 l + w)) (P w)by definition. WithP l = vecMatPairs v A (32 β + l), the pairs of column32 β + l, warpw's value iswarpDotof column32 β + w's pairs, inwarpDot's order (lanelholds listl), so statement 6 (warpDot_vecMat) bounds it.
Proofs. 1: t = n q + r with q, r < n; Nat.mul_add_mod, Nat.mul_add_div give
tpose n (n r + q) = n q + r, and n r + q < n² from r + 1 ≤ n (omega); then
Set.InvOn.bijOn. 2: volume = 1024 · y · z ≤ 1024 with y, z ≥ 1 forces 1024 (omega);
then Launch.env, coord and Nat.mod_mod_of_dvd (32 divides 1024). 3: distinct threads of
β have distinct remainders, so distinct cells (statement 1), and stride_lt (Buffer.lean)
separates the cells; an empty tile is disjoint from every tile. 4: racy_eq_false_of_phased
with own := id, the tiling Tiling.tpose at β's array in phase 0, none after, G elsewhere:
hO from the premises, hG because two accesses of one array are by threads of its block, hX
because own is the identity. 5: lane l < 32 loads cell 32 w + l = tpose 32 (32 l + w),
thread 32 l + w's sum, list l of P w; the rounds read only the lanes below 32, the leaves
of lane 0's tree (leaves_warp, bflyRounds_congr, bfly.md statement 7).
Instances (MojoProofTest/Transpose.lean, tests of one example each): thread1061, thread 1061 of
a launch of grid (2, 1, 1) and block (1024, 1, 1) (thread 37 of block 1) stores to cell 161 and
loads cell 37, thread 161's cell and no other's (statements 1, 2); racy4, statement 4 at
n = 2 and 1-byte cells on a trace of 4 threads (each writes its transposed byte, a barrier,
each reads its own); col40, statement 5 at binary32 with every lane's pairs wd40: warp 5's
value is 2 ^ 24 + 38, the word of vals40.
Not proved: that a grid run of gevm_kernel stores and loads these cells (the getelementptr
on the shared global, gemv.md item 5), that its trace meets statement 4's premises, and that its
loop computes dotLoop of the strided lists, which needs K and N multiples of 32 (gemv.md,
"The specifications' premises": the loop reads row 32 i + w for every i < ⌈K / 32⌉).
Not proved
- That a grid run of
gemv_kernelorgevm_kernelcomputeswarpDotof its loaded pairs: the loops' loads, the shuffles of every lane of the warp at the same round, and thatgevm_kernel's run stores and loads the transposed cells (the cells' arithmetic, the race freedom of a trace that does, and the values each warp then reduces are proved, in the section above); both kernels are outside the block checker's fragment from their entry block (bfly.md). - That the oracle numbers a grid run draws for the rounds'
faddare a familyo r lby round and lane of statement 9: statement 9 holds for every such family, and that a run computes the rounds at all is the item above. - Any bound when the result is infinite or a NaN.