The spec layer: specifications are mathematics
Lean: GPUProof/Spec/Basic.lean (steps 1 to 8 below) and GPUProof/Spec/Linear.lean (steps 9 to 11),
with the equality up to NaN payloads in GPUProof/NaN.lean, tested in
MojoProofTest/GPUProof/Spec.lean. Still plan: the importer (step 12) and the tests marked "plan"
below; the kernels that meet Spec.matVec matVecGrade are in MojoProof/Tile/MatVec.lean (step 9).
This document fixes the definitions of the core's spec layer, the order in which they enter Lean,
the first instance of each, and which FloatLib, TorchLean and Mathlib definitions each one reuses.
Where the Lean departs from the design's sketch, the departure is listed with its reason (last
section). Spec cannot enter Lean alone: its rule field is a FloatRule, whose cases read
encodings, formats and grades, so the first unit that builds with an instance is steps 1 to 8.
Scope. Every definition below is stated for every size type Sz and every spec Sp : Spec Sz;
nothing fixes a machine, a format or a size. The instances are about one spec at a time
(GPUProof.Spec.matVec, GPUProof.Spec.vecMat, GPUProof.Spec.sumReal,
GPUProof.Spec.sumInt), at every size and grade, and one encoding family (FloatLib's binary
interchange formats, entry by entry). The importer is about one TorchLean operation
(Tensor.contract … .matVec), at every shape.
Where it lives. The spec layer is core: modules GPUProof.Spec.*, importing only Mathlib.*,
FloatLib.* and GPUProof.*, as MojoProofTest/GPUProof/Imports.lean requires of every core
module. The TorchLean importer imports TorchLean, so it cannot be a module of lean_lib GPUProof:
that test refuses any TorchLean.* module in the core's import closure. It goes into a library of
its own (GPUProofImport, below).
What is reused
DType.Val:ℝ,ℤandBool(Mathlib, Lean).NumFormat, its phase 0 form: FloatLib'sFloatFormat(FloatLib.Floats.Formats.BinaryInterchange).safeMax: FloatLib'sModel.posMaxFinite(Model/Carrier.lean) andModel.toReal(Model/RealSemantics.lean); its range lemma is FloatLib'sisFinite_roundDyadic_of_isIEEE_of_abs_toReal_le_posMaxFinite(Arithmetic/Finiteness.lean).Approx: FloatLib'sModel.isFinite,Model.toRealandModel.toReal?.Grade: new. FloatLib'sMixedError(Numerics/MixedError/Basic.lean) and MojoProof'sMojoProof.Sem.Estbecome instances of it, not copies.ScalarEnc.ieee: FloatLib'sModel.toReal?as its decoder (noneat a NaN and an infinity) andModel.isNaNas its NaN words, with FloatLib'sModel.toDyadic?_eq_none_of_isNaNfor the law that a NaN decodes tonone. ItsnanEqisGPUProof.UpToNaN Model.isNaN, and so is MojoProof'sMojoProof.Sem.NaNEq(MojoProof/Sem/FloatRel.lean), by definition.Spec.matVecandSpec.vecMat: Mathlib'sMatrix.mulVec,Matrix.vecMulandMatrix.of.Spec.sumRealandSpec.sumInt: Mathlib'sFinset.sumoverFinset.univ.- The matVec importer: TorchLean's
Tensor.contract … .matVecatα := ℝasdenote(Tensor/Contract.lean);Tensor.toVecₗᵢ,TorchLean.Matmul.idxMNandTensor.getScalarforreadInandreadOut;getScalar_contract_matVec_eq_sumandTorchLean.Matmul.toVec_idxMNforeq.
FloatLib also has generic format classes (EncodedFormat with Code and Scalar,
FormatSemantics with denote : Code → NumericalValue Scalar, and the structure
NumericalSystem). ScalarEnc is the same shape (a word type and a meaning of every word). When
FloatLib releases its format sum NumFormat through its intake, ScalarEnc.ofSystem reads any
NumericalSystem whose scalars are reals, and the phase 0 NumFormat below is replaced by
FloatLib's in one change. Nothing of FloatLib is copied: FloatLib v4.1.0 has no safeMax, no
grade, no NaN equivalence on Model (GPUProof.UpToNaN is new) and no format sum, so those are
new here.
The definitions, in the order they enter Lean
Each step builds with its instance before the next starts. Module GPUProof.Spec.Basic holds
steps 1 to 8 (with UpToNaN of step 6 in GPUProof.NaN, which imports nothing),
GPUProof.Spec.Linear steps 9 to 11, and GPUProofImport.TorchLean will hold step 12. All names
below are in the namespace GPUProof.
DType(real | int | bool),DType.Val(ℝ,ℤ,Bool) andEnts ι d:= (i : ι) → (d i).Val. Instance: the entries ofSpec.matVecat(m, n), allreal.NumFormat, the phase 0 form:ieee (fmt : FloatFormat) | int (bits : Nat) | bool. Instance:ieee .binary32,int 32.Grade{ err mag : ℝ }with its order (fieldwise≤, the order of(err, mag)in the product). Plan: the grade of0error and magnitude|a|of an exact inputa.NumFormat.safeMax: atieee fmt,(Model.posMaxFinite fmt).toReal; atint bits,2 ^ (bits - 1) - 1; atbool,1. The range lemmaApprox.finite_of_le, at IEEE formats: underApprox's premiseg.mag ≤ safeMax, a dyadic of magnitude at mostg.magrounds to a finite word, from FloatLib'sisFinite_roundDyadic_of_isIEEE_of_abs_toReal_le_posMaxFinite(a rounding of a dyadic of magnitude at mostsafeMaxis finite). Binary32'ssafeMaxis(2 - 2⁻²³) · 2¹²⁷and bfloat16's255 · 2¹²⁰, each by evaluation of the word's rational value (testsoverflow_edge,copy_meets_bfloat16).-
Approx d g fmt v a, for an entry typed, on a decoded valuev : Option d.Val(the decoder's output,noneat a NaN or an infinity):g.mag ≤ fmt.safeMax → d.Near g v a, whereDType.Nearatrealis∃ r, v = some r ∧ |r - a| ≤ g.err, and atintandboolisv = some a. The design's form on words, forw : Model fmt, is the corollaryApprox.modelatv = w.toReal?: `g.mag ≤ safeMax → w.isFinite = true ∧|w.toReal - a| ≤ g.err
. Instances: the testsnan_approxandoverflow_edge` (below). -
ScalarEnc d, one entry's storage:Word,decode : Word → Option d.Val,isNaN : Word → Bool(its NaN words),fmt : NumFormat, and the lawdecode_isNaN(a NaN decodes tonone). Its equality up to NaN payloads is defined, not a field:ScalarEnc.nanEq e:= UpToNaN e.isNaN, whereUpToNaN nan x y(GPUProof/NaN.lean) isx = y ∨ (nan x = true ∧ nan y = true), an equivalence (UpToNaN.equivalence), and related words decode alike (ScalarEnc.decode_eq).Encoding ι d, one side of a spec at one size: its word positionsPos, the wordsWord pat each position,decode : ((p : Pos) → Word p) → (i : ι) → Option (d i).Val, the NaN wordsisNaN pat each position andfmt : ι → NumFormat, with two laws that tie the NaN words to the decoder: words equal up to NaN payloads at every position decode alike (decode_eq: the decoder reads no payload), and a NaN at a position leaves some entry with no value, whatever the other positions hold (decode_isNaN). Its words areEncoding.Words e := (p : e.Pos) → e.Word p, and its equality up to NaN payloads is defined once,Encoding.nanEq e W W':= ∀ p, UpToNaN (e.isNaN p) (W p) (W' p), an equivalence (the theoremEncoding.nanEq_equiv).Encoding.ofScalars (e : (i : ι) → ScalarEnc (d i))is the entrywise case, a position per entry, withWord i := (e i).WordandisNaN i := (e i).isNaN; it proves both laws from its scalars'.Encodings In Out dIn dOut σpairs an input and an output encoding at sizeσ. Instances:ScalarEnc.ieee fmt(wordsModel fmt, decoderModel.toReal?, NaNsModel.isNaN),ScalarEnc.int bits(wordsBitVec bits, decoderBitVec.toInt, no NaN),ScalarEnc.bool(no NaN), andScalarEnc.std fmt bits, which stores reals infmt, integers inbitsbits and booleans asBool. -
FloatRulewith its three casesbitwise w hw,exactandgraded g mono, andFloatRule.Holds, what a rule says of input wordsWand output wordsW'at an encoding:bitwise E₀ w hw, at the encodingsE₀ σit names and nowhere else:W'equalsw σ Wup to NaN payloads;hw : DecodesAs Dom f E₀ wsays thatwdecodes asfwherever the inputs decode intoDom;exact: for inputsWthat decode toAwithDom σ A, and for which everyf σ A ois the decoding of some output word, every output decodes tof σ A o;graded: for exact inputsAwithDom σ Aand gradesGwithApprox (dIn σ i) (G i) (E.inp.fmt i) (E.inp.decode W i) (A i)at every inputi,Approx (dOut σ o) (g σ E A G o) (E.out.fmt o) (E.out.decode W' o) (f σ A o)at every outputo.
So, from the rule at
E₀ σand inputsWthat decode toAwithDom σ A, the outputs arew σ Witself (FloatRule.Holds.bitwise_eq: every output ofw σ Whas a value, so byEncoding.decode_isNaNnone of its words is a NaN), and every output decodes tof σ A o(FloatRule.Holds.bitwise, byEncoding.decode_eqandhw). Instances:exacton the identity spec at every size (a copy kernel's rule), andbitwiseon entrywise negation in every binary interchange format, with FloatLib'sModel.neg(testsneg_meets,neg_decode). -
Spec Sz, with the design's fields (In,Out,fin,dIn,dOut,Dom,f,rule),Spec.Encs Sp σ(the encodings ofSpatσ),MeetsAt Sp k E(for every sizeσ, input wordsWand output wordsW' ∈ k σ (E σ) W,Sp.rule.Holds σ (E σ) W W'),Meets Sp k(MeetsAt Sp k Efor every family of encodingsE),Encodings.uniform Sp u(every entry of typedin the scalar encodingu d) andMeets.uniform, a one-line corollary:h (Encodings.uniform Sp u). Instance: the copy spec at every size, and a copy behavior that meets it (testscopy_meets,copy_meets_binary32,copy_meets_bfloat16). Spec.matVec g mono, at sizes(m, n) : ℕ × ℕ: inputs(Fin m × Fin n) ⊕ Fin n, outputsFin m, every entryreal,Domeverything (only+and·, so no junk value of Mathlib's arises), andf (m, n) X i = Matrix.mulVec (Matrix.of fun i k => X (.inl (i, k))) (fun k => X (.inr k)) i, with rulegraded g. It isSpec.ofRealat that function:Spec.ofReal In Out f g monois the spec of a real functionf, every entryreal, meant everywhere, with rulegraded g, for grade functionsg : RealGrades In Out. The testmatVec_f: the function is∑ k : Fin n, A i k * x k, byrfl.laneGrade fmt W d L n a x ga gx(GPUProof/Spec/Linear.lean), the grade of a dot product of lengthnrounded tofmt, split overWlanes of at mostLterms each whose sums are added along a tree of depthd: error((1 + u) ^ (L + d) − 1) S + W (1 + u) ^ d (2 + u) η ((1 + u) ^ L − 1) / u + P, withS = Σₖ (|aₖ| + eₐₖ)(|xₖ| + eₓₖ)and the propagated errorP = Σₖ (|aₖ| eₓₖ + |xₖ| eₐₖ + eₐₖ eₓₖ).dotGrade fmt n a x ga gxis its case of one lane ofnterms and depth0, by definition: errorγₙ S + (2 + u) η γₙ / u + P, withγₙ = (1 + u)ⁿ − 1, the output format's unit roundoffuand underflow allowanceη(NumFormat.roundoff,NumFormat.underflow: FloatLib'sModel.unitRoundoffAt fmtandModel.underflowErrorAt fmt,0at an integer or Boolean format), and the inputs' grade errors taken at least0(Grade.pos: a negative error would make|a| + eshrink, and the grade not monotone); magnitude bound the larger of the first sum plus the error and every input grade's magnitude bound (laneGrade_mag, sodotGrade's too): an input whose grade's magnitude bound exceeds the largest finite value may be a NaN, which the loop carries to its result, so a smaller bound would claim a finite result that the loop does not give.laneGrade_mono,dotGrade_mono: they grow with the inputs' grades, for every format, counts, length and exact entries.laneVecGrade W d LislaneGradeat rowi, lengthn,L nterms per lane, outputi's format, withlaneVecGrade_mono, andmatVecGradeis its caselaneVecGrade 1 0 id(dotGradeat rowi), by definition, withmatVecGrade_mono; the testmatVecDotisSpec.matVec matVecGrade matVecGrade_mono, anddotGrade_one_zerochecks that atn = 1, exact entries0and grades0, the error is(2 + u) η > 0. The sequential loop meets the grade:MojoProof.Sem.dotLoop_approxproves that the word of the contracted loopMojoProof.Sem.dotLoopfrom+0isApproxatdotGradeof the exact dot product, for every IEEE format, length, input grade,contractflag and oracle, when each input word isApproxat its grade of its exact entry (finite and within the grade's error when the grade's magnitude bound is at most the largest finite value,GPUProof.Approx.model);MojoProof.Sem.dotGrade_ieeeshows thatdotGrade's error is the loop's own boundMojoProof.Sem.dotLoopBoundat the first sum (withγₙ, since the loop's first addition, to+0, is exact) plus the second sum (docs/proofs/dot.md, statements 12-14). Lanes meetlaneGrade:MojoProof.Sem.treeDot_approxproves the same ofWsuch loops added along any tree over the lanes (FloatLib'sNumerics.ReductionTree) of depthd, each of at mostLpairs, for every IEEE format, flag, oracle sequences,W,L, length, tree and input grade, anddotLoop_approxis its case of one lane and one leaf (docs/proofs/dot.md, statements 15-16). Kernels meet the grade.MojoProof.Tile.Meets, whichMojoProof.Tile.mat_refinesgives at every cell of every kernel ofmojo_kernel'smatclause, says that the cell's word isApproxatdotGradeof every exact row and column at which the cell's inputs areApprox(instances: MojoProofTest/TileNaive.lean at the naive kernel's corpus launch, MojoProofTest/TileGrade.lean at sizes 3 × 4 and 5 × 7 and a grade one ulp tighter refused). A matrix product whose second matrix has one row is a matrix-vector product, so those kernels meetSpec.matVec matVecGrade(MojoProof/Tile/MatVec.lean):MojoProof.Tile.rowLoops_meetsAt: for every IEEE formatfmt, widthbitsand flagc,MeetsAt (Spec.matVec matVecGrade matVecGrade_mono) (rowLoops fmt bits c) (matVecEnc fmt bits).matVecEnc fmt bitsisEncodings.uniformatScalarEnc.std fmt bits, by definition, and the same encoding at every grade, by unfolding (testMojoProofTest.TileMatVec.enc_grades), androwLoops fmt bits care the behaviors whose outputi, at that encoding, isMojoProof.Sem.dotLoop cfrom+0at some oracle sequence over rowiand the vector (none at another encoding, so the claim isMeetsAtat that family, notMeets). The rule unfolded isMojoProof.Tile.holds_of; the step isMojoProof.Sem.dotLoop_approx.MojoProof.Tile.meets_holds: words that meet the product at the cells(i, 0)(Meets) meet the rule (FloatRule.Holds) at the inputs read from the matrices (MojoProof.Tile.matIn), andMojoProof.Tile.mat_holdsgives that for every kernel of thematclause whose second matrix has one row and whose launch covers the rows and column 0 (instance:MojoProofTest.TileNaive.naive_holds, the naive matmul kernel with one column).- Tests (MojoProofTest/TileMatVec.lean): the product by rows at sizes 3 × 4 and 5 × 7, and the
spec graded one ulp tighter, not met by
rowLoopsunfused (rowLoops_mutant). MojoProof.Tile.groupDot_holds: for every IEEE format, width, number of roundsk, flag, size, oracle sequences and input words, the lane group's dot productMojoProof.Sem.groupDot kper row (2 ^ kloops over the pairs strided by2 ^ k, thenkbutterfly rounds;MojoProof.Sem.warpDotatk = 5) meets the rule ofSpec.matVec (laneVecGrade (2 ^ k) k fun n => ⌈n / 2 ^ k⌉), byholds_ofandMojoProof.Tile.groupDot_approx(docs/proofs/dot.md, statements 15-16; tests MojoProofTest/TileLanes.lean at 3 lanes and length 7, 4 lanes and length 10, and the grade at depth 0 refused).Spec.vecMat vecMatGradeis the case of one row of the first matrix, with the vector-matrix product's matrix transposed into the second; it is not stated yet. No matrix-product spec enters: a matrix product is met through these two as cases. Without the underflow allowance no kernel that rounds meets the grade: atn = 1a producta xbelow the normal range is rounded with an absolute error of up to half the spacing of the subnormals, whichγ₁ |a x|does not bound when|a x|is small. An instance is MojoProofTest/DotGrade.leanmutant_one: in binary32,3 · 2⁻¹⁴⁹ · 1/2is a tie between subnormals, rounded to2 · 2⁻¹⁴⁹, an error ofη = 2⁻¹⁵⁰, and the grade with2⁻¹⁴⁹(one subnormal spacing) less error, which leaves4 u ηof it, is not met. The sequential loop's bounds in MojoProof (MojoProof.Sem.dotLoopBound, andMojoProof.Sem.dotBoundwith one more power of1 + uon the sum) have the allowance(2 + u) η ((1 + u)^K − 1) / uafterKiterations.
Spec.vecMat g mono: the same atMatrix.vecMul, outputsFin n(testvecMat_f).vecMatGrade:dotGradeagain, at columnj, lengthm, withvecMatGrade_mono(testvecMatDot).- The sums, over
ℝ(Spec.sumReal g mono, rulegraded g) and overℤ(Spec.sumInt, ruleexact), at sizesn : ℕ, inputsFin n, one output,f n x () = ∑ i, x i(testsumReal_f). Instance:Spec.sumIntatint 32entries, where theexactrule's representability premise is what excludes a wrapped sum (below), checked at two inputs whose sum is2³¹(testsumInt_wraps). - The TorchLean importer for
matVec(GPUProofImport.TorchLean):Importerwith the design's fields, and its first instance at the one operationcontract … .matVec:Srcis the operation,Szthe shape(m, n);denote (m, n) (A, x) := Tensor.contract A x _ _ [m] .matVec, TorchLean's own operation atα := ℝ, defined before and apart from the spec;readInreadsAthroughTensor.toVecₗᵢ [m, n]atTorchLean.Matmul.idxMN i k(row major, entry(i, k)atk + n · i) andxthroughTensor.getScalar;readOutreads the result throughTensor.getScalar;translategivesSpec.matVec gat the operation andnoneelsewhere;-
eqisTorchLean.matVec_eq, the design's first equality, in the formtheorem TorchLean.matVec_eq (A : Tensor ℝ [m, n]) (x : Tensor ℝ [n]) (i : Fin m) : (Tensor.contract A x _ _ [m] .matVec).getScalar i = Matrix.mulVec (Matrix.of fun i k => Tensor.get2 A i k) (Tensor.getScalar x) iproved by
getScalar_contract_matVec_eq_sumandMatrix.mulVec's unfolding, and stated throughreadInbyTorchLean.Matmul.toVec_idxMN. Instance: the importer at every shape; a test states the equality at one2 × 3matrix and closes it bysimp.
The existing MojoProof statements against TorchLean (MojoProof.Sem.groupDot_matVec,
MojoProof.Sem.warpDot_matVec, MojoProof.Sem.warpDot_vecMat, MojoProof/Sem/WarpDot.lean)
stay as they are. Once the math statements exist, each is their instance through
TorchLean.matVec_eq, at the uniform encoding of its format.
Tests, one per definition and one per premise
The tests are in the namespace MojoProofTest.GPUProof.Spec.
nan_approx, in every binary interchange format with IEEE encoding, throughApprox.model: with a grade of magnitude0the canonical NaN meetsApproxat no real, and with a magnitude abovesafeMaxevery word meets it (nan_approx_binary32at binary32).sumInt_wraps: theexactrule without its representability premise is refused atSpec.sumIntby a 32-bit sum of2³⁰and2³⁰. Its words decode and its inputs are inDom, but the 32-bit sum decodes to-2³¹, and no output word of the uniform 32-bit storage decodes to the sum2³¹.copy_meets,copy_meets_binary32andcopy_meets_bfloat16: oneMeetson the copy spec, andMeets.uniformat binary32 and at bfloat16, whosesafeMaxis255 · 2¹²⁰, eight bits of precision at binary32's largest exponent.matVec_f,vecMat_fandsumReal_f: the specs' functions are Mathlib's sums.overflow_edge:Approxat the overflow edge (the design's test), by evaluation of FloatLib'sModel.mul,Model.addandModel.fmain binary32. The words8390108and16774216 · 2⁸¹have the exact product(2⁴⁷ - 4500000) · 2⁸¹, abovesafeMax((2⁴⁷ - 2²³) · 2⁸¹) and below the overflow threshold ((2⁴⁷ - 2²²) · 2⁸¹), so it rounds to the largest finite word. With the addend2¹⁰⁰the unfused result is finite and the fused one infinite. The exact magnitude is abovesafeMax, soApproxclaims nothing there and every word, both results among them, meets it.neg_holds,neg_meets,neg_decodeandneg_nan_finite: in every binary interchange format the negation spec'sbitwiserule holds exactly when each output is, up to NaN payloads, the negated input; negation meets it at every input, NaNs included; its outputs decode to the negated inputs (FloatRule.Holds.bitwise); and at a NaN input of binary32 a finite output breaks it, where theexactrule says nothing.neg_words, at two formats of different widths, by evaluation of the words: in binary32 at one entry and in binary16 at two, the output1from the input1is refused (another value), and from the canonical NaN a NaN with another payload and sign is accepted.bool_total_refusedandboolId_refuses: no NaN words make the equality up to NaN payloads relate every two words at an encoding with words decoding totrueand tofalseat one entry, and thebitwiseidentity on Booleans refuses the outputfalsefrom the inputtrue, at every size.zero_sign, the sign of zero: binary32 at one position, decoded byModel.toReal?(b32 nan h), with FloatLib's NaNs and with every NaN predicatenanwhose words decode to no real, under thebitwiseidentity (id32 nan h), refuses-0(0x80000000) for+0(0x00000000), throughFloatRule.Holds.bitwise_eq.- Plan: the importer's
eqevaluated at one shape, andtranslaterefusing a second operation.
Where the plan departs from the design, and why
safeMaxis not "the largest magnitude whose rounding is finite". Under nearest-even rounding no such magnitude exists: every magnitude below FloatLib'soverflowThreshold fmt(the largest finite value plus half an ulp) rounds to a finite value, and the threshold itself rounds to infinity.safeMaxis the largest finite value,(Model.posMaxFinite fmt).toReal, for which FloatLib already has the range lemma; the design's overflow-edge test is unchanged.Approxis stated on decoded values, with the word form as a corollary. A graded rule reads its outputs throughEncoding.decode, which may decode several words at once (block scales), so it has valuesOption ℝand noModel fmtword per entry.FloatRuletakesDomandfas parameters. The design'shw : DecodesAs wmust say thatwdecodes as the spec'sfon itsDom, which are fields ofSpec;Spec.rulethen has typeFloatRule In Out dIn dOut Dom f.exacthas a representability premise. On a 32-bit integer sum the design'sexactrule is false on all ofDom, since the words wrap: the output decodes, but not to the sum. The integer sum is phase 2's exit test, so the rule claims only where eachf σ A odecodes from some output word, the integer counterpart ofApprox'ssafeMaxpremise.Spec.matVectakes its grade. Kernels with one mathematics have different proved bounds: gemv'sMojoProof.Sem.warpDot_matVechas the error ofGPUProof.laneGrade (.ieee fmt) 32 5 ⌈n / 32⌉ nat the grades⟨0, 0⟩, a sequential loop hasγₙ T, and atn = 1the first is above the second. A spec with one fixed grade either refuses gemv or is weaker than its proof.Spec.matVec g monosharesDomandffor everyg(testmatVec_f), and a kernel's headline names its grade.Encodings.uniformtakes one scalar encoding perDType, not oneNumFormat, so a spec withrealandintentries (an index input, a mask) also has a uniform case.NumFormathas a phase 0 form in the core. FloatLib's format sum is an intake item and not released; the core's three cases are replaced by it in one change.- The NaN equivalence is defined once, in a core module that imports nothing.
GPUProof.UpToNaN nan(GPUProof/NaN.lean) is equality up to the NaN wordsnan, for every word type, with its equivalence proved once (GPUProof.UpToNaN.equivalence). The encodings'GPUProof.ScalarEnc.nanEqandGPUProof.Encoding.nanEqareUpToNaNat their NaN words, and MojoProof'sMojoProof.Sem.NaNEqisUpToNaN Model.isNaNat FloatLib's words, and itsMojoProof.Sem.FinEqisUpToNaNat the words that are not finite, each with its name, type and every lemma's statement unchanged; soScalarEnc.ieee's relation and MojoProof's are one definition. The core cannot import MojoProof, so the definition is the core's, in a module of its own, so that a change to the spec layer does not rebuild MojoProof. FloatLib's intake (withModel.add_comm_nanEq) is its later home. - The importer is a library of its own.
MojoProofTest/GPUProof/Imports.leanrefuses TorchLean in the core's closure, soGPUProofImportneeds alean_libentry in the lakefile, with its own imports test (onlyGPUProof.*,Mathlib.*,FloatLib.*andTorchLean.*). - TorchLean has no
Tensor.toMatrixand noTensor.toFun. The design's statement ofTorchLean.matVec_equses both; the form above usesMatrix.ofoverTensor.get2andTensor.getScalar, which TorchLean has, andreadInconnects them toTensor.toVecₗᵢ. MeetsandMeetsAttake the spec first,Meets Sp kand notMeets k Sp: the type of the behaviorkreadsSp's encodings (Spec.Encs Sp σ), soSpis bound before it.Approxtakes the entry typed, so one definition covers real, integer and boolean entries; a graded rule passesdIn σ ianddOut σ o.bitwisenames its encodings. The design'swmaps input words to output words at every encoding, and no suchwexists: at an encoding whose input words areUnitand whose output words areEmptyit would give a word ofEmpty, and at an encoding whose output decoder givesnoneeverywhere nowdecodes asf. A bitwise rule is about one storage (NaN payloads, sign bits), sobitwise E₀ w hwcarries its encodingsE₀,wandhware stated atE₀alone, and the rule claims nothing at other encodings.-
Equality up to NaN payloads is defined from NaN words, at every encoding. In the design
nanEqis a field of each encoding with no law, and abitwiserule trusts it: an encoding of Booleans withnanEq := fun _ _ => Truelets every output meet the bitwise identity spec. Laws on a free relation are not enough either: binary32 at one entry, decoded byModel.toReal?, withnanEq x y := x.toReal? = y.toReal?, is an equivalence whose related words decode alike, and it relates+0and-0, so the bitwise identity would accept-0(0x80000000) for+0(0x00000000), a word with another sign that is no NaN. So no encoding carries a relation. A scalar encoding names its NaN words, with the law that a NaN decodes tonone(GPUProof.ScalarEnc.decode_isNaN). An encoding of a whole side names its word positions, since its words need not be one word per entry (block scales share bits), and the NaN words at each position, with two laws that tie them to the decoder: words equal up to NaN payloads at every position decode alike (GPUProof.Encoding.decode_eq), and a NaN at a position leaves some entry with no value, whatever the other positions hold (GPUProof.Encoding.decode_isNaN). The relation is defined once,GPUProof.UpToNaNat each position (GPUProof.ScalarEnc.nanEq,GPUProof.Encoding.nanEq), and its equivalence is a theorem (GPUProof.UpToNaN.equivalence,GPUProof.Encoding.nanEq_equiv). Both laws, and not the second alone, because the decoder reads all positions at once: with the second alone, a decoder could read another entry's value from a NaN's payload, which abitwiserule lets change.The counterexample is refused at every NaN predicate, not only FloatLib's:
+0and-0decode to0, so by the second law neither is a NaN, andUpToNaNrelates them only if they are equal (testzero_sign). In general, at inputs that decode into the domain every output of the word function has a value, so none of its words is a NaN and the rule asks for those words themselves (GPUProof.FloatRule.Holds.bitwise_eq): payloads are free only where an output of the word function has no value. The Boolean encoding cannot be built either: NaN words that relate every two words relate a word decoding totrueand one decoding tofalse, whichdecode_eqrefuses (testbool_total_refused); and atGPUProof.ScalarEnc.bool, which has no NaN, the bitwise identity refusesfalsefromtrue(testboolId_refuses). With the laws the outputs of a bitwise rule decode as its word function's (GPUProof.FloatRule.Holds.bitwise).What the laws do not exclude. An encoding may call NaN any word that leaves an entry with no value: an infinity, or a word out of range. A bitwise rule then accepts any such word in place of another,
+∞for a NaN or-∞for+∞;GPUProof.ScalarEnc.ieeetakes FloatLib'sModel.isNaN, so not at FloatLib's formats. The second law asks for some entry with no value, not for the entry that the word stores: an encoding with an entry that never has a value (padding stored as an entry, say) may call NaN any words that its decoder reads alike,+0and-0among them. Abitwiserule whose outputs are stored so has no word function that decodes asf(DecodesAsasks for a value at every output entry) unless no input decodes into the domain, so it claims nothing about values. Padding is modelled as positions whose words areUnitor have no NaN, not as entries. Which words are NaNs remains the encoding's claim; the laws make it a claim about its decoder.
Not in this layer
Wiring, Meets.comp, Meets.choice and Meets.ofLocal come after the three specs, with
softmax and the norms. Meets.comp needs one more condition than the design states: a graded
rule must bound its inputs' magnitudes by its output's, (G i).mag ≤ (g σ E A G o).mag for every
input i that output o reads, or an input that its own magnitude premise lets be a NaN makes
the output's claim false. laneGrade has that condition (laneGrade_mag), so laneVecGrade,
matVecGrade and vecMatGrade have it at every input that their output reads. MixedRadix follows the spec
layer.